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:
1. takes the result of Ball#colors, which is an array of Color objects
2. do something with the array
3. 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
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?
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