Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create multiple identical methods in Ruby

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?

like image 412
superluminary Avatar asked Jan 10 '13 12:01

superluminary


2 Answers

%w(lendable free skill).each do |name|
  define_method "#{name}_category" do |i|
    set_category(i)
  end
end
like image 105
sailor Avatar answered Oct 26 '22 20:10

sailor


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
like image 23
Andrew Haines Avatar answered Oct 26 '22 21:10

Andrew Haines