Forum: Ruby on Rails Custom view helpers

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
Nickolay K. (Guest)
on 2006-02-01 11:52
(Received via mailing list)
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
Lugovoi N. (Guest)
on 2006-02-01 11:52
(Received via mailing list)
2006/2/1, Nickolay K. <removed_email_address@domain.invalid>:
> 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)
Nickolay K. (Guest)
on 2006-02-01 11:52
(Received via mailing list)
> 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
Lugovoi N. (Guest)
on 2006-02-01 14:49
(Received via mailing list)
Source code: actionpack/lib/action_view/helpers/form_helper.rb

2006/2/1, Nickolay K. <removed_email_address@domain.invalid>:
Nickolay K. (Guest)
on 2006-02-08 08:49
(Received via mailing list)
> 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 topic is locked and can not be replied to.