Commit 1bf007f8 by Pablo Cantero

Merge pull request #1 from WesKetch/master

add to_query! for stricter validations
parents a86d5646 eab7be2b
......@@ -2,7 +2,7 @@
[![Build Status](https://travis-ci.org/phstc/ransack_mongo.svg)](https://travis-ci.org/phstc/ransack_mongo)
Ransack Mongo is based on [Ransack](https://github.com/activerecord-hackery/ransack), but for MongoDB.
Ransack Mongo is based on [Ransack](https://github.com/activerecord-hackery/ransack), but for MongoDB.
With Ransack Mongo you can convert query params into Mongo queries.
......@@ -67,6 +67,16 @@ query.to_query(params[:q])
# => { name: 'Pablo', '$or' => { middle_name: /Cantero/i, last_name: /Cantero/i } }
```
### to_query!
You can use to_query! for stricter validations. This method will raise an exception if a query cannot be produced.
```ruby
query.to_query({ name: 'Pablo' })
# => {}
query.to_query!({ name: 'Pablo' })
# => RansackMongo::MatcherNotFound: No matchers found. To allow empty queries use .to_query instead
```
## Contributing
1. Fork it ( https://github.com/phstc/ransack_mongo/fork )
......
......@@ -34,6 +34,16 @@ module RansackMongo
db_adapter.to_query
end
def to_query!(params)
selector = to_query params
if selector.empty?
raise MatcherNotFound, "No matchers found. To allow empty queries use .to_query instead"
end
selector
end
def or_query(db_adapter, attr, value, p)
db_adapter.or_op do
attr.split('_or_').each do |or_attr|
......
......@@ -32,6 +32,19 @@ module RansackMongo
end
context 'when MongoAdapter' do
describe '#to_query!' do
it 'raises exception when query evaluates to an empty hash' do
params = { 'name' => 'Pablo' }
expect { described_class.new.to_query!(params) }.to raise_error(MatcherNotFound)
end
it 'returns the query' do
params = { 'name_eq' => 'Pablo', 'fullname_cont' => 'Cantero' }
expect(described_class.new.to_query!(params)).to eq('name' => 'Pablo', 'fullname' => /Cantero/i)
end
end
describe '#to_query' do
it 'returns the query' do
params = { 'name_eq' => 'Pablo', 'fullname_cont' => 'Cantero' }
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment