2007年5月17日木曜日

[Rails] Accessing :object_name :method passed from the view in your custom helpers

While making a wrapper helper to extend the functionality of the stock date_select, I needed to access the actual date object attributes within the helper method.

The api of the date_select helper is like this:

date_select(object_name, method, options = {})

Where object_name is is the object in the template, and method is the method of that object which returns a date for the select boxes to show.

I wanted to make an enhanced version of the date_select with some javascript goodness, while maintaining the same parameters, and needed the actual date object so I can use it on the javascript output.
Basically I needed to do this:
date = object_name.method

Here is how I did it:

def ajax_date_select(object_name, method, options = {})
# Get the object_name.method value
date = instance_variable_get("@#{object_name.to_s.dup}").send(method.to_s.dup)


The instance_variable_get method allows you to reference the variables in the rendered view.
So for example in the controller, if you said something like:

@hoge = Hoge.find(1)

and in the view:

<%= ajax_date_select :hoge :created_at %>

by using instance_variable_get, you can do the equivalent of

date = hoge.created_at

from within the custom helper code.

0 コメント: