hash_conditions 0.1.3

Sign up to get free protection for your applications and to get access to all the features.
data/.gitignore ADDED
@@ -0,0 +1,10 @@
1
+ /.bundle/
2
+ /.yardoc
3
+ /Gemfile.lock
4
+ /_yardoc/
5
+ /coverage/
6
+ /doc/
7
+ /pkg/
8
+ /spec/reports/
9
+ /tmp/
10
+ .*.sw?
data/.rspec ADDED
@@ -0,0 +1,3 @@
1
+ --format documentation
2
+ --color
3
+ --require spec_helper
data/.ruby-gemset ADDED
@@ -0,0 +1 @@
1
+ hash_conditions
data/.ruby-version ADDED
@@ -0,0 +1 @@
1
+ ruby-1.9.3-p327
data/.travis.yml ADDED
@@ -0,0 +1,3 @@
1
+ language: ruby
2
+ rvm:
3
+ - 2.0.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 hash_conditions.gemspec
4
+ gemspec
data/LICENSE.txt ADDED
@@ -0,0 +1,21 @@
1
+ The MIT License (MIT)
2
+
3
+ Copyright (c) 2015 Giancarlo Palavicini
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,39 @@
1
+ # HashConditions
2
+
3
+ Welcome to your new gem! In this directory, you'll find the files you need to be able to package up your Ruby library into a gem. Put your Ruby code in the file `lib/hash_conditions`. To experiment with that code, run `bin/console` for an interactive prompt.
4
+
5
+ TODO: Delete this and the text above, and describe your gem
6
+
7
+ ## Installation
8
+
9
+ Add this line to your application's Gemfile:
10
+
11
+ ```ruby
12
+ gem 'hash_conditions'
13
+ ```
14
+
15
+ And then execute:
16
+
17
+ $ bundle
18
+
19
+ Or install it yourself as:
20
+
21
+ $ gem install hash_conditions
22
+
23
+ ## Usage
24
+
25
+ TODO: Write usage instructions here
26
+
27
+ ## Development
28
+
29
+ After checking out the repo, run `bin/setup` to install dependencies. Then, run `bin/console` for an interactive prompt that will allow you to experiment.
30
+
31
+ To install this gem onto your local machine, run `bundle exec rake install`. To release a new version, update the version number in `version.rb`, and then run `bundle exec rake release` to create a git tag for the version, push git commits and tags, and push the `.gem` file to [rubygems.org](https://rubygems.org).
32
+
33
+ ## Contributing
34
+
35
+ 1. Fork it ( https://github.com/[my-github-username]/hash_conditions/fork )
36
+ 2. Create your feature branch (`git checkout -b my-new-feature`)
37
+ 3. Commit your changes (`git commit -am 'Add some feature'`)
38
+ 4. Push to the branch (`git push origin my-new-feature`)
39
+ 5. Create a new Pull Request
data/Rakefile ADDED
@@ -0,0 +1,9 @@
1
+ require "bundler/gem_tasks"
2
+
3
+ begin
4
+ require 'rspec/core/rake_task'
5
+ RSpec::Core::RakeTask.new(:spec)
6
+ rescue LoadError
7
+ end
8
+
9
+ task default: [:spec]
data/bin/console ADDED
@@ -0,0 +1,14 @@
1
+ #!/usr/bin/env ruby
2
+
3
+ require "bundler/setup"
4
+ require "hash_conditions"
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,33 @@
1
+ # coding: utf-8
2
+ lib = File.expand_path('../lib', __FILE__)
3
+ $LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
4
+ require 'hash_conditions/version'
5
+
6
+ Gem::Specification.new do |spec|
7
+ spec.name = "hash_conditions"
8
+ spec.version = HashConditions::VERSION
9
+ spec.authors = ["Giancarlo Palavicini"]
10
+ spec.email = ["kasthor@gmail.com"]
11
+
12
+ spec.summary = %q{ Ability to parse and match hashes against Mongo-like querys }
13
+ spec.description = %q{ Ability to parse and match hashes against Mongo-like querys }
14
+ spec.homepage = "http://kasthor.com"
15
+ spec.license = "MIT"
16
+
17
+ # Prevent pushing this gem to RubyGems.org by setting 'allowed_push_host', or
18
+ # delete this section to allow pushing this gem to any host.
19
+ # if spec.respond_to?(:metadata)
20
+ # spec.metadata['allowed_push_host'] = "TODO: Set to 'http://mygemserver.com'"
21
+ # else
22
+ # raise "RubyGems 2.0 or newer is required to protect against public gem pushes."
23
+ # end
24
+
25
+ spec.files = `git ls-files -z`.split("\x0").reject { |f| f.match(%r{^(test|spec|features)/}) }
26
+ spec.bindir = "bin"
27
+ spec.executables = spec.files.grep(%r{^bin/}) { |f| File.basename(f) }
28
+ spec.require_paths = ["lib"]
29
+
30
+ spec.add_development_dependency "bundler", "~> 1.7"
31
+ spec.add_development_dependency "rake", "~> 10.0"
32
+ spec.add_development_dependency "rspec"
33
+ end
@@ -0,0 +1,138 @@
1
+ module HashConditions
2
+ module Core
3
+ # Modular Matchers
4
+ def modules
5
+ @@modules ||= []
6
+ end
7
+
8
+ def reset
9
+ @@modules = []
10
+ end
11
+
12
+ def bundles
13
+ @@bundles ||= []
14
+ end
15
+
16
+ def add_bundle name
17
+ bundles << name
18
+ end
19
+ def contains_bundle name
20
+ bundles.include? name
21
+ end
22
+
23
+ def module_match matcher, writer = nil, operations = [], &block
24
+ writer = block if block
25
+ modules << ModuleMatcher.new(matcher, writer, operations)
26
+ end
27
+
28
+ # Iterator
29
+
30
+ def iterator conditions, options = {}
31
+ options = { glue: :and }.merge options
32
+
33
+ result = case conditions
34
+ when ::Hash
35
+ conditions.map do | key, value |
36
+ case key
37
+ when '$and' then iterator(value, options.merge( glue: :and ))
38
+ when '$or' then iterator(value, options.merge( glue: :or))
39
+ when '$eval' then results_from_expression( eval_expression( value ), options )
40
+ when _ext_match( value, options ) then _ext_parse( key, value, options )
41
+ else results_from_expression( extract_expression( key, value ), options )
42
+ end
43
+ end
44
+ when ::Array
45
+ conditions.map do | condition |
46
+ iterator condition, options
47
+ end
48
+ end
49
+
50
+ options[:finalize].call result, options
51
+ end
52
+
53
+ def results_from_expression expression, options
54
+ options[:result].call( expression, options )
55
+ end
56
+
57
+ def eval_expression value
58
+ raise "Invalid eval expression" unless value.is_a? Array and value.length == 3
59
+
60
+ Hash[ [ :key, :operator, :value ].zip( value ) ].tap do | exp |
61
+ exp[ :operator ] = get_op exp[ :operator ]
62
+ end
63
+ end
64
+
65
+ def extract_expression key, value
66
+ result = {}
67
+ result[:key] = key
68
+
69
+ case value
70
+ when String, Integer, Float
71
+ result[:operator] = :==
72
+ result[:value] = value
73
+ when Array
74
+ result[:operator] = :in
75
+ result[:value] = value
76
+ when Hash
77
+ if value.length == 1
78
+ key, value = value.to_a.first
79
+
80
+ result[:operator] = get_op key
81
+ result[:value] = value
82
+ else
83
+ case
84
+ when value.keys.include?('$between')
85
+ result[:operator] = :between
86
+ result[:value] = value.values_at [ '$between', '$and' ]
87
+ end
88
+ end
89
+ end
90
+
91
+ result
92
+ end
93
+
94
+ def get_op key
95
+ case key
96
+ when '$eq', '$equal' then :==
97
+ when '$ne', '$not_equal' then :!=
98
+ when '$gt' then :>
99
+ when '$lt' then :<
100
+ when '$gte' then :>=
101
+ when '$lte' then :<=
102
+ when '$between' then :between
103
+ when '$in' then :in
104
+ when '$contains' then :contains
105
+ else
106
+ raise "No operator for '#{ op }"
107
+ end
108
+ end
109
+
110
+ def _ext_match condition, options
111
+ ->(key) { _ext_get_module( key, condition, options ) != nil }
112
+ end
113
+
114
+ def _ext_parse key, condition, options
115
+ mod = _ext_get_module key,condition, options
116
+ parser = mod.replacement
117
+
118
+ case parser
119
+ when String then options[:result].call(extract_expression( parser, condition ), options)
120
+ when Proc then _ext_read_module( parser.call( key, condition ), options )
121
+ end
122
+ end
123
+
124
+ def _ext_get_module key, condition, options
125
+ modules.select{ |m| m.for_operation? options[:operation] }.find do | matcher |
126
+ matcher.apply_for key, condition
127
+ end
128
+ end
129
+
130
+ def _ext_read_module parser_output, options
131
+ case parser_output
132
+ when Hash then iterator(parser_output, options)
133
+ when NilClass then nil
134
+ else raise "return data of type #{ parser_output.class } not supported"
135
+ end
136
+ end
137
+ end
138
+ end
@@ -0,0 +1,92 @@
1
+ module HashConditions
2
+ class Matcher
3
+ extend Core
4
+
5
+ def self.configurations
6
+ @@configurations ||= {}
7
+ end
8
+
9
+ def self.configure config
10
+ configurations.merge! config
11
+ end
12
+
13
+ def self.configuration key
14
+ configurations[key]
15
+ end
16
+
17
+ def self.match hash, conditions
18
+ iterator conditions,
19
+ operation: :match,
20
+ result: lambda{ | expression, options |
21
+ match_single hash, expression
22
+ },
23
+ finalize: lambda{ | array, options |
24
+ finalize hash, array, options
25
+ }
26
+ end
27
+
28
+ def self.finalize hash, array, options
29
+ case options[:glue]
30
+ when :or then array.any?
31
+ when :and then array.all?
32
+ end
33
+ end
34
+
35
+ ARITMETIC_OPERATORS = {
36
+ '$add' => :+,
37
+ '$substract' => :-,
38
+ '$multiply' => :*,
39
+ '$divide' => :/,
40
+ }
41
+
42
+ def self.get_key hash, key
43
+ case key
44
+ when String, Symbol
45
+ if key.to_s == '$now'
46
+ Time.now
47
+ else
48
+ hash[key]
49
+ end
50
+ when Hash
51
+ op, values = key.to_a.first
52
+
53
+ values = values.map{ |x| get_key hash, x }
54
+
55
+ case op.to_s
56
+ when *ARITMETIC_OPERATORS.keys
57
+ values.inject( ARITMETIC_OPERATORS[ op ] )
58
+ when '$ifNull'
59
+ val = values.shift
60
+ val.nil? ? values.shift : val
61
+ end
62
+ end
63
+ end
64
+
65
+ def self.match_single hash, expression
66
+ hash_value = get_key hash, expression[:key]
67
+ comparisson_value = expression[ :value ]
68
+
69
+ case expression[:operator]
70
+ when :==
71
+ if configuration( :force_string_comparations )
72
+ hash_value = hash_value.to_s
73
+ comparisson_value = comparisson_value.to_s
74
+ end
75
+ hash_value == comparisson_value
76
+ when :in
77
+ if configuration( :force_string_comparations )
78
+ hash_value = hash_value.to_s
79
+ comparisson_value = comparisson_value.map(&:to_s)
80
+ end
81
+
82
+ comparisson_value.include? hash_value
83
+ when :between
84
+ hash_value > comparisson_value.shift and hash_value < comparisson_value.shift
85
+ when :contains
86
+ !! %r{#{comparisson_value}}.match( hash_value )
87
+ else
88
+ hash_value.send( expression[:operator], comparisson_value )
89
+ end
90
+ end
91
+ end
92
+ end
@@ -0,0 +1,27 @@
1
+ module HashConditions
2
+ class ModuleMatcher
3
+ attr_accessor :replacement
4
+
5
+ def initialize matcher, replacement, operations = []
6
+ operations = [ :parse, :match ] if operations.empty?
7
+
8
+ @matcher = matcher
9
+ @replacement = replacement
10
+ @operations = operations
11
+ end
12
+
13
+ def for_operation? operation
14
+ @operations.include? operation
15
+ end
16
+
17
+ def apply_for key, condition
18
+ case @matcher
19
+ when Symbol then @matcher == key.to_sym
20
+ when String then @matcher == key.to_s
21
+ when Regexp then @matcher =~ key.to_s
22
+ when Proc then !! @matcher.call( key, condition )
23
+ else false
24
+ end
25
+ end
26
+ end
27
+ end
@@ -0,0 +1,48 @@
1
+ module HashConditions
2
+ class Parser
3
+ extend Core
4
+
5
+ def self.get_conditions conditions, options = {}
6
+ result = iterator conditions,
7
+ operation: :parse,
8
+ result: lambda{ | expression, options |
9
+ _parse_key_value_condition expression
10
+ },
11
+ finalize: lambda{ | array, options |
12
+ "( #{ array.join( " #{ options[:glue].upcase } " ) } )"
13
+ }
14
+
15
+ result.
16
+ gsub!(/^\( /, '').
17
+ gsub!(/ \)$/, '')
18
+
19
+ result
20
+ end
21
+
22
+ def self._parse_key_value_condition expression
23
+ # "#{key} #{_parse_value_condition condition}"
24
+ comparisson = case expression[:operator]
25
+ when :==
26
+ "= #{_parse_value expression[:value]}"
27
+ when :>, :<, :>=, :<=
28
+ "#{ expression[:operator] } #{_parse_value expression[:value]}"
29
+ when :in
30
+ "IN ( #{ expression[:value].map{ |v| _parse_value v }.join ", " } )"
31
+ when :contains
32
+ "LIKE #{ _parse_value(expression[:value], '%', '%') }"
33
+ when :between
34
+ "BETWEEN #{ _parse_value expression[:value].shift } AND #{ _parse_value expression[:value].shift }"
35
+ end
36
+
37
+ "#{expression[:key]} #{comparisson}"
38
+ end
39
+
40
+ def self._parse_value value, prepend = '', append = ''
41
+ case value
42
+ when String then "'#{prepend}#{value}#{append}'"
43
+ when DateTime, Date, Time then "'#{value.strftime("%Y-%m-%d %I:%M%p")}'"
44
+ when Integer, Float then "#{value}"
45
+ end
46
+ end
47
+ end
48
+ end
@@ -0,0 +1,3 @@
1
+ module HashConditions
2
+ VERSION = "0.1.3"
3
+ end
@@ -0,0 +1,6 @@
1
+ require "date"
2
+ require "hash_conditions/version"
3
+ require "hash_conditions/core"
4
+ require "hash_conditions/matcher"
5
+ require "hash_conditions/parser"
6
+ require "hash_conditions/module_matcher"
metadata ADDED
@@ -0,0 +1,121 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: hash_conditions
3
+ version: !ruby/object:Gem::Version
4
+ version: 0.1.3
5
+ prerelease:
6
+ platform: ruby
7
+ authors:
8
+ - Giancarlo Palavicini
9
+ autorequire:
10
+ bindir: bin
11
+ cert_chain: []
12
+ date: 2015-05-29 00:00:00.000000000 Z
13
+ dependencies:
14
+ - !ruby/object:Gem::Dependency
15
+ name: bundler
16
+ requirement: !ruby/object:Gem::Requirement
17
+ none: false
18
+ requirements:
19
+ - - ~>
20
+ - !ruby/object:Gem::Version
21
+ version: '1.7'
22
+ type: :development
23
+ prerelease: false
24
+ version_requirements: !ruby/object:Gem::Requirement
25
+ none: false
26
+ requirements:
27
+ - - ~>
28
+ - !ruby/object:Gem::Version
29
+ version: '1.7'
30
+ - !ruby/object:Gem::Dependency
31
+ name: rake
32
+ requirement: !ruby/object:Gem::Requirement
33
+ none: false
34
+ requirements:
35
+ - - ~>
36
+ - !ruby/object:Gem::Version
37
+ version: '10.0'
38
+ type: :development
39
+ prerelease: false
40
+ version_requirements: !ruby/object:Gem::Requirement
41
+ none: false
42
+ requirements:
43
+ - - ~>
44
+ - !ruby/object:Gem::Version
45
+ version: '10.0'
46
+ - !ruby/object:Gem::Dependency
47
+ name: rspec
48
+ requirement: !ruby/object:Gem::Requirement
49
+ none: false
50
+ requirements:
51
+ - - ! '>='
52
+ - !ruby/object:Gem::Version
53
+ version: '0'
54
+ type: :development
55
+ prerelease: false
56
+ version_requirements: !ruby/object:Gem::Requirement
57
+ none: false
58
+ requirements:
59
+ - - ! '>='
60
+ - !ruby/object:Gem::Version
61
+ version: '0'
62
+ description: ! ' Ability to parse and match hashes against Mongo-like querys '
63
+ email:
64
+ - kasthor@gmail.com
65
+ executables:
66
+ - console
67
+ - setup
68
+ extensions: []
69
+ extra_rdoc_files: []
70
+ files:
71
+ - .gitignore
72
+ - .rspec
73
+ - .ruby-gemset
74
+ - .ruby-version
75
+ - .travis.yml
76
+ - CODE_OF_CONDUCT.md
77
+ - Gemfile
78
+ - LICENSE.txt
79
+ - README.md
80
+ - Rakefile
81
+ - bin/console
82
+ - bin/setup
83
+ - hash_conditions.gemspec
84
+ - lib/hash_conditions.rb
85
+ - lib/hash_conditions/core.rb
86
+ - lib/hash_conditions/matcher.rb
87
+ - lib/hash_conditions/module_matcher.rb
88
+ - lib/hash_conditions/parser.rb
89
+ - lib/hash_conditions/version.rb
90
+ homepage: http://kasthor.com
91
+ licenses:
92
+ - MIT
93
+ post_install_message:
94
+ rdoc_options: []
95
+ require_paths:
96
+ - lib
97
+ required_ruby_version: !ruby/object:Gem::Requirement
98
+ none: false
99
+ requirements:
100
+ - - ! '>='
101
+ - !ruby/object:Gem::Version
102
+ version: '0'
103
+ segments:
104
+ - 0
105
+ hash: -2284979545467229792
106
+ required_rubygems_version: !ruby/object:Gem::Requirement
107
+ none: false
108
+ requirements:
109
+ - - ! '>='
110
+ - !ruby/object:Gem::Version
111
+ version: '0'
112
+ segments:
113
+ - 0
114
+ hash: -2284979545467229792
115
+ requirements: []
116
+ rubyforge_project:
117
+ rubygems_version: 1.8.23
118
+ signing_key:
119
+ specification_version: 3
120
+ summary: Ability to parse and match hashes against Mongo-like querys
121
+ test_files: []