Sha256: 715e1143eb7f02aff4ba048933a2e13e4c0c3830f4ba8b0c92504526b2df43cc

Contents?: true

Size: 1.05 KB

Versions: 1

Compression:

Stored size: 1.05 KB

Contents

module CurlyMustache
  class AssociationCollection
    
    delegate :[], :inspect, :length, :to => :implementation
    
    def initialize(owner, reflection)
      @owner, @reflection = owner, reflection
      reload
    end
    
    def reload
      klass = @reflection[:class_name].constantize
      @array = klass.find(get_ids)
    end
    
    def to_a
      @array.dup
    end
    
    def <<(value)
      raise InvalidAssociation unless value.kind_of?(CurlyMustache::Base)
      @array << value
      ids = get_ids
      ids << value.id
      set_ids(ids)
    end
    
  private
    
    def implementation
      @array
    end
    
    def get_ids
      ids = @owner.send(foreign_key)
      if fkey_type == :string
        ids.split(',')
      else
        ids
      end
    end
    
    def set_ids(ids)
      ids = ids.join(',') if fkey_type == :string
      @owner.send("#{foreign_key}=", ids)
    end
    
    def foreign_key
      @reflection[:foreign_key]
    end
    
    def fkey_type
      @owner.send(:attribute_type, foreign_key)
    end
    
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
cjbottaro-curly_mustache-0.0.0 lib/association_collection.rb