Pastie now auto-senses if line-wrap is a bad or good idea. Feedback?
## mark a section (Learn more)
## phase 3 (by technoweenie from http://pastie.caboo.se/32063) # Now the incoming/outgoing methods are on item, so you can do: # # Item.incoming(:all, :order => 'created_at desc', :limit => 15) # # or # # @asset.items.incoming(:all, :order => 'created_at desc', :limit => 15) class Item < ActiveRecord::Base belongs_to :asset def self.incoming(*args) with_scope(:find => { :conditions => 'base_amount > 0'}) { find(*args) } end def self.outgoing(*args) with_scope(:find => { :conditions => 'base_amount < 0'}) { find(*args) } end end class Asset < ActiveRecord::Base has_many :items, :dependent => :destroy_all end ## phase 4 # Now the incoming/outgoing methods are on Item, so you can do: # # Item.incoming(:all, :order => 'created_at desc', :limit => 15) # # but, there is also memoization in the Asset # # @asset.incoming_items(:all, :order => 'created_at desc', :limit => 15) class Item < ActiveRecord::Base belongs_to :asset def self.incoming(*args) with_scope(:find => { :conditions => 'base_amount > 0'}) { find(*args) } end def self.outgoing(*args) with_scope(:find => { :conditions => 'base_amount < 0'}) { find(*args) } end end class Module def memoized_subcollection(pklass, name, conditions=nil) class_eval <<-STR def #{name}_#{pklass}(reload=false) @#{name}_#{pklass} = nil if reload @#{name}_#{pklass} ||= #{pklass.to_s.singularize.camelize}.#{name}(#{conditions}) end STR end end class Asset < ActiveRecord::Base has_many :items, :dependent => :destroy_all memoized_subcollection(:items, :incoming) memoized_subcollection(:items, :outgoing) end
This paste will be private.
From the Design Piracy series on my blog: