I have two form field types ( f.text_field
or f.text_area
) that I want to define through a helper:
def helper_thing(tagtype, field_id)
tagtype("#{field_id}", class: 'input-group-field')
end
I want to use tagtype
as a variable for either form text helper in the view (using haml):
= helper_thing(f.text_field, 'random_id')
I'm hoping the output would be something like:
f.text_field('random_id')
I always get an error saying "invalid number of args 0 of 1..3)" essentially causing the rest of my arguments to fail. For the sake of brevity I only used one argument in my example though.
Is what I'm trying to do possible?
Yes, it's possible:
def helper_thing(form, tagtype, field_id)
form.send(tagtype, "#{field_id}", class: 'input-group-field')
end
Call:
= helper_thing(f, :text_field, 'random_id')
The problem with your attempt was that you tried to pass in f.text_field
, which is a call of the text_field
method on f
without arguments. Since said method expects 1-3 arguments you end up with the error you saw.
Besides Michael Kohls excellent answer there is one additional way of doing this without changing the method signature.
Since parens are optional in Ruby all objects have a special method
method which can be used if you want a reference to a method - without calling it:
= helper_thing(f.method(:text_field), 'random_id')
Then use .call
on the passed Method object:
def helper_thing(tagtype, field_id)
tagtype.call("#{field_id}", class: 'input-group-field')
end
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.