Hi all:
For example I have:
class Color < ActiveRecord::Base
belongs_to :ball
end
class Ball < ActiveRecord::Base
has_many :colors
end
What I want to do is to write a method that:
- takes the result of Ball#colors, which is an array of Color objects
- do something with the array
- return the result
but I want to name my method Ball#colors, i.e. I want to overload the
generated association method:
class Ball < ActiveRecord::Base
def colors
# do something here
end
end
Is there anyway to do this?
Thanks,
Jesse
Hmmm… I’m thinking somewhere along the lines of using Object#method
to store the original method as a class variable, but this seems very
hacky to me. Is there any other way?
Best regards,
Jesse
Well, you could use the “alias” method:
http://ruby.about.com/od/learnruby/qt/using_alias.htm
But really, what you originally wrote is perfectly fine. The
has_many :colors just creates, among other things, a getter and setter
method. Then, by (re)defining “colors” via your “def colors…” code,
you are overriding that.
I did a quick test and it works just fine. You could still use alias
so you keep a reference to the assocation. For example, wrap it up in
a single class and do this:
class Ball < ActiveRecord::Base
has_many :colors
alias :old_colors :colors
def colors
puts "in new colors def
end
end
That works just fine.
-Danimal
Hi Danimal:
Your suggestion works perfectly! Thanks 
Best regards,
Jesse