I would make this code shorter.
def foo type, user
if type == "foo"
user.foo
elsif type == "bar"
user.bar
end
end
user is ActiveRecord object
type is string "foo" or "bar"
If I have more types then I need to make more elsif. It's possible to make it shorter (without using the model method or any other additional code) using type variable as a column name? Something like:
user.{type} # ???
CodePudding user response:
You may use public_send to achieve this:
user.public_send(type)
