mongoid_hash_query 0.2.0

Sign up to get free protection for your applications and to get access to all the features.
checksums.yaml ADDED
@@ -0,0 +1,7 @@
1
+ ---
2
+ SHA1:
3
+ metadata.gz: 38cb5283bf7399e66d57f5040f3575d3982ddc98
4
+ data.tar.gz: 3a3a92fd0fe6a84c51362a0da71f25446c10cb27
5
+ SHA512:
6
+ metadata.gz: c7c6c5b45715c6352d487a5f4b7baa2bf7a3c194136e7951bf77c650646681001977cf295927246d8fa7c3758615cf6db45944020a1f99332520084e2c2d9cbe
7
+ data.tar.gz: 9e8a7e0d5881d1e0f11f4159723b21ccfad4c2eaade7c89fd5807da2432a58849e865d8789f515469e4e96c875ae95be74339b589f629c3e7359681382d3bc03
data/.gitignore ADDED
@@ -0,0 +1,9 @@
1
+ /.bundle/
2
+ /.yardoc
3
+ /Gemfile.lock
4
+ /_yardoc/
5
+ /coverage/
6
+ /doc/
7
+ /pkg/
8
+ /spec/reports/
9
+ /tmp/
data/.rspec ADDED
@@ -0,0 +1,2 @@
1
+ --format documentation
2
+ --color
data/.travis.yml ADDED
@@ -0,0 +1,3 @@
1
+ language: ruby
2
+ rvm:
3
+ - 2.2.0
@@ -0,0 +1,13 @@
1
+ # Contributor Code of Conduct
2
+
3
+ As contributors and maintainers of this project, we pledge to respect all people who contribute through reporting issues, posting feature requests, updating documentation, submitting pull requests or patches, and other activities.
4
+
5
+ We are committed to making participation in this project a harassment-free experience for everyone, regardless of level of experience, gender, gender identity and expression, sexual orientation, disability, personal appearance, body size, race, age, or religion.
6
+
7
+ Examples of unacceptable behavior by participants include the use of sexual language or imagery, derogatory comments or personal attacks, trolling, public or private harassment, insults, or other unprofessional conduct.
8
+
9
+ Project maintainers have the right and responsibility to remove, edit, or reject comments, commits, code, wiki edits, issues, and other contributions that are not aligned to this Code of Conduct. Project maintainers who do not follow the Code of Conduct may be removed from the project team.
10
+
11
+ Instances of abusive, harassing, or otherwise unacceptable behavior may be reported by opening an issue or contacting one or more of the project maintainers.
12
+
13
+ This Code of Conduct is adapted from the [Contributor Covenant](http:contributor-covenant.org), version 1.0.0, available at [http://contributor-covenant.org/version/1/0/0/](http://contributor-covenant.org/version/1/0/0/)
data/Gemfile ADDED
@@ -0,0 +1,4 @@
1
+ source 'https://rubygems.org'
2
+
3
+ # Specify your gem's dependencies in mongoid_hash_query.gemspec
4
+ gemspec
data/LICENSE.txt ADDED
@@ -0,0 +1,21 @@
1
+ The MIT License (MIT)
2
+
3
+ Copyright (c) 2015 Filippos Vasilakis
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in
13
+ all copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
21
+ THE SOFTWARE.
data/README.md ADDED
@@ -0,0 +1,151 @@
1
+ # MongoidHashQuery
2
+
3
+ ## Introduction
4
+ __Important: text with ~~strikethrough~~ are future features not yet implemented__
5
+
6
+ That's the little brother of [ActiveHashRelation](https://github.com/kollegorna/active_hash_relation) gem.
7
+
8
+ Simple gem that allows you to manipulate Mongoid queries using Hash/JSON. For instance:
9
+ ```ruby
10
+ apply_filters(resource, {name: 'RPK', start_date: {leq: "2014-10-19"}, act_status: "ongoing"})
11
+ ```
12
+ It's perfect for filtering a collection of resources on APIs.
13
+
14
+ It should be noted that `apply_filters` calls `MongoidHashQuery::FilterApplier` class
15
+ underneath with the same params.
16
+
17
+ _\*A user could retrieve resources based
18
+ on unknown attributes (attributes not returned from the API) by brute forcing
19
+ which might or might not be a security issue. If you don't like that check
20
+ [whitelisting](https://github.com/kollegorna/mongoid_hash_query#whitelisting)._
21
+
22
+ ## Installation
23
+
24
+ Add this line to your application's Gemfile:
25
+
26
+ gem 'mongoid_hash_query'
27
+
28
+ And then execute:
29
+
30
+ $ bundle
31
+
32
+ Or install it yourself as:
33
+
34
+ $ gem install mongoid_hash_query
35
+
36
+ ## How to use
37
+ The gem exposes only one method: `apply_filters(resource, hash_params, include_associations: false, model: nil)`. `resource` is expected to be an Mongoid::Criteria.
38
+ That way, you can add your custom filters before calling `apply_filters`.
39
+
40
+ In order to use it you have to include MongoidHashQuery module in your class. For instance in a Rails API controller you would do:
41
+
42
+ ```ruby
43
+ class Api::V1::ResourceController < Api::V1::BaseController
44
+ include MongoidHashQuery
45
+
46
+ def index
47
+ resources = apply_filters(Resource.all, params)
48
+
49
+ authorized_resources = policy_scope(resource)
50
+
51
+ render json: resources
52
+ end
53
+ end
54
+ ```
55
+
56
+ ## The API
57
+ ### Fields
58
+ For each param, `apply_filters` method will search in the model (derived from the first param, or explicitly defined as the last param) all the record's field names ~~and associations~~. ~~(filtering based on scopes are not working at the moment but will be supported soon).~~ For each column, if there is such a param, it will apply the filter based on the column type. The following column types are supported:
59
+
60
+ #### Id
61
+ Mongo's documents have an `id`, names `_id` of type BSON::ObjectId. You can just pass in `id` instead of `_id`:
62
+ * `{id: 5}`
63
+ * ~~`{id: [1,3,4,5,6,7]}`~~
64
+
65
+ #### Integer, Float, BigDecimal, Date, Time or Datetime
66
+ You can apply an equality filter:
67
+ * `{example_column: 500}`
68
+ or using a hash as a value you get more options:
69
+ * `{example_field: {le: 500}}`
70
+ * `{example_field: {leq: 500}}`
71
+ * `{example_field: {ge: 500}}`
72
+ * `{example_field: {geq: 500}}`
73
+
74
+ Of course you can provide a compination of those like:
75
+ * `{example_column: {geq: 500, le: 1000}}`
76
+
77
+ The same api is for Float, BigDecimal, Date, Time or Datetime.
78
+
79
+ #### Boolean
80
+ I am not sure how Mongoid converts input to boolean but according to [that spec](https://github.com/mongoid/mongoid/blob/master/spec/mongoid/extensions/boolean_spec.rb) a value to be true must be one of the following: `[true, 1, '1', 't', 'T', 'true', 'TRUE']`. Anything else is false.
81
+ * `{example_field: true}`
82
+ * `{example_field: 0}`
83
+
84
+ #### String
85
+ You can apply an equality filter:
86
+ * `{example_field: test}`
87
+
88
+ Soon you will be able to send in regex..
89
+
90
+ ### Hash
91
+ You can apply an equality filter on hashes like that:
92
+ * `{example_field: {foo: 'bar', bar: 'foo'}}`
93
+
94
+
95
+ ### Limit
96
+ A limit param defines the number of returned resources. For instance:
97
+ * `{limit: 10}`
98
+
99
+ However I would strongly advice you to use a pagination gem like Kaminari, and use `page` and `per_page` params.
100
+
101
+
102
+ ### Sorting
103
+ You can apply sorting using the `property` and `order` attributes. For instance:
104
+ * `{created_at: 'desc'}`
105
+
106
+ If there is no column named after the property value, sorting is skipped.
107
+
108
+
109
+ ### Associations (later)
110
+ ~~If the association is a `belongs_to` or `has_one`, then the hash key name must be in singular. If the association is `has_many` the attribute must be in plural reflecting the association type. When you have, in your hash, filters for an association, the sub-hash is passed in the association's model. For instance, let's say a user has many microposts and the following filter is applied (could be through an HTTP GET request on controller's index method):~~
111
+ * `{email: test@user.com, microposts: {created_at { leq: 12-9-2014} }`
112
+
113
+
114
+ ### Scopes
115
+ If you want to filter based on a scope in a model, the scope names should go under `scopes` sub-hash. For instance the following:
116
+ * `{ scopes: { planned: true } }`
117
+
118
+ will run the `.planned` scope on the resource.
119
+
120
+
121
+ ### Whitelisting
122
+ If you don't want to allow a column/association/scope just remove it from the params hash.
123
+
124
+ #### Filter Classes (later)
125
+ ~~Sometimes, especially on larger projects, you have specific classes that handle
126
+ the input params outside the controllers. You can configure the gem to look for
127
+ those classes and call `apply_filters` which will apply the necessary filters when
128
+ iterating over associations.~~
129
+
130
+ ~~In an initializer:~~
131
+ ```ruby
132
+ #config/initializers/mongoid_hash_query.rb
133
+ MongoidHashQuery.configure do |config|
134
+ config.has_filter_classes = true
135
+ config.filter_class_prefix = 'Api::V1::'
136
+ config.filter_class_suffix = 'Filter'
137
+ end
138
+ ```
139
+ ~~With the above settings, when the association name is `resource`,
140
+ `Api::V1::ResourceFilter.new(resource, params[resource]).apply_filters` will be
141
+ called to apply the filters in resource association.~~
142
+
143
+
144
+
145
+ ## Contributing
146
+
147
+ 1. Fork it ( https://github.com/kollegorna/mongoid_hash_query/fork )
148
+ 2. Create your feature branch (`git checkout -b my-new-feature`)
149
+ 3. Commit your changes (`git commit -am 'Add some feature'`)
150
+ 4. Push to the branch (`git push origin my-new-feature`)
151
+ 5. Create a new Pull Request
data/Rakefile ADDED
@@ -0,0 +1,2 @@
1
+ require "bundler/gem_tasks"
2
+
data/bin/console ADDED
@@ -0,0 +1,14 @@
1
+ #!/usr/bin/env ruby
2
+
3
+ require "bundler/setup"
4
+ require "mongoid_hash_query"
5
+
6
+ # You can add fixtures and/or initialization code here to make experimenting
7
+ # with your gem easier. You can also use a different console, if you like.
8
+
9
+ # (If you use this, don't forget to add pry to your Gemfile!)
10
+ # require "pry"
11
+ # Pry.start
12
+
13
+ require "irb"
14
+ IRB.start
data/bin/setup ADDED
@@ -0,0 +1,7 @@
1
+ #!/bin/bash
2
+ set -euo pipefail
3
+ IFS=$'\n\t'
4
+
5
+ bundle install
6
+
7
+ # Do any other automated setup that you need to do here
@@ -0,0 +1,36 @@
1
+ require 'mongoid_hash_query/version'
2
+ require 'mongoid_hash_query/field_filters'
3
+ require 'mongoid_hash_query/limit_filters'
4
+ require 'mongoid_hash_query/sort_filters'
5
+ require 'mongoid_hash_query/scope_filters'
6
+ require 'mongoid_hash_query/filter_applier'
7
+
8
+ module MongoidHashQuery
9
+ class << self
10
+ attr_accessor :configuration
11
+ end
12
+
13
+ def self.configure
14
+ self.configuration
15
+ yield(configuration)
16
+ end
17
+
18
+ def self.configuration
19
+ @configuration ||= Configuration.new do
20
+ self.has_filter_classes = false
21
+ end
22
+ end
23
+
24
+ def apply_filters(resource, params, include_associations: false, model: nil)
25
+ FilterApplier.new(
26
+ resource,
27
+ params,
28
+ include_associations: include_associations,
29
+ model: model
30
+ ).apply_filters
31
+ end
32
+
33
+ class Configuration
34
+ attr_accessor :has_filter_classes, :filter_class_prefix, :filter_class_suffix
35
+ end
36
+ end
@@ -0,0 +1,78 @@
1
+ module MongoidHashQuery::FieldFilters
2
+ def filter_primary(resource, field, param)
3
+ resource = resource.where(id: param)
4
+ end
5
+
6
+ def filter_array(resource, field, param)
7
+ return resource
8
+ end
9
+
10
+ def filter_big_decimal(resource, field, param)
11
+ return filter_integer(resource, field, param)
12
+ end
13
+
14
+ def filter_boolean(resource, field, param)
15
+ return resource.where(field => param)
16
+ end
17
+
18
+ def filter_date(resource, field, param)
19
+ return filter_time(resource, field, param)
20
+ end
21
+
22
+ def filter_date_time(resource, field, param)
23
+ return filter_time(resource, field, param)
24
+ end
25
+
26
+ def filter_float(resource, field, param)
27
+ return filter_integer(resource, field, param)
28
+ end
29
+
30
+ def filter_hash(resource, field, param)
31
+ param.each do |k, v|
32
+ resource = resource.where("#{field}.#{k}" => v)
33
+ end
34
+
35
+ return resource
36
+ end
37
+
38
+ def filter_integer(resource, field, param)
39
+ if !param.is_a? Hash
40
+ return resource.where(column => param)
41
+ else
42
+ return apply_leq_geq_le_ge_filters(resource, field, param)
43
+ end
44
+ end
45
+
46
+ def filter_string(resource, field, param)
47
+ return resource.where(field => param)
48
+ end
49
+
50
+ def filter_symbol(resource, field, param)
51
+ return resource.where(field => param)
52
+ end
53
+
54
+ def filter_time(resource, field, param)
55
+ if !param.is_a? Hash
56
+ return resource.where(field => param)
57
+ else
58
+ return apply_leq_geq_le_ge_filters(resource, field, param)
59
+ end
60
+ end
61
+
62
+ private
63
+ def apply_leq_geq_le_ge_filters(resource, field, param)
64
+ if param[:lte]
65
+ resource = resource.where(field.to_sym.lte => param[:lte])
66
+ elsif param[:lt]
67
+ resource = resource.where(field.to_sym.lt => param[:lt])
68
+ end
69
+
70
+ if param[:gte]
71
+ resource = resource.where(field.to_sym.gte => param[:gte])
72
+ elsif param[:gt]
73
+ resource = resource.where(field.to_sym.gt => param[:gt])
74
+ end
75
+
76
+ return resource
77
+ end
78
+ end
@@ -0,0 +1,76 @@
1
+ module MongoidHashQuery
2
+ class FilterApplier
3
+ include FieldFilters
4
+ #include AssociationFilters
5
+ include ScopeFilters
6
+ include SortFilters
7
+ include LimitFilters
8
+
9
+ attr_reader :configuration
10
+
11
+ def initialize(resource, params, include_associations: true, model: nil)
12
+ @configuration = Module.nesting.last.configuration
13
+ @resource = resource
14
+ @params = HashWithIndifferentAccess.new(params)
15
+ @include_associations = include_associations
16
+ @model = model
17
+ end
18
+
19
+ def apply_filters
20
+ unless @model
21
+ @model = model_class_name(@resource)
22
+ end
23
+ #table_name = @model.table_name
24
+ @model.fields.each do |k, v|
25
+ next if @params[v.name.to_s].nil?
26
+
27
+ if k.eql?('_id')
28
+ @resource = filter_primary(@resource, v.name, @params[id])
29
+ next
30
+ end
31
+
32
+ case v.options[:type].to_s
33
+ when Array.to_s
34
+ @resource = filter_array(@resource, v.name, @params[v.name])
35
+ when BigDecimal.to_s
36
+ @resource = filter_big_decimal(@resource, v.name, @params[v.name])
37
+ when Boolean.to_s
38
+ @resource = filter_boolean(@resource, v.name, @params[v.name])
39
+ when Date.to_s
40
+ @resource = filter_date(@resource, v.name, @params[v.name])
41
+ when DateTime.to_s
42
+ @resource = filter_date_time(@resource, v.name, @params[v.name])
43
+ when Float.to_s
44
+ @resource = filter_float(@resource, v.name, @params[v.name])
45
+ when Hash.to_s
46
+ @resource = filter_hash(@resource, v.name, @params[v.name])
47
+ when Integer.to_s
48
+ @resource = filter_integer(@resource, v.name, @params[v.name])
49
+ when String.to_s
50
+ @resource = filter_string(@resource, v.name, @params[v.name])
51
+ when Symbol.to_s
52
+ @resource = filter_symbol(@resource, v.name, @params[v.name])
53
+ when Time.to_s
54
+ @resource = filter_time(@resource, v.name, @params[v.name])
55
+ end
56
+ end
57
+
58
+ @resource = filter_scopes(@resource, @params[:scopes]) if @params.include?(:scopes)
59
+ @resource = apply_limit(@resource, @params[:limit]) if @params.include?(:limit)
60
+ @resource = apply_sort(@resource, @params[:sort]) if @params.include?(:sort)
61
+
62
+ =begin
63
+ @resource = filter_associations(@resource, @params) if @include_associations
64
+ =end
65
+
66
+ return @resource
67
+ end
68
+
69
+ def filter_class(resource_name)
70
+ end
71
+
72
+ def model_class_name(resource)
73
+ resource.klass
74
+ end
75
+ end
76
+ end
@@ -0,0 +1,6 @@
1
+ module MongoidHashQuery::LimitFilters
2
+ def apply_limit(resource, limit)
3
+ return resource.limit(limit)
4
+ end
5
+ end
6
+
@@ -0,0 +1,12 @@
1
+ module MongoidHashQuery::ScopeFilters
2
+ def filter_scopes(resource, params)
3
+ resource.scopes.each do |k, v|
4
+ if params.include?(k)
5
+ resource = resource.send(k)
6
+ end
7
+ end
8
+
9
+ return resource
10
+ end
11
+ end
12
+
@@ -0,0 +1,13 @@
1
+ module MongoidHashQuery::SortFilters
2
+ def apply_sort(resource, params)
3
+ if !params.is_a? Hash
4
+ return resource
5
+ else
6
+ params.each do |k, v|
7
+ resource = resource.order_by([k, v || :asc])
8
+ end
9
+
10
+ return resource
11
+ end
12
+ end
13
+ end
@@ -0,0 +1,3 @@
1
+ module MongoidHashQuery
2
+ VERSION = "0.2.0"
3
+ end
@@ -0,0 +1,23 @@
1
+ # coding: utf-8
2
+ lib = File.expand_path('../lib', __FILE__)
3
+ $LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
4
+ require 'mongoid_hash_query/version'
5
+
6
+ Gem::Specification.new do |spec|
7
+ spec.name = "mongoid_hash_query"
8
+ spec.version = MongoidHashQuery::VERSION
9
+ spec.authors = ["Filippos Vasilakis"]
10
+ spec.email = ["vasilakisfil@gmail.com"]
11
+
12
+ spec.summary = %q{Simple gem that allows you to run any Mongoid query using a hash API. Perfect for RESTful APIs}
13
+ spec.description = %q{Simple gem that allows you to run any Mongoid query using a hash API. Perfect for RESTful APIs}
14
+ spec.homepage = "https://github.com/kollegorna/mongoid_hash_query"
15
+ spec.license = "MIT"
16
+
17
+ spec.files = `git ls-files -z`.split("\x0").reject { |f| f.match(%r{^(test|spec|features)/}) }
18
+ spec.executables = spec.files.grep(%r{^exe/}) { |f| File.basename(f) }
19
+ spec.require_paths = ["lib"]
20
+
21
+ spec.add_development_dependency "bundler", "~> 1.8"
22
+ spec.add_development_dependency "rake", "~> 10.0"
23
+ end
metadata ADDED
@@ -0,0 +1,92 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: mongoid_hash_query
3
+ version: !ruby/object:Gem::Version
4
+ version: 0.2.0
5
+ platform: ruby
6
+ authors:
7
+ - Filippos Vasilakis
8
+ autorequire:
9
+ bindir: bin
10
+ cert_chain: []
11
+ date: 2015-06-03 00:00:00.000000000 Z
12
+ dependencies:
13
+ - !ruby/object:Gem::Dependency
14
+ name: bundler
15
+ requirement: !ruby/object:Gem::Requirement
16
+ requirements:
17
+ - - "~>"
18
+ - !ruby/object:Gem::Version
19
+ version: '1.8'
20
+ type: :development
21
+ prerelease: false
22
+ version_requirements: !ruby/object:Gem::Requirement
23
+ requirements:
24
+ - - "~>"
25
+ - !ruby/object:Gem::Version
26
+ version: '1.8'
27
+ - !ruby/object:Gem::Dependency
28
+ name: rake
29
+ requirement: !ruby/object:Gem::Requirement
30
+ requirements:
31
+ - - "~>"
32
+ - !ruby/object:Gem::Version
33
+ version: '10.0'
34
+ type: :development
35
+ prerelease: false
36
+ version_requirements: !ruby/object:Gem::Requirement
37
+ requirements:
38
+ - - "~>"
39
+ - !ruby/object:Gem::Version
40
+ version: '10.0'
41
+ description: Simple gem that allows you to run any Mongoid query using a hash API.
42
+ Perfect for RESTful APIs
43
+ email:
44
+ - vasilakisfil@gmail.com
45
+ executables: []
46
+ extensions: []
47
+ extra_rdoc_files: []
48
+ files:
49
+ - ".gitignore"
50
+ - ".rspec"
51
+ - ".travis.yml"
52
+ - CODE_OF_CONDUCT.md
53
+ - Gemfile
54
+ - LICENSE.txt
55
+ - README.md
56
+ - Rakefile
57
+ - bin/console
58
+ - bin/setup
59
+ - lib/mongoid_hash_query.rb
60
+ - lib/mongoid_hash_query/field_filters.rb
61
+ - lib/mongoid_hash_query/filter_applier.rb
62
+ - lib/mongoid_hash_query/limit_filters.rb
63
+ - lib/mongoid_hash_query/scope_filters.rb
64
+ - lib/mongoid_hash_query/sort_filters.rb
65
+ - lib/mongoid_hash_query/version.rb
66
+ - mongoid_hash_query.gemspec
67
+ homepage: https://github.com/kollegorna/mongoid_hash_query
68
+ licenses:
69
+ - MIT
70
+ metadata: {}
71
+ post_install_message:
72
+ rdoc_options: []
73
+ require_paths:
74
+ - lib
75
+ required_ruby_version: !ruby/object:Gem::Requirement
76
+ requirements:
77
+ - - ">="
78
+ - !ruby/object:Gem::Version
79
+ version: '0'
80
+ required_rubygems_version: !ruby/object:Gem::Requirement
81
+ requirements:
82
+ - - ">="
83
+ - !ruby/object:Gem::Version
84
+ version: '0'
85
+ requirements: []
86
+ rubyforge_project:
87
+ rubygems_version: 2.4.5
88
+ signing_key:
89
+ specification_version: 4
90
+ summary: Simple gem that allows you to run any Mongoid query using a hash API. Perfect
91
+ for RESTful APIs
92
+ test_files: []