From: "David A. Black" Date: 2009-09-24T20:14:56+09:00 Subject: Re: Monkey Patching 2 Methods, Overrides One Method, Not The Other --1926193751-701430878-1253790882=:7493 Content-Type: MULTIPART/MIXED; BOUNDARY="1926193751-701430878-1253790882=:7493" This message is in MIME format. The first part should be readable text, while the remaining parts are likely unreadable without MIME-aware tools. --1926193751-701430878-1253790882=:7493 Content-Type: TEXT/PLAIN; charset=ISO-8859-1; format=flowed Content-Transfer-Encoding: 8BIT Hi -- On Thu, 24 Sep 2009, MaggotChild wrote: > On Sep 17, 5:02�am, "David A. Black" wrote: >> I think I'd have to see >> code that exhibits the problem you're describing in order to analyze > > This is suited for the Rails group, but the problem can be seen in its > simplest form here: > > #config/initializers/ar_attributes.rb > > module ActiveRecord > module AttributeMethods > > alias_method :ar_read_attribute, :read_attribute > def read_attribute(attr_name) > p "read_override" > ar_read_attribute(attr_name) > end > > alias_method :ar_write_attribute, :write_attribute > def write_attribute(attr_name, value) > raise 'You made it!' > end > end > end > > In the Rails console: > >>> person.read_attribute :name > "read_override" > => "Joe" >>> person.write_attribute :name, "Bilal" > => "Bilal" >>> person.read_attribute :name > "read_override" > => "Bilal" OK, here's what's happening. On startup, ActiveRecord::Base mixes in a module called Dirty. That module includes the instruction: def self.included(base) # ... base.alias_method_chain :write_attribute, :dirty # ... end At that point, write_attribute is now an instance method of ActiveRecord::Base -- and your initializer has not yet been run. That means that when you run the initializer and make the change in the AttributesMethod module, it's too late: write_attribute has been copied and put directly in the class. Of course you can change it in the initializer, if you open AR::Base. But anyway, that's why the change in the module is not having any effect. David -- David A. Black, Director Ruby Power and Light, LLC (http://www.rubypal.com) Ruby/Rails training, consulting, mentoring, code review Book: The Well-Grounded Rubyist (http://www.manning.com/black2) --1926193751-701430878-1253790882=:7493-- --1926193751-701430878-1253790882=:7493--