Newer posts are loading.
You are at the newest post.
Click here to check if anything new just came in.

December 05 2013

19:59

Kickstarting Your Rails Education

It's been a long time since I last coded on the server-side. In fact, if you've read some of my tutorials, you may have noticed that I use ColdFusion as my application server. While ColdFusion still works great, it definitely doesn't have the panache and coolness of newer server-side technologies like Ruby on Rails. Wanting to be a bit more modern, I've decided to jump on the Ruby on Rails train. Both Ruby and the Rails framework are proven technologies that are stable and widely embraced so I think it's a great direction to head to in my server-side renaissance.

Picking it is the easy part. The hard part is actually learning how to properly use RoR and finding good resources learn from, the latter being the hardest part of it. With so many sites coming and going or not being maintained, it can be difficult to find information that's relevant and useful.

Luckily for you, I've done a lot of homework recently and started to collect a list of current. up-to-date resources that have been recommended to me and look really promising.

Let me share these with you.


The Ruby Language

You've got to walk before you can run and learning the ins-and-outs of the Ruby language will help you get a leg up. I'm a firm believer that having a good understanding of a programming language will make leveraging complementary technologies (e.g.: Rails) much easier and allow you to build maintainable code from the get-go. I know it may seem obvious but I've seen plenty of cowboys out there that learn something half-assed in a weekend and throw up production code the following Monday.


TryRuby.org

The great thing about the web is the abundance of interactive tools available for learning. The slogan for Try Ruby is:

Got 15 minutes? Give Ruby a shot right now!

And they hit the mark by providing an interactive editor that takes you step by step through the learning process. You follow some simple exercises, enter your answers in the editor and get immediate feedback.

tryruby

RubyMonk

Like Try Ruby, RubyMonk takes an interactive approach but they've also broken down the learning into skill levels. Each tutorial is listed by which level the content applies to allowing you to scale your learning appropriately. The site even offers an in-progress tutorial on using Rails.


Why's Poignant Guide to Ruby

When you first hit this site, you may actually think you've landed in the wrong place or a hipster book club. Don't be fooled. Go ahead and click on the book, then follow the pages. Initially, the imagery and cartoons may be confusing but as you get further along, you'll see it's just the author's eccentric style of writing meant to make his presentation of Ruby topics more inviting. The books is actually very good from what I've seen and a good resource to have.

whysbook

Ruby-Doc.org

As you learn Ruby, you'll see how rich the language can be. Being "rich" also means there's a lot to learn and language APIs to get comfortable with. This is where Ruby documentation project comes in. It is absolutely invaluable and you will live in this as you start to ramp up in Ruby. Seriously, bookmark it now.


Programming Ruby 1.9 & 2.0 (4th edition): The Pragmatic Programmers' Guide

Affectionately called the "pick axe" book, this is the must-have reference guide for Ruby. It's like the holy grail of the language and the one I found recommended all over the place. The key thing to keep in mind is that it's a "reference" and meant to complement your learning efforts as opposed to actually walking you through the learning process.


The Rails Framework

Once you feel you have a good grasp of the Ruby language, next it's time to jump into the Rails framework. Currently at version 4.0.x, it's become a mainstay for most startups that want a robust framework to get them up and running quickly. From what I've seen, it's very opinionated about how it does things, focusing on a lot of abstractions to make common tasks (e.g.: database access and interaction) easier.


Ruby on Rails Tutorial by Michael Hartl

In terms of learning Rails, this tutorial by Michael Hartl is one of the most complete I've seen and amazingly, he offers it up for free. He does offer some other niceties like screencasts and ebook versions for a cost but unless you want to place the book on your Kindle, reading it online should suffice.

What I love about this is that it covers every major aspect of the Rails framework and is updated with each major Rails version including v4.0.x. It's the reason that I listed it as the first Rails tutorial to check out.


Rails Guides

The tutorials in the Rails Guides will give you a solid foundation to work from. Looking through the Getting Started tutorial, it looks to cover the basics well but it does feel like Michael Hartl's stuff is a bit more comprehensive. Nonetheless, it's still a great option to learn by.


The Rails 3 Way

Obie Fernandez is a Rails guru and this book is recommended by everyone as the must-have Rails reading material. So I bowed to peer pressure and got it. Can't say yet if it's awesome but enough people I know who are good Rails developers said it's good so I'll go with that.

rails3way

Online Courses

Sometimes having someone walk you step-by-step through the learning process works better. Thankfully, there are some free courses available that provide a nice walk-through of Ruby on Rails and help make piecing things together a bit easier.


Tuts+ Premium Courses

I'd be remiss if I didn't mention Tuts+ as a great place to crank up my Ruby and Rails education. I also think Jeffrey Way would totally disown me as well!

Jose Mota's course, The Fundamentals of Ruby is a great example of the high-quality courses available for aspiring Rails developers like me.


RailsCasts

RailsCasts was created by Ryan Bates and currently lists over 400 instructional videos. Most of them are short and cover very specific topics allowing you to zero in on what you'd like to learn about.


Lots of Goodness to Learn From

Well that's my list. I think it's a pretty solid one at that. I know there are a ton of other blog posts, newsletters, sites and resources that aren't listed but that's okay. This is a list to get things kickstarted and as with any new thing, it's easy to get overwhelmed with too much information. I actually wrote about how hard it can be to stay on top of emerging technologies and finding time to learn new things in my op-ed, The Learning Conundrum.

I'm trying to keep things nice and tidy so I can focus and set realistic learning goals. I find this list to be short and sweet providing a good balance of reading material and interactive learning. But if you feel like I'm absolutely missing out on a good learning resource, mention it in the comments.

April 15 2013

15:00

Digging Into Rails 4

Rails 4 is rapidly approaching. In this article, let’s take a look at some of the new features that it offers, as well as the changes that may affect your current applications.


Some Bookkeeping

Cache digests are Rails 4′s solution for tracking the changes of aggressively cached templates.

There are several configuration and structural changes that comes with Rails 4.

Ruby >= 1.9.3

Rails 4 will only support Ruby 1.9.3+. Get ready for an upgrade if haven’t yet done so.

Threadsafe by Default

Rails 4 will be thread-safe by default, removing overhead and improving performance on threaded servers, like thin and puma. You need to ensure that your application (and its dependencies) are thread-safe, which typically means avoiding global state (e.g. class or global variables).

Aaron Patterson wrote and spoke about this subject. Definitely check those out!

No More vendor/plugins

Rails 3 embraced the idea of using gems to add custom functionality to Rails, and deprecated the use of plugins. Rails 4 completes this transition by removing the vendor/plugins directory altogether.

New Testing Directories

The default test directory naming scheme is more clear than in Rails 3.

The following directories will now be generated: test/models, test/helpers, test/controllers, test/mailers, and test/integration.

Executables

The script directory has been removed in favor of a new bin directory. This is where your app’s executables will live, and running rake rails:update:bin will put bundle, rake, and rails binstubs into your app’s bin directory.

This change can be useful in development, especially on a machine with multiple Ruby versions and gems. You can use bin/rails instead of bundle exec rails to ensure you run your executables in the correct environment.


Strong Parameters

Rails 4 tackles the mass assignment problem with the new Strong Parameters gem. A Rails 3 application might have a create action similar to the following example:

class UsersController < ApplicationController
  def create
    @user = User.create(params[:user])
    # ... check validity, redirect, etc.
  end
end

You can protect against unexpected input with declarations in the model:

class User < ActiveRecord::Base
  # Only allow the following attributes to be mass-assigned
  attr_accessible :name, :email
end

Using Rails 4′s Strong Parameters gem moves user input into the controller:

class UsersController < ApplicationController
  def create
    @user = User.create(user_params)
    # ... check validity, redirect, etc.
  end

  def user_params
    params.require(:user).permit(:name, :email)
  end
end

As you can see, the params hash in your controller is not a normal hash. It’s actually an instance of ActionController::Parameters, which exposes the require and permit methods.

The require method ensures that the specified key is available in the params hash, and raises an ActionController::ParameterMissing exception if the key doesn’t exist.

The permit method protects you from unexpected mass assignment.

The call User.create(params[:user]) raises an ActiveModel::ForbiddenAttributesError exception, but using User.create(params.require(:user).permit(:name, :email)) makes it work without complaint.

The Rails 3 mass-assignment functionality is not only disabled in Rails 4, but has been extracted to a gem, in case you require that functionality.


Turbolinks

Rails 4 will be thread safe by default, removing overhead and improving performance.

A controversial new feature in Rails 4 is Turbolinks, a JavaScript plugin designed to make app navigation faster in the browser.

In browsers with pushState support, clicking a link causes the Turbolinks plugin to kick in. It makes an Ajax request, updates the URL with pushState (so your back button works) and uses JavaScript to update the <title> and <body> in the DOM. The speed gains come from not having to download and reparse JavaScript and CSS assets.

Turbolinks gracefully degrade for browsers which do not support pushState. In these situations, the page’s links behave as normal—causing a full page refresh.

Events and Cache

It’s common in applications to wait for a page to completely load before executing any JavaScript. For example:

$(document).ready(/* some function to run */) {
  // or event just $(/* some function to run */)
}

With Turbolinks, the page load events won’t fire when users navigate from “page” to “page” because the DOM never actually reloads. The library, therefore, adds new events that you can listen for, in order to perform any subsequent initializations that your app might need:

  • page:fetch – starting to fetch a page from the server
  • page:change – a page has been loaded
  • page:load – a page has been loaded from a server fetch
  • page:restore – a page has been loaded from a cache fetch

The page:change event always fires when Turbolinks loads a page, followed by page:load or page:restore, depending on whether the load came from the server or the cache.

Potential Issues

Rails 4 is coming, and it brings a slew of changes to the framework.

Turbolinks have a few issues that you might need to address:

  • Memory leaks: Turbolinks does not clear or reload your JavaScript when the page changes. You could potentially see the effects of memory leaks in your applications, especially if you use a lot of JavaScript.
  • Event Bindings: You have to take older browsers into consideration. Make sure you listen for page:* events, as well as DOMContentLoaded.
  • Client-side frameworks: Turbolinks may not play nicely with other client-side frameworks like Backbone, Angular, Knockout, Ember, etc.

Opting Out

You may opt out of Turbolinks by:

  1. removing turbolinks from your Gemfile, and
  2. removing the //= require turbolinks line from application.js

Caching

Rails 4 brings an overhauled caching strategy. First, action and page caching, as you may know it from previous versions of Rails, have been removed and extracted to gems: action and page, respectively.

Russian Dolls

The new kid on the block is Russian doll caching, or nested fragment caching. The easiest way to understand this system is to look at some code. Suppose that you have a project management application. You may have the following models:

class Milestone < ActiveRecord::Base
  has_many :todos
end

class Todo < ActiveRecord::Base
  belongs_to :milestone, :touch => true
end

The :touch option is required for this caching strategy to work properly. If a todo is added to a milestone, we need to break cache on the milestone to avoid serving stale views.

We now have finely-grained caches in our views. Consider this file as an example (app/views/milestones/show.html.erb):

<% cache @milestone do %>
  <h1><%= @milestone.name %></h1>
  <div class="description"><%= @milestone.description %></div>

  <ul class="todos">
    <%= render @milestone.todos %>
  </ul>
<% end %>

And in app/views/todos/_todo.html.erb:

<% cache todo do %>
  <li class="todo">
    <%= todo.description %>
    <span class="status"><%= todo.status %></span>
  </li>
<% end %>

Now, suppose that you have a milestone with ten todos. Editing only one todo causes the milestone’s cache to break, but when generating the HTML, all but one of the todo partials can be fetched from the cache, thus improving render times.

PATCH is now the new HTTP verb for updating resources.

You’re trading time for space, as this generates a lot of cruft in your cache. But, as DHH points out, cache stores like Memcached just chuck out old data to make space for new data. So this isn’t an issue in most cases.

Cache Digests

Cache digests are Rails 4′s solution for tracking the changes of aggressively cached templates. Rails 4 tracks templates and their dependencies, and it suffixes fragment cache keys with the MD5 digest of the template (and its dependencies). When you edit one of your templates, its cache key recieves the update, and you won’t have to manually version your templates.

For more information (and for use in Rails 3), check out the README for the cache digests gem.


Streaming, via ActionController::Live

The new ActionController::Live module provides the ability to stream data to clients. Simply include the module into a controller to enable your app to send arbitrary streamed data. You’ll have to use a threaded server, like thin and puma, in order to stream data; actions from streaming controllers run in a separate thread.

Here’s an example from the Rails 4 documentation:

class MyController < ActionController::Base
  include ActionController::Live

  def stream
    response.headers['Content-Type'] = 'text/event-stream'
    100.times {
      response.stream.write "hello world
"
        sleep 1
    }
    response.stream.close
  end
end

As the docs note, there are three things to keep in mind:

  • You must write any headers before you call write or close on the response stream.
  • You have to call close on the response stream when you’re finished writing data.
  • Ensure that your actions are thread-safe, as they will run in a separate thread.

Niceties and Other Things

We’ve talked about the “headline” features in Rails 4. But this release is a big one, and includes a number of smaller changes to be aware of.

PATCH

As described in the Rails blog, PATCH is now the HTTP verb for updating resources.

This change will typically be transparent to developers, as PUT requests will still route to the update action for RESTful-style routes.

But it is a change that you should be aware of; PUT routing may change in the future.

Custom Flash Types

This small feature may help clean up some code. You can register your own flash types to use in redirect_to calls and in templates. For example:

# app/controllers/application_controller.rb
class ApplicationController
  add_flash_types :error, :catastrophe
end

# app/controllers/things_controller.rb
class ThingsController < ApplicationController
  def create
    # ... create a thing
  rescue Error => e
    redirect_to some_path, :error => e.message
  rescue Catastrophe => e
    redirect_to another_path, :catastrophe => e.message
  end
end

# app/views/layouts/application.html.erb
<div class="error"><%= error %></div>
<div class="catastrophe"><%= catastrophe %></div>

Deprecated Finders

Rails 4 deprecates the old-style finder option hashes, as well as all dynamic finder methods (with the exception of find_by_... and find_by_...). Instead, you’ll use where:

  • find_all_by_... can be rewritten using where(...).
  • find_last_by_... can be rewritten using where(...).last.
  • scoped_by_... can be rewritten using where(...).
  • find_or_initialize_by_... can be rewritten using where(...).first_or_initialize.
  • find_or_create_by_... can be rewritten using find_or_create_by(...) or where(...).first_or_create.
  • find_or_create_by_...! can be rewritten using find_or_create_by!(...) or where(...).first_or_create!.

The deprecated finders gem will be included as a dependency in 4.0. and removed in 4.1. The gem, however, will be around and maintained until 5.0.

Routing Concerns

Routing Concerns is an attempt to DRY up your config/routes.rb. The basic idea is to define common sub-resources (like comments) as concerns and include them in other resources/routes. Here’s the obvious example:

concern :commentable do
  resources :comments
end

concern :remarkable do
  resources :remarks
end

resources :posts, :concerns => :commentable  
resources :articles, :concerns => [:commentable, :remarkable] # can include several  

The above is equivalent to the following Rails 3 code:

resources :posts do
  resources :comments
end

resources :articles do
  resources :comments
  resources :remarks
end

Personally, I’m not sure this adds much value; perhaps it makes sense for large applications with hundreds of routes.

Renamed Callbacks

Action callbacks in controllers have been renamed from *_filter to *_action. For example:

class UsersController < ApplicationController
  before_action :set_user, :except => [:index, :new, :create}
  before_action :require_the_president, :only => [:fire_the_missiles]

  private

  def set_user
    @user = somehow_find_and_set_the_user(params[:id])
  end

  def require_the_president
    @user.is_the_president?
  end
end

The old *_filter callbacks still work and are not deprecated; so, you can still use them if you wish. DHH’s reason for the change was:

“To avoid the misconception that these callbacks are only suited for transforming or halting the response. With the new style, it’s more inviting to use them as they were intended, such as setting shared ivars for views.”


Wrapping Up

Rails 4 is coming, bringing with it a slew of changes. I hope that this article has given you a sense of what to expect, and perhaps a launching point into investigating what this new version has to offer.

If you really want to wade into the deep end, check out our Tuts+ Premium course on Rails 4!

Tags: Ruby rails
Sponsored post
feedback2020-admin
14:56
you are awesome!
Reposted bysirthomasbolton sirthomasbolton

March 15 2012

21:00

Intelligent ActiveRecord Models

ActiveRecord models in Rails already do a lot of the heavy lifting, in terms of database access and model relationships, but with a bit of work, they can do more things automatically. Let’s find out how!


Step 1 - Create a Base Rails App

This idea works for any sort of ActiveRecord project; however, since Rails is the most common, we’ll be using that for our example app. The app we’ll be using has lots of Users, each of whom can perform a number of actions on Projects .

If you’ve never created a Rails app before, then read this tutorial, or syllabus, first. Otherwise, fire up the old console and type rails new example_app to create the app and then change directories to your new app with cd example_app.


Step 2 - Create Your Models and Relationships

First, we generate the user that will own:


 rails generate scaffold User name:text email:string password_hash:text

Likely, in a real world project, we’d have a few more fields, but this will do for now. Let’s next generate our project model:


 rails generate scaffold Project name:text started_at:datetime started_by_id:integer completed_at:datetime completed_by_id:integer

We then edit the generated project.rb file to describe the relationship between users and projects:


 class Project < ActiveRecord::Base
  belongs_to :starter, :class_name =>"User", :foreign_key =>"started_by_id"
  belongs_to :completer, :class_name =>"User", :foreign_key =>"completed_by_id"
 end

and the reverse relationship in user.rb:


 class User < ActiveRecord::Base
  has_many :started_projects, :foreign_key =>"started_by_id"
  has_many :completed_projects, :foreign_key =>"completed_by_id"
 end

Next, run a quick rake db:migrate, and we’re ready to begin getting intelligent with these models. If only getting relationships with models was as easy in the real world! Now, if you’ve ever used the Rails framework before, you’ve probably learned nothing… yet!


Step 3 - Faux Attributes Are Cooler Than Faux Leather

The first thing we’re going to do is use some auto generating fields. You’ll have noticed that when we created the model, we created a password hash and not a password field. We’re going to create a faux attribute for a password that will convert it to a hash if it’s present.

So, in your model, we’ll add a definition for this new password field.


 def password={new_password)
  write_attribute(:password_hash, SHA1::hexdigest(new_password))
 end

 def password
  ""
 end

We only store a hash against the user so we’re not giving out the passwords without a bit of a fight.

The second method means we return something for forms to use.

We also need to ensure that we have the Sha1 encryption library loaded; add require 'sha1' to your application.rb file after line 40: config.filter_parameters += [:password].

As we’ve changed the app at the configuration level, reload it with a quick touch tmp/restart.txt in your console.

Now, let’s change the default form to use this instead of password_hash. Open _form.html.erb in the app/models/users folder:


 <div class="field">
  <%= f.label :password_hash %><br />
  <%= f.text_area :password_hash %>
 </div>

becomes


 <div>
  <%= f.label :password %><br/>
  <%= f.text_field :password %>
 </div>

