Aug 29 2011
12 notes

Link

Check out my new node.js app!

livewall is a public real-time text wall. Edit the text on the wall and all users will see those changes in real-time as they are being made. Fire it up on two side-by-side browser windows to see the magic. livewall is built on node.js and uses socket.io. Upcoming features include caret position conservation and sending only changes.

May 10 2011
5 notes

Autotest

If you use testing in your development, and I really hope you do, take a look at Autotest. This beauty runs the appropriate tests every time you edit a file. This saves you a TON of development time. So don’t even think about it. Go to your terminal and type

$ gem install ZenTest
$ sudo gem install autotest-rails

Now go have a drink, you just shaved a few days off your next rails job.


May 06 2011

Link

The Ruby Toolbox

This site is priceless for ruby developers. It basically list a bashitload of the most popular ruby gems and projects out there. Seriously. Tons. Of. Gems. Check it out.


Sep 13 2010

Link

loboto.me

So this is my first official rails 3 app. It uses jQuery as well. It’s a password repository to store all your credentials in an encrypted state, and retrieve and decrypt them when necessary using your main account password. The app uses MD5 hashing and AES symmetric encryption. I’ll be writing a few tutorials regarding the app. In the mean time, you can play with the code all you like here at github as usual.


Sep 01 2010

REST Resources and Actions Tutorial

This tutorial covers what in my opinion is the most essential rails concept. Representational State Transfer, or REST, is a client-server web architecture in which clients can issue an HTTP request to the server, and the server will interpret the request and issue an HTTP response back to the client. The REST server holds the application’s “resources” (data), and provides REST actions for clients to interact with those resources. The only way the client can access the application’s resources is by using the provided REST actions; this translates to a more secure application, since clients shouldn’t be able to mess with the data in any way o ther than how the developers intended. This is often referred to as a REST API.

For example, in Twitter, Tweets are a REST resource, as are users and trends. When you go to your profile page on Twitter at a URL like twitter.com/codepron, you’re actually issuing an HTTP Get request asking the twitter servers for the latest tweets belonging to the user with username “codepron”. The string “codepron” is sent as a parameter, so that the server knows which user’s tweets to fetch. The server then issues an HTTP response, which you see as an HTML page with codepron’s latest tweets.

In this tutorial we’ll build an app that indexes books. We’ll scaffold a Book class with title and author attributes. Rails scaffolding will automatically include the basic CRUD actions (create, read, update, destroy) in the controller, along with the Book model and the index, new, show, and edit views. Then we’ll add a custom search action and add parameters to it in order to have an advanced search option where we can filter by author or title.

1. Create a rails app named ‘books’

$ rails books

2. Change directory into the app’s directory

$ cd books

3. Generate the book scaffolding

$ script/generate scaffold Book title:string author:string

3. Migrate database

$ rake db:migrate

4. Test app so far

$ script/server

You should now be able to see the books app index page at http://localhost:3000/books, and add, edit, and delete books using the generated forms. We will now add a search REST action to the app.

5. Add the search action definition to the books controller. We’ll show the search results in the index view rather than creating its own search results view.

def search
  @books = Book.search(params[:query])
  respond_to do |format| 
    format.html { render :template => 'books/index' }
    format.xml { render :xml => @books }
  end 
end

6. The actual search algorithm will reside in the Book model as a class method.

class Book < ActiveRecord::Base
  def self.search(query)
    Book.all(:conditions => ['lower(title) LIKE :q or lower(author) LIKE :q', {:q => "%#{query}%"} ])    
  end
end

7. In config/routes.rb, add the search action declaration to the books resources declaration:

ActionController::Routing::Routes.draw do |map|
  map.resources :books, :collection => { :search => :get }
  
  map.connect ':controller/:action/:id'
  map.connect ':controller/:action/:id.:format'
end

Notice we specify to use the HTTP Get method near the end of the route declaration, so our search URLs are easily sharable and crawlable by search engines. You should always use the HTTP Get method for REST actions that are passive, that is, they don’t alter the database in anyway. Examples are the index and show actions, as well as the edit and new actions, since they only show you a page. The actual changes are made with the update and create methods, which, as you would expect, use the HTTP post method to send their data. You can tell when a browser uses the post method because it asks yow if you want to “re-send the data” when you press your browser’s Back button.

8. Now let’s add the search form to the index page right under the heading:

