Commit 3933f3b5 by Pablo Cantero

Initial commit

parents
*.gem
*.rbc
.bundle
.config
.yardoc
Gemfile.lock
InstalledFiles
_yardoc
coverage
doc/
lib/bundler/man
pkg
rdoc
spec/reports
test/tmp
test/version_tmp
tmp
source 'https://rubygems.org'
# Specify your gem's dependencies in ransack_mongo.gemspec
gemspec
Copyright (c) 2014 Pablo Cantero
MIT License
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
# Ransack Mongo
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.
## Installation
Add this line to your application's Gemfile:
gem 'ransack_mongo'
And then execute:
$ bundle
Or install it yourself as:
$ gem install ransack_mongo
## Usage
```ruby
# GET /customers?q[name_eq]=Pablo&q[middle_name_or_last_name_cont]=Cantero
# params[:q]
# => { name_eq: 'Pablo', middle_name_or_last_name_cont: 'Cantero' }
# query.to_query(params[:q])
# => { name: 'Pablo', '$or' => { middle_name: /Cantero/i, last_name: /Cantero/i } }
# GET /customers
def index
query = RansackMongo::Query.new
selector = query.to_query(params[:q])
# Mongo Ruby Driver
@customers = db.customers.find(selector)
# Mongoid
@customers = Customer.where(selector)
end
```
### Available predicates
* eq
* not_eq
* cont
* in
* gt
* lt
* gteq
* lteq
### OR operator
You can also combine predicates for OR queries.
```ruby
query_param = { name_eq: 'Pablo', middle_name_or_last_name_cont: 'Cantero' }
query.to_query(params[:q])
# => { name: 'Pablo', '$or' => { middle_name: /Cantero/i, last_name: /Cantero/i } }
```
## Contributing
1. Fork it ( https://github.com/phstc/ransack_mongo/fork )
2. Create your feature branch (`git checkout -b my-new-feature`)
3. Commit your changes (`git commit -am 'Add some feature'`)
4. Push to the branch (`git push origin my-new-feature`)
5. Create new Pull Request
require "bundler/gem_tasks"
require 'ransack_mongo/version'
require 'ransack_mongo/query'
require 'ransack_mongo/predicate'
require 'ransack_mongo/mongo_adapter'
module RansackMongo
# Your code goes here...
end
module RansackMongo
class MongoAdapter
PREDICATES = %w[eq not_eq cont in gt lt gteq lteq]
def initialize
@query = {}
end
def to_query
@query
end
def eq_matcher(attr, value)
@query[attr] = value
end
def not_eq_matcher(attr, value)
@query[attr] = { '$ne' => value }
end
def cont_matcher(attr, value)
@query[attr] = /#{value}/i
end
def in_matcher(attr, value)
@query[attr] = { '$in' => value }
end
def gt_matcher(attr, value)
@query[attr] ||= {}
@query[attr]['$gt'] = value.to_f
end
def lt_matcher(attr, value)
@query[attr] ||= {}
@query[attr]['$lt'] = value.to_f
end
def gteq_matcher(attr, value)
@query[attr] ||= {}
@query[attr]['$gte'] = value.to_f
end
def lteq_matcher(attr, value)
@query[attr] ||= {}
@query[attr]['$lte'] = value.to_f
end
def or_op # or operation
return unless block_given?
original_query = @query
@query = {}
yield
original_query['$or'] ||= []
original_query['$or'].concat @query.map { |attr, value| { attr => value } }
@query = original_query
end
def self.predicates
PREDICATES
end
end
end
module RansackMongo
class Predicate
def initialize(predicates)
@predicates = predicates
end
def parse(params)
params.keys.inject({}) do |query, query_param|
attr = query_param.to_s
p, attr = detect_and_strip_from_string(attr)
if p && attr
query[p] ||= []
query[p] << { 'attr' => attr, 'value' => params[query_param] }
end
query
end
end
def names_by_decreasing_length
@predicates.sort { |a, b| b.length <=> a.length }
end
def detect_from_string(str)
names_by_decreasing_length.detect { |p| str.end_with?("_#{p}") }
end
def detect_and_strip_from_string(str)
if p = detect_from_string(str)
[p, str.sub(/_#{p}$/, '')]
end
end
end
end
module RansackMongo
class MatcherNotFound < StandardError; end
# https://github.com/activerecord-hackery/ransack/wiki/Basic-Searching
class Query
def initialize(db_adapter_class = MongoAdapter)
@db_adapter_class = db_adapter_class
end
def to_query(params)
parsed_predicates = Predicate.new(@db_adapter_class.predicates).parse(params)
db_adapter = @db_adapter_class.new
parsed_predicates.keys.each do |p|
parsed_predicates[p].each do |parsed_predicate|
attr = parsed_predicate['attr']
value = parsed_predicate['value']
begin
if attr.include? '_or_'
# attr => name_or_lastname
or_query(db_adapter, attr, value, p)
else
# attr => name
db_adapter.send("#{p}_matcher", attr, value)
end
rescue NoMethodError => e
raise MatcherNotFound, "The matcher #{p} `#{p}_matcher` was not found in the #{@db_adapter_class.name}. Check `#{@db_adapter_class}.predicates`"
end
end
end
db_adapter.to_query
end
def or_query(db_adapter, attr, value, p)
db_adapter.or_op do
attr.split('_or_').each do |or_attr|
db_adapter.send("#{p}_matcher", or_attr, value)
end
end
end
end
end
module RansackMongo
VERSION = '0.0.1'
end
# coding: utf-8
lib = File.expand_path('../lib', __FILE__)
$LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
require 'ransack_mongo/version'
Gem::Specification.new do |spec|
spec.name = 'ransack_mongo'
spec.version = RansackMongo::VERSION
spec.authors = ['Pablo Cantero']
spec.email = ['pablo@pablocantero.com']
spec.homepage = 'https://github.com/phstc/ransack_mongo'
spec.summary = %q{Query params based searching for MongoDB}
spec.description = %q{Ransack Mongo is based on Ransack but for MongoDB}
spec.license = 'MIT'
spec.files = `git ls-files`.split($/)
spec.executables = spec.files.grep(%r{^bin/}) { |f| File.basename(f) }
spec.test_files = spec.files.grep(%r{^(test|spec|features)/})
spec.require_paths = ['lib']
spec.add_development_dependency 'bundler'
spec.add_development_dependency 'rake'
spec.add_development_dependency 'rspec'
end
require 'spec_helper'
module RansackMongo
describe MongoAdapter do
describe '#eq_matcher' do
it 'returns the matcher' do
subject.eq_matcher('name', 'Pablo')
expect(subject.to_query).to eq('name' => 'Pablo')
end
end
describe '#not_eq_matcher' do
it 'returns the matcher' do
subject.not_eq_matcher('name', 'Pablo')
expect(subject.to_query).to eq('name' => { '$ne' => 'Pablo' })
end
end
describe '#cont_matcher' do
it 'returns the matcher' do
subject.cont_matcher('name', 'Pablo')
expect(subject.to_query).to eq('name' => /Pablo/i)
end
end
describe '#in_matcher' do
it 'returns the matcher' do
subject.in_matcher('name', %w[Pablo Cantero])
expect(subject.to_query).to eq('name' => { '$in' => %w[Pablo Cantero] })
end
end
context 'when combine gt lt gteq and lteq' do
it 'returns all matchers' do
subject.gt_matcher('count', '1')
subject.lt_matcher('count', '5')
subject.gteq_matcher('quantity', '10.5')
subject.lteq_matcher('quantity', '15')
# all string values must be convert to float `to_f` otherwise mongo will not filter them properly
expect(subject.to_query).to eq('count' => { '$gt' => 1.0, '$lt' => 5.0 },
'quantity' => { '$gte' => 10.5, '$lte' => 15.0 })
end
end
describe '#gt_matcher' do
it 'returns the matcher' do
subject.gt_matcher('quantity', 1)
expect(subject.to_query).to eq('quantity' => { '$gt' => 1 })
end
end
describe '#lt_matcher' do
it 'returns the matcher' do
subject.lt_matcher('quantity', 1)
expect(subject.to_query).to eq('quantity' => { '$lt' => 1 })
end
end
describe '#gteq_matcher' do
it 'returns the matcher' do
subject.gteq_matcher('quantity', 1)
expect(subject.to_query).to eq('quantity' => { '$gte' => 1 })
end
end
describe '#lteq_matcher' do
it 'returns the matcher' do
subject.lteq_matcher('quantity', 1)
expect(subject.to_query).to eq('quantity' => { '$lte' => 1 })
end
end
describe '#or_op' do
it 'returns the or operation' do
subject.or_op do
subject.eq_matcher('name', 'Pablo')
subject.eq_matcher('lastname', 'Pablo')
end
expect(subject.to_query).to eq('$or' => [{ 'name' => 'Pablo' }, { 'lastname' => 'Pablo' }])
end
it 'preserves other criterias' do
subject.or_op do
subject.eq_matcher('name', 'Pablo')
subject.eq_matcher('lastname', 'Pablo')
end
subject.eq_matcher('country', 'Brazil')
expect(subject.to_query).to eq('$or' => [{ 'name' => 'Pablo' }, { 'lastname' => 'Pablo' }], 'country' => 'Brazil')
end
end
end
end
require 'spec_helper'
module RansackMongo
describe Predicate do
subject { described_class.new(%w[eq not_eq cont]) }
describe '#parse' do
it 'parses predicates' do
params = { 'name_eq' => 'Pablo', 'name_not_eq' => 'Paul', 'fullname_cont' => 'Cantero' }
expect(subject.parse(params)).to eq('eq' => [{ 'attr' => 'name', 'value' => 'Pablo', }],
'not_eq' => [{ 'attr' => 'name', 'value' => 'Paul', }],
'cont' => [{ 'attr' => 'fullname', 'value' => 'Cantero' }])
end
it 'ignores unknown predicates' do
params = { 'name_eq' => 'Pablo', 'name_bbb' => 'Paul' }
expect(subject.parse(params)).to eq('eq' => [{ 'attr' => 'name', 'value' => 'Pablo', }])
end
end
end
end
require 'spec_helper'
module RansackMongo
describe Query do
context 'when FooAdapter' do
class FooAdapter
PREDICATES = %w[foo]
def initialize
@query = {}
end
def to_query
@query
end
def self.predicates
PREDICATES
end
end
describe '#to_query' do
context 'when not implement matcher' do
it 'raises proper exception' do
params = { 'name_foo' => 'Pablo' }
expect {
described_class.new(FooAdapter).to_query(params)
}.to raise_error(MatcherNotFound, 'The matcher foo `foo_matcher` was not found in the RansackMongo::FooAdapter. Check `RansackMongo::FooAdapter.predicates`')
end
end
end
end
context 'when MongoAdapter' do
describe '#to_query' do
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
context 'when or' do
it 'returns the query' do
params = { 'name_or_fullname_eq' => 'Pablo' }
expect(described_class.new.to_query(params)).to eq('$or' => [{ 'name' => 'Pablo' }, { 'fullname' => 'Pablo' }])
end
it 'preserves other criterias' do
params = { 'name_or_fullname_eq' => 'Pablo', 'country_eq' => 'Brazil' }
expect(described_class.new.to_query(params)).to eq('$or' => [{ 'name' => 'Pablo' }, { 'fullname' => 'Pablo' }], 'country' => 'Brazil')
end
end
end
end
end
end
require 'rspec'
require 'fileutils'
require 'tempfile'
Dir['../lib/**/*.rb'].each &method(:require)
require './lib/ransack_mongo'
RSpec.configure do |config|
config.color_enabled = true
config.formatter = 'progress'
end
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