Posted in Uncategorized

self.send

In Ruby the send method is a helper in passing a method and its arguments to the corresponding object. Its a way to DRY things up, but if you dont know what you are looking at, it can be really confusing.

class Report
  def basic
    “This is a basic report"
  end

  def complex
    “This is a complex report"
  end
end

@report = Report.new
@report.send(:basic)# same thing as @report.basic
>> “This is a basic report”

My initial confusion was in the context of a controller action ‘show’ —

  def show
    @sub_title = "Reports: " + @report.title
    self.send(@report.type)
    respond_to do |format|
      format.html
      format.xml
    end
  end

@report is instantiated in a before_filter based on what a user selected on the index page. In this particular case, self is the controller object, so you find the @report.type which is the report type attribute, is also a method within the controller.

Lets call type in the this case ‘basic’, so you would find in the controller(in my case) a method corresponding to it…although,I would likely move this to a controller helper to keep the controller skinny.

  def basic
    
  end

As you can imagine, this gives you alot of flexibity in building out templates and supplying the needed objects to each report.

Advertisements

Author:

I love finding resources that help me do life.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s