Sha256: 45d07f00bf145d5e0816bfa8fb1fb4c03489c55e86b7b782516d9d1510a17b98

Contents?: true

Size: 1.64 KB

Versions: 7

Compression:

Stored size: 1.64 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 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

    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

7 entries across 7 versions & 1 rubygems

Version Path
ninja-model-0.5.7 lib/ninja_model/relation.rb
ninja-model-0.5.6 lib/ninja_model/relation.rb
ninja-model-0.5.5 lib/ninja_model/relation.rb
ninja-model-0.5.4 lib/ninja_model/relation.rb
ninja-model-0.5.3 lib/ninja_model/relation.rb
ninja-model-0.5.2 lib/ninja_model/relation.rb
ninja-model-0.5.1 lib/ninja_model/relation.rb