inasuma
inasuma

Reputation: 11

Can you pass a _tag as a rails helper argument?

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?

Upvotes: 1

Views: 238

Answers (2)

max
max

Reputation: 101831

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

Upvotes: 0

Michael Kohl
Michael Kohl

Reputation: 66837

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.

Upvotes: 2

Related Questions