:birthday end class Dog def breed @breed end def breed=(breed) @breed = breed end def age @age end def birthday=(birthday) @birthday = birthday end end attr_* Macros
was a great #{beer}!" } def buy_beer(beer) puts "Just bought some #{beer}!" end end pete = BeerDrinker.new pete.drink_beer("Heady Topper") pete.buy_beer("Natty Light") 101: Dynamic Methods define_method equivalent
puts "#{klass} just inherited the Animal class" end def self.method_added(method) puts "The method '#{method}' was just added" end end class Dog < Animal def bark? true end end # => "Dog just inherited the Animal class"" # => "The method 'bark?' was just added"
> ?', 6.months.ago) scope :profitable, where('gross > budget') def self.filter_by_title(title) where('title LIKE ?', "%#{title}%") end def release_year released_at.year end def profitable? gross > budget end end A class that manages collections and instances
Movies scope :recent, where('released_at > ?', 6.months.ago) scope :profitable, where('gross > budget') def self.filter_by_title(title) where('title LIKE ?', "%#{title}%") end end
< Herd::Base model Movie # optional scope :recent, where('released_at > ?', 6.months.ago) scope :profitable, where('gross > budget') def self.filter_by_title(title) where('title LIKE ?', "%#{title}%") end end
models and must be “registered” so that ActiveRecord::Relation classes are aware of them. Collections need to “inherit” collection methods from their members
= self.method(method_name).to_proc @model_class.define_singleton_method(method_name, method) end # ...omitted... end end Code Walkthrough Registering Collection Methods on Model Callback Context Probe Dynamic Method Callback
ArgumentError, 'collection must inherit from Herd::Base' end herd_collection end end end ActiveRecord::Base.extend Herd::ActiveRecord Code Walkthrough Working with ActiveRecord Introspection Extending ActiveRecord class Movie < ActiveRecord::Base herded_by Movies end
name implicitly from the collection name' do Directors.create!(:name => 'Richard Donner') Directors.all.should have(1).director end it 'should delegate class methods to model' do Movies.find_by_name('The Goonies').should == movie1 end