alias_method_chain :<<

Hi

I’d like to modify the behavior of the << method so that duplicates are not appended to my AR objects association.

I thought I could just use alias_method_chain on it but I can’t seem to make the right method for it let alone make the call to alias_method_chain.

I tried in the console.

a = “”
=> “”

def a.<<_with_extra( *args )
puts “Test”
end

so that I could use
alias_method_chain :<<, :extra

How is this done?

Cheers
Daniel

Hi --

Hi

I'd like to modify the behavior of the << method so that duplicates are not
appended to my AR objects association.

I thought I could just use alias_method_chain on it but I can't seem to make
the right method for it let alone make the call to alias_method_chain.

I tried in the console.

a = ""

=> ""

def a.<<_with_extra( *args )

puts "Test"
end

so that I could use
alias_method_chain :<<, :extra

How is this done?

I think you're going to have to use a word, like "append_extra".
While << is a legitimate method name, <<_other_stuff is parsed as a
here-document.

Of course, you can smuggle in weird method names with define_method
and send:

   class << a
     define_method("<<_with_extra_args") {|*args| ... }
   end

   a.send("<<_with_extra_args",x,y,z)

but that of course is awkward and opaque.

David

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.

-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