Class: Middleman::Sitemap::Queryable::Query

Inherits:
Object
  • Object
show all
Defined in:
lib/middleman-core/sitemap/queryable.rb

Instance Method Summary collapse

Constructor Details

#initialize(model, opts = {}) ⇒ Query

Returns a new instance of Query.



68
69
70
71
72
73
74
# File 'lib/middleman-core/sitemap/queryable.rb', line 68

def initialize(model, opts={})
  @model = model
  @where = opts[:where] || {}
  @order_by = opts[:order_by]
  @offset = opts[:offset]
  @limit = opts[:limit]
end

Instance Method Details

#allObject



114
115
116
117
118
119
120
121
122
123
# File 'lib/middleman-core/sitemap/queryable.rb', line 114

def all
  result = @model.select(:where => @where, :order_by => @order_by)
  if @offset.present?
    result = result.last([result.size - @offset, 0].max)
  end
  if @limit.present?
    result = result.first(@limit)
  end
  result
end

#firstObject



106
107
108
# File 'lib/middleman-core/sitemap/queryable.rb', line 106

def first
  self.all.first
end

#lastObject



110
111
112
# File 'lib/middleman-core/sitemap/queryable.rb', line 110

def last
  self.all.last
end

#limit(number) ⇒ Object



102
103
104
# File 'lib/middleman-core/sitemap/queryable.rb', line 102

def limit(number)
  Query.new @model, opts(:limit => number)
end

#offset(number) ⇒ Object



98
99
100
# File 'lib/middleman-core/sitemap/queryable.rb', line 98

def offset(number)
  Query.new @model, opts(:offset => number)
end

#opts(new_opts) ⇒ Object



86
87
88
89
90
91
92
# File 'lib/middleman-core/sitemap/queryable.rb', line 86

def opts new_opts
  { :where => {}.merge(@where),
    :order_by => @order_by,
    :offset => @offset,
    :limit => @limit
  }.merge(new_opts)
end

#order_by(field) ⇒ Object



94
95
96
# File 'lib/middleman-core/sitemap/queryable.rb', line 94

def order_by(field)
  Query.new @model, opts(:order_by => field.is_a?(Symbol) ? {field => :asc} : field)
end

#where(constraints_hash) ⇒ Object



76
77
78
79
80
81
82
83
84
# File 'lib/middleman-core/sitemap/queryable.rb', line 76

def where(constraints_hash)
  selector_hash = constraints_hash.reject { |key, value| !key.is_a? Selector }
  symbol_hash = constraints_hash.reject { |key, value| key.is_a? Selector }
  symbol_hash.each do |attribute, value|
    selector = Selector.new(:attribute => attribute, :operator => 'equal')
    selector_hash.update({ selector => value })
  end
  Query.new @model, opts(:where => @where.merge(selector_hash))
end