Sunday, February 13, 2011

Sharing code in respond_to blocks

I have the following before_filter:

  def find_current_membership
    respond_to do |wants|
      wants.html { @current_membership = @group.memberships.for(@current_user) }
      wants.rss  {}
      wants.js   { @current_membership = @group.memberships.for(@current_user) }
    end
  end

I would like to share the code for the HTML and JS blocks. Is there a better way than just throwing the code into a method? I was hoping this would work:

  def find_current_membership
    respond_to do |wants|
      wants.rss  {}
      wants.all  { @current_membership = @group.memberships.for(@current_user) }
    end
  end

But alas, it did not.

  • In this case you could probably do something like:

    before_filter :only => :find_current_membership do |c|
        load_current_membership if not request.format.rss?
    end
    

    Alternatively you could use the request.format.rss? in your controller method to conditionally load the memberships.

    Either way your first step should be to refactor that into a method.

    From jonnii
  • If I'm reading this right, it looks like find_current_membership is your before_filter method, is that right? eg:

    class SomeController < ApplicationController
      before_filter :find_current_membership
      ...
    

    I think it's a bit non-standard to use respond_to inside a before_filter, they are meant to just do something and render on failure. It seems to me like you want something more like this

        class SomeController < ApplicationController
          before_filter :find_current_membership
    
          def some_action
            # stuff, or maybe nothing
          end
    
       private
          def find_current_membership
             @current_membership = @group.memberships.for(@current_user) unless request.format.rss?
          end
       end
    
  • How about this simple solution!?

    def find_current_membership
      @current_membership = @group.memberships.for(@current_user)
      respond_to do |wants|
        wants.html
        wants.rss  {}
        wants.js
      end
    end
    
    From allesklar

0 comments:

Post a Comment