Commit eab7be2b by Wes Ketchum

add to_query! for stricter validations

parent a86d5646
...@@ -67,6 +67,16 @@ query.to_query(params[:q]) ...@@ -67,6 +67,16 @@ query.to_query(params[:q])
# => { name: 'Pablo', '$or' => { middle_name: /Cantero/i, last_name: /Cantero/i } } # => { 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 ## Contributing
1. Fork it ( https://github.com/phstc/ransack_mongo/fork ) 1. Fork it ( https://github.com/phstc/ransack_mongo/fork )
......
...@@ -34,6 +34,16 @@ module RansackMongo ...@@ -34,6 +34,16 @@ module RansackMongo
db_adapter.to_query db_adapter.to_query
end 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) def or_query(db_adapter, attr, value, p)
db_adapter.or_op do db_adapter.or_op do
attr.split('_or_').each do |or_attr| attr.split('_or_').each do |or_attr|
......
...@@ -32,6 +32,19 @@ module RansackMongo ...@@ -32,6 +32,19 @@ module RansackMongo
end end
context 'when MongoAdapter' do 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 describe '#to_query' do
it 'returns the query' do it 'returns the query' do
params = { 'name_eq' => 'Pablo', 'fullname_cont' => 'Cantero' } 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