CSC/ECE 517 Fall 2012/ch1 1w19 sa

From Expertiza_Wiki
Revision as of 00:33, 15 September 2012 by Sbhatta9 (talk | contribs)
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Jump to navigation Jump to search

Introduction

Rails is a MVC (Model-View-Controller) based architecture for web development based on the Ruby language. Rails 2[1] was released in December 2007. Initially Rails 2 supported Ruby 1.8[2]. It now has been updated to support Ruby 1.9.1[3]. Rails 3 which brings in many improvements over Rails 2 supports Ruby 1.9 and above. The current stable version of Rails is 3.2.8[4] released on Aug 9, 2012. This wikibook chapter focuses mainly on the differences of Rails 2 and Rails 3.

Differences between Rails 2 and Rails 3

Unobtrusive Javascript[5]

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:

<a href="/posts/6" onclick="if (confirm('Do you really want to delete this post?')) { var f = document.createElement('form');

      f.style.display = 'none'; this.parentNode.appendChild(f); f.method = 'POST'; f.action = this.href;
      var m = document.createElement('input'); m.setAttribute('type', 'hidden'); m.setAttribute('name', '_method');
      m.setAttribute('value', 'delete'); f.appendChild(m);f.submit(); };return false;">Delete this Post</a> 

Rails 3 would generate something much simpler:

<a href='/posts/6"' rel="nofollow" data-method="delete" data-confirm="Do you really want to delete this post?">Delete this Post</a>

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.

No more dependency on only Prototype Javascript library

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[6].

Improved Security

Another awesome new feature of Rails 3 is that XSS[7] 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 %>

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 flexibility 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, :order => "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.

Easier Email

The ActionMailer module has been rewritten to make it a lot easier for your application to send email in Rails 3.

1-Default Setting 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 API 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.

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[8], handling financial[9] transactions[10], 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[11] 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.

ActiveRecord finder methods

In Rails 2

User.find(:all, : order => "created_at desc", :limit => 5)

Rails 3 looks at the hash of options that is being passed to find(:all, : order, and :limit) and replace each item in the hash with an equivalent method. Rails 3 has a new API for the dynamic fiders

where, having, select, group, order, limit, offset, joins, includes, ...

So, in Rails 3 it becomes

User.order("created_at desc").limit(5)

Active Record Validations

There sre separate validations in Rails 2

validates_presence_of :username

validates_uniqueness_of :username

validates_length_of :email, :maximum => 40


In Rails 3 these can be clubbed together

validates :email, :presence => true,

uniqueness => true,
length => {:maximum => 30}

References

Rails 3 Documentation

Rails 2 Documentation

Rails API

Rails Mailer