{"id":525,"date":"2009-12-23T11:06:04","date_gmt":"2009-12-23T14:06:04","guid":{"rendered":"http:\/\/blog.plataformatec.com.br\/?p=525"},"modified":"2010-04-22T14:57:12","modified_gmt":"2010-04-22T17:57:12","slug":"one-in-three-inherited-resources-has-scope-and-responders","status":"publish","type":"post","link":"https:\/\/blog.plataformatec.com.br\/2009\/12\/one-in-three-inherited-resources-has-scope-and-responders\/","title":{"rendered":"One in Three: Inherited Resources, Has Scope and Responders"},"content":{"rendered":"

Inherited Resources<\/a> always had a hate\/love history with Rails Edge<\/a>. Just after DHH posted about respond_with<\/a>, it was already there in Inherited Resources. This initial implementation provided a nice test suite and several use cases for a improved Rails’ implementation<\/a>, based in Responders<\/a>, which encapsulates all the behavior in one class<\/a>, and can be added, modified or updated.<\/p>\n

After that, Inherited Resources<\/a> was outdated and envy. It needed to be updated and it was: responders has been available in Inherited Resources<\/a> for more than four months, and consequently in Rails 2.3.<\/p>\n

Everything looked great until we started to develop a fresh Rails 3 application. The main purpose of this fresh application is to be a sample of Rails 3 features, including generators and responders. Based on that, it doesn’t make sense to use a tool like Inherited Resources<\/a>, since it would abstract almost all controllers away and the application would no longer fit as an example.<\/p>\n

So we were there, building an application based on scaffold, and as we saw duplicated code we started to realize Inherited Resources<\/a> contains a lot of tools that could be used outside its context. And this is what is happening right now, two new gems are being launched: Responders<\/a> and HasScope<\/a>.<\/p>\n

Responders<\/h3>\n

Responders<\/a> is a repository of Rails 3 responders<\/a>, mainly based on this post on Ruby on Rails weblog<\/a>. And as a proof of concept, we wrote two Responders: FlashResponder<\/a> and HttpCacheResponder<\/a>.<\/p>\n

FlashResponder<\/a> uses I18n to automatically look up flash messages for you, even allowing you to set generic messages. In other words, your old create action:<\/p>\n

\r\n  def create\r\n    @post = Post.new(params[:post])\r\n    flash[:notice] = \"Post was successfully created\" if @post.save\r\n    respond_with(@post)\r\n  end\r\n<\/pre>\n

Can now be written as:<\/p>\n

\r\n  def create\r\n    @post = Post.new(params[:post])\r\n    @post.save\r\n    respond_with(@post)\r\n  end\r\n<\/pre>\n

Your locale just needs to have the following configuration:<\/p>\n

\r\n  flash:\r\n    actions:\r\n      create:\r\n        notice: \"{resource_name} was successfully created\"\r\n      update:\r\n        notice: \"{resource_name} was successfully updated\"\r\n      destroy:\r\n        notice: \"{resource_name} was successfully destroyed\"\r\n        alert: \"{resource_name} could not be destroyed\"\r\n<\/pre>\n

If you want to change a message, let’s say, the success message when creating a post, there are several ways to achieve that. You can give :notice to respond_with<\/em> or even update your I18n under the key: “flash.posts.create.notice”<\/em>.<\/p>\n

For us it came as a nice tool to provide I18n by default in our controllers and decouple messages from code.<\/p>\n

The HttpCacheResponder<\/a> automatically adds a Last-Modified header to API requests without any extra configuration. This allows clients to easily query the server if a resource changed and also replies with 304 (Not Modified) status.<\/p>\n

As usual, the code for both implementations came from Inherited Resources<\/a>. And since it contains a Rails 3.0 Responders shim, those responders can already be used in Inherited Resources<\/a> and they are!<\/p>\n

In other words, Inherited Resources<\/a> code got simplified and such features can now be used by any Rails 3 application without a need to load all Inherited Resources<\/a> stack. Besides, as more Responders appears, they can be added to Responders<\/a> repository and be used in Inherited Resources<\/a> easily.<\/p>\n

HasScope<\/h3>\n

The other tool extracted from Inherited Resources<\/a> is HasScope<\/a>. <\/p>\n

Let’s suppose that we have a ProjectsController and at some point you want to add some filters on the index action like showing just featured projects, selecting projects by methodology or even let the user choose how many projects he can see per page. The first thing to do? Add named scopes to your model:<\/p>\n

\r\nclass Project < ActiveRecord::Base\r\n  named_scope :featured, :conditions => { :featured => true }\r\n  named_scope :by_methodology, proc {|methodology| { :conditions => { :methodology => methodology } } }\r\n  named_scope :limit, proc{|limit| :limit => limit.to_i }\r\nend\r\n<\/pre>\n

The next step would be to add a lot of code in your controllers that check which named scopes you should call, based on the parameters sent right? Well, not anymore. Your controller can be as simple as:<\/p>\n

\r\nclass ProjectsController < ApplicationController\r\n  has_scope :featured, :type => :boolean\r\n  has_scope :by_methodology\r\n  has_scope :limit, :default => 10, :only => :index\r\n\r\n  def index\r\n    @projects = apply_scopes(Project).all\r\n  end\r\nend\r\n<\/pre>\n

Then for each request:<\/p>\n

\r\n\/projects\r\n#=> acts like a normal request, but returning only 10 projects\r\n\r\n\/projects?featured=true\r\n#=> calls the featured named scope and bring 10 featured projects\r\n\r\n\/projects?featured=true&by_methodology=agile&limit=20\r\n#=> brings 20 featured projects with methodology agile\r\n<\/pre>\n

If you configure your routes, you could even have pretty urls with it:<\/p>\n

\r\n\/projects\/agile\/featured\r\n#=> brings 10 featured projects with methodology agile\r\n<\/pre>\n

All in all, you can now call has_scope in any controller and in case you are using it inside an Inherited Resources controller, everything gets handled automatically, so enjoy!<\/p>\n

So Inherited Resources finally reaches 1.0<\/h3>\n

After this refactoring and a complete clean up of Inherited Resources<\/a> issues, it finally reaches 1.0! When you install it, responders and has_scope gems should be installed as well. Responders is always loaded, since it’s a dependency, but if you want to use has_scope you will need to add it to your environment as well.<\/p>\n

After you install the gem, the upgrade process in any application can be handled in three steps:<\/p>\n

1) Add config.gem “has_scope”<\/em> to your “config\/environment.rb”<\/em>.<\/p>\n

2) Configure which flash keys are used by your application. At first, Inherited Resources<\/a> used :notice and :error. Then we changed to :success and :failure, but just after this DHH established :notice and :alert as Rails default.<\/p>\n