<h1>Listing books</h1>

<% form_tag search_books_path, :method => :get do -%> 
	<%= text_field_tag :query, params[:query] %>
	<%= submit_tag 'Search' %>
<% end -%>

<table>
  <tr>
    <th>Title</th>
    <th>Author</th>
  </tr>

<% @books.each do |book| %>
  <tr>
    <td><%=h book.title %></td>
    <td><%=h book.author %></td>
    <td><%= link_to 'Show', book %></td>
    <td><%= link_to 'Edit', edit_book_path(book) %></td>
    <td><%= link_to 'Destroy', book, :confirm => 'Are you sure?', :method => :delete %></td>
  </tr>
<% end %>
</table>

<br />

<%= link_to 'New book', new_book_path %>

If we run the app now, we should be able to search for with title or author like the search query.

To implement an advanced search option we will add 2 optional parameters to the search action: author and title.

9. Add the extra parameters to the search algorithm in the books model:

class Book < ActiveRecord::Base
  def self.search(query, author, title) 
    conditions = ''
    unless query == ''
      conditions += '(lower(title) LIKE :q or lower(author) LIKE :q)'
    end
    
    unless author == ''
      unless conditions == ''
        conditions += ' and '
      end
      conditions += 'lower(author) LIKE :a'
    end
    
    unless title == ''
      unless conditions == ''
        conditions += ' and '
      end
      conditions += 'lower(title) LIKE :t'
    end
    
    if conditions == ''
      Book.all
    else 
      Book.all(:conditions => [conditions, {:q => "%#{query}%", :a => "%#{author}%", :t => "%#{title}%"}])    
    end
  end
end

10. Edit the books controller search action to take the new parameters into account:

def search
  @books = Book.search(params[:query],params[:author],params[:title])
  respond_to do |format| 
    format.html { render :template => 'books/index' }
    format.xml { render :xml => @books }
  end 
end

11. Now let’s create the new advanced options below our search bar in the books index view:

<h1>Listing books</h1>

<% form_tag search_books_path, :method => :get do -%> 
	search: <%= text_field_tag :query, params[:query] %><br /><br />
	Advanced Options<br />
	title: <%= text_field_tag :title, params[:title] %><br />
	author: <%= text_field_tag :author, params[:author] %><br /><br />
	<%= submit_tag 'Search' %>
<% end -%>

<table>
  <tr>
    <th>Title</th>
    <th>Author</th>
  </tr>

<% @books.each do |book| %>
  <tr>
    <td><%=h book.title %></td>
    <td><%=h book.author %></td>
    <td><%= link_to 'Show', book %></td>
    <td><%= link_to 'Edit', edit_book_path(book) %></td>
    <td><%= link_to 'Destroy', book, :confirm => 'Are you sure?', :method => :delete %></td>
  </tr>
<% end %>
</table>

<br />

<%= link_to 'New book', new_book_path %>

That’s it. You should now be able to run the app and use the optional advanced search parameters. As always, check out the demo app and the source code.


Aug 30 2010
3 notes

Deploying a Rails App to Heroku

If you’ve used Git, using Heroku will be a walk in the park. Heroku is free, robust, and extremely simple to use. Use it. You’ll need to have Git installed, so if you don’t, follow this tutorial to get it working.

1. Get a Heroku account here.

2. Install Heroku gem

$ sudo gem install heroku

3. Add your Heroku login credentials

$ heroku keys:add

4. Create a sample rails project and cd into it.

$ rails sampleproject
$ cd sampleproject

5. Now create a Heroku project out of your app by typing:

$ heroku create

6. Now upload your app to Heroku by typing:

$ git push heroku master

That’s it. Your app should be running on Heroku at the address it generated. To get a more familiar address, type:

$ heroku rename whateveryoulike

Your app will now be running at the address http://whateveryoulike.heroku.com You can choose whichever subdomain you like, as long as it hasn’t been used yet. That’s it. Now go take a nap son, you just deployed a rails app.


Aug 29 2010
1 note

Using Git and Github

Git is the version control system of choice for rails developers, and it’s no coincidence. Git is hands-down the simplest source code management system to date.

1. To get Git download the installer for your OS from their downloads page and run it to install Git.

2. After installing Git, configure it with your name and email by pulling up a terminal and (I hope I don’t have to tell you to type your own name and email rather than mine) typing: 