We’ll make it an actual password field when we’re happy with it.

Now, load http://localhost/users and have a play with adding users. It should look a bit like the image below; great, isn’t it!

User Form

Wait, what’s that? It overwrites your password hash every time you edit a user? Let’s fix that.

Open up user.rb again, and change it like so:


 write_attribute(:password_hash, SHA1::hexdigest(new_password)) if new_password.present?

This way, only when you supply a password does the field get updated.


Step 4 - Automatic Data Guarantees Accuracy or Your Money Back

The last section was all about changing the data that your model gets, but what about adding more information based on things already known without having to specify them? Let’s have a look at that with the project model. Begin by having a look at http://localhost/projects.

Make the following changes quickly.

*app/controllers/projects_controler.rb* line 24


 # GET /projects/new
 # GET /projects/new.json
 def new
  @project = Project.new
  @users = ["--",nil] + User.all.collect { |u| [u.name,u.id] }

  respond_to do |format|
   format.html # new.html.erb
   format.json { render :json =>@project }
  end
 end

 # GET /projects/1/edit
 def edit
  @project = Project.find(params[:id])
  @users = ["--",nil] + User.all.collect { |u| [u.name,u.id] }
 end

*app/views/projects/_form.html.erb* line 24


 <%= f.select :started_by_id, @users %>

*app/views/projects/_form.html.erb* line 24


 <%= f.select :completed_by , @users%>

In MVC frameworks, the roles are clearly defined. Models represent the data. Views display the data. Controllers get data and pass them to the view.

Who Enjoys Filling Out Date/time Fields?

We now have a full functioning form, but it bugs me that I have to set the start_at time manually. I’d like to have it set when I assign a started_by user. We could put it in the controller, however, if you’ve ever heard the phrase “fat models, skinny controllers” you’ll know this makes for bad code. If we do this in the model, it’ll work anywhere we set a the starter or completer. Let’s do that.

First edit app/models/project.rb, and add the following method:


 def started_by=(user)
  if(user.present?)
   user = user.id if user.class == User
   write_attribute(:started_by_id,user)
   write_attribute(:started_at,Time.now)
  end
 end

This code ensures that something has actually been passed. Then, if it’s a user, it retrieves its ID and finally writes both the user *and* the time it happened – holy smokes! Let’s add the same for the completed_by field.


 def completed_by=(user)
  if(user.present?)
   user = user.id if user.class == User
   write_attribute(:completed_by_id,user)
   write_attribute(:started_at,Time.now)
  end
 end

Now edit the form view so we don’t have those time selects. In app/views/projects/_form.html.erb, remove lines 26-29 and 18-21.

Open up http://localhost/projects and have a go!

Spot the Deliberate Mistake

Whoooops! Someone (I’ll take the heat since it’s my code) cut and paste, and forgot to change the :started_at to :completed_at in the second largely identical (hint) attribute method. No biggie, change that and everything is go… right?


Step 5 - Help Your Future Self by Making Additions Easier

So apart from a little cut-and-paste confusion, I think we did fairly good job, but that slip up and the code around it bothers me a bit. Why? Well, let’s have a think:

  • It’s cut and paste duplication: DRY (Don’t repeat yourself) is a principle to follow.
  • What if someone wants to add another somethingd_at and somethingd_by to our project, like, say, authorised_at and authorised_by>
  • I can imagine quite a few of these fields being added.

Lo and behold, along comes a pointy haired boss and asks for, {drumroll}, authorised_at/by field and a suggested_at/by field! Right then; let’s get those cut and paste fingers ready then… or is there a better way?

The Scary Art of Meta-progamming!

That’s right! The holy grail; the scary stuff your mothers warned you about. It seems complicated, but actually can be pretty simple – especially what we’re going to attempt. We’re going to take an array of the names of stages we have, and then auto build these methods on the fly. Excited? Great.

Of course, we’ll need to add the fields; so let’s add a migration rails generate migration additional_workflow_stages and add those fields inside the newly generated db/migrate/TODAYSTIMESTAMP_additional_workflow_stages.rb.


class AdditionalWorkflowStages < ActiveRecord::Migration
 def up
  add_column :projects, :authorised_by_id, :integer
  add_column :projects, :authorised_at, :timestamp
  add_column :projects, :suggested_by_id, :integer
  add_column :projects, :suggested_at, :timestamp
 end

 def down
  remove_column :projects, :authorised_by_id
  remove_column :projects, :authorised_at
  remove_column :projects, :suggested_by_id
  remove_column :projects, :suggested_at
 end
end

Migrate your database with rake db:migrate, and replace the projects class with:


 class Project < ActiveRecord::Base
 # belongs_to :starter, :class_name =>"User"

 # def started_by=(user)
 # if(user.present?)
 #   user = user.id if user.class == User
 #   write_attribute(:started_by_id,user)
 #   write_attribute(:started_at,Time.now)
 # end
 # end
 #
 # def started_by
 # read_attribute(:completed_by_id)
 # end

 end

I’ve left the started_by in there so you can see how the code was before.


 [:starte,:complete,:authorise,:suggeste].each do |arg|
  ..MORE..
  end

Nice and gentle – goes through the names(ish) of the methods we wish to create:


 [:starte,:complete,:authorise,:suggeste].each do |arg|

  attr_by = "#{arg}d_by_id".to_sym
  attr_at = "#{arg}d_at".to_sym
  object_method_name = "#{arg}r".to_sym	  

  ...MORE...
 end

For each of those names, we work out the two model attributes we’re setting e.g started_by_id and started_at and the name of the association e.g. starter


 [:starte,:complete,:authorise,:suggeste].each do |arg|

  attr_by = "#{arg}d_by_id".to_sym
  attr_at = "#{arg}d_at".to_sym
  object_method_name = "#{arg}r".to_sym	  

  belongs_to object_method_name, :class_name =>"User", :foreign_key =>attr_by

 end

This seems pretty familiar. This is actually a Rails bit of metaprogramming already that defines a bunch of methods.


 [:starte,:complete,:authorise,:suggeste].each do |arg|

  attr_by = "#{arg}d_by_id".to_sym
  attr_at = "#{arg}d_at".to_sym
  object_method_name = "#{arg}r".to_sym	  

  belongs_to object_method_name, :class_name =>"User", :foreign_key =>attr_by

  get_method_name = "#{arg}d_by".to_sym

  define_method(get_method_name) { read_attribute(attr_by) }

 end

Ok, we come to some real meta programming now that calculates the ‘get method’ name – e.g. started_by, and then creates a method, just as we do when we write def method, but in a different form.


 [:starte,:complete,:authorise,:suggeste].each do |arg|

  attr_by = "#{arg}d_by_id".to_sym
  attr_at = "#{arg}d_at".to_sym
  object_method_name = "#{arg}r".to_sym	  

  belongs_to object_method_name, :class_name =>"User", :foreign_key =>attr_by

  get_method_name = "#{arg}d_by".to_sym

  define_method(get_method_name) { read_attribute(attr_by) }

  set_method_name = "#{arg}d_by=".to_sym

  define_method(set_method_name) do |user|
   if user.present?
    user = user.id if user.class == User
    write_attribute(attr_by,user)
    write_attribute(attr_at,Time.now)
   end
  end

 end

A little bit more complicated now. We do the same as before, but this is the set method name. We define that method, using define(method_name) do |param| end, rather than def method_name=(param).

That wasn’t so bad, was it?

Try it Out in the Form

Let’s see if we can still edit projects as before. It turns out that we can! So we’ll add the additional fields to the form, and, hey, presto!

app/views/project/_form.html.erb line 20


 <div class="field">
  <%= f.label :suggested_by %><br/>
  <%= f.select :suggested_by, @users %>
 </div>

 <div class="field">
  <%= f.label :authorised_by %><br/>
  <%= f.select :authorised_by, @users %>
 </div>

And to the show view… so we can see it working.

*app/views-project/show.html.erb* line 8


 <p>
  <b>Suggested at:</b> <%= @project.suggested_at %>
 </p>

 <p>
  <b>Suggested by:</b> <%= @project.suggested_by_id %>
 </p>

 <p>
  <b>Authorised at:</b> <%= @project.authorised_at %>
 </p>

 <p>
  <b>Authorised by:</b> <%= @project.authorised_by_id %>
 </p>

Have another play with http://localhost/projects, and you can see we have a winner! No need to fear if someone asks for another workflow step; simply add the migration for the database, and put it in the array of methods… and it gets created. Time for a rest? Maybe, but I’ve just two more things to make note of.


Step 6 - Automate the Automation

That array of methods seems quite useful to me. Could we do more with it?

First, let’s make the list of method names a constant so we can access it from outside.


 WORKFLOW_METHODS = [:starte,:complete,:authorise,:suggeste]
 WORKFLOW_METHODS.each do |arg|....

Now, we can use them to auto create form and views. Open up the _form.html.erb for projects, and let’s try it by replacing lines 19 -37 with the snippet below:


 <% Project::WORKFLOW_METHODS.each do |workflow| %>
  <div class="field">
  <%= f.label "#{workflow}d_by" %><br/>
  <%= f.select "#{workflow}d_by", @users %>
  </div>
 <% end %> 

But app/views-project/show.html.erb is where the real magic is:


 <p id="notice"><%= notice %></p>

 <p>
  <b>Name:</b>: <%= @project.name %>
 </p>

 <% Project::WORKFLOW_METHODS.each do |workflow|
  at_method = "#{workflow}d_at"
  by_method = "#{workflow}d_by_id"
  who_method = "#{workflow}r"
 %>

 <p>
  <b><%= at_method.humanize %>:</b>: <%= @project.send(at_method) %>
 </p>

 <p>
  <b><%= who_method.humanize %>:</b>: <%= @project.send(who_method) %>
 </p>

 <p>
  <b><%= by_method.humanize %>:</b>: <%= @project.send(by_method) %>
 </p>

 <% end %>

 <%= link_to 'Edit', edit_project_path(@project) %> |
 <%= link_to 'Back', projects_path %>

This should be fairly clear, although, if you’re not familiar with send(), it’s another way to call a method. So object.send("name_of_method") is the same as object.name_of_method.

Final Sprint

We’re almost done, but I’ve noticed two bugs: one is formatting, and the other is a bit more serious.

The first is that, while I view a project, the whole method is showing an ugly Ruby object output. Rather than adding a method to the end, like this


 @project.send(who_method).name

Let’s modify User to have a to_s method. Keep things in the model if you can, and add this to the top of the user.rb, and do the same for project.rb as well. It always makes sense to have a default representation for a model as a string:


 def to_s
  name
 end

Feels a bit mundane writing methods the easy way now, eh? No? Anyhow, on to more serious things.

An Actual Bug

When we update a project because we send all of the workflow stages that have been assigned previously, all our time stamps are mixed up. Fortunately, because all our code is in one place, a single change will fix them all.


 define_method(set_method_name) do |user|
  if user.present?
   user = user.id if user.class == User

   # ADDITION HERE
   # This ensures it's changed from the stored value before setting it
   if read_attribute(attr_by).to_i != user.to_i
    write_attribute(attr_by,user)
    write_attribute(attr_at,Time.now)
   end
  end
 end

Conclusion

What have we learned?

  • Adding functionality to the model can seriously improve the rest of you code
  • Meta programming isn’t impossible
  • Suggesting a project might get logged
  • Writing smart in the first place means less work later
  • No-one enjoys cutting, pasting and editing and it causes bugs
  • Smart Models are sexy in all walks of life

Thank you so much for reading, and let me know if you have any questions.


February 16 2012

22:39

How to Upload Files with Ease Using DragonFly: New on Premium

File uploads are generally a tricky area in web development. In this Tuts+ Premium tutorial, we will learn how to use Dragonfly, a powerful Ruby gem that makes it easy and efficient to add any kind of upload functionality to a Rails project.

Become a Premium member to read this tutorial, as well as hundreds of other advanced tutorials and screencasts from the Tuts+ network.


What We’re Going to Build

Our sample application will display a list of users, and for each one of them, we will be able to upload an avatar and have it stored. Additionally, Dragonfly will allow us to:

  • Dynamically manipulate images without saving additional copies
  • Leverage HTTP caching to optimize our application load

Additionally, in this lesson, we will follow a BDD [Behavior Driven Development] approach, using Cucumber and RSpec.


Tuts+ Premium

The recently re-launched Tuts+ Premium is a service that provides top-tier training in a variety of creative fields. Whether you prefer books, visual training, or in depth tutorials, we have you covered. While we unfortunately can’t afford to provide the service for free, it’s only $19 a month – less than you’d spend on dinner.

I hope you’ll consider checking it out! In addition to learning a huge variety of new skills, it’s also a fantastic way to say thank you to Nettuts+.


October 10 2011

22:20

The Intro to Rails Screencast I Wish I Had

Isn’t it funny how most “introduction to Ruby on Rails” screencasts are overly simplistic, and rely on generators like scaffolding? The teacher typically follows up the tutorial by stating that most Rails developer don’t use scaffolding generators. Well that’s not much help then! I’d like to give you the tutorial I wish I had. Along the way, we’ll also rely heavily on test-driven development to build a simple app.

Choose 720p for the clearest picture.

Covered in this Screencast…

  • Create models and generators
  • Use test-driven development to plan and test an application’s features
  • Work with ActiveRecord
  • Autotest with Guard
  • Use Rspec and Capybara to simulate the user.
  • Create partials
  • Take advantage of Flash notices
  • …and plenty more

Conclusion

If you watched the entire screencast, I hope you enjoyed it! There’s certainly much more to cover, but we crammed a great deal into thirty minutes or so! What other tricks and techniques have you picked up, if you’re just digging into Rails?


September 30 2011

18:41

How to Deploy your First Rails App: New on Premium

In this Premium video tutorial, we’ll teach you how to deploy your first Rails web application with Heroku. Particularly if you’re somewhat new to Rails, you may find that you’re met with a long string of errors when pushing your app and database to their servers. Don’t worry, though; this screencast will take you through the entire process from scratch.

Become a Premium member to watch this video, as well as hundreds of other advanced tutorials and screencasts from the Tuts+ network.


You’ll Learn How To…

  • Work with models and controllers
  • Adjust routes
  • Source control with Git
  • Install and work with Heroku
  • Convert a Sqlite3 database to PostgreSQL
  • Debugging Heroku errors


September 15 2011

21:04

The Best Way to Learn Ruby on Rails

I come from a PHP background, but these days, I’m a full-time Rails developer. The difficulty for most people who make the switch lies in the learning curve that’s involved. Once you’ve become proficient in a language or framework, switching to a new one feels like an unnecessary (and time-consuming) challenge.

However, learning Ruby and Rails is actually pretty easy! It’s an incredibly powerful framework, and has a huge community pushing it along. So that begs the question: what’s the best way to learn Rails? Here’s a lesson plan.

This article details a full lesson plan that will get you up and running in no time! Follow each assignment below in order.


Assignment 1 - Work Through the “Try Ruby” Exercises

You might think learning Ruby is the most important step, and this is probably the part where everyone stops learning and just sticks with their current framework. Don’t do that! Don’t be scared to learn this language (or any language, really). Ruby is a fun, beautiful, and easy-to-learn language. Plus, you don’t really need to dominate the language 100% to be able to learn Rails. You just need the basics to begin.

Tryruby

Work through the Try Ruby exercises.

The most recommended tool for dipping into Ruby’s syntax is the Try Ruby website. It provides you with an interactive, web-based shell to play with the language. If you type help, you’ll be greeted with an interactive, 15 minute tutorial that’ll teach you the very basics of the language. Typing help 2 will take you to the second chapter of the tutorial.

Once you’ve worked through these exercises a couple of times, you’ll have a solid base. Personally, completing those two tutorials is all I initially did. The rest I’ve learned by creating web sites with Rails, Googling, and playing in IRB.

Assignment 2 - Install Ruby And Ruby on Rails

Run gem install rails to install Rails.

If you want to learn Rails, you’ll of course need to install it on your machine. There are multiple ways to do this, depending on your platform. If you’re on a Mac or a Linux-based computer, I recommend you use RVM. It’s a great tool to install Ruby. Refer to this article for installation instructions. If you’re on Windows, refer to RubyInstaller for Windows.

Next, you need to install Rails. To do so you should have RubyGems installed on your computer. If you used RVM to install Ruby, congratulations, you already have it! If you’re on Windows, refer here. To install Rails, run gem install rails, and, tada, you’re all set up!

Bonus Credit

rbenv is another increasingly popular method for installing Ruby. Research that as well.


Assignment 3 - Take The Rails For Zombies Course

Zombies

I’ve always thought that learning by example is the best (and only) way to learn a language and a framework. A free and incredible course that you must take is Rails For Zombies, from the folks at EnvyLabs. It’s interactive, which means that, after watching each video, you’ll work through a handful of exercises.


Assignment 4 - Read A Book

Agile Rails

Purchase Agile Web Development with Rails.

Up until now, every tool I’ve given you has been free and interactive. Now, you need to purchase the book on Rails: Agile Web Development with Rails. It teaches you Rails by means of building a website from scratch. It goes through the very basics, creating controllers, models, scaffolding and even unit and functional testing, plus some AJAX! Be sure to buy the latest edition though!

Bonus Credit

Here’s some more popular Rails books that you might consider.


Assignment 5 - Build A Simple Blog

I know it sounds boring (it does to me), but it’s a great example and is used everywhere for a reason: it’s simple, you can finish that kind of tutorial in under an hour, and you learn the basics very fast. Now, if you read the book from assignment four, you should already have enough knowledge to build something like this. I encourage you to try and build one by yourself, from memory, without checking any tutorials on the subject. You can check some methods, look at how to validate some fields, etc., but the idea is that you need to put your knowledge to the test.

Blog Post

Build a simple blog that has support for comments. You don’t need to implement a fancy authentication system; just something simple to get started.

If You Do Get Stuck…


Assignment 6 - Add Some Complexity To Your Blog

Great! You’ve built yourself a basic blog. It certainly lacks some basic functionality one would expect from a blogging platform, but it’s a start. Let’s put more work into it.

Auth

Add a basic authentication system to your blog. This might sound somewhat complicated, but I won’t force you to do this completely on your own. There are a number of tools/gems available that will make the job a lot simpler, but they’re too advanced for your current skill level. Plus, we need you to keep learning the inner workings of a Rails application before relying on third-party tools.

Watch this screencast by Ryan Bates, where he covers the entire process of creating a basic authentication system from scratch. Apply that to your blog and make sure only you are able to create and edit posts, and delete comments (but make sure every one can create comments!).

Bonus Credit

  • Form validation is equally important, and isn’t difficult to implement. Refer to this screencast to make the task easier.
  • Refer to this article for more information on model associations in Rails. You can use the techniques outlined to add tagging to your blog.

Assignment 7 - Create Something On Your Own

This is where you need to get creative. For me, learning a language or framework by following tutorials works well up to a point. The first thing I created after I finished my sample blogging applications was an invoicing application. I found a simple design template online and started working on that. That allowed me to build something useful and according to my needs, while having actual fun!

