Update queryable interface so that it doesn't mutate
This commit is contained in:
parent
87aa288f1e
commit
2e70cc5d99
3 changed files with 36 additions and 9 deletions
|
@ -29,3 +29,7 @@ Feature: Queryable Selector
|
|||
Then should support ordering by attribute descending
|
||||
Then should order by attribute ascending by default
|
||||
Then should exclude documents that do not own the attribute
|
||||
Scenario: Passing queries around
|
||||
Given a simple 'where' query
|
||||
When I chain a where clause onto that query
|
||||
Then the original query should remain unchanged
|
||||
|
|
|
@ -1,3 +1,15 @@
|
|||
Given /^a simple 'where' query$/ do
|
||||
@query = Middleman::Sitemap::Queryable::Query.new({}).where(:foo => 'bar')
|
||||
end
|
||||
|
||||
When /^I chain a where clause onto that query$/ do
|
||||
@new_query = @query.where(:baz => 'foo')
|
||||
end
|
||||
|
||||
Then /^the original query should remain unchanged$/ do
|
||||
@query.should_not eql @new_query
|
||||
end
|
||||
|
||||
Then /^should initialize with an attribute and an operator$/ do
|
||||
selector = ::Middleman::Sitemap::Queryable::Selector.new :attribute => :author, :operator => 'equal'
|
||||
:author.should == selector.attribute
|
||||
|
|
|
@ -65,9 +65,12 @@ module Middleman
|
|||
end
|
||||
|
||||
class Query
|
||||
def initialize(model)
|
||||
def initialize(model, opts={})
|
||||
@model = model
|
||||
@where = {}
|
||||
@where = opts[:where] || {}
|
||||
@order_by = opts[:order_by]
|
||||
@offset = opts[:offset]
|
||||
@limit = opts[:limit]
|
||||
end
|
||||
|
||||
def where(constraints_hash)
|
||||
|
@ -78,22 +81,30 @@ module Middleman
|
|||
selector_hash.update({ selector => value })
|
||||
end
|
||||
@where.merge! selector_hash
|
||||
self
|
||||
Query.new @model, opts
|
||||
end
|
||||
|
||||
def opts
|
||||
{ :where => @where,
|
||||
:order_by => @order_by,
|
||||
:offset => @offset,
|
||||
:limit => @limit
|
||||
}
|
||||
end
|
||||
|
||||
def order_by(field)
|
||||
@order_by = field.is_a?(Symbol) ? {field => :asc} : field
|
||||
self
|
||||
Query.new @model, opts
|
||||
end
|
||||
|
||||
def offset(number)
|
||||
@offset = number
|
||||
self
|
||||
Query.new @model, opts
|
||||
end
|
||||
|
||||
def limit(number)
|
||||
@limit = number
|
||||
self
|
||||
Query.new @model, opts
|
||||
end
|
||||
|
||||
def first
|
||||
|
|
Loading…
Add table
Reference in a new issue