In one of my models I have code like this:
def lendable_category=(i)
set_category(i)
end
def free_category=(i)
set_category(i)
end
def skill_category=(i)
set_category(i)
end
The methods are virtual parameters which I've added so I can save an object using a params hash without coercing the hash in my controller.
It doesn't feel great to say the same thing three times. Is there a better way to create identical methods like this?
%w(lendable free skill).each do |name|
define_method "#{name}_category" do |i|
set_category(i)
end
end
Alternatively, since your methods aren't doing anything other than calling set_category
, you can save a couple of lines by just aliasing the method:
%w(lendable free skill).each do |name|
alias_method "#{name}_category=", :set_category
end
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With