Sha256: 8de5c64d15f9afc335a8bc72681eba1502cbb352c82b133bf4ec608145f84608

Contents?: true

Size: 1.1 KB

Versions: 6

Compression:

Stored size: 1.1 KB

Contents

require 'active_support/core_ext'

class Mailroute::Relation
  delegate :inspect, :each, :count, :&, :to_ary, :all?, :empty?, :to => :to_a
  include Enumerable

  attr_reader :search_options

  def initialize(klass, search_options = {})
    @klass = klass
    @search_options = search_options
  end

  def to_a
    @records ||= @klass.all(search_options)
  end

  def limit(n)
    new_relation(:params => { :limit => n })
  end

  def offset(n)
    new_relation(:params => { :offset => n })
  end

  def filter(options)
    new_relation(:params => options)
  end

  def order_by(attribute)
    new_relation(:params => { :order_by => attribute })
  end

  def search(term)
    new_relation(:params => { :q => term })
  end

  def ==(other)
    case other
    when Relation
      search_options == other.search_options
    when Array
      to_a == other
    else
      false
    end
  end

  def total_count
    meta = to_a.instance_variable_get(:@_meta)
    meta && meta['total_count']
  end

  private

  def new_relation(options_update)
    Mailroute::Relation.new(@klass, search_options.deep_merge(options_update))
  end
end

Version data entries

6 entries across 6 versions & 1 rubygems

Version Path
mailroute-0.0.6 lib/mailroute/extensions/relation.rb
mailroute-0.0.5 lib/mailroute/extensions/relation.rb
mailroute-0.0.4 lib/mailroute/extensions/relation.rb
mailroute-0.0.3 lib/mailroute/extensions/relation.rb
mailroute-0.0.2 lib/mailroute/extensions/relation.rb
mailroute-0.0.1 lib/mailroute/extensions/relation.rb