Custom view helpers

Hi all,

I would like to write some custom helpers like the ones available as
form helpers text_field, text_area and the like. My first try was this:

custom_helper(obj, meth)
‘some_string’ + obj.send(meth) + ‘some_other_string’
end

Object and method are being passed as symbols like this:

custom_helper(:person, :name)

and Ruby rightfully complains that the symbol person does not have a
method named name. Second try was this. @person is an instance
variable of the controller, right?

custom_helper(obj, meth)
‘some_string’ + self.get_instance_variable(obj).send(meth) +
‘some_other_string’
end

and I get “`person’ is not allowed as an instance variable name”.

How does Rails do that? I can see the text_field being Implemented
like this:

InstanceTag.new(object, method, self)

but I have no idea what the InstanceTag class does or where I can
find it.

Many thanks in advance for any pointers!

–Nicky

2006/2/1, Nickolay K. [email protected]:

Hi all,

I would like to write some custom helpers like the ones available as
form helpers text_field, text_area and the like. My first try was this:

custom_helper(obj, meth)
‘some_string’ + obj.send(meth) + ‘some_other_string’
end

In your views just call custom_helper(@person, :name)

In your views just call custom_helper(@person, :name)

That was kind of obvious. I want to know how the ‘official’ helpers
are implemented so that they can work with symbols as well as stings
being passed as parameters.

Nicky

Source code: actionpack/lib/action_view/helpers/form_helper.rb

2006/2/1, Nickolay K. [email protected]:

That was kind of obvious. I want to know how the ‘official’ helpers
are implemented so that they can work with symbols as well as
stings being passed as parameters.

I had worked around it when I needed it but stumbled across the
solution today. This is an excerpt from code for the
error_messages_for method:

instance_variable_get("@#{obj.to_s}")

I had not realised the parameter to instance_variable_get should be a
string or a symbol with an @-sign up front. I guess I should have
looked it up first, it is well documented in the Pickaxe book.

Nicky