If you want to follow in my footsteps, download the Twitter Bootstrap web app template (if you wish), so that you may spend more time programming than designing, and build yourself an invoicing application. Try to include authentication, clients, invoices (which should let the user apply a discount and taxes), and invoice items (which should include a description, quantity and price). This will teach you various important parts of a Rails application, such as nested forms.

Resources to Get you Started

  • Nested Model Form Parts One and Two: You’ll need this the moment you create an invoice, since invoice items will be “nested” inside the invoice form. Watch the videos to learn more.
  • Simple Invoicing App: This is the invoicing app I created to learn Rails. It’s built with Rails 3.0.4 though, so keep that in mind. It might be handy to check the models, associations, and JavaScript files.

Assignment 8 - Stay Up To Date …

Learning to program well is a never-ending process. That’s why you should subscribe to various blogs and Twitter accounts on the subject. Here’s a list of influential Rails people for you to follow on Twitter:

  • @dhh: The creator of Ruby on Rails. Posts insight on new releases and various tips.
  • @rbates: Producer of Railscasts, posts tips and tricks very often.
  • @rails: The official Ruby on Rails Twitter account. Follow them if you want insight on release dates, and development.
  • @rails_apps: They’re posting new Rails example apps pretty often, pretty useful.

And here are some websites you should subscribe to:

  • Railscasts: A must! Awesome screencasts about Ruby on Rails, best practices, tips, new gems, etc.
  • Asciicasts: If you’re not into watching videos, this site mimics Railscasts’ tutorials in text. It’s not as up-to-date as the first one, but it’s excelent.
  • Nettuts+: While we’re not 100% focused on Ruby and Rails, we’re posting more and more applicable content these days!
  • The Rails Way: Cool blog with various articles and tutorials.
  • Riding Rails: The official Ruby on Rails blog. They don’t post many tips or tutorials, but they announce official releases, so it’s good to read it often.
  • Planet Ruby on Rails: A Ruby on Rails blog aggregator. It’s no as filtered as reading one of the blogs I listed above, but it’s a good resource to check every once in a while.

Conclusion

This lesson plan will turn you into a Rails developer in no time. As you’ll find, Rails is an amazing framework, and it continues to get better every single year. I learned Rails using the same tools I recommended above; you should too!

If you have any questions, feel free to ask them in the comments or tweet me. And feel free to share your experience! Tell us how you learned Rails, what tools you used, and how you’re using it today.


Tags: Ruby basix rails

September 12 2011

13:00

Create Beautiful Administration Interfaces with Active Admin

Every web developer knows that creating an administration interface for their projects is an incredibly tedious task. Luckily, there are tools that make this task considerably simpler. In this tutorial, I’ll show you how to use Active Admin, a recently launched administration framework for Ruby on Rails applications.

You can use Active Admin to add an administration interface to your current project, or you can even use it to create a complete web application from scratch – quickly and easily.

Today, we’ll be doing the latter, by creating a fairly simple project management system. It might sound like quite a bit of work, but Active Admin will do the bulk of the work for us!


Step 1 – Set up the Development Environment

I’m going to assume you have some previous Ruby on Rails knowledge, especially involving model validations, since the rest of the application interface is going to be taken care of by Active Admin. Apart from that, you should have a development environment for Ruby on Rails 3.1 already set up, including Ruby 1.9.2.

Refer to this article if you require assistance installing Ruby and Rails.

Create the application we’ll be working on, by running the following command in your Terminal:

rails new active_admin

Next, open your Gemfile and add the following lines:

gem 'activeadmin'
gem 'meta_search', '>= 1.1.0.pre'

The last gem is required for Active Admin to work with Rails 3.1, so don’t forget it. After that’s done, run the bundle install command to install the gems. Now, we need to finish installing Active Admin, by running the following command:

rails generate active_admin:install

This will generate all needed initializers and migrations for Active Admin to work. It will also create an AdminUser model for authentication, so run rake db:migrate to create all the needed database tables. Apart from that, you need to add one line to your config/environments/development.rb file, so sending emails works:

config.action_mailer.default_url_options = { :host => 'localhost:3000' }

Once that’s done, run rails server and point your browser to localhost:3000/admin. You’ll be greeted with a nice login form. Just type “admin@example.com” as the email and “password” as the password, and hit “Login”. You should now see a nice administration interface.


Step 2 – Configuring our User Model

As you can see from the webpage you just generated, there’s not much you can do, yet. We’re going to need a way to edit our users, and we can do that using Active Admin. The framework uses what it calls “Resources”. Resources map models to administration panels. You need to generate them using a command in your terminal, so Active Admin can know their existence, so go ahead and run:

rails generate active_admin:resource AdminUser

The syntax for that command is simple: just write the database model’s name at the end. This will generate a file inside the app/admin folder, called admin_users.rb. Now, if you refresh your browser you’ll see a new link at the top bar, called “Admin Users”. Clicking that will take you to the Admin User administration panel. Now, it’ll probably look a little too cluttered, since by default, Active Admin shows all of the model’s columns, and considering that the framework uses Devise for authentication, you’ll see a bunch of columns that are not really necessary. This takes us to the first part of our customization: the index page.

Admin User

Customizing Active Admin resources is fairly easy (and fun if you ask me). Open app/admin/admin_users.rb on your favorite text editor and make it look like this:

ActiveAdmin.register AdminUser do
  index do
    column :email
    column :current_sign_in_at
    column :last_sign_in_at
    column :sign_in_count
    default_actions
  end
end

Let’s review the code:

  • The first line is created by Active Admin, and, like it says, it registers a new resource. This created the menu link at the top bar and all of the default actions, like the table you just saw.
  • The index method allows us to customize the index view, which is the table that shows all rows.
  • Inside of the block you pass to the index method, you specify which columns you do want to appear on the table, ie. writing column :email will have Active Admin show that column on the view.
  • default_actions is a convenience method that creates one last column with links to the detail, edition and deletion of the row.

One final step for this view is to customize the form. If you click the “New Admin User” link on the top right, you’ll see that the form also contains all of the columns on the model, which is obviously not very useful. Since Active Admin uses Devise, we only need to enter an email address to create a user, and the rest should be taken care of by the authentication gem. To customize the forms that Active Admin displays, there’s a method, called (you guessed it) form:

ActiveAdmin.register AdminUser do
  index do
    # ...
  end

  form do |f|
    f.inputs "Admin Details" do
      f.input :email
    end
    f.buttons
  end
end

If the code looks familiar to you, you’ve probably used the Formtastic gem before. Let’s take a look at the code:

  • You specify the form’s view by calling the form method and passing it a block with an argument (f in this case).
  • f.inputs creates a fieldset. Word of advice: you have to add at least one fieldset. Fields outside of one will simply not appear on the view.
  • To create a field, you simply call f.input and pass a symbol with the name of the model’s column, in this case, “email”.
  • f.buttons creates the “Submit” and “Cancel” buttons.

You can further customize the forms using the DSL (Domain Specific Language) provided by Formtastic, so take a look at tutorials about this gem.

One last step for this form to work: since we’re not providing a password, Devise is not going to let us create the record, so we need to add some code to the AdminUser model:

after_create { |admin| admin.send_reset_password_instructions }

def password_required?
  new_record? ? false : super
end

The after_create callback makes sure Devise sends the user a link to create a new password, and the password_required? method will allow us to create a user without providing a password.

Go try it out. Create a user, and then check your email for a link, which should let you create a new password, and log you into the sytem.


Step 3 – Projects

We are going to create a simple Project Management system. Not anything too complicated though, just something that will let us manage projects and tasks for the project, and assign tasks to certain users. First thing, is to create a project model:

rails generate model Project title:string

Active Admin relies on Rails’ models for validation, and we don’t want projects with no title, so let’s add some validations to the generated model:

# rails
validates :title, :presence => true

Now, we need to generate an Active Admin resource, by running:

rails generate active_admin:resource Project

For now, that’s all we need for projects. After migrating your database, take a look at the interface that you just created. Creating a project with no title fails, which is what we expected. See how much you accomplished with just a few lines of code?


Step 4 – Tasks

Projects aren’t very useful without tasks right? Let’s add that:

rails generate model Task project_id:integer admin_user_id:integer title:string is_done:boolean due_date:date

This creates a task model that we can associate with projects and users. The idea is that a task is assigned to someone and belongs to a project. We need to set those relations and validations in the model:

class Task < ActiveRecord::Base
  belongs_to :project
  belongs_to :admin_user

  validates :title, :project_id, :admin_user_id, :presence => true
  validates :is_done, :inclusion => { :in => [true, false] }
end

Remember to add the relations to the Project and AdminUser models as well:

class AdminUser < ActiveRecord::Base
  has_many :tasks

  # ...
end
class Project < ActiveRecord::Base
  has_many :tasks

  # ...
end

Migrate the database, and register the task model with Active Admin:

rails generate active_admin:resource Task

Now go and take a look at the tasks panel in your browser. You just created a project management system! Good job.


Step 5 – Making It Even Better

The system we just created isn’t too sophisticated. Luckily, Active Admin is not just about creating a nice scaffolding system, it gives you far more power than that. Let’s start with the Projects section. We don’t really need the id, created and updated columns there, and we certainly don’t need to be able to search using those columns. Let’s make that happen:

index do
  column :title do |project|
    link_to project.title, admin_project_path(project)
  end

  default_actions
end

# Filter only by title
filter :title

A few notes here:

  • When you specify columns, you can customize what is printed on every row. Simply pass a block with an argument to it, and return whatever you want in there. In this case, we are printing a link to the project’s detail page, which is easier than clicking the “View” link on the right.
  • The filters on the right are also customizable. Just add a call to filter for every column you want to be able to filter with.

The project’s detail page is a little boring don’t you think? We don’t need the date columns and the id here, and we could show a list of the tasks more directly. Customizing the detail page is accomplished by using the show method in the app/admin/projects.rb file:

show :title => :title do
  panel "Tasks" do
    table_for project.tasks do |t|
      t.column("Status") { |task| status_tag (task.is_done ? "Done" : "Pending"), (task.is_done ? :o k : :error) }
      t.column("Title") { |task| link_to task.title, admin_task_path(task) }
      t.column("Assigned To") { |task| task.admin_user.email }
      t.column("Due Date") { |task| task.due_date? ? l(task.due_date, :format => :long) : '-' }
    end
  end
end

Let’s walk through the code:

  • show :title => :title specifies the title the page will have. The second :title specifies the model’s column that will be used.
  • By calling panel "Tasks" we create a panel with the given title. Within it, we create a custom table for the project’s tasks, using table_for.
  • We then specify each column and the content’s it should have for each row.
    • The “Status” column will contain “Done” or “Pending” whether the task is done or not. status_tag is a method that renders the word passed with a very nice style, and you can define the color by passing a second argument with either : ok, :warning and :error for the colors green, orange and red respectively.
    • The “Title” column will contain a link to the task so we can edit it.
    • The “Assigned To” column just contains the email of the person responsible.
    • The “Due Date” will contain the date the task is due, or just a “-” if there’s no date set.

Step 6 – Some Tweaks for the Tasks

How about an easy way to filter tasks that are due this week? Or tasks that are late? That’s easy! Just use a scope. In the tasks.rb file, add this:

scope :all, :default => true
scope :due_this_week do |tasks|
  tasks.where('due_date > ? and due_date < ?', Time.now, 1.week.from_now)
end
scope :late do |tasks|
  tasks.where('due_date < ?', Time.now)
end
scope :mine do |tasks|
  tasks.where(:admin_user_id => current_admin_user.id)
end

Let’s review that code:

  • scope :all defines the default scope, showing all rows.
  • scope accepts a symbol for the name, and you can pass a block with an argument. Inside the block you can refine a search according to what you need. You can also define the scope inside the model and simply name it the same as in this file.
  • As you can see, you can access the current logged in user’s object using current_admin_user.
Tasks2

Check it out! Just above the table, you’ll see some links, which quickly show you how many tasks there are per scope, and lets you quickly filter the list. You should further customize the table and search filters, but I’ll leave that task to you.

We’re now going to tweak the task’s detail view a bit, since it looks rather cluttered:

show do
  panel "Task Details" do
    attributes_table_for task do
      row("Status") { status_tag (task.is_done ? "Done" : "Pending"), (task.is_done ? :o k : :error) }
      row("Title") { task.title }
      row("Project") { link_to task.project.title, admin_project_path(task.project) }
      row("Assigned To") { link_to task.admin_user.email, admin_admin_user_path(task.admin_user) }
      row("Due Date") { task.due_date? ? l(task.due_date, :format => :long) : '-' }
    end
  end

  active_admin_comments
end

This will show a table for the attributes of the model (hence the method’s name, attributes_table_for). You specify the model, in this case task, and in the block passed, you define the rows you want to show. It’s roughly the same we defined for the project’s detail page, only for the task. You may be asking yourself: What’s that “active_admin_comments” method call for? Well, Active Admin provides a simple commenting system for each model. I enabled it here because commenting on a task could be very useful to discuss functionality, or something similar. If you don’t call that method, comments will be hidden.

Tasks

There’s another thing I’d like to show when viewing a task’s detail, and that’s the rest of the assignee’s tasks for that project. That’s easily done using sidebars!

sidebar "Other Tasks For This User", :o nly => :show do
  table_for current_admin_user.tasks.where(:project_id => task.project) do |t|
    t.column("Status") { |task| status_tag (task.is_done ? "Done" : "Pending"), (task.is_done ? :o k : :error) }
    t.column("Title") { |task| link_to task.title, admin_task_path(task) }
  end
end

This creates a sidebar panel, titled “Other Tasks For This User”, which is shown only on the “show” page. It will show a table for the currentadminuser, and all tasks where the project is the same as the project being shown (you see, task here will refer to the task being shown, since it’s a detail page for one task). The rest is more or less the same as before: some columns with task details.


Step 7 – The Dashboard

You may have noticed, when you first launched your browser and logged into your app, that there was a “Dashboard” section. This is a fully customizable page where you can show nearly anything: tables, statistics, whatever. We’re just going to add the user’s task list as an example. Open up the dashboards.rb file and revise it, like so:

ActiveAdmin::Dashboards.build do
  section "Your tasks for this week" do
    table_for current_admin_user.tasks.where('due_date > ? and due_date < ?', Time.now, 1.week.from_now) do |t|
      t.column("Status") { |task| status_tag (task.is_done ? "Done" : "Pending"), (task.is_done ? :o k : :error) }
      t.column("Title") { |task| link_to task.title, admin_task_path(task) }
      t.column("Assigned To") { |task| task.admin_user.email }
      t.column("Due Date") { |task| task.due_date? ? l(task.due_date, :format => :long) : '-' }
    end
  end

  section "Tasks that are late" do
    table_for current_admin_user.tasks.where('due_date < ?', Time.now) do |t|
      t.column("Status") { |task| status_tag (task.is_done ? "Done" : "Pending"), (task.is_done ? :o k : :error) }
      t.column("Title") { |task| link_to task.title, admin_task_path(task) }
      t.column("Assigned To") { |task| task.admin_user.email }
      t.column("Due Date") { |task| task.due_date? ? l(task.due_date, :format => :long) : '-' }
    end
  end
end

The code should be fairly familiar to you. It essentially creates two sections (using the section method and a title), with one table each, which displays current and late tasks, respectively.

Dashboard

Conclusion

We’ve created an extensive application in very few steps. You may be surprised to know that there are plenty more features that Active Admin has to offer, but it’s not possible to cover them all in just one tutorial, certainly. If you’re interested in learning more about this gem, visit activeadmin.info.

You also might like to check out my project, called active_invoices on GitHub, which is a complete invoicing application made entirely with Active Admin. If you have any questions, feel free to ask them in the comments, or send me a tweet.


May 23 2011

15:47

Advanced Data Models with Rails

Advertise here

Model, View, Controller. If you’ve ever tried Ruby on Rails, those words have probably been drilled into your head a thousand times over. On the other hand, if this is new to you, there’s plenty of resources on Nettuts+ for beginners – but this is not one of them.

If you’ve made it this far, then It’s safe to assume you’re at least an intermediate user of Rails. If so, I congratulate you! The hardest learning curve is behind you. Now, you can start mastering the really cool stuff. In this post, I want to focus on my favorite third of MVC – the one that I think Rails does best: Models.


Object-Orientation

By far the best thing about ActiveRecord (in my opinion) is how rows in a database correspond so directly to classes in your code. But don’t make the mistake of assuming that your Model classes are the database rows! Rather, you should realize that the Model classes are simply a way to interface with the database. The brilliant part is that Rails makes this process so frictionless that you might think that you’re manipulating the information directly. Do not make this mistake.

The key to mastery of Models is using them as “regular” classes, with instance methods, class methods, attributes and the like. You should treat the columns in the database just like parts of your Model, accessing them from outside, but also using them from inside within other constructs like instance and private methods. Learn to integrate the two for a truly object-oriented system.

All that the database does is provide the information. You’re the one who should provide the logic.

Think of Model objects just like any other object; if there’s logic in another part of your code that relates to this object, it’s always better to integrate it within the class. All the database does is provide the information. You’re the one that should provide the logic.

Methods

Let’s say you have a Model that corresponds to a post in a blog. You decide to write all your blog posts with Markdown and store just the Markdown versions in the database. Now, you have to parse this content into HTML whenever you want to display it.

<article>
  <h1><%= @post.title %<</h1>

  <%= format_markdown(@post.content) # Just an example, not a real method %>
</article>

This basic view file would run the post’s content through a method every time it is displayed. Okay. How can we make it better?

# ./app/models/post.rb

class Post < ActiveRecord::Base

  ...

  def formatted_content
    format_markdown(self.content)
  end

end
<article>
  <h1><%= @post.title %<</h1>

  <%= @post.formatted_content # much better! %>
</article>

I’ve consolidated the content formatting into an instance method. While this doesn’t have any noticeable effect yet, imagine if later you decided to add some more logic to the formatting, for instance checking to see if the content is already in HTML form. This way would make a lot easier to adapt the code later.

It also has the added benefit of making your code more organized and easier to read. If I were looking at your project, the very first place I would look for a method like this would be in your Post class. This kind of organization directly mimics the kind already built into Rails: small, lightweight methods attached to classes.

Class Methods

Class methods allow you consolidate methods that are related to specific functionality into a consistent location. It’s really not a crazy idea. In fact, as an intermediate Ruby developer, it’s one that you should be very comfortable with. Many don’t realize that you can also build class methods in a Model, but Models are classes like any other, why shouldn’t we!?

Instead of putting helper methods in a separate helper file, just add them on to the Model.

A perfect example of this is helper methods, or helper code grouped by its purpose. Instead of putting them in a separate helper file/module (which should only be used for controller and view helpers), just add them on to the Model. For instance, if you wanted a method that will validate the authenticity of a given username and password, you could implement a User.authenticate() method. Now, if you later want to alter the function for authentication, it’ll be easy to find among the rest of the User-related code.

That last one is an important point. One of the mantras of Rails is “Convention over Configuration.” If all projects stick to similar file and code structure, it’s easy for another developer to come in and start making changes to a project. One of these conventions is grouping model-related helper methods as class methods.