From 1.0 on, Inherited Resources<\/a> will be using :notice and :alert, but it allows you to change it:<\/p>\n

\r\n  InheritedResources.flash_keys = [ :success, :failure ]\r\n<\/pre>\n

3) Finally, you may need to do a final change in your application due to how responders work. The default way a resource tells a responder if it was created\/updated\/destroyed with success or not, is through errors. If the errors are empty, it assumes it succeeded, otherwise it failed.<\/p>\n

This will be true in all create\/update scenarios, but not in destroy. In other words, if you have a code with similar structure in your model (please don’t!):<\/p>\n

\r\n  def before_destroy\r\n    if some_condition_is_not_valid?\r\n      false\r\n    else\r\n      true\r\n    end\r\n  end\r\n<\/pre>\n

It won’t work anymore. You need to add an error to your model to really invalidate it:<\/p>\n

\r\n  def before_destroy\r\n    if some_condition_is_not_valid?\r\n      errors.add(fault_attribute, :invalid)\r\n      false\r\n    else\r\n      true\r\n    end\r\n  end\r\n<\/pre>\n

Now you should be ready to go. Enjoy!<\/p>\n","protected":false},"excerpt":{"rendered":"

Inherited Resources always had a hate\/love history with Rails Edge. Just after DHH posted about respond_with, it was already there in Inherited Resources. This initial implementation provided a nice test suite and several use cases for a improved Rails’ implementation, based in Responders, which encapsulates all the behavior in one class, and can be added, … \u00bb<\/a><\/p>\n","protected":false},"author":4,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"ngg_post_thumbnail":0,"footnotes":""},"categories":[1],"tags":[24,23,7,17,57],"aioseo_notices":[],"jetpack_sharing_enabled":true,"jetpack_featured_media_url":"","_links":{"self":[{"href":"https:\/\/blog.plataformatec.com.br\/wp-json\/wp\/v2\/posts\/525"}],"collection":[{"href":"https:\/\/blog.plataformatec.com.br\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/blog.plataformatec.com.br\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/blog.plataformatec.com.br\/wp-json\/wp\/v2\/users\/4"}],"replies":[{"embeddable":true,"href":"https:\/\/blog.plataformatec.com.br\/wp-json\/wp\/v2\/comments?post=525"}],"version-history":[{"count":13,"href":"https:\/\/blog.plataformatec.com.br\/wp-json\/wp\/v2\/posts\/525\/revisions"}],"predecessor-version":[{"id":910,"href":"https:\/\/blog.plataformatec.com.br\/wp-json\/wp\/v2\/posts\/525\/revisions\/910"}],"wp:attachment":[{"href":"https:\/\/blog.plataformatec.com.br\/wp-json\/wp\/v2\/media?parent=525"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/blog.plataformatec.com.br\/wp-json\/wp\/v2\/categories?post=525"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/blog.plataformatec.com.br\/wp-json\/wp\/v2\/tags?post=525"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}