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.
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.
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
This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.