You can do it, but you’ve got to be careful because you cant simply
write
def <<_without_extra(*args)
Ruby sees the “<<” as the beginning of a heredoc. Something like this
should
work, making sure method names starting with “<<” are defined with
strings:
class Array
define_method “<<_with_extra” do |*args|
# Do whatever you like here
send("<<_without_extra")
end
alias_method_chain :<<, :extra
end
That should work as expected, but there may be a better way to stop
duplicates being added to the association. If it is a has_many :through
you
could add uniqueness validation on the join model, or if it’s
has_and_belongs_to_many you could use the :uniq option on the
association.
define_method “<<_with_extra” do |*args|
has_and_belongs_to_many you could use the :uniq option on the association.
-Jonathan.
It is a has_many :through, but I didn’t realise that the :uniq option
would
prevent duplicates from being added. That’s all I’m really after. I
guess
I should realize by now that these kinds of things are already easy!
Cheers
This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.