$ git config --global user.name "Andrés Bonilla"
$ git config --global user.email andresbonilla@gmail.com

3. Now just go into your project folder and create a Git repository by typing:

$ git init

4. to add all the project files to the repository just type:

$ git add .

5. Now run your first commit:

$ git commit -m "commit message goes here, explaining the changes"

That’s all you need to create and maintain local git repositories. But the real advantages to Git are pushing and pulling changes to and from remote repositories. Github is the most popular free Git repository service. The only catch is, in order for your repositories to be free, your code must be public. This isn’t as much a catch as it is wanting to contribute to the open-source community, but if you want to keep your code repositories private, then you’ll have to cough up some cash.

6. To use github, go to github.com and create an account.

7. Then go to your Account Settings section, and click on SSH Public Keys. You’ll have to generate a key on your local machine, and then register that key there on Github  by clicking on “Add a public key”. If you have any doubts or problems generating a public key on your machine, click on the link to the right that reads “Need help with public keys?”. That will link you to a tutorial specific to your local operating system on generating keys.

8. After setting up the SSH key, you should be all set to use Github. Go to your home page on Github and click on “New Repository”. Give your project a name,  a description, and a URL if it has one. Here you can also choose to make this repository private. Then click on “Create Repository”.

9. Since we already configured Git on our machine and have a local repository in our project folder, we will follow the steps under the heading “Existing Git Repo?” near the bottom of the page. All we have to do to copy that repository to Github is pull up a local terminal, cd to our project folder, where we created the Git repository earlier, and then type (substituting andresbonilla for your github username and yourprojectname for the name you gave your Github repository) something like:

$ git remote add origin git@github.com:andresbonilla/yourprojectname.git

The exact line you need to type is displayed in the instructions we’re following on Github.

10. Now type:

$ git push origin master

Click “continue” near the bottom and now your code is safely stored in github (for everyone to see, unless you pay up).


Aug 28 2010

Collapsing Parent CSS Pitfall

This is one of the most essential CSS tricks in modern front-end development. When you have a div with several floated elements inside, you get a collapsing parent, which means that the div looks vertically shorter than the contained elements, which seem to overflow out of the div. The solution is adding:

<div style=”clear:both;”></div>

after the floating elements, inside the div that was collapsing. This stretches the div around the contained floated objects, making it look like it actually contains them. Be careful when adding extra floated elements with javascript; remember to add them above the clear:both div. In such a case case it might be a good idea to assign an id or class to the clear:both div in order to reference it from the javascript, and move the style data over to our CSS stylesheets as well to clean up your views.


Aug 25 2010
2 notes

Link

Trend Console

Trend Console is a small jQuery-powered web app I recently developed, which uses the twitter trends api as a data source for tweets, images, and video. Check out the source code as always, on github.


Aug 24 2010
1 note

jQuery Selector Optimization

This one comes from Paul Irish’s awesome 10 Things I Learned from the jQuery Source webcast, which I highly recommend. It’s a simple tip that goes a long way when you consider how often selectors are used, so here it is:

When using jQuery selectors, this:

$('#id').find('tag.thing')

is way faster than this:

$('#id tag.thing')

jQuery eventually reduces the second expression to the first, so next time, cut you app some slack and use optimized selectors. Your code will thank you.


Aug 22 2010
1 note

Disable Right-Click Menu With jQuery

$(document).ready(function(){
  $("#elementId").bind("contextmenu",function(e){
    return false;
  });
});

Just call that bind function on whatever it is that you want to disable right-clicking on. In this case, it will only affect the element with the id “elementId”. You can also use a class rather than an id to affect a set of elements, or use $(document).bind(… to affect the entire page.


Aug 21 2010

jQuery Stealing Your Clicks?

If you’ve ever used the jQuery draggable plugin on a div that happened to contain anything from a youtube video to plain old html UI inputs, then you have probably come across the problem that jQuery intercepts all mouse clicks within that draggable div, and impedes proper interaction with the elements inside. The following code allows you to selectively turn off ‘draggability’ on certain elements inside the draggable div.

$("#someElement").bind('mousedown mouseup', function(e) {
  e.stopPropagation();
});

Here, someElement is the id of the element which we want to interact with and remove ‘draggability’ from. We can also use a class instead of an id here to affect multiple elements at once.