Helper methods that are only used internally in the Model can also exist as class methods. In this case they would be private or protected methods, but the basic idea is the same. If the method needs information specific to an instance, it’s a private instance method. If not, it’s a class method. It’s as simple as that, really.

Virtual Attributes

A Model is not the record in the database. They are created not when data is written to the database, but when you, the programmer, initialize them.

In order to properly understand Models, you should understand their object lifestyle. As I said before, a Model is not the record in the database. They are created not when data is written to the database, but when you, the programmer, initialize them. Since the Model is only an interface to the database’s raw data, you can create a new object from the class to correspond with existing data.

Likewise, they can be deleted by calling their destroy method. This removes the row from the database, and also deletes the Model object.

But you can delete the Model object (not the database row!) by setting the variable to nil, or just letting it go out of scope.

Once you comprehend this, it’s trivial to realize that a Model can have attributes that don’t correspond to a database column. Think about a User Model. This User has a username and password, but because you are a security-conscious programmer, you only want to store a hashed password in the database, not the plain text password.

To accomplish this, you can implement a “virtual attribute,” or an instance variable that isn’t a column in the database. To keep things simple, the user won’t have to do any sort of password confirmation.

# ./app/models/user.rb

class User < ActiveRecord::Base

  attr_accessor :password

  # database has encrypted_password column

  ...

end

This is a simple, pure Ruby construct that adds getter and setter methods to an object. Now you can encrypt the password before saving it to the database, so the plain-text password is only ever stored in memory, not written to any files.

user = User.new(params[:user])
user.password = params[:user][:password] # redundant, since the above call does this already
user.encrypt_password # sets the encrypted password attribute to the virtual attribute encrypted
user.save!

While this is far from a perfect implementation (I’ll show you how to improve it later on in the post) it demonstrates the power of Virtual Attributes. You can now go on to implement the encrypt_password method in any way you like, probably hashing the password stored in memory along with some kind of salt based on the current date or something like that. In this case, it’s important to call that method before saving the user, so the hashed password is generated


Scopes

Consider this:

Post.where("created_at > ?", 1.week.ago).order("created_at ASC")

These objects contain all the information necessary to get data from the database. The object responds to the methods above, so you can incrementally build up a database query by chaining the methods.

Easy enough. We’re just building up a database query by chaining methods together. Have you ever thought, though: where do do those methods come from? It’s actually pretty simple. Certain methods like .where(), .order() and .select() are all used to generate queries. They do this by all returning objects of the class ActiveRecord::Relation. These objects contain all the information necessary to get data from the database. The object responds to the methods above, so you can incrementally build up a database query by chaining the methods.

These methods are called scopes. As you can imagine, they are an incredibly powerful tool, made doubly so by the fact that you can create scopes of your very own!

Imagine again our Post Model. For displaying posts, you often want to have them appear in the order in which they were created. However, it becomes cumbersome to tack on .order("created_at ASC") to every single query you write. You could implement it in a class method of Post, like this:

# ./app/models/post.rb

class Post < ActiveRecord::Base

  ...

  def self.chronological
    self.order("created_at ASC")
  end

end

At first glance, this would seem like a good solution. We’ve bundled relevant code into our object, like the good object-oriented developers that we are, so what’s the problem. The problem comes is if you try to build up a query like before:

Post.where("created_at > ?", 1.week.ago).chronological

Since it’s only Post that has this method, you’ll see an error like this:

