require 'facet/string/singular' require 'facet/string/demodulize' require 'facet/string/underscore' require 'og/relation' require 'og/collection' module Og class HasManyCollection < Collection end # A 'has_many' relation. There should be a respective # 'belongs_to' relation. # # === Examples # # article.comments << Comment.new # article.comments.size class HasMany < Relation =begin def initialize(args, options = {}) super # TODO: clean this up. unless target_class.relations.find { |r| r.is_a?(BelongsTo) and r.target_class == owner_class } target_class.belongs_to(owner_class) end end =end def resolve_polymorphic if target_class.relations unless target_class.relations.find { |r| r.is_a?(BelongsTo) and r.target_class == owner_class } target_class.belongs_to(owner_class) end end end def enchant self[:owner_singular_name] = owner_class.to_s.demodulize.underscore.downcase self[:target_singular_name] = target_plural_name.to_s.singular self[:foreign_key] = "#{foreign_name || owner_singular_name}_#{owner_pk}" owner_class.module_eval %{ attr_accessor :#{target_plural_name} def #{target_plural_name}(options = nil) unless @#{target_plural_name} @#{target_plural_name} = HasManyCollection.new( self, :add_#{target_singular_name}, :remove_#{target_singular_name}, :find_#{target_plural_name}, options ) end @#{target_plural_name}.reload(options) if options and options[:reload] @#{target_plural_name} end def add_#{target_singular_name}(obj) obj.#{foreign_key} = @#{owner_pk} obj.save end def remove_#{target_singular_name}(obj) obj.#{foreign_key} = nil end def find_#{target_plural_name}(options = {}) find_options = { :condition => "#{foreign_key} = \#\{@#{owner_pk}\}" } find_options.update(options) if options #{"find_options.update(:order => #{options[:order].inspect})" if options[:order]} #{target_class}.find(find_options) end } end end end __END__