Sha256: 07ea8a565f4c5fa68dc8979afa101be98581db803852210c761fe154738892e5

Contents?: true

Size: 1.48 KB

Versions: 2

Compression:

Stored size: 1.48 KB

Contents

class Cistern::Collection < Array
  extend Cistern::Attributes::ClassMethods
  include Cistern::Attributes::InstanceMethods

  %w[reject select slice].each do |method|
    define_method(method) do |*args, &block|
      unless @loaded
        lazy_load
      end
      data = super(*args, &block)
      self.clone.clear.concat(data)
    end
  end

  %w[first last].each do |method|
    define_method(method) do
      unless @loaded
        lazy_load
      end
      super()
    end
  end

  def self.model(new_model=nil)
    if new_model == nil
      @model
    else
      @model = new_model
    end
  end

  def initialize(attributes = {})
    @loaded = false
    merge_attributes(attributes)
  end

  def create(attributes={})
    model = self.new(attributes)
    model.save
  end

  def get(identity)
    raise NotImplementedError
  end

  def clear
    @loaded = true
    super
  end

  def model
    self.class.instance_variable_get('@model')
  end

  attr_accessor :connection

  def new(attributes = {})
    unless attributes.is_a?(::Hash)
      raise(ArgumentError.new("Initialization parameters must be an attributes hash, got #{attributes.class} #{attributes.inspect}"))
    end
    model.new(
      attributes.merge(
        :collection => self,
        :connection => connection
      )
    )
  end

  def load(objects)
    clear
    for object in objects
      self << new(object)
    end
    self
  end

  def reload
    clear
    lazy_load
    self
  end

  private

  def lazy_load
    self.all
  end
end

Version data entries

2 entries across 2 versions & 1 rubygems

Version Path
cistern-0.1.4 lib/cistern/collection.rb
cistern-0.1.2 lib/cistern/collection.rb