NoMethodError: undefined method `chronological' for #

So what’s a guy to do. Simple.

# ./app/models/post.rb

class Post < ActiveRecord::Base

  scope :chronological, : order => 'created_at ASC'

  ...

end

Great! Now the example from above works perfectly, plus we still have the code in the right place, in our Post Model.

Scopes are very flexible. If you wanted, you could write the example above like this:

scope :chronological, order('created_at ASC')

The second argument to the scope method can be a hash (like the first example), an ActiveRecord::Relation object (like the second example), or even a lambda (anonymous function) like this:

scope :chronological, lambda { order('created_at ASC') }

With this technique, you could even pass an argument into .chronological. Maybe a boolean for ordering ascending or descending?

scope :chronological, lambda { |ascending| ascending ? order('created_at ASC') : order('created_at DESC') }

And call the method like this:

Post.where("created_at > ?", 1.week.ago).chronological(false)

You can do more than just ordering, though.

scope :chronological, : order => 'created_at ASC', :where => 'published = true'
scope :chronological, where(:published => true).order('created_at ASC')
scope :chronological, lambda { |ascending| where(:published => true).order("created_at #{ascending ? 'ASC' : 'DESC'}") }

The last thing I want to show you about scopes is that you can supply what’s called a default_scope. This is a scope that will be applied to every query based off of this Model. If you only wanted to ever display them in chronological order, you could do:

# ./app/models/post.rb

class Post < ActiveRecord::Base

  default_scope order("created_at ASC")

  ...

end

Isn’t this fun?


Callbacks

If you remember my password encryption example from above, you’ll recall that I mentioned that how we call the encrypt_password method could be improved. Here’s the original snippet for reference:

user = User.new(params[:user])
user.password = params[:user][:password]
user.encrypt_password
user.save!

As you can see, if we encrypt the password in this way, we’ll have to call that encryption method every single time we initialize a new User. If we forget to call it, the user won’t have a hashed password. Far from an ideal solution.

Fortunately, in typical Rails fashion, there’s a simple way to fix it.

We can use what’s called a callback, or a piece of code that is called when a certain phase of an object’s lifecycle is reached. For instance:

  • Before saving
  • After saving
  • Before validation
  • After validation
# ./app/models/user.rb

class User < ActiveRecord::Base

  ...

  before_save :encrypt_password

  def encrypt_password
    # do something
  end

end

It’s really as simple as that. Whenever a user object is about to be saved, a method is called. In fact, you don’t even have to use a method!

# ./app/models/user.rb

class User < ActiveRecord::Base

  ...

  before_save do
    # do something
  end

end

Instead of passing a symbol into the before_save call, you can just give it a code block. This is ideal for situations where the code you’re calling is only a line or two long, or if it’s only ever used before saving the record.

The full list of callback methods is available in the API documentation. They include ones like before_validation, after_validation, after_save, and others. There’s a lot of them, but they all work pretty much exactly like you’d expect after seeing before_save in action.


The information above speaks for itself, so I’ll keep this brief. Hopefully you’ve learned something, maybe even a few things. If you already knew this stuff, what tips would you give to others about Rails Models? Post them in comments and keep the learning going!

Tags: Ruby rails

April 25 2011

14:23

Essential Ruby & Rails 3 Reading

Advertise here

Nearly two years ago, we published a round-up of the greatest Ruby and Rails learning resources available. Since then, big things have happended in the glorious world of Ruby. Rails 3 brought many fundamental improvements to the framework. So, naturally, our “essential resources” list needed to be updated!

Read on for a round-up of the greatest articles, books, and screencasts to come out of the Ruby community!


1 - Beginning Ruby

  • Ruby Programming Language

    Ruby is… A dynamic, open source programming language with a focus on simplicity and productivity. It has an elegant syntax that is natural to read and easy to write.

  • TryRuby

    Try out Ruby in an interactive console directly in your browser! Enter help to start a 15-minute interactive tutorial.

  • Ruby Koans

    The Koans walk you along the path to enlightenment in order to learn Ruby. The goal is to learn the Ruby language, syntax, structure, and some common functions and libraries. We also teach you culture. Testing is not just something we pay lip service to, but something we live. It is essential in your quest to learn and do great things in the language.

    The koans are broken out into areas by file, hashes are covered in about_hashes.rb, modules are introduced in about_modules.rb, etc. They are presented in order in the path_to_enlightenment.rb file.

  • Ruby for Newbies

    This ongoing video session will introduce you to Ruby, as well as the great frameworks and tools that go along with Ruby development. If you’re hoping to make the switch, now is the perfect time to get started!

  • Hackety Hack

    Hackety Hack will teach you the absolute basics of programming from the ground up. No previous programming experience is needed!

    With Hackety Hack, you’ll learn the Ruby programming language Ruby is used for all kinds of programs, including desktop applications and websites.

  • PeepCode – Ruby 1.9 series

    PeepCode has teamed up with Gregg Pollack and David A. Black of Envycasts to provide you with their current library of screencasts!

    Jump into the future of Ruby with this two part series on the distinguishing new features of Ruby 1.9. Topics covered in this 41-minute screencast include: hashes, arrays, symbols, enumerators, enuerable and RubyGems.


2 - Beginning Rails

  • Ruby on Rails Tutorial: Learn Rails by Example

    The Ruby on Rails 3 Tutorial book and screencast series teach you how to develop and deploy real, industrial-strength web applications with Ruby on Rails, the open-source web framework that powers many top websites, including Hulu, GitHub, and the Yellow Pages. The companion screencast series includes 12 individual lessons totaling more than 15 hours. The best deal is the PDF/screencast bundle, which includes more than 500 pages of total content and more than 15 hours of video.

  • Dive into Rails 3

    Gregg Pollack from EnvyLabs presents five short video tutorials to help you learn about all the new components found in Rails 3 like Bundler, Active Model and Active Relation, as well as the new syntax of the router and Action Mailer. It’s everything you need to get started.

  • CodeSchool – Rails for Zombies

    In this free course Gregg Pollack from Envy Labs will walk you the basics of learning Ruby on Rails in five levels, each of which is followed by a series of code challenges where you get to start coding Rails immediately in the browser.

  • Rails Guides – Getting Started with Rails

    Install Rails, create an application, using databases, the principles of MVC and RESTful design – this is an essential resource for getting started with Rails and learning the best practices.

  • PeepCode – Meet Rails 3 series

    This 75 minute screencast introduces Rails 3, the result of two years of low-level improvements, API refinements, and performance optimizations. If you are just learning Rails or if you have limited knowledge and want to learn more, this is the video for you!

    This highly-polished screencast will give you a gentle introduction to the ideas that have transformed modern web development.

  • SitePoint – Getting Started with Rails 3

    Today, I’m going to show you a quick example of building a simple Rails 3 application to give you an idea of what working with Rails is like. For this tutorial in two parts, we’ll be building a database-backed application: a URL shortener named “Shorty.”

  • Create a Simple Music Streaming App with Ruby on Rails

    Amazon S3 is a great way to store files, but learning how to integrate it into your website can be a challenge. In this article, you will learn how to integrate Amazon S3 and Ruby on Rails through the construction of a simple music streaming application.

  • Ruby and Rails for Attractive .NET Developers

    The thoughts of a .NET developer as they learn the world of Ruby and Rails.

  • ThinkVitamin Membership

    High quality video training to keep you on the cutting edge.

  • Build a Dropbox-like File Sharing Site with Ruby on Rails

    In this massive and advanced Premium Nettuts+ tutorial, we’ll learn how to build a file-sharing web application, like Dropbox, using Ruby on Rails.

  • Rails for PHP Developers: Reference Guide

    If you’re proficient with PHP, you already have the essential skills needed to build web applications. This site will present an ongoing discussion of techniques for learning Rails and Ruby from a PHP perspective.


3 - Advanced Resources

  • CodeSchool – Rails Best Practicies

    The Ruby on Rails framework uses a great deal of convention over configuration, which means that if you follow the golden path and develop in a certain way you can do away with lots of the configuration involved. Unfortunately as your system starts to become complex, so can your code, and without proper design patterns and techniques your codebase can quickly devolve. In this course we’ve put together some of the most useful patterns, so you can keep your code clean and maintainable.

  • Railscasts

    Every week Ryan Bates will host a new Railscasts episode featuring tips and tricks with Ruby on Rails. These screencasts are short and focus on one technique so you can quickly move on to applying it to your own project. The topics target the intermediate Rails developer, but beginners and experts will get something out of it as well.

    Prefer text tutorials? Check out the next item.

  • ASCIIcasts

    Railscasts (above) is the #1 resource for quickly learning new Rails tricks. If you prefer text tutorials over video, ASCIIcasts is for you!

    ASCIIcasts are detailed, illustrated text versions of each Railscast, each with a link to the original video.

  • Live Coding Rails 3 Upgrade

    For several months people have wondered, “Where can I download a video that features a developer stumbling through an upgrade of a Rails 2 app to Rails 3?” I’m proud to say that an answer is now available!

    In only 25 minutes, I convert my news screenshot site from Rails 2.x to Rails 3 (prerelease, from source). It features the newest bundler (0.9.0.pre), Jeremy McAnally’s rails-upgrade script, new routes, Arel-based ActiveRecord queries, and more.

    Stay tuned for the explosions at the end!

  • RubySource – 10 RoR Best Practicies

    If you’re new to Ruby on Rails, one of the most daunting aspects is knowing what’s the preferred way of accomplishing a given task. While a lot of techniques and libraries have come and gone as the community’s preferred way of doing something, there are some best practices that remain, and can lead to writing the cleanest, most secure and maintainable Rails code possible.

    Listed here today are ten of the most popular and useful best practices you can use as a Ruby developer.

  • Ruby Quicktips

    Random Ruby and Rails tips. This blog is dedicated to deliver short, interesting and practical tidbits of the Ruby language and Ruby on Rails framework.

  • RubySource – Introducing Test-Driven Development with Rails 3

    An introduction to following a TDD approach when developing your Ruby on Rails applications.

  • 5 Awesome New Rails 3 Features

    Finally found the time to upgrade from Rails 2, to 3? Keep reading to learn five of the most awesome new features in Ruby Rails 3.

  • Rails Forum – Tutorials

    A collection of community-produced short tutorials covering a huge range of Rails techniques, from beginners advice and installation to debugging and tests.

  • Singing with Sinatra

    In this Session, we’ll be taking a look at Sinatra; a small, yet incredibly powerful DSL for quickly creating Ruby web applications. You’ll learn everything from installing the framework, all the way up to building an app.


4 - Ruby Books

  • Programming Ruby 1.9

    Affectionately known simply as the ‘PickAxe’ in the Ruby community (due to the PickAxe on the cover), this is almost Ruby’s de-facto official book. A must-have for any serious Rubyist!

    The First Edition of the PickAxe is available for free at Ruby Central.

  • The Ruby Programming Language

    Bestselling author David Flanagan teams up with Ruby creator Yukihiro “Matz” Matsumoto and writer/cartoonist/programmer why the lucky stiff to bring you the authoritative guide to Ruby. Covering versions 1.9 and 1.8, this book helps you learn Ruby’s lexical structure, primary expressions, conditionals, syntax, classes, the data it manipulates, and more. For experienced programmers who want to look at this language in depth, this guide is invaluable.

  • Why’s (Poignant) Guide to Ruby

    Written by Ruby’s very own crazy-genius, why the lucky stiff (or _why), this is a free and very unusual guide to the language. Take a read through the first few pages, and you’ll see why this book is a massive success.

  • The Ruby Way

    The Ruby Way takes a “how-to” approach to Ruby programming with the bulk of the material consisting of more than 400 examples arranged by topic. Each example answers the question “How do I do this in Ruby?” Working along with the author, you are presented with the task description and a discussion of the technical constraints. This is followed by a step-by-step presentation of one good solution. Along the way, the author provides detailed commentary and explanations to aid your understanding.

    This book is not recommended for beginners to Ruby, however.

  • The RSpec Book

    Behaviour-Driven Development (BDD) gives you the best of Test Driven Development, Domain Driven Design, and Acceptance Test Driven Planning techniques, so you can create better software with self-documenting, executable tests that bring users and developers together with a common language.

    Get the most out of BDD in Ruby with The RSpec Book, written by the lead developer of RSpec, David Chelimsky.

  • Everyday Scripting with Ruby

    Everyday Scripting with Ruby is divided into four parts. In the first, you’ll learn the basics of the Ruby scripting language. In the second, you’ll see how to create scripts in a steady, controlled way using test-driven design. The third part is about finding, understanding, and using the work of others – and about preparing your scripts for others to use. The fourth part, more advanced, is about saving even more time by using application frameworks.

  • Eloquent Ruby

    It’s easy to write correct Ruby code, but to gain the fluency needed to write great Ruby code, you must go beyond syntax and absorb the “Ruby way” of thinking and problem solving. In Eloquent Ruby, Russ Olsen helps you write Ruby like true Rubyists do–so you can leverage its immense, surprising power.

    Olsen draws on years of experience internalizing the Ruby culture and teaching Ruby to other programmers. He guides you to the “Ah Ha!” moments when it suddenly becomes clear why Ruby works the way it does, and how you can take advantage of this language’s elegance and expressiveness.

  • The Well-Groomed Rubyist

    The Well-Grounded Rubyist takes you from interested novice to proficient practitioner. It’s a beautifully written tutorial that begins with the basic steps to get your first Ruby program up and running and goes on to explore sophisticated topics like callable objects, reflection, and threading The book concentrates on the language, preparing you for any way you may choose to use Ruby. Whether the topic is simple or tough, the book’s easy-to-follow examples and explanations give you immediate confidence as you build your Ruby programming skills.


5 - Rails Books

  • Agile Web Development with Rails

    This book is essentially the de-facto official Rails book.

    Rails just keeps on changing. Rails 3 and Ruby 1.9 bring hundreds of improvements, including new APIs and substantial performance enhancements. The fourth edition of this award-winning classic has been reorganized and refocused so it’s more useful than ever before for developers new to Ruby and Rails.

  • The Rails 3 Way

    Ruby on Rails strips complexity from the development process, enabling professional developers to focus on what matters most: delivering business value via clean and maintainable code. The Rails™ 3 Way is the only comprehensive, authoritative guide to delivering production-quality code with Rails 3. Pioneering Rails expert Obie Fernandez and a team of leading experts illuminate the entire Rails 3 API, along with the idioms, design approaches, and libraries that make developing applications with Rails so powerful. Drawing on their unsurpassed experience and track record, they address the real challenges development teams face, showing how to use Rails 3 to maximize your productivity.

  • Beginning Rails 3

    Rails 3 is a massive shake-up to the Rails community because it includes the surprise merger of the powerful Merb framework. This means a lot of people will be interested in knowing what’s new in Rails if they’ve used it before, and getting started with it from scratch if they haven’t.


6 - Misc Resources

  • The Changelog

    The Changelog is a weekly podcast and blog that covers what’s fresh and new in Open Source.

  • Ruby5 Podcast

    A regular podcast covering the latest news in the Ruby and Rails community.

  • The Ruby Show

    “The Ruby Show is the best Ruby-related podcast of all time, featuring news and discussion about the latest topics in the Ruby and Rails communities.”

  • Rails Searchable API Doc

    A JavaScript-enhanced, fast and searchable implementation of the Rails API Docs.

Nearly two years ago, we published a round-up of the greatest Ruby and Rails learning resources available. Since then, big things have happended in the glorious world of Ruby. Rails 3 brought many fundamental improvements to the framework. So, naturally, our “essential resources” list needed to be updated!

Read on for a round-up of the greatest articles, books, and screencasts to come out of the Ruby community!


1 - Beginning Ruby

  • Ruby Programming Language

    Ruby is… A dynamic, open source programming language with a focus on simplicity and productivity. It has an elegant syntax that is natural to read and easy to write.

  • TryRuby

    Try out Ruby in an interactive console directly in your browser! Enter help to start a 15-minute interactive tutorial.

  • Ruby Koans

    The Koans walk you along the path to enlightenment in order to learn Ruby. The goal is to learn the Ruby language, syntax, structure, and some common functions and libraries. We also teach you culture. Testing is not just something we pay lip service to, but something we live. It is essential in your quest to learn and do great things in the language.

    The koans are broken out into areas by file, hashes are covered in about_hashes.rb, modules are introduced in about_modules.rb, etc. They are presented in order in the path_to_enlightenment.rb file.

  • Ruby for Newbies

    This ongoing video session will introduce you to Ruby, as well as the great frameworks and tools that go along with Ruby development. If you’re hoping to make the switch, now is the perfect time to get started!

  • Hackety Hack

    Hackety Hack will teach you the absolute basics of programming from the ground up. No previous programming experience is needed!

    With Hackety Hack, you’ll learn the Ruby programming language Ruby is used for all kinds of programs, including desktop applications and websites.

  • PeepCode – Ruby 1.9 series

    PeepCode has teamed up with Gregg Pollack and David A. Black of Envycasts to provide you with their current library of screencasts!

    Jump into the future of Ruby with this two part series on the distinguishing new features of Ruby 1.9. Topics covered in this 41-minute screencast include: hashes, arrays, symbols, enumerators, enuerable and RubyGems.


2 - Beginning Rails

  • Ruby on Rails Tutorial: Learn Rails by Example

    The Ruby on Rails 3 Tutorial book and screencast series teach you how to develop and deploy real, industrial-strength web applications with Ruby on Rails, the open-source web framework that powers many top websites, including Hulu, GitHub, and the Yellow Pages. The companion screencast series includes 12 individual lessons totaling more than 15 hours. The best deal is the PDF/screencast bundle, which includes more than 500 pages of total content and more than 15 hours of video.

  • Dive into Rails 3

    Gregg Pollack from EnvyLabs presents five short video tutorials to help you learn about all the new components found in Rails 3 like Bundler, Active Model and Active Relation, as well as the new syntax of the router and Action Mailer. It’s everything you need to get started.

  • CodeSchool – Rails for Zombies

    In this free course Gregg Pollack from Envy Labs will walk you the basics of learning Ruby on Rails in five levels, each of which is followed by a series of code challenges where you get to start coding Rails immediately in the browser.

  • Rails Guides – Getting Started with Rails

    Install Rails, create an application, using databases, the principles of MVC and RESTful design – this is an essential resource for getting started with Rails and learning the best practices.

  • PeepCode – Meet Rails 3 series

    This 75 minute screencast introduces Rails 3, the result of two years of low-level improvements, API refinements, and performance optimizations. If you are just learning Rails or if you have limited knowledge and want to learn more, this is the video for you!

    This highly-polished screencast will give you a gentle introduction to the ideas that have transformed modern web development.

  • SitePoint – Getting Started with Rails 3

    Today, I’m going to show you a quick example of building a simple Rails 3 application to give you an idea of what working with Rails is like. For this tutorial in two parts, we’ll be building a database-backed application: a URL shortener named “Shorty.”

  • Create a Simple Music Streaming App with Ruby on Rails

    Amazon S3 is a great way to store files, but learning how to integrate it into your website can be a challenge. In this article, you will learn how to integrate Amazon S3 and Ruby on Rails through the construction of a simple music streaming application.

  • Ruby and Rails for Attractive .NET Developers

    The thoughts of a .NET developer as they learn the world of Ruby and Rails.

  • ThinkVitamin Membership

    High quality video training to keep you on the cutting edge.

  • Build a Dropbox-like File Sharing Site with Ruby on Rails

    In this massive and advanced Premium Nettuts+ tutorial, we’ll learn how to build a file-sharing web application, like Dropbox, using Ruby on Rails.

  • Rails for PHP Developers: Reference Guide

    If you’re proficient with PHP, you already have the essential skills needed to build web applications. This site will present an ongoing discussion of techniques for learning Rails and Ruby from a PHP perspective.


3 - Advanced Resources

  • CodeSchool – Rails Best Practicies

    The Ruby on Rails framework uses a great deal of convention over configuration, which means that if you follow the golden path and develop in a certain way you can do away with lots of the configuration involved. Unfortunately as your system starts to become complex, so can your code, and without proper design patterns and techniques your codebase can quickly devolve. In this course we’ve put together some of the most useful patterns, so you can keep your code clean and maintainable.

  • Railscasts

    Every week Ryan Bates will host a new Railscasts episode featuring tips and tricks with Ruby on Rails. These screencasts are short and focus on one technique so you can quickly move on to applying it to your own project. The topics target the intermediate Rails developer, but beginners and experts will get something out of it as well.

    Prefer text tutorials? Check out the next item.

  • ASCIIcasts

    Railscasts (above) is the #1 resource for quickly learning new Rails tricks. If you prefer text tutorials over video, ASCIIcasts is for you!

    ASCIIcasts are detailed, illustrated text versions of each Railscast, each with a link to the original video.

  • Live Coding Rails 3 Upgrade

    For several months people have wondered, “Where can I download a video that features a developer stumbling through an upgrade of a Rails 2 app to Rails 3?” I’m proud to say that an answer is now available!

    In only 25 minutes, I convert my news screenshot site from Rails 2.x to Rails 3 (prerelease, from source). It features the newest bundler (0.9.0.pre), Jeremy McAnally’s rails-upgrade script, new routes, Arel-based ActiveRecord queries, and more.

    Stay tuned for the explosions at the end!

  • RubySource – 10 RoR Best Practicies

    If you’re new to Ruby on Rails, one of the most daunting aspects is knowing what’s the preferred way of accomplishing a given task. While a lot of techniques and libraries have come and gone as the community’s preferred way of doing something, there are some best practices that remain, and can lead to writing the cleanest, most secure and maintainable Rails code possible.

    Listed here today are ten of the most popular and useful best practices you can use as a Ruby developer.

  • Ruby Quicktips

    Random Ruby and Rails tips. This blog is dedicated to deliver short, interesting and practical tidbits of the Ruby language and Ruby on Rails framework.

  • RubySource – Introducing Test-Driven Development with Rails 3

    An introduction to following a TDD approach when developing your Ruby on Rails applications.

  • 5 Awesome New Rails 3 Features

    Finally found the time to upgrade from Rails 2, to 3? Keep reading to learn five of the most awesome new features in Ruby Rails 3.

  • Rails Forum – Tutorials

    A collection of community-produced short tutorials covering a huge range of Rails techniques, from beginners advice and installation to debugging and tests.

  • Singing with Sinatra

    In this Session, we’ll be taking a look at Sinatra; a small, yet incredibly powerful DSL for quickly creating Ruby web applications. You’ll learn everything from installing the framework, all the way up to building an app.


4 - Ruby Books

  • Programming Ruby 1.9

    Affectionately known simply as the ‘PickAxe’ in the Ruby community (due to the PickAxe on the cover), this is almost Ruby’s de-facto official book. A must-have for any serious Rubyist!

    The First Edition of the PickAxe is available for free at Ruby Central.

  • The Ruby Programming Language

    Bestselling author David Flanagan teams up with Ruby creator Yukihiro “Matz” Matsumoto and writer/cartoonist/programmer why the lucky stiff to bring you the authoritative guide to Ruby. Covering versions 1.9 and 1.8, this book helps you learn Ruby’s lexical structure, primary expressions, conditionals, syntax, classes, the data it manipulates, and more. For experienced programmers who want to look at this language in depth, this guide is invaluable.

  • Why’s (Poignant) Guide to Ruby

    Written by Ruby’s very own crazy-genius, why the lucky stiff (or _why), this is a free and very unusual guide to the language. Take a read through the first few pages, and you’ll see why this book is a massive success.

  • The Ruby Way

    The Ruby Way takes a “how-to” approach to Ruby programming with the bulk of the material consisting of more than 400 examples arranged by topic. Each example answers the question “How do I do this in Ruby?” Working along with the author, you are presented with the task description and a discussion of the technical constraints. This is followed by a step-by-step presentation of one good solution. Along the way, the author provides detailed commentary and explanations to aid your understanding.

    This book is not recommended for beginners to Ruby, however.

  • The RSpec Book

    Behaviour-Driven Development (BDD) gives you the best of Test Driven Development, Domain Driven Design, and Acceptance Test Driven Planning techniques, so you can create better software with self-documenting, executable tests that bring users and developers together with a common language.

    Get the most out of BDD in Ruby with The RSpec Book, written by the lead developer of RSpec, David Chelimsky.

  • Everyday Scripting with Ruby

    Everyday Scripting with Ruby is divided into four parts. In the first, you’ll learn the basics of the Ruby scripting language. In the second, you’ll see how to create scripts in a steady, controlled way using test-driven design. The third part is about finding, understanding, and using the work of others – and about preparing your scripts for others to use. The fourth part, more advanced, is about saving even more time by using application frameworks.

  • Eloquent Ruby

    It’s easy to write correct Ruby code, but to gain the fluency needed to write great Ruby code, you must go beyond syntax and absorb the “Ruby way” of thinking and problem solving. In Eloquent Ruby, Russ Olsen helps you write Ruby like true Rubyists do–so you can leverage its immense, surprising power.

    Olsen draws on years of experience internalizing the Ruby culture and teaching Ruby to other programmers. He guides you to the “Ah Ha!” moments when it suddenly becomes clear why Ruby works the way it does, and how you can take advantage of this language’s elegance and expressiveness.

  • The Well-Groomed Rubyist

    The Well-Grounded Rubyist takes you from interested novice to proficient practitioner. It’s a beautifully written tutorial that begins with the basic steps to get your first Ruby program up and running and goes on to explore sophisticated topics like callable objects, reflection, and threading The book concentrates on the language, preparing you for any way you may choose to use Ruby. Whether the topic is simple or tough, the book’s easy-to-follow examples and explanations give you immediate confidence as you build your Ruby programming skills.


5 - Rails Books

  • Agile Web Development with Rails

    This book is essentially the de-facto official Rails book.

    Rails just keeps on changing. Rails 3 and Ruby 1.9 bring hundreds of improvements, including new APIs and substantial performance enhancements. The fourth edition of this award-winning classic has been reorganized and refocused so it’s more useful than ever before for developers new to Ruby and Rails.

  • The Rails 3 Way

    Ruby on Rails strips complexity from the development process, enabling professional developers to focus on what matters most: delivering business value via clean and maintainable code. The Rails™ 3 Way is the only comprehensive, authoritative guide to delivering production-quality code with Rails 3. Pioneering Rails expert Obie Fernandez and a team of leading experts illuminate the entire Rails 3 API, along with the idioms, design approaches, and libraries that make developing applications with Rails so powerful. Drawing on their unsurpassed experience and track record, they address the real challenges development teams face, showing how to use Rails 3 to maximize your productivity.

  • Beginning Rails 3

    Rails 3 is a massive shake-up to the Rails community because it includes the surprise merger of the powerful Merb framework. This means a lot of people will be interested in knowing what’s new in Rails if they’ve used it before, and getting started with it from scratch if they haven’t.


6 - Misc Resources

  • The Changelog

    The Changelog is a weekly podcast and blog that covers what’s fresh and new in Open Source.

  • Ruby5 Podcast

    A regular podcast covering the latest news in the Ruby and Rails community.

  • The Ruby Show

    “The Ruby Show is the best Ruby-related podcast of all time, featuring news and discussion about the latest topics in the Ruby and Rails communities.”

  • Rails Searchable API Doc

    A JavaScript-enhanced, fast and searchable implementation of the Rails API Docs.

March 24 2011

20:50

Mastering Sass: Lesson 2


In lesson one of our quick tip series, we learned how to install Sass, and how to use variables, nesting, and compression in our stylesheets. Today, we’ll review mixins and selector inheritance, which can provide us with a great deal of convenience and flexibility!

March 22 2011

01:03

Mastering Sass: Lesson 1


After numerous requests, we’re launching a 3-part quick tip video mini-series on mastering Sass. To begin, in this introductory eight-minute screencast, I’ll teach you how to install Sass, and then how to get started with the beginning functionality and options.


In the next lesson, we’ll take things a step further, and dig into mixins, Math operations, and add-ons! Stay tuned!

March 09 2011

05:56

Ruby for Newbies: Working with Directories and Files


Ruby is a one of the most popular languages used on the web. We’ve recently started a new Session here on Nettuts+ that will introduce you to Ruby, as well as the great frameworks and tools that go along with Ruby development. Today, we’ll look at the Dir and File classes, and how we can use them to work with directories and files.

 


View Screencast


Directories

pwd

If you’ve done much work with the terminal (AKA command line, AKA shell), you’ll know that it has the notion of a current directory, called the working directory. This is the folder you are currently in. Whenever you type a command that uses a file, the working directory will be the first place your shell looks to find the file.

Ruby has a similar notion when executing code. It understands the OS’s folder structure, and has some helpful tools for working with it.

So, how do you find out what folder you’re ruby script thinks it is in?

Dir.pwd # "/Users/andrew/Documents" 

The pwd (print working directory) method on the Dir class gives us that information. If you’re in irb, your working directory will be—by default—the folder you started irb in. If you’re in a script, will be the location you’re calling the script from.

chdir

If you want to change the working directory, you can use the chdir method; pass it the path to the directory you want to move to:

Dir.chdir "Documents"

Dir.chdir "/users/andrew/Documents"

As you can see, the string parameter can be either an absolute or a relative path.

glob

If you’re looking for certain files within the working directory (Dir.pwd), you can get them by using the Dir.glob method. Pass that method a “glob”; that’s a search pattern that’s somewhere between a static string and a full regular expression. You can use an asterisk * as a wildcard, just as you might in the shell; you can use a double asterisk ** to match directories recursively. You can also use sets in square brackets as you would with regular expressions. If you need more, check out the full docs. Dir.glob with return an array … or, you can pass it a block and get each match one by on.

# Remember, this runs on the current directory
all_text_files = Dir.glob "*.txt"

Dir.glob("**/*.[a-z]") do |filename|
    # will match any file in any child directory with a single lower-case letter extension
end

new & open

Besides housing useful functions, you can also make an instance of the Dir class. You pass it the name of the directory you want to use; as with all functions that take a path, it can be absolute or relative.

reciepts = Dir.new "reciepts"
me = Dir.open "/users/andrew"

Both new and open return a Dir object; however, there’s another way to use open:

Dir.open "/users/andrew" do |dir|
    # use it here
end

This is a common convention with many classes in Ruby; instead of storing the Dir object in a variable, you can pass it to a block and use it from in there. It’s a pretty different style of coding that I haven’t seen in any other language, but it’s rather nice only you get used to it.

There’s a good chance that when you create a Dir object, you’ll want to work with the contents of it. There are a few ways to do that.

each

Assuming some_dir is Dir object,

some_dir.each do |file|
    # do something
end

You can use the each method on Dir objects to iterate over each file or directory that is inside it. Note that you’re not getting a File or Dir object; just a string with the name of it; if you want to do more, you’ll have to instantiate the appropriate object yourself.

entries

If you just want to see what’s inside a directory, you can use the entries property, to get an array of the contents:

some_dir.entries # [ ".", "..", "file_one.txt", "another_directory"]

As you’ll note above, the entires for a directory include ”.” and “..”, pointer it itself and its parent directory.


Files

Ruby also offers a helpful API for working with files.

absolute_path

When you’re working with files, you may find yourself wanting to get the absolute path of one. The File class offers exactly what you need:

File.absotule_path "plans.txt" # => "/users/andrew/Documents/plans.txt"

basename

But what about the other way around? You’ve got the absolute path, and you want just the filename? Instead, use basename

File.basename("/users/andrew/Documents/plans.txt") # => "plans.txt"

File.basename("/users/andrew/Documents/plans.txt", ".txt") # => "plans"

If you pass a second string parameter, the method will look for that string at the end of the file name, and remove it if it is there; this doesn’t have to be the file extension, but that’s the obvious main use for this.

delete

The obvious use of this is to delete the file you pass into the method:

File.delete "code.rb"

directory?

This is a useful one; say you’re each-ing over the entries of a Dir object, but you only want to deal with files. The File.directory? method will return true if the string parameter you pass to it is a directory, and false if it’s a file.

Dir.open(Dir.pwd).each do |filename|
    next if File.directory? filename

    # otherwise, process file
end

This snippet opens the current directory and passes a block to the each method. The each method passes the entries of directory one by one to the block. That first line inside the block may confuse you a bit if you’re not used to Ruby, but look at it carefully. The only part you aren’t familiar with is the next keyword, which skips the rest of the block and goes to the next iteration of it. So, we’re saying, “skip to the next entry if the entry we currently have is a directory. If it’s not a directory, we can do whatever we want to.

new & open

Making instances of the File class works just the same as with Dir; File.new returns a File object, while File.open can return it, or pass it to a block. You should also pass a second parameter, which decides how the file will be opened. Most of the time, you’ll probably use these:

  • ”r” : read-only
  • ”w” : write-only (overwrites anything in the file, if the file exists)
  • “w+” : read and write (overwrites anything in the file, if the file exists)
  • ”a” : write-only (starts at the end of the file, if the file exists)

So, what methods does an instance of File give you? Well, these methods actually come from the IO class, from which File inherits. Most of the time, you’ll be opening a file to read or write content from it, so let’s look at that functionality.

Reading

Before we get started, remember this: the way a file works, once a line has been read, it doens’t show up again; you’re working your way through the file. At any point, you can use the f.rewind method to go back to the beginning of the file.

If you want to just read the whole thing, you can do so with read.

f = File.open("sample.txt", "r") # assume this file for the next couple of snippets

f.read # => "something\nline 2\na third\nfour!\n5555\nsixy\nsevenly\neight" 

However, you’ll probably want to read one line at a time; to do that, use the method readline:

f.rewind # back at the beginning

f.readline # "something\n"

f.readline # "line 2\n"

f.readline # "a third\n"

You could also use the method gets instead of readline.

There’s also a readlines method, which returns an array in which the lines as entries:

f.rewind

f.readlines # => ["something\n", "line 2\n", "a third\n", "four!\n", "5555\n", "sixy\n", "sevenly\n", "eight"] 

Finally, you can use each, and pass a block to the method to work with each line, one by one

f.rewind

f.each do |line|
    puts line
end

Writing

For writing, you’ve got two options: write and puts. The main difference is that puts adds a line break to the end of your string, while write does not.

f = File.open("file.txt", "w+")

f.puts "first line"
f.write "second "
f.write "line"

f.rewind

f.readlines # => ["first line\n", "second line"]

Question for You

Well, that’s it for Ruby For Newbies, Lesson 7. There’s more to discover in the Dir and File classes; check out the docs for Dir, File, and IO for more (the IO class is where File inherits its instance methods from).

However, I’m curious about where you want this series to go from here: do you want to continue with the Ruby language, or do you want to move towards using Ruby on the web? Both directions will be valuable to you as a web developer, so voice your opinion in the comments!

February 08 2011

05:27

Ruby for Newbies: Operators and their Methods


Ruby is a one of the most popular languages used on the web. We’ve started a new screencast series here on Nettuts+ that will introduce you to Ruby, as well as the great frameworks and tools that go along with Ruby development. In this lesson, we’ll be taking a deeper look at operators in Ruby, and why their different from anything you’ve ever seen before.

Press the HD button for a clearer picture.

Subscribe to our YouTube page to watch all of the video tutorials!


Operators

You’ve familiar with operators.

1 + 2 # 3

person[:name] = "Joe"

Operators are things like the plus sign (one of the arithmetic operators), or the equal sign (the assignment operator). These things don’t look to much different from the ones you use in JavaScript, PHP, or any other language. But—like most of Ruby—there’s a lot more than meets the eye going on here.

Here’s the secret: operators in Ruby are really method calls. Try this:

1.+(2) # 3

Here, we’re calling the + operator on the object 1, passing in the object 2 as a parameter. We get back the object 3. We can do this with strings too:

name = "Joe"

name.+(" Smith") # "Joe Smith", but `name` is still "Joe"

name += " Smith" # name is now "Joe Smith"

As you can see, we can do string concatenation with the + method. As a bonus here, ruby defines the += operator based on the + operator (note: you can’t use += as a method).

As you might realize, this gives us incredible power. We can customize the meaning of adding, subtracting, and assigning objects in our custom classes. We saw how this works with properties on objects in our lesson on classes (we defined a property and property= method in the class, and got the expected syntax sugar for using them). What we’re looking at here is taking that a step further.


Building our own Operator Methods

Let’s try to create one of these methods ourselves. For this example, let’s create a refrigerator object, that we can add things to via the + operator and take things out of via the - operator.

Here’s the start of our class:

class Fridge
    def initialize (beverages=[], foods=[])
        @beverages = beverages
        @foods     = foods
    end

    def + (item)

    end

    def - (item)

    end
end

Our initialize function is pretty simple: we take two parameters (that fall back to empty arrays if nothing is given), and assign them to instance variables. Now, let’s build those two functions:

def + (item)
    if item.is_a? Beverage
        @beverages.push item
    else
        @foods.push item
    end
end

This is pretty simple. Every object has an is_a? method that takes a single parameter: a class. If the object is an instance of that class, it will return true; otherwise, it will return false. So, this says that if the item we’re adding to the fridge is a Beverage, we’ll add it to the @beverages array. Otherwise, we’ll add it to the @food array.

That’s good; now, how about taking things out of the fridge? (Note: this method is different from the one shown in the video; this shows you that these operator method give us a great deal of flexibility; they are really just normal methods that you can do anything with. Also, I think this is a better version of the method; however, it’s more complex.)

def - (item)
    ret = @beverages.find do |beverage|
        beverage.name.downcase == item.downcase
    end

    return @beverages.delete ret unless ret.nil?

    ret = @foods.find do |food|
        food.name.downcase == item.downcase
    end

    @foods.delete ret
end

Here’s what’s going on when we use the minus operator. The parameter that it takes is a string, with the name of the item we’re looking for (By the way, we’ll create the Beverage and Food classes soon). We start by using the find method that arrays have. There are a few ways to use this method; we’re passing it a block; this block says that we’re trying to find the item in the array which has a name property that’s the same as the string we passed in; note that we’re converting both strings to lowercase, to be safe.

If there’s an item that matches in the array, that will be stored in ret; otherwise, ret will be nil. Next, we’ll return the result of @beverage.delete ret, which removes the item from the array and returns it. Notice we’re using a statement modifier at the end of that line: we do this unless ret is nil.

You might wonder why we’re using the keyword return here, since it’s not required in Ruby. If we didn’t use it here, the function wouldn’t return yet, since there’s more code to the function. Using return here allows us to return a value from a place the function wouldn’t normally return.

If we don’t return, that means the item wasn’t found in @beverages. Therefore, we’ll assume it’s in @foods. We’ll do the same thing to find the item in @foods and then return it.

Before testing this out, we’ll need our Food and Beverages classes:

class Beverage
    attr_accessor :name

    def initialize name
        @name = name
        @Time = Time.now
    end
end
class Food
    attr_accessor :name

    def initialize name
        @name = name
        @Time = Time.now
    end
end

Note that in the video, I didn’t make @name accessible from outside the object. Here, I’m doing that with attr_accessor :name, so that we can check the name of these object when they’re inside a fridge.

So, let’s test it out in irb; we’ll start by requiring the file that holds the code; then, give the classes a try; note that I’ve added line breaks to the output for easier reading.

> require './lesson_6'
=> true

> f = Fridge.new
=> #<Fridge:0x00000100a10378 @beverages=[], @foods=[]> 

> f + Beverage.new("water")
=> [#<Beverage:0x000001009fe8d0 @name="water", @Time=2011-01-15 13:20:48 -0500>] 

> f + Food.new("bread")
=> [#<Food:0x000001009d3c98 @name="bread", @Time=2011-01-15 13:20:59 -0500>] 

> f + Food.new("eggs")
=> [
    #<Food:0x000001009d3c98 @name="bread", @Time=2011-01-15 13:20:59 -0500>,
    #<Food:0x000001009746a8 @name="eggs", @Time=2011-01-15 13:21:04 -0500>
   ] 

> f + Beverage.new("orange juice")
=> [
    #<Beverage:0x000001009fe8d0 @name="water", @Time=2011-01-15 13:20:48 -0500>,
    #<Beverage:0x00000100907cd8 @name="orange juice", @Time=2011-01-15 13:21:16 -0500>
   ]

> f
=> #<Fridge:0x00000100a10378
        @beverages=[
            #<Beverage:0x000001009fe8d0 @name="water", @Time=2011-01-15 13:20:48 -0500>,
            #<Beverage:0x00000100907cd8 @name="orange juice", @Time=2011-01-15 13:21:16 -0500> ],
        foods[
            #<Food:0x000001009d3c98 @name="bread", @Time=2011-01-15 13:20:59 -0500>,
            #<Food:0x000001009746a8 @name="eggs", @Time=2011-01-15 13:21:04 -0500> ]
> f - "bread"
=> #<Food:0x000001009d3c98 @name="bread", @Time=2011-01-15 13:20:59 -0500>
> f
=> #<Fridge:0x00000100a10378
        @beverages=[
            #<Beverage:0x000001009fe8d0 @name="water", @Time=2011-01-15 13:20:48 -0500>,
            #<Beverage:0x00000100907cd8 @name="orange juice", @Time=2011-01-15 13:21:16 -0500>],
        foods[#<Food:0x000001009746a8 @name="eggs", @Time=2011-01-15 13:21:04 -0500>]

As we go along, you can see things being added to the @beverages and @foods arrays, and then subsequently removed.


Get and Set Operators

Now let’s write methods for the get and set operators used with hashes. You’ve seen this before:

person = {}

person[:name] = "Joe"

But, since these operators are methods, we can do it this way:

person.[]=(:age, 35) # to set

person.[](:name) # to get

That’s right; these are normal methods, with special sugar for your use.

Let’s give this a try; we’ll make a Club class. Our club with have members with different roles. However, we may want to have more than one member with a given role. So, our Club instance will keep track of members and their roles with a hash. If we try to assign a second member to a role, instead of overwriting the first one, we’ll add it.

class Club
    def initialize
        @members = {}
    end

    def [] (role)
        @members[role]
    end

    def []= (role, member)

    end
end

The get version is pretty simple; we just forward it to the @members array. But set is a little more complicated:

def []== (role, member)
    if @members[role].nil?
        @members[role] = member
    elsif @members[role].is_a? String
        @members[role] = [ @members[role], member ]
    else
        @members[role].push member
    end
end

If that role has not been set, we’ll just set the value of that key to our member hash. If it has been set as a string, we want to convert that to an array, and put the original member and the new member in that array. Finally, if neither of those options are true, it’s already an array, and so we just push the member into the array. We can test this class this way:

c = Club.new

c[:chair] = "Joe"

c[:engineer] = "John"

c[:engineer] = "Sue"

c[:chair] # "Joe"

c[:engingeer] # [ "John", "Sue" ]

There you go!


Other Operators

These aren’t the only operators that we can do this with, of course. Here’s the whole list:

  • Arithmetic Operators: + - * \
  • Get and Set Operators: [] []=
  • Shovel Operator: <<
  • Comparison Operators: == < > <= >=
  • Case equality Operator: ===
  • Bit-wise Operator: | & ^

Thanks for Reading!

If you’ve got any questions about this lesson, or anything else we’ve discussed in Ruby, ask away in the comments!

December 22 2010

18:39

Ruby for Newbies: Iterators and Blocks


Ruby is a one of the most popular languages used on the web. We’ve started a new screencast series here on Nettuts+ that will introduce you to Ruby, as well as the great frameworks and tools that go along with Ruby development. In this chapter, we’ll talk about in blocks and iterators.


Catch Up


View Screencast

Click the HD button for a clearer picture.

Subscribe to our YouTube page to watch all of the video tutorials!


Blocks

In the last lesson, we talked about loops. You actually won’t use loops too often in Ruby, because of a feature called blocks (and—as a result of blocks—iterators). To refresh your memory, look at the two following method calls (you can try this in IRB):

name = "Joe"

name.reverse  # => "eoJ"

name.concat(" the Plumber") # => "Joe the Plumber"

As you know, the parentheses after the method call are usually optional. We’ll learn today when they are required.

So, here are the parts of a method call:

  • The object receiving the method; name above.
  • The dot.
  • The method name; reverse or concat above.
  • The arguments; " the Plumber" in the second example above.
  • The code block; stay tuned!

The first three parts are required, obviously. The arguments and the code block are optional. What is this code block? Look at this example, and then we’ll discuss it:

sites = ["net", "psd", "mobile"]

sites.map! do |site|
    site += ".tutsplus.com"
end

sites # => ["net.tutsplus.com", "psd.tutsplus.com", "mobile.tutsplus.com"]

In this case, the array sites is the receiver; the method is map!. Next we have the block. If the block is on multiple lines, you can use the keywords do and end to delimit it. If you’re putting it on a single line, you can use curly braces (these work for multi-line blocks, too).

After the opening of the block, we have the block parameters, within pipes ( | ). What this is really depends on the method you’re executing. The most common use of blocks are in iterator methods, so the block parameter will be the current item in the looping. If this sounds rather abstract, we’ll do a few examples.


Iterators

We’ll start by looking at the iterators of arrays, because they’re the most commonly looped over thing.

Instead of using a for loop, you’ll probably use each:

sites = ["net", "psd", "mobile"]

sites.each { |site|
    puts "#{site}.tutsplus.com"
}
# net.tutsplus.com
# psd.tutsplus.com
# mobile.tutsplus.com    

This is just like doing a for loop; one by one, each item in sites will be assigned to the block parameter site; then, the code inside the block will be executed.

In case you’re curious, the each method returns the original array.

Sometimes, you’ll want to return a value from the block. That’s not hard to do, if you use the right method.

# assume sites above

sites = sites.map do |s|
    "#{s}.tutsplus.com"
end

The map method collects whatever values are returned from each iteration of the block. Then, an array of those values is returned from the method. In this case, we’re reassigning the sites variable to the new array.

There’s a better way to do this, though. Several Ruby methods have duplicates with the exclamation mark (or bang); this means they are destructive: they replace the value they are working on. So the above could be done this way:

sites.map! { |site_prefix| "#{site_prefix}.tutsplus.com" }

Now, sites will be the array of values returned from the block.

More than just arrays have iterator methods, though. Numbers have a pretty cool times method:

5.times do |i|
    puts "Loop number #{i}"
end

# Loop number 0
# Loop number 1
# Loop number 2
# Loop number 3
# Loop number 4

As you continue coding Ruby, you’ll find a lot of useful methods that use blocks. Now, let’s see how to create our own blocks.


Building Blocks

Now that you’re familiar with using blocks, let’s see how to write methods that take advantage of them. Here are two other block tidbits that you haven’t learned yet:

  • Block parameters are not required; you can write a block that doesn’t use them.
  • Blocks themselves can be optional. You can write a function that works with or without blocks.

Here’s what happens you call a method that takes a block. Behind the scenes, Ruby is executing some method code, then, yielding to the block code. After that, control is returned to the method. Let’s check it out.

Since most of the simple iterator functions are built into Ruby, we’ll “rewrite” one of those. Let’s do the each method on arrays:

class Array
    def each2
        i = 0;
        while self[i]
            yield self[i]
            i += 1
        end
        self
    end
end

As you can see, this is just a normal method. Remember that within an instance method, the self keyword refers to the instance of the class, in this case, Array. Inside the method, we’re using a while loop to loop over the items in the array. Then, inside the loop, we use the yield keyword. We’re passing it self[i]; that will end up being the block parameter. After that, we increment i for the loop and continue.

If we wanted this method to return the array of values that the block returned, we could just capture the returned value of yield and return that, instead of self, we return that array.

class Array
    def each2_returning_new_values
        i = 0;
        new_vals = [];
        while self[i]
            new_vals[i] = yield self[i]
            i += 1
        end
        new_vals
    end
end

Methods, revisited

Let’s finish up by talking about methods. We know that using parentheses is optional … most of the time. Here’s when you need to use the parenthesis when method calling.

Sometimes, you’ll have both method parameters and a block.

obj.some_method "param" { |x|
    #block code here
}

What I’ve just done won’t work; we need to use parentheses in this case, because otherwise the block is associated with the last parameter. This is only the case if you use the curly braces to delimit the block; if you use doend, the parentheses aren’t required.

The other time parenthesis are required is when you’re passing a literal hash (not a variable that points to a hash) as the first parameter of the method. Ruby will think it’s a block, because of the curly brace

arr.push { :name => "Andrew" } # Fails!
arr.push({ :name => "Andrew" }) # Passes

November 23 2010

14:21

Ruby for Newbies: Conditional Statements and Loops


Ruby is a one of the most popular languages used on the web. We’ve started a new screencast series here on Nettuts+ that will introduce you to Ruby, as well as the great frameworks and tools that go along with Ruby development. In this chapter, we’ll be looking at how conditional statements and loops work in Ruby.


Catch Up


View Screencast

Click the HD button for a clearer picture.

Subscribe to our YouTube page to watch all of the video tutorials!


Conditional #1: If Statement

The if statement is one of the first types of branching you learn when programming. You can guess what it means: if this is true, do one thing; if it’s not, do something else. In Ruby, these are pretty easy to write:

name = "Andrew"

if name == "Andrew"
	puts "Hello Andrew"
end

if name == "Andrew"
	puts "Hello Andrew"
else
	puts "Hello someone else"
end

After the keyword if, code in your conditional statement. After that comes the code to execute if the condition returns true. You close the statement with the end keyword. If you’d like, you can squeeze an else statement in there, which will predictably execute if the condition is false.

elsif

It’s not hard to check for multiple conditions. Just put as many elsif statements as you’d like between the if and else statements. Yes, that’s elsif, a marriage of else and if.

order = { :size => "medium" }

def make_medium_cofee
	puts "making medium statement"
end

#assume other functions

if order[:size] == "small"
	make_small_coffee;
elsif order[:size] == "medium"
	make_medium_coffee;
elsif order[:size] == "large"
	make_large_coffee;
else
    make_coffee;
end

As I mentioned, you can have as many elsif conditions and their corresponding code blocks as you want.

Statements vs. Expressions

Most programming languages make a distinction between statements and expressions. A statements is a code construct that doens’t evaluate to a certain value. An expression is a code construct does return a value. For example, calling a function is an expression, because it returns a value. However, an if statement is exactly that, a statement, because it does not return a value. This means that you can’t do this in your JavaScript:

message = if (someTruthyValue) {
		"this is true";
	} else {
		"this is false";
	}

Obviously, you can’t do this because the if statement does not return a value that you can assign to message.

However, you can do this with Ruby, because statements are actually expressions, meaning they return a value. So we can do this

message = if order[:size] == "small"
        "making a small"
    elsif order[:size] == "medium"
        "making a medium"
    else
        "making coffee"
    end

Whichever block of code is executed will become the value of message.

If as a Modifier

If you don’t have any elsif or else clauses, and your if statement has only one line, you can use it as a modifier to a “normal” line.

puts "making coffee" if customer.would_like_coffee?

Conditional #2: Unless Statement

In most programming languages, we want to reverse the return of the conditional expression, we have to negate it, usually with the bang (!) operator.

engine_on = true

if !engine_on   # meaning "if not engine_on"
	puts "servicing engine"  #should not be put, because "not engine_on" is false
end

However, Ruby has a really nice unless operator, that keeps us from having to do that, while giving us much more readable code:

unless engine_on  # "unless engine_on" is better than "if not engine_on"
	"servicing engine"
end

Just like if, you can use unless as a modifier:

puts "servicing engine" unless engine_on

Conditional #3: Case / When Statement

If you’ve got a lot of options to work through, using if/elsif/else might be somewhat wordy. Try the case statement.

hour = 15

case
when hour < 12
	puts "Good Morning"
when hour > 12 && hour < 17
	puts "Good Afternoon"
else
	puts "Good Evening"
end

It’s kinda-sorta-maybe like a switch/case statement in JavaScript (or other languages), except that there’s no one variable you’re evaluating. Inside the case/end keywords, you can put as many when statements as you’d like. Follow that when by the conditional expression, and then the lines of code go after it. Just like the if statement, the case statement is really an expression, so you can assign it to an expression and capture a returned value.

hour = 15

message = case
    when hour < 12
        "Good Morning"
    when hour > 12 && hour < 17
        "Good Afternoon"
    else
        "Good Evening"
    end

puts message

Breaking Up Expressions

If you’re familiar with JavaScript, you’ll know that the blocks of code in an if statement are surrounded by curly braces. We don’t do this in Ruby, so it may seem like Ruby is dependant on the whitespace. Nothing could be further from the truth (take that, pythonistas :) ).

If we want write your statements as one-liners, have to separate the different parts of the statements … but how? Well, you can use semi-colons:

if name == "Andrew"; some_code;
else; some_code; end

If you don’t like the look of that (which I don’t), you can put the keyword then between the conditional expressions and the line of code.

if name == "Andrew" then sode_code; end

This also works for a case statement.

case
    when x > 20; puts "<20"
    when x < 20 then puts "<20"
end

Loop #1: While Loop

So, those are conditional statements (I mean, expressions). How about loops? Let’s look at while loops first.

A while loop will continue to execute until the condition stated is false:

arr = ["John", "George", "Paul", "Ringo"]
i = 0

while arr[i]
    puts arr[i]
    i += 1
end

Here we’re looping over an array; when arr[i] returns false (meaning there are no items left in the array), the loop will stop executing. Inside the loop, we print out the current item in the array, and them add one to our increment variable.

You can also use while as a modifier

arr = ["John", "George", "Paul", "Ringo"]
i = -1

puts arr[i += 1] while arr[i]

Loop #2: Until Loop

Just like unless is the opposite of if, until is the opposite of while. It will continue to loop until the condition is true:

days_left = 7;

until days_left == 0
    puts "there are still #{days_left} in the week"
    days_left -= 1
end

And of course, it’s a modifier, too.

days_left = 8

puts "there are still #{days_left -= 1} in the week" until days_left == 1

Loop #3: For Loop

Yes, Ruby has a for loop. No, it’s not like the for loop in other languages. It acts like a foreach loop, for looping over the values in an array or hash:

arr = ["John", "George", "Paul", "Ringo"]

for item in arr
    puts item
end

If you’re looping over a hash, you can use two variable names, one for the key and one for the value:

joe = { :name => "Joe", :age => 30, :job => "plumber" }

for key, val in joe
    puts "#{key} is #{val}"
end

That’s it!

I hope you’re enjoying our Ruby for Newbies Screencast series. If there’s something you’d like to see, let me know in the comments! (And if you’re not watching the videos, you should be. There’s a screencast-only bonus at the end of each one.)

October 26 2010

18:09

Successful Freelancing With Ruby On Rails: Workflow, Techniques And Tools

Smashing-magazine-advertisement in Successful Freelancing With Ruby On Rails: Workflow, Techniques And ToolsSpacer in Successful Freelancing With Ruby On Rails: Workflow, Techniques And Tools
 in Successful Freelancing With Ruby On Rails: Workflow, Techniques And Tools  in Successful Freelancing With Ruby On Rails: Workflow, Techniques And Tools  in Successful Freelancing With Ruby On Rails: Workflow, Techniques And Tools

Warning: Freelancing Is Not for Everyone

A freelancer is a self-employed person who pursues a profession without a long-term commitment to any particular employer. Your curiosity in this opportunity was probably sparked by posts marked “Freelance” or “Work from anywhere” on the myriad of job boards around the Web. Freelancing is equal parts freedom and responsibility. While you have the freedom to choose when you work, where you work and what you work on, you are also responsible for everything: deadlines, finding work, the quality of your work, communication and so much more.

Workplace in Successful Freelancing With Ruby On Rails: Workflow, Techniques And Tools
Photo by Dmitry Belitsky

Ruby, with all of its frameworks and libraries (such as Rails, Merb and Sinatra), is a practical tool to use in your freelance Web development career because of its focus on clean code, object-oriented syntax, efficient development practices and strong community (whether a simple IRC chat room or large conference). For all of these reasons, I find that it is also quite fun to use and exciting to be a part of.

So, your skill may be in Ruby and your approach is to freelance, but it’s not that easy: freelancing is no walk in the park. It could become a living nightmare if you’re not able to use your time efficiently and remain focused and motivated until a project comes to a close. It could also become a nightmare if you market yourself poorly, are constantly desperate for work or surrender too much power to a client, putting you in the position of a monkey-worker responding to petty demands.

Over the four years that I’ve been freelancing, I have figured out the intricacies of it and grown to completely love it. I cannot envision myself working any other way.

[Offtopic: by the way, did you know that there is a Smashing eBook Series? Book #2 is Successful Freelancing for Web Designers, 260 pages for just $9,90.]

Pros

Alone in Successful Freelancing With Ruby On Rails: Workflow, Techniques And Tools
Photo by Giorgio Montersino.

Be your own boss.
Report to no one but yourself. You are at once king, countryman, peasant, squire, blacksmith and merchant. You will work on excruciatingly boring tasks, grand and exciting ventures and everything in between. You will have very tough times and very beautiful times.

Enjoy your freedom.
You have the freedom to work when and where you please, the freedom to structure your day as you please and the freedom to fail. Structure and discipline can be daunting and intimidating but also rewarding and empowering.

Choose what to work on.
Want to spend 50% of your time on open-source projects? Interested in building your own Web app? You have the power to make that a reality. Want to work exclusively on projects in social media? Make it happen.

Set your rates.
Value is both a reflection of how you perceive yourself and how others perceive you. Are you capable of meeting deadlines, communicating well and delivering quality code? Charge what you think that is worth. Often the market will decide. If you are just starting out, charging $80 per hour will be hard; you have to earn that rate over time and with experience.

But what’s to stop you from charging $80 per hour after just a year of full-time freelance work as a Ruby developer? Only yourself. You will have to be confident, and I suspect that most people reading this article do not charge that rate. But if you truly feel capable, then by all means.

In sum, you will experience highs and lows, but with the right attitude, the lows will always pay off.

Cons

Freelance-freedom in Successful Freelancing With Ruby On Rails: Workflow, Techniques And Tools

Selling yourself
Many dislike the notion of having to sell themselves. That’s understandable: the task is certainly not without its unpleasantness. If coding is an art, then like any good artist you’ll be critical of your own work. But maintain perspective. Recognize that you have to take responsibility for the quality of your code, but also understand that your clients probably won’t be programmers themselves. Hacking together something that works will be okay in many cases; and if it breaks because it was poorly written, offer to fix it for free.

When you write code that is efficient and powerful, explain as much to the client in vocabulary that they will understand; something like, “I changed the application so that it can perform × task at twice the speed.” Remember that your clients will likely not be developers and that in the freelancing game communication skills are often more important than programming skills. Be aware of yourself, be realistic in your expectations of yourself, be humble yet straightforward, and understand that if you truly believe in yourself, selling becomes easy. You are just being honest when you say to someone, “I’m good at what I do.”

Responsibility and discipline
No one will prevent you from procrastinating. No one will stop you from meeting with a friend in the middle of the day for lunch or a walk. No one will tell you what to do or when to do it. This may sound amazing—and it is if you’re disciplined—but discipline becomes rarer as we get increasingly overloaded with details that demand our attention. (In my opinion, discipline is one of the most important traits any freelancer can have.)

Time management
Manage your time as if each hour were a brick of gold. Time is more precious than any other resource. Tools are out there to help you become aware of how you spend it and that help you figure out where you are going wrong and right. Harvest, Trails, Tick and a slew of other applications are all designed to help you understand how you spend your time.

Emotions
The freelancing life is often isolating and can get lonely. It has often been said that running a small business is an emotional roller coaster: well, it is. Fight the inclination to stay cooped up and out of touch with the world. Get out and meet people; it could save you from serious bouts of depression.

Ultimately, freelancing is not for the faint of heart, but that doesn’t mean it isn’t worth your best shot!

Tools Of The Trade

Plenty of tools will help you get your projects done, but the best ones help you complete your projects effectively. We all work differently, and numerous tools are at our disposal that will help us accomplish the same task in different ways.

You’ll find a lot of discussion on the Web (some of it bordering on holy wars) about the relative merit of Vim vs. Emacs, Prototype vs. jQuery, Haml vs. ERB. But it doesn’t matter what you use: results matter. Properly caring for your code will help you grow, so use tools that allow you to craft the best possible code. Tools are always relative.

Text Editor (Vim, Emacs, TextMate, IDE)

MacVim in Successful Freelancing With Ruby On Rails: Workflow, Techniques And Tools

As with most other tools, choose a text editor by trying it out. I used TextMate in the past and now work in Vim most of the time. Some folks prefer Emacs or big IDEs such as RubyMine. You can try all of these just by downloading a trial version. You’ll know when you’ve found your favorite.

*Nix Server Management and Working in the Unix Shell

Many useful resources on Linux server management are available in various Slicehost articles. You’ll also find a lot of info about working in the command line at commandlinefu.com. Beyond that, let Google guide you.

Ruby Will Become Your Best Friend

Ruby in Successful Freelancing With Ruby On Rails: Workflow, Techniques And Tools

Yukihiro Matsumoto (a.k.a. Matz), creator of Ruby, said that he wanted to minimize his frustration with programming, minimize his effort in programming and have fun with software development. In fact, Ruby was designed to make programmers happy. But while Ruby is simple in appearance, it is complex inside, like the human body.

As hard as it is to believe, Ruby has been around for 15 years. As the years go by, more and more people see the beauty in this language and become passionate users. Today, Ruby is the language of choice for hundreds of thousands of developers worldwide. Several lively Ruby conferences take place each year around the world. And big corporations use Ruby: Microsoft and Sun have created their own Ruby interpreters (IronRuby, jRuby), and Apple now includes Ruby with OS X 10.6. Countless Ruby developers are hired every day on every continent.

The community around a language is one of my primary considerations in deciding whether to learn that language. Ruby’s community is vibrant and growing; it is friendly to people of all skill levels and comprises both online communication such as chatting and mailing lists and in-the-flesh interaction at meet-up groups and conferences. Ruby and its frameworks—especially Rails—have become their own sub-culture; full of life and passion and changing every day.

A very useful resource is confreaks.com, where you can watch videos from great Ruby-related events such as Rubyconf, acts_as_conference and more. Highly recommended.

Popular Ruby-related resources:

  • The official Ruby website
  • Ruby mailing list
    A useful place to get help or advice from those active in the Ruby community.
  • Ruby Inside
    A Ruby blog with daily news, links, code and tips. Claims to be “the #1 Ruby programming blog.”
  • RubyFlow
    A community-driven Ruby links website, with more than 1000 members. Posts are made by members of the community. Enjoy the links and leave comments.
  • RubyForum
    Helpful forum for Ruby and Rails.
  • Ruby Learning
    “A thorough collection of Ruby study notes for those who are new to the Ruby programming language and in search of a solid introduction to Ruby’s concepts and constructs.”
  • Planet Ruby
    RSS aggregator of top Ruby-related blogs.

The Ruby on Rails Framework (and Alternatives: Merb, Sinatra, Ramaze, Rango)

Rails is my MVC framework of choice because of its ease of use as well as the vast community of passionate users who stand behind it. If you’d like to learn it, a great starting point is Agile Web Development With Rails. UC Berkeley has a series of intensive Ruby on Rails classes on YouTube, which are rather useful. And a lot of screencasts are on the Web. I also like confreaks (already mentioned but worth a second push); it delivers videos from large Ruby conferences, and I’ve learned a lot from the talks.

Railsguides in Successful Freelancing With Ruby On Rails: Workflow, Techniques And Tools

Some general Rails-related resources:

  • RailsGuides
    A great Rails documentation project.
  • RailsBridge
    A friendly Rails community.
  • Ruby on Rails 3.0 Release Notes
    A new Rails 3 guide, with details on the new Rails release.
  • Dive into Rails 3
    Rails 3 screencasts on new features such as Bundler, Active Model, the new router syntax and more.
  • The New Ruby Ecosystem
    An interesting post from Paolo “Nusco” Perrotta about the most used development tools in the Ruby community.
  • Rails Tutorial
    An extensive series of tutorials (one of the most comprehensive resources for beginners I’ve found).
  • RubyonRailsTutorials.com
    A great catalog of links, to further satiate your appetite for Rails knowledge.

Some more specific tools for Ruby to check out:

  • The Ruby Development Tool
    An IDE consisting of Ruby-aware features and plug-ins for the Eclipse platform.
  • Watir
    An open-source (BSD) library for automating Web browsers. It allows you to write tests that are easy to read and maintain. It is at once flexible and simple.
  • Radrails
    A Ruby on Rails IDE, either standalone or as an Eclipse plug-in. Free, open source and cross-platform, Radrails includes an integrated shell console, rich code completion for Ruby and Rails, an integrated debugger and cloud deployment options.

    Radrails in Successful Freelancing With Ruby On Rails: Workflow, Techniques And Tools

  • Heroku
    An online Ruby on Rails cloud platform-as-a-service. A “fast, frictionless and maintenance-free Rails hosting platform” with a free plan. The platform is effective, though not invincible.
  • Capistrano
    An open-source tool for running scripts on multiple servers, most commonly used to deploy Web applications. It automates the process of making a new version of an application available on one or more Web servers, including support for tasks such as changing databases.
  • The Ruby Toolbox
    Provides an overview of tools available to Ruby developers. Tools are sorted by category and rated according to the number of watchers and forks in the corresponding source code repository on GitHub, so you can easily figure out your options and which are the most common ones in the Ruby community.

    Toolbox in Successful Freelancing With Ruby On Rails: Workflow, Techniques And Tools

  • RailRoad
    “A class diagrams generator for Ruby on Rails applications. It’s a Ruby script that loads the application classes and analyzes its properties (attributes, methods) and relationships (inheritance, model associations like has_many, etc.).”
  • Instant Rails
    “A one-stop Rails runtime solution containing Ruby, Rails, Apache and MySQL, all preconfigured and ready to run (on Windows, OS X, Linux and BSD). No installer—you simply drop it into the directory of your choice and run it. It does not modify your system environment.”
  • Ruby on Rails Toolbox
    A list of 20+ tools to help you with your Ruby on Rails coding.

TDD and BDD

Test-driven development (TDD) is a software development technique that involves repeating a very short development cycle: the developer writes a failing automated test case that defines a desired improvement or new function; then they produce code to pass that test; and finally they refactor the new code to meet recognized standards.

Behaviour-driven development (BDD) is an evolution of the thinking behind TDD and acceptance test-driven planning. It brings together strands of TDD and domain-driven design in an integrated whole, making the relationship between these two powerful approaches to software development more evident.

Cuke Logo in Successful Freelancing With Ruby On Rails: Workflow, Techniques And Tools

BDD helps focus development on the delivery of prioritized, verifiable business value by providing a common vocabulary (also referred to as an “ubiquitous language”) that spans the divide between business and technology.

Cuke in Successful Freelancing With Ruby On Rails: Workflow, Techniques And Tools

HTML, CSS, HAML, SASS, LESS

Nothing can be done on the Web without hypertext mark-up. Every page has its own mark-up and style, and you have to know the basics in order to work with mark-up. Learning HTML basics should take about an hour, and becoming a CSS expert a lot more time, but everything starts with your first step. Once you know how each works, diving into tools that simplify them, such as HAML, SASS and LESS, will be enjoyable and rewarding.

VCS (Version Control Systems)

Version control is essential whether you work alone or on a team, because it tracks all significant changes you have made to a project (called “commits”), and you can easily save the project’s growth history, make new branches to test new functionality, jump back and forth through changes and distribute those changes to others involved in writing the code. I prefer Git and use it most often. It’s fast and reliable, but other systems offer their own functions and strengths. “7 Version Control Systems Reviewed” covers the spectrum of options.

Git in Successful Freelancing With Ruby On Rails: Workflow, Techniques And Tools

“Git is a free distributed revision control, or software source-code management, project, with an emphasis on being fast. It was initially designed and developed by Linus Torvalds for Linux kernel development.”

Wikipedia

Here is a list of helpful resources to help you jump into working with Git:

Finding Clients

You’ve weighed the pros and cons, and the pros won. You’ve learned enough Ruby and Rails to start looking for work. Now, where do you find clients?

Finding clients is a big topic, so I’ll stick to the basics for now and leave out details on marketing strategies and brand development.

Communicate with potential clients first through simple emails. Write your thoughts in short and effective paragraphs; be selective with your words, and get to the point quickly, mindful of the time people are spending reading your message. You will not only deliver your message effectively but show that you are focused on important matters and that you avoid wasting people’s time.

If you have no portfolio, you may have to do work for very little pay—or even for free—to entice prospects. As you develop your portfolio, describe each project very briefly (one to two sentences), and then start adding these summaries to your emails. The inclusion of references to real work greatly increases your chances of securing more work.

In your search, follow up on every interesting job posting that you’ve found, mentioning your professional experience, technologies you know and your professional qualities, such as being responsible and being able to deliver projects on time and on budget. Ideally, you would show testimonials from previous clients.

Job Boards

Wwr in Successful Freelancing With Ruby On Rails: Workflow, Techniques And Tools

A lot of freelance job boards are around. Here are the ones I know of and have used successfully:

Contributing to Open Source

Github in Successful Freelancing With Ruby On Rails: Workflow, Techniques And Tools

If you want clients, you need to prove yourself. Nothing speaks better of developers than their code (although technical skill is only part of the puzzle).

Choose projects that interest you; you’ll get better results. Choose projects that give you a chance to learn and grow. But be careful: your learning should not prolong project deadlines. I find that the best projects are those in which I can work with a passionate team and learn new things along the way.

Learn How People Hire

Read articles that explain how to hire developers for insights into the hiring and hunting process. Articles such as these:

Get Your First Project

If you have no previous development experience, create some first. Write tests for open-source apps, fix bugs, put together a simple Web app: over time you will have developed a portfolio and eventually become confident enough to take on client work.

One way to start: choose a project on GitHub and learn its internals; offer help by writing tests and fixing bugs. Over time you will learn how to work as a team player and how to read code written by others. This knowledge will help you tremendously.

Focus on Building Your Profile

Linkedin in Successful Freelancing With Ruby On Rails: Workflow, Techniques And Tools

This could be the first thing people read about you, and first impressions count. Make this impression as good as possible, and use all of the best-known networks: LinkedIn, Working With Rails and GitHub.

Create a Website or Blog

You should have your own website or blog because that’s expected in the Web development field. On it, you can describe your professional experience, new technologies that you have been working with, book reviews (this might also bring in new readers from search engines) and interviews with people you find interesting. Include productivity tips and personal thoughts on things you’re interested in. Remember, describe your own experiences and show your face. Be authentic. Read about writing for the Web on useit.com and A List Apart (the writing section).

Get Involved in the Community

Railsbridge in Successful Freelancing With Ruby On Rails: Workflow, Techniques And Tools

Make something useful for yourself and people like you. This could be a library or plug-in, an article or a tutorial—anything usable. Writing documentation for RailsBridge will surely increase your understanding of Rails, too.

Write a Lot of Emails to Employers

If all goes well you might have a pool of a few jobs to chose from. Choose wisely, and then work vigorously to deliver something great—on time! When you reach out at first, don’t expect many responses. If you get only a few clients from 50 emails that you send, you’re doing good. Now you need to get things done, and that takes time and a good process.

Working Process

There are many well-known methods of working, and each offers a different approach to solving the same problem: how the heck do I get things done effectively?

Here are the two techniques I follow:

Getting Things Done (GTD) is a method created by David Allen and described in his book of the same name. GTD relies on the principle that a person needs to move tasks out of their brain by recording them externally. That way, the mind is freed from having to remember everything that has to get done and can concentrate on actually performing those tasks. Check out the interesting introductory video by David Allen on YouTube.

GTD is an easy step-by-step and highly efficient method of achieving this relaxed, productive state. It includes:

  1. Capturing anything and everything that has your attention;
  2. Categorizing actionable tasks discretely as outcomes and concrete next steps;
  3. Organizing reminders and information in the most streamlined way, in appropriate categories, based on how and when you need to access them;
  4. Staying current and “on your game” with appropriately frequent reviews of the six horizons of your commitments (purpose, vision, goals, areas of focus, projects and actions).

The Pomodoro Technique is a way to get the most out of your time. Turn time into a valuable ally to accomplish what you want to do, and chart continual improvement in the way you do it. Francesco Cirillo created the Pomodoro Technique in 1992. It is now practiced by professional teams and individuals around the world. A great way to learn it is through this cheat sheet.

It can be described simply in five steps:

  1. Choose a task to be accomplished;
  2. Set the Pomodoro (i.e. the timer) to 25 minutes;
  3. Work on the task until the Pomodoro rings, and then put a check on your sheet of paper;
  4. Take a short break (about five minutes);
  5. After every four Pomodoros, take a longer break.

My own productivity method mixes these two techniques. I break big tasks into smaller chunks, and then I write them down in a Pomodoro-like table and work on them for 25 to 30 minutes, with 5 to 10 minutes breaks.

Getting Perspective

Get Some Rest

Rest in Successful Freelancing With Ruby On Rails: Workflow, Techniques And Tools
Photo by Dmitry Belitsky

Rest is just as important as work. They are a yin and yang, work and rest. Rest both your body and mind. No one can work much more than 40 hours per week and still be productive.

Here are a few tips to rest the right way:

Take a break.
If you have worked on the computer for more than an hour, switch your focus. Go exercise, wash the dishes or take a walk. Attend to something that doesn’t involve staring incessantly at a screen. When you get back to work, you will find your mind relaxed and rested.

Meditate.
Meditation comes down to us from the ancient sages as a method of training the mind to be at peace. It helps you to relax your mind and body and become at once joyful and calm. There are a lot of different techniques of meditating; try the simplest one, making it a part of your daily routine. This is a great
article on meditation
because it relates to creative fields, but the principles apply to any profession (and who says good code isn’t art, anyway?).

Go for a walk.
Walking is a great way to calm your mind, exercise your body and take in fresh air. Integrate walking into your daily or weekly routine, too.

Don’t overeat.
Overeating takes blood away from your brain and moves it to your hard-working stomach to help it digest all that food. This makes you tired and less focused. Food is great, but don’t overdo it.

Take up a non-computer-related hobby.
We should all find something that keeps us away from our computers for a while. If you live alone and work as a freelancer, you can lose yourself for weeks, working too hard and forgetting everything else. Jamis Buck has some great advice on the subject:

“You should be well balanced. Computers are great and everything, but you should definitely have hobbies that are completely unrelated to computers. In the last two years I’ve taken up both wood carving and string figuring, and they have helped me immensely in recovering from burn-out.”

Success

  • “Everything you write is crap, so always try to improve yourself.”
    Dirkjan Bussink.
  • Hard work is the secret to success.
  • Passion is critical; it makes or breaks any endeavor.
  • Love what you do.
  • “Never let anyone (yourself included) convince you not to do something that will make you happy or fulfilled.”
    Yehuda Katz

Video Resources

Parting Thought

Decide how good you want to be. Do you want to master the craft or just fulfill the basic needs of employment? As a freelance developer, you might find yourself in a constant struggle. You could be forced to produce code that you are dissatisfied with because of a tight deadline or unforeseen problems with other parts of the project. Be patient and relentless. Know that you will become more skilled over time, and trust that you will eventually—even if it takes years—be proud of your abilities.

(al)


© Dmitry Belitsky, Grayson Stebbins for Smashing Magazine, 2010. | Permalink | Post a comment | Add to del.icio.us | Digg this | Stumble on StumbleUpon! | Tweet it! | Submit to Reddit | Forum Smashing Magazine
Post tags: freelancing, rails, ruby

October 19 2010

19:20

Using Unobtrusive JavaScript and AJAX with Rails 3


As I mentioned in my previous Ruby on Rails tutorial, Unobtrusive JavaScript (UJS) is one of the coolest new features in Rails 3. UJS allows Rails-generated code to be much cleaner, helps separate your JavaScript logic from your HTML layouts, and uncouples Rails from the Prototype JavaScript library. In this tutorial, we’re going to look at these features and learn how to use them in a simple Rails 3 application.


Background: What is Unobtrusive JavaScript?

To start off, what exactly is UJS? Simply, UJS is JavaScript that is separated from your HTML markup. The easiest way to describe UJS is with an example. Take an onclick event handler; we could add it obtrusively:

<a href='#' onclick='alert("Inline Javscript")'>Link</a>

Or we could add it unobtrusively by attaching the event to the link (using jQuery in this example):

<a href='#'>Link</a>
<script>
$('a').bind('click', function() {
    alert('Unobtrusive!');
}
</script>

As mentioned in my introduction, this second method has a variety of benefits, including easier debugging and cleaner code.

“Rails 3, on the other hand, is JavaScript framework agnostic. In other words, you can use your JavaScript framework of choice, provided a Rails UJS implementation exists for that framework.”

Up until version 3, Ruby on Rails generated obtrusive JavaScript. The resulting code wasn’t clean, but even worse, it was tightly coupled to the Prototype JavaScript framework. This meant that unless you created a plugin or hacked Rails, you had to use the Prototype library with Rail’s JavaScript helper methods.

Rails 3, on the other hand, is JavaScript framework agnostic. In other words, you can use your JavaScript framework of choice, provided a Rails UJS implementation exists for that framework. The current UJS implementations include the following:

Rails 3 now implements all of its JavaScript Helper functionality (AJAX submits, confirmation prompts, etc) unobtrusively by adding the following HTML 5 custom attributes to HTML elements.

  • data-method – the REST method to use in form submissions.
  • data-confirm – the confirmation message to use before performing some action.
  • data-remote – if true, submit via AJAX.
  • data-disable-with – disables form elements during a form submission

For example, this link tag

<td><a href="/posts/2" class="delete_post" data-confirm="Are you sure?" data-method="delete" data-remote="true" rel="nofollow">Destroy</a></td>

would send an AJAX delete request after asking the user “Are you sure?.”

You can imagine how much harder to read that would be if all that JavaScript was inline.

Now that we’ve reviewed UJS and how Rails implements UJS, let’s set up a project and look at some specific applications. We’ll be using the jQuery library and UJS implementation in this tutorial.


Step 1: Setting up the Project

Since we’re creating a new project from scratch, the first thing we need to do is create the project by typing the following:

	rails new blog --skip-prototype

Notice that I’m instructing Rails to skip the prototype JavaScript file, since I’m going to be using the jQuery library.

Let’s start the server just to make sure everything appears to be working.

And, voila!

Now that we’ve set up our project, we need to add jQuery and the jQuery UJS to our project. You are free to organize your JavaScript however you want, but the Rails convention for structuring your JavaScript files is as follows (all these files go in public/javascripts):

  • framework JavaScript file (jquery.js, prototype.js, or mootools.js)
  • rails.js – the code implementing rails UJS (for whatever framework you’ve chosen)
  • application.js – your application JavaScript

If you haven’t already, download jquery.js (or refer to a CDN) and rails.js and include them in your public/javascripts directory.

The last thing we need to do to get up and running is to actually tell Rails to include these js files on each of our pages. To do this, open application.rb in your config directory and add the following line

config.action_view.JavaScript_expansions[:defaults] = %w(jquery rails application)

This configuration item tells Rails to include the three JavaScript files mentioned above by default.

Alternatively, you could grab jQuery from a CDN (i.e. http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js) by manually included a script tag pointing to the correct location. If you do this, be sure to remove ‘jquery’ from the JavaScript_expansions configuration item.


Step 2: Generating Some Code

To demonstrate the rails UJS functionality, we’re first going to have to have some code to work with. For this demo we’re just going to have a simple Post object. Let’s generate that now

	rails generate scaffold Post name:string title:string content:text

And then let’s migrate our database to create the posts table.

	rake db:migrate

Ok, we’re good to go! If we navigate to http://localhost:3000/posts/new, we should see a form to create a new Post.

Ok, it’s all working! Now let’s dig in and see how to use the UJS and AJAX functionality baked into Rails.


Step 3: Adding AJAX

Now that all the required JavaScript files are being included, we can actually start using Rails 3 to implement some AJAX functionality. Although you can write all of the custom JavaScript that you want, Rails provides some nice built-in methods that you can use to easily perform AJAX calls and other JavaScript actions.

Let’s look at a couple of commonly used rails helpers and the JavaScript they generate

AJAX Form Submission and Javascript ERB Files

If we look at our Posts form, we can see that whenever we create or edit a Post, the form is manually submitted and then we’re redirected to a read-only view of that Post. What if we wanted to submit that form via AJAX instead of using a manual submission?

Rails 3 makes it easy to convert any form to AJAX. First, open your _form.html.erb partial in app/views/posts, and change the first line from:

<%= form_for(@post) do |f| %>

to

<%= form_for(@post, :remote => true) do |f| %>

Prior to Rails 3, adding :remote => true would have generated a bunch of inline JavaScript inside the form tag, but with Rails 3 UJS, the only change is the addition of an HTML 5 custom attribute. Can you spot it?

<form accept-charset="UTF-8" action="/posts" class="new_post" data-remote="true" id="new_post" method="post">

The attribute is data-remote="true", and the Rails UJS JavaScript binds to any forms with that attribute and submits them via AJAX instead of a traditional POST.

That’s all that’s needed to do the AJAX submit, but how do we perform a callback after the AJAX call returns?

The most common way of handling a return from an AJAX call is through the use of JavaScript ERB files. These work exactly like your normal ERB files, but contain JavaScript code instead of HTML. Let’s try it out.

The first thing we need to do is to tell our controller how to respond to AJAX requests. In posts_controller.rb (app/controllers) we can tell our controller to respond to an AJAX request by adding

format.js

in each respond_to block that we are going to call via AJAX. For example, we could update the create action to look like this:

def create
    @post = Post.new(params[:post])

    respond_to do |format|
      if @post.save
        format.html { redirect_to(@post, :notice => 'Post created.') }
        format.js
      else
        format.html { render :action => "new" }
        format.js
      end
    end
end

Because we didn’t specify any options in the respond_to block, Rails will respond to JavaScript requests by loading a .js ERB with the same name as the controller action (create.js.erb, in this case).

Now that our controller knows how to handle AJAX calls, we need to create our views. For the current example, add create.js.erb in your app/views/posts directory. This file will be rendered and the JavaScript inside will be executed when the call finishes. For now, we’ll simply overwrite the form tag with the title and contents of the blog post:

	$('body').html("<h1><%= escape_JavaScript(@post.title) %></h1>").append("<%= escape_JavaScript(@post.content) %>");

Now if we create a new Post we get the following on the screen. Success!

The advantage of this method is that you can intersperse ruby code that you set up in your controller with your JavaScript, making it really easy to manipulate your view with the results of a request.

AJAX Callbacks Using Custom JavaScript Events

Each Rails UJS implementation also provides another way to add callbacks to our AJAX calls – custom JavaScript events. Let’s look at another example. On our Posts index view (http://localhost:3000/posts/), we can see that each post can be deleted via a delete link.

Let’s AJAXify our link by adding :remote=>true and additionally giving it a CSS class so we can easily find this POST using a CSS selector.

<td><%= link_to 'Destroy', post, :confirm => 'Are you sure?', :method => :delete, :remote=>true, :class=>'delete_post' %></td>

Which produces the following output:

<td><a href="/posts/2" class="delete_post" data-confirm="Are you sure?" data-method="delete" rel="nofollow">Destroy</a></td>

Each rails UJS AJAX call provides six custom events that can be attached to:

  • ajax:before – right before ajax call
  • ajax:loading – before ajax call, but after XmlHttpRequest object is created)
  • ajax:success – successful ajax call
  • ajax:failure – failed ajax call
  • ajax:complete – completion of ajax call (after ajax:success and ajax:failure)
  • ajax:after – after ajax call is sent (note: not after it returns)

In our case we’ll add an event listener to the ajax:success event on our delete links, and make the deleted post fade out rather than reloading the page. We’ll add the following JavaScript to our application.js file.

	$('.deletePost').bind('ajax:success', function() {
		$(this).closest('tr').fadeOut();
	});

We’ll also need to tell our posts_controller not to try to render a view after it finishes deleting the post.

  def destroy
    @post = Post.find(params[:id])
    @post.destroy

    respond_to do |format|
      format.html { redirect_to(posts_url) }
      format.js   { render :nothing => true }
    end

Now when we delete a Post it will gradually fade out.


Conclusion

Well, there you have it. Now you know how to make AJAX calls using Rails 3 UJS. While the examples explained were simple, you can use these same techniques to add all kinds of interactivity to your project. I hope you’ll agree that it’s a big improvement over previous versions, and that you’ll try it out on your next Rails project.

What techniques do you use when implementing AJAX in Rails?

September 21 2010

18:04

5 Awesome New Rails 3 Features

After more than a year of development, Ruby on Rails 3 was officially released to the public a few weeks ago. More than just an iterative update, this highly anticipated release was a major refactoring of the popular Ruby framework. Keep reading to learn five of the most awesome new features in Ruby Rails 3.


1. Unobtrusive JavaScript

One of my favorite new Ruby on Rails 3 features is the introduction of Unobtrusive JavaScript (UJS) to all of its JavaScript helper functions. In previous versions of Rails, JavaScript was generated inline with HTML, causing ugly and somewhat brittle code.

As an example, Rails allows you to use its link_to method to generate a delete link for some object.

<%= link_to "Delete this Post", @post, :confirm => "Do you really want to delete this post?", :method => :delete %>

Using this method in your view would generate the following in Rails 2:

Delete this Post

Rails 3 would generate something much simpler:

Delete this Post

Rails 3 replaces all of the inline JavaScript with a couple of HTML5 attributes. All of the JavaScript event handlers to handle the actual confirmation box and deletion are stored in one central JavaScript file that is included with every rails project.

One big advantage to this new method is that the JavaScript helpers are framework agnostic. Instead of being tied to the Prototype library like you were in Rails 2, you can now choose whatever JavaScript framework you like (Rails apps come with Prototype by default, but jQuery is now officially supported.


2. Improved Security

Another awesome new feature of Rails 3 is that XSS protection is now enabled by default. Rails 2 supported XSS protection through the use of the h method.

<%= h @comment.text %>

The h method would escape html and JavaScript to ensure that no malicious client-side code was executed. This method worked great, but there was one problem: you had to actually remember to use the h method everywhere the user entered input was displayed. If you forgot even one place, then you were vulnerable to an XSS attack.

In Rails 3, all input is escaped by default, taking the burden off of the developer of having to remember to escape everywhere that malicious code might be present. For those times that you do want to allow unescaped data to appear in your view, you can use the raw method to tell Rails 3 not to escape the data.

<%= raw @comment.text %>

3. New Query Engine

Rails 3 includes a cool new query engine that makes it easier to get back the data you want and gives you more flexibilitiy in your controller code. These changes show up in various places, but the most common case is fetching data in your controller. In Rails 2, you could use the find method to retrieve the data you were looking for, passing in arguments to specify conditions, grouping, limits, and any other query information. For example:

@posts = Post.find(:all, :conditions => [ "category IN (?)", categories], :limit => 10, :o rder => "created_on DESC")

finds the first ten posts within some specified categories ordered by the creation time.

In Rails 3, each of the passed in parameters has its own method, which can be chained together to get the same results.

@posts = Post.where([ "category IN (?)", categories]).order("created_on DESC").limit(10)

The query is not actually executed until the data is needed; so these methods can even be used across multiple statements.

@posts = Post.where([ "category IN (?)", categories])
if(condition_a)
 @posts = @posts.where(['approved=?', true])
else
 @posts = @posts.where(['approved=?', false])
end

This is only a simple example, but should provide you with an idea of some of the ways this new syntax can be more useful.


4. Easier Email

The ActionMailer module has been rewritten to make it a lot easier for your application to send email in Rails 3. There are quite a few changes, but here are a couple of my favorites.

1. Default Settings

In Rails, a Mailer is a class that can have many methods, each of which generally configure and send an email. Previously, you had to set all of the parameters for each email separately in each method.

class UserMailer < ActionMailer::Base

 def welcome_email(user)
    from       "system@example.com"

    # other paramters
 end

 def password_reset(user)
    from       "system@example.com"

    # other parameters

 end

end

In Rails 3, you can specify defaults that can be optionally overwritten in each method.

class UserMailer < ActionMailer::Base
  default :from => 'no-reply@example.com',*           :return_path => 'system@example.com'

 def welcome_email(user)
    # no need to specify from parameter*  end

end

2. Cleaner APIs

Previous versions of Rails required you to send email using special methods that were dynamically created by ActionMailer. For instance, if you wanted to deliver the welcome email in the example above, you would need to call:

UserMailer.deliver_welcome_email(@user)

ln Rails 3, you can just call

    UserMailer.welcome_email(@user).deliver

This makes more sense semantically, and additionally allows you to retrieve and manipulate the Mail object before delivering the email.


5. Dependency Management

One of the strengths of the Ruby on Rails framework is the plethora of gems available for use by developers. Whether it's authentication, handling financial transactions, handling file uploads, or nearly anything else, chances are a gem exists to help with your problem.

Issues can arise, however, if your gems require other gems, or developers are on different environments, among other things. To help solve these types of situations, Rails 3 adds the Bundler gem to help manage your dependencies. Using Bundler in Rails 3 is extremely simple; add a line for each gem you require in your Gemfile, a file included in the root of each of your applications.

gem 'authlogic'

Once you've included all your gems, run:

    bundle install

and Bundler will download and configure all of the gems and their dependencies that you need for the project.

Bundler also allows you to specify certain gems to only be configured in certain environments (development vs production vs testing).

These are only a few of the many changes included in Ruby on Rails 3. Many of the old APIs still work in Rails, even if they've been deprecated, to make it easier to update. So, if you're on the fence about whether or not to upgrade your existing rails app, then go for it!

Thanks for reading!

May 26 2010

20:43

2 New Premium Tutorials: Refinery and Modernizr


This week, we have two excellent new Net Premium tutorials for our members. First, Glenn Goodrich will teach you how to work with Refinery – a Rails CMS. Next, I’ll teach you how to detect CSS3 and HTML5 support in browsers, by using the wonderful Modernizr library. Help give back to Nettuts+ by signing up for a Premium membership.


Getting Started with Refinery: A Rails CMS

Refinery is an open-source, Rails-based CMS that really attempts to use “the Rails Way” for content management. Anyone familiar with Rails will be able to pick up Refinery and be productive almost instantly. The folks over at Resolve Digital created Refinery to scratch their own itch, and then were kind enough to release it on GitHub (MIT License). Refinery has a growing set of users and developers, making it ideal if you’re just starting out with Rails-base content management systems. I’ll teach you how to get started with it!


A Video Crash-Course in Modernizr

It’s a common misconception that the JavaScript library, Modernizr, miraculously upgrades all browsers to allow for HTML5 and CSS3 support. Unfortunately, this isn’t the case. However, instead, it detects support, which provides us with a lot of power! I’ll show you how to get started today!


Join Net Premium

NETTUTS+ Screencasts and Bonus Tutorials

For those unfamiliar, the family of TUTS sites runs a premium membership service. For $9 per month, you gain access to exclusive premium tutorials, screencasts, and freebies from Nettuts+, Psdtuts+, Aetuts+, Audiotuts+, and Vectortuts+! For the price of a pizza, you’ll learn from some of the best minds in the business. Join today!

Older posts are this way If this message doesn't go away, click anywhere on the page to continue loading posts.
Could not load more posts
Maybe Soup is currently being updated? I'll try again automatically in a few seconds...
Just a second, loading more posts...
You've reached the end.
(PRO)
No Soup for you

Don't be the product, buy the product!

close
YES, I want to SOUP ●UP for ...