Sha256: 287954661996ac3052c137d142d645ad358fec3c0446f7c046ba4f135427a20c

Contents?: true

Size: 1.95 KB

Versions: 3

Compression:

Stored size: 1.95 KB

Contents

require 'ninja_model/relation/query_methods'
require 'ninja_model/relation/finder_methods'
require 'ninja_model/relation/spawn_methods'

module NinjaModel
  class Relation
    include QueryMethods, FinderMethods, SpawnMethods

    delegate :length, :each, :map, :collect, :all?, :include?, :to => :to_a

    attr_reader :klass, :loaded

    attr_accessor :ordering, :predicates, :limit_value, :offset_value

    alias :loaded? :loaded

    SINGLE_VALUE_ATTRS = [:limit, :offset]
    MULTI_VALUE_ATTRS = [:ordering, :predicates]

    def initialize(klass)
      @klass  = klass
      @loaded = false

      SINGLE_VALUE_ATTRS.each do |v|
        instance_variable_set("@#{v}_value".to_sym, nil)
      end

      MULTI_VALUE_ATTRS.each do |v|
        instance_variable_set("@#{v}".to_sym, [])
      end
    end

    def new(*args, &block)
      scoping { @klass.new(*args, &block) }
    end

    alias build new

    def to_a
      @records ||= begin
        records = @klass.adapter.read(self)
        @loaded = true
        records
      end
    end
    alias :to_ary :to_a

    def scoping
      @klass.scoped_methods << self
      begin
        yield
      ensure
        @klass.scoped_methods.pop
      end
    end

    def size
      to_a.length
    end

    def blank?
      empty?
    end

    def empty?
      size.zero?
    end

    alias :inspect! :inspect
    def inspect
      to_a.inspect
    end

    def scope_for_create
      Hash[@predicates.find_all { |w|
        w.respond_to?(:meth) && w.meth == :eq
      }.map { |where|
        [
          where.attribute,
          where.value
        ]
      }]
    end

    protected

    def method_missing(method, *args, &block)
      if Array.method_defined?(method)
        to_a.send(method, *args, &block)
      elsif @klass.scopes[method]
        merge(@klass.send(method, *args, &block))
      elsif @klass.respond_to?(method)
        scoping { @klass.send(method, *args, &block) }
      else
        super
      end
    end
  end
end

Version data entries

3 entries across 3 versions & 1 rubygems

Version Path
ninja-model-0.6.2 lib/ninja_model/relation.rb
ninja-model-0.6.1 lib/ninja_model/relation.rb
ninja-model-0.6.0 lib/ninja_model/relation.rb