goodyear 0.1.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: 5c0e7a5df2d732be684ff4696771e3f6746a363c
4
+ data.tar.gz: 731af182b52f774cd37d02ce2f05755c4addd351
5
+ SHA512:
6
+ metadata.gz: 87df72d054ec674f2b3b06e8ebb747001dc7a7ed709627a7dcfad7848337dcc478f12c3d3141737f0f60a04def4f6183073274bdb38aed32e758554e940b509a
7
+ data.tar.gz: 57ee26b0a4f0cfa3f2038980ad235b084b56aca6e5807ad3f8527f7e0a07747d48d92e3c1ed6622008b3a76a3cd515e975f942b01d8da09e3a7e3b1aea3bf850
data/.gitignore ADDED
@@ -0,0 +1,17 @@
1
+ *.gem
2
+ *.rbc
3
+ .bundle
4
+ .config
5
+ .yardoc
6
+ Gemfile.lock
7
+ InstalledFiles
8
+ _yardoc
9
+ coverage
10
+ doc/
11
+ lib/bundler/man
12
+ pkg
13
+ rdoc
14
+ spec/reports
15
+ test/tmp
16
+ test/version_tmp
17
+ tmp
data/Gemfile ADDED
@@ -0,0 +1,4 @@
1
+ source 'https://rubygems.org'
2
+
3
+ # Specify your gem's dependencies in goodyear.gemspec
4
+ gemspec
data/LICENSE.txt ADDED
@@ -0,0 +1,22 @@
1
+ Copyright (c) 2013 Spencer Markowski
2
+
3
+ MIT License
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining
6
+ a copy of this software and associated documentation files (the
7
+ "Software"), to deal in the Software without restriction, including
8
+ without limitation the rights to use, copy, modify, merge, publish,
9
+ distribute, sublicense, and/or sell copies of the Software, and to
10
+ permit persons to whom the Software is furnished to do so, subject to
11
+ the following conditions:
12
+
13
+ The above copyright notice and this permission notice shall be
14
+ included in all copies or substantial portions of the Software.
15
+
16
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
17
+ EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
18
+ MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
19
+ NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
20
+ LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
21
+ OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
22
+ WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
data/README.md ADDED
@@ -0,0 +1,171 @@
1
+ # Goodyear
2
+
3
+ Adds ActiveRecord-like query interface to Tire.
4
+
5
+ ## Installation
6
+
7
+ Add this line to your application's Gemfile:
8
+
9
+ gem 'goodyear'
10
+
11
+ And then execute:
12
+
13
+ $ bundle
14
+
15
+ Or install it yourself as:
16
+
17
+ $ gem install goodyear
18
+
19
+ ## Usage
20
+
21
+
22
+ ```ruby
23
+ class SomeModel < Tire
24
+ include Goodyear::ElasticQuery
25
+ end
26
+ ```
27
+
28
+ #### Better persistence via dynamic attributes.
29
+
30
+ Including `Goodyear::Persistence` in your model means you don't have to worry about defining everything with Tire's `#property` method.
31
+
32
+ ```ruby
33
+ class SomeModel < Tire
34
+ include Goodyear::ElasticQuery
35
+ include Goodyear::Persistence
36
+ end
37
+ ```
38
+
39
+
40
+ ### Query Builder
41
+
42
+ #### where()
43
+
44
+ ```ruby
45
+ SomeModel.where( published: true, topic: "goats")
46
+ ```
47
+
48
+ #### or()
49
+
50
+ ```ruby
51
+ SomeModel.where(status: 'inactive').or.where( retired: true)
52
+ ```
53
+
54
+ #### sort()
55
+
56
+ Orders results by field
57
+
58
+ ```ruby
59
+ SomeModel.where( published: true, name: "Candy").sort(:score, :desc)
60
+ ```
61
+
62
+ #### fields()
63
+
64
+ Specify fields to include in results
65
+
66
+ ```ruby
67
+ SomeModel.where( published: true, name: "Candy").fields(:published, :name, :score)
68
+ ```
69
+
70
+ #### first()
71
+
72
+ Sets size to 1 and fetches the first result. Returns `SomeModel`
73
+
74
+ ```ruby
75
+ SomeModel.where( published: true, name: "Candy").first
76
+ ```
77
+
78
+ #### last()
79
+
80
+ Returns the last result
81
+
82
+ ```ruby
83
+ SomeModel.where( published: true).last
84
+ ```
85
+
86
+
87
+ #### fetch()
88
+
89
+ Exectues the query and returns `TireCollection`
90
+
91
+ ```ruby
92
+ SomeModel.where( published: true).size(100).sort(:score, :desc)
93
+ ```
94
+
95
+
96
+ #### routing(id)
97
+
98
+ Sets routing to id in search options and returns `SomeModel`
99
+
100
+ ```ruby
101
+ SomeModel.routing(10).where( published: true)
102
+ ```
103
+
104
+ #### count
105
+
106
+ Sets search_type to 'count' in search options, fetches and returns total
107
+
108
+ ```ruby
109
+ SomeModel.where( published: true).count
110
+ ```
111
+
112
+ #### search_options(options = {})
113
+
114
+ Sets search options. Overwrites previously set values
115
+
116
+ ```ruby
117
+ SomeModel.search_options(routing: 1, search_type: 'count').where( published: true).fetch
118
+ ```
119
+
120
+
121
+ ### Scopes
122
+
123
+ Add chainable scopes just like you do in ActiveRecord.
124
+
125
+ ```ruby
126
+ class SomeModel
127
+ include Tire::Model::Persistence
128
+ include ActiveRecord::Callbacks
129
+ include Goodyear::ElasticQuery
130
+ include Goodyear::Persistence
131
+ ...
132
+ scope :published, -> { where published: true }
133
+ end
134
+ ```
135
+
136
+ ### Facets
137
+
138
+ Terms facet
139
+ ```ruby
140
+ SomeModel.where(created_at: 1.year.ago).facet('top_users') { terms 'users', size: 50 }
141
+ ```
142
+
143
+ Or maybe a date histogram facet:
144
+ ```ruby
145
+ SomeModel.facet('stats') { date :created_at, interval: "1m",
146
+ pre_zone_adjust_large_interval: true,
147
+ time_zone: "-0500"}
148
+ ```
149
+
150
+
151
+
152
+ ### Query Filters
153
+
154
+ ```ruby
155
+ SomeModel.where(width: 10).filter(:range, {height: { gte: 10, lte: 200} })
156
+ ```
157
+
158
+ There's also a convenience method for Exists filters.
159
+
160
+ ```ruby
161
+ SomeModel.has_field?(:width).where(width:10)
162
+ ```
163
+
164
+
165
+ ## Contributing
166
+
167
+ 1. Fork it
168
+ 2. Create your feature branch (`git checkout -b my-new-feature`)
169
+ 3. Commit your changes (`git commit -am 'Add some feature'`)
170
+ 4. Push to the branch (`git push origin my-new-feature`)
171
+ 5. Create new Pull Request
data/Rakefile ADDED
@@ -0,0 +1 @@
1
+ require "bundler/gem_tasks"
data/goodyear.gemspec ADDED
@@ -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 'goodyear/version'
5
+
6
+ Gem::Specification.new do |spec|
7
+ spec.name = "goodyear"
8
+ spec.version = Goodyear::VERSION
9
+ spec.authors = ["Spencer Markowski"]
10
+ spec.email = ["spencer@theablefew.com"]
11
+ spec.description = %q{ActiveRecord-like query interface for tire}
12
+ spec.summary = %q{ActiveRecord-like query interface for tire}
13
+ spec.homepage = "https://github.com/theablefew/goodyear"
14
+ spec.license = "MIT"
15
+
16
+ spec.files = `git ls-files`.split($/)
17
+ spec.executables = spec.files.grep(%r{^bin/}) { |f| File.basename(f) }
18
+ spec.test_files = spec.files.grep(%r{^(test|spec|features)/})
19
+ spec.require_paths = ["lib"]
20
+
21
+ spec.add_development_dependency "bundler", "~> 1.3"
22
+ spec.add_development_dependency "rake"
23
+ end
@@ -0,0 +1,8 @@
1
+ module Goodyear
2
+ module BooleanMethods
3
+ def or
4
+ self.add_query_segment
5
+ return self
6
+ end
7
+ end
8
+ end
@@ -0,0 +1,23 @@
1
+ module Goodyear
2
+ module Enumerable
3
+ def each &block
4
+ fetch.results.each do |result|
5
+ if block_given?
6
+ block.call result
7
+ else
8
+ yield result
9
+ end
10
+ end
11
+ end
12
+
13
+ def collect &block
14
+ fetch.results.collect do |result|
15
+ if block_given?
16
+ block.call result
17
+ else
18
+ yield result
19
+ end
20
+ end
21
+ end
22
+ end
23
+ end
@@ -0,0 +1,9 @@
1
+ module Goodyear
2
+ module FacetMethods
3
+ def facet(name, options = {}, &block)
4
+ @_facets ||= []
5
+ @_facets << {name: name, args: options, l: block}
6
+ return self
7
+ end
8
+ end
9
+ end
@@ -0,0 +1,21 @@
1
+ module Goodyear
2
+ module FilterMethods
3
+ def filter(name, options = {}, &block)
4
+ @_filters ||= []
5
+ @_filters << {name: name, args: options, l: block}
6
+ return self
7
+ end
8
+
9
+ def has_field?(field)
10
+ filter :exists, {field: field}
11
+ return self
12
+ end
13
+
14
+ def query_filter(name, options = {})
15
+ @_query_filters ||= []
16
+ @_query_filters << {name: name, options: options}
17
+ self
18
+ end
19
+
20
+ end
21
+ end
@@ -0,0 +1,61 @@
1
+ module Goodyear
2
+ module FinderMethods
3
+ def where(*query)
4
+ serialize_arguments(query)
5
+ return self
6
+ end
7
+
8
+ def fields(*f)
9
+ @_fields ||= []
10
+ @_fields = f.collect(&:to_s)
11
+ return self
12
+ end
13
+
14
+ def size(size)
15
+ @_size = size
16
+ return self
17
+ end
18
+
19
+ def sort(*sort_order)
20
+ @_sort = sort_order.compact
21
+ return self
22
+ end
23
+ alias :order :sort
24
+
25
+ def highlight(fields)
26
+ @_highlights = fields
27
+ return self
28
+ end
29
+
30
+ def first
31
+ self.size(1) #maybe more performant?
32
+ self.fetch.first
33
+ end
34
+
35
+ def last
36
+ self.size(1).fetch.results.last
37
+ end
38
+
39
+ def all
40
+ self.size(9999).fetch
41
+ end
42
+
43
+ protected
44
+ def add_query_segment
45
+ @query_segments ||= []
46
+ @query_segments << @_and
47
+ @_and = []
48
+ end
49
+
50
+ private
51
+ def serialize_arguments(q)
52
+ @_and ||= []
53
+ q.each do |arg|
54
+ arg.each_pair { |k,v| @_and << "#{k}:#{v}" } if arg.class == Hash
55
+ @_and << arg if arg.class == String
56
+ end
57
+ end
58
+
59
+
60
+ end
61
+ end
@@ -0,0 +1,13 @@
1
+ module Goodyear
2
+ module Persistence
3
+ def initialize(attrs={})
4
+ attrs.each do |attr, value|
5
+ # call Tire's property method if it hasn't been set explicitly
6
+ self.class.property attr unless self.class.property_types.keys.include? attr
7
+ # set instance variable
8
+ instance_variable_set("@#{attr}", value)
9
+ end
10
+ super attrs
11
+ end
12
+ end
13
+ end
@@ -0,0 +1,51 @@
1
+ module Goodyear
2
+ class Query
3
+ def initialize(q,f,s, sort, highlights, facets, filters, query_filters)
4
+ @q = q || []
5
+ @f = f || []
6
+ @s = s || []
7
+ @sort = sort || []
8
+ @highlights = highlights || []
9
+ @facets = facets
10
+ @filters = filters
11
+ @query_filters = query_filters || []
12
+ end
13
+
14
+ def facets
15
+ @facets || []
16
+ end
17
+
18
+ def filters
19
+ @filters || []
20
+ end
21
+
22
+ def query
23
+ @q
24
+ end
25
+
26
+ def fields
27
+ @f
28
+ end
29
+
30
+ def highlights
31
+ @highlights
32
+ end
33
+
34
+ def size
35
+ @s
36
+ end
37
+
38
+ def sort
39
+ @sort
40
+ end
41
+
42
+ def query_filters
43
+ @query_filters
44
+ end
45
+
46
+
47
+ private
48
+
49
+
50
+ end
51
+ end
File without changes
@@ -0,0 +1,44 @@
1
+ module Goodyear
2
+ module QueryCache
3
+
4
+ def store
5
+ @query_cache ||= setup_store!
6
+ end
7
+
8
+ def cache_query(query)
9
+ cache_key = sha(query)
10
+ Goodyear.force_cache
11
+ result = if store.exist?(cache_key) && Goodyear.force_cache
12
+ ActiveSupport::Notifications.instrument "cache.query.elasticsearch", name: self.name, query: query
13
+ store.fetch cache_key
14
+ else
15
+ res = []
16
+ ActiveSupport::Notifications.instrument "query.elasticsearch", name: self.name, query: query do
17
+ res = yield
18
+ end
19
+ store.write(cache_key, res) if Goodyear.force_cache
20
+ res
21
+ end
22
+ result.dup
23
+ end
24
+
25
+
26
+ private
27
+
28
+ def sha(str)
29
+ Digest::SHA256.new.hexdigest(str)
30
+ end
31
+
32
+ def setup_store!
33
+ case Rails.application.config.goodyear_cache_store
34
+ when :redis_store
35
+ ActiveSupport::Cache::RedisStore
36
+ when :memory_store
37
+ ActiveSupport::Cache::MemoryStore
38
+ else
39
+ ActiveSupport::Cache::MemoryStore
40
+ end.new(namespace: 'elasticsearch', expires_in: Rails.application.config.goodyear_expire_cache_in)
41
+ end
42
+
43
+ end
44
+ end
@@ -0,0 +1,127 @@
1
+ require 'goodyear/query'
2
+ require 'goodyear/finder_methods'
3
+ require 'goodyear/facet_methods'
4
+ require 'goodyear/filter_methods'
5
+ require 'goodyear/boolean_methods'
6
+ require 'goodyear/query_cache'
7
+ require 'goodyear/enumerable'
8
+
9
+ module Goodyear
10
+ module QueryMethods
11
+ include Goodyear::FinderMethods
12
+ include Goodyear::BooleanMethods
13
+ include Goodyear::FacetMethods
14
+ include Goodyear::FilterMethods
15
+ include Goodyear::QueryCache
16
+
17
+ def fetch
18
+ es = self.perform
19
+ options = {wrapper: self, type: document_type}
20
+ options.merge!( @_search_options ) unless @_search_options.nil?
21
+
22
+ @_search_options = nil
23
+
24
+ tire = Tire::Search::Search.new(self.index_name, options)
25
+ if es.query_filters.empty?
26
+ tire.query { string es.query } unless es.query.blank?
27
+ else
28
+ tire.query do
29
+ filtered do
30
+ query { string es.query } unless es.query.blank?
31
+ es.query_filters.each { |f| filter(f[:name], f[:options]) }
32
+ end
33
+ end
34
+ end
35
+
36
+ tire.sort{ by *es.sort } unless es.sort.blank?
37
+ tire.size( es.size ) unless es.size.nil?
38
+ tire.fields( es.fields ) unless es.fields.empty?
39
+ tire.highlight( es.highlights ) unless es.highlights.empty?
40
+
41
+ es.filters.each do |f|
42
+ tire.filter(f[:name], f[:args], &f[:l])
43
+ end
44
+
45
+ es.facets.each do |f|
46
+ tire.facet(f[:name], f[:args], &f[:l] )
47
+ end
48
+
49
+ cache_query(tire.to_curl) { tire.version(true).results }
50
+
51
+ end
52
+
53
+ def perform
54
+ construct_query
55
+ esq = Query.new(@_query, @_fields, @_size, @_sort, @_highlights, @_facets, @_filters, @_query_filters)
56
+ clean
57
+ return esq
58
+ end
59
+
60
+ def search_options(options)
61
+ @_search_options = options
62
+ self
63
+ end
64
+
65
+ def search_type(type)
66
+ @_search_options ||= {}
67
+ @_search_options.merge! search_type: type
68
+ self
69
+ end
70
+
71
+ def count
72
+ search_type 'count'
73
+ fetch.total
74
+ end
75
+
76
+ def results
77
+ fetch.results
78
+ end
79
+
80
+ def routing(r)
81
+ @_search_options ||= {}
82
+ @_search_options.merge! routing: r
83
+ self
84
+ end
85
+
86
+ def scope(name, scope_options = {})
87
+ name = name.to_sym
88
+
89
+ scope_proc = lambda do |*args|
90
+ options = scope_options.respond_to?(:call) ? scope_options.call(*args) : scope_options
91
+ end
92
+
93
+ singleton_class.send(:define_method, name, &scope_proc)
94
+ end
95
+
96
+ alias :to_query :perform
97
+
98
+ def reset_query
99
+ clean
100
+ end
101
+
102
+ private
103
+
104
+ def clean
105
+ @_fields = []
106
+ @_and = []
107
+ @_size = nil
108
+ @_sort = []
109
+ @_or = []
110
+ @_facets = []
111
+ @_filters = []
112
+ @_highlights = []
113
+ @query_segments = []
114
+ @_query_filters = nil
115
+ end
116
+
117
+ def construct_query
118
+ @query_segments ||= []
119
+ @query_segments << @_and
120
+ @_query = @query_segments.collect do |segment|
121
+ next if segment.nil?
122
+ segment.uniq.join(" AND ")
123
+ end.join(" OR ")
124
+ end
125
+
126
+ end
127
+ end
@@ -0,0 +1,27 @@
1
+ module Goodyear
2
+ class Railtie < Rails::Railtie
3
+ include ActionView::Helpers::NumberHelper
4
+ def time_diff(start, finish)
5
+ begin
6
+ ((finish.to_time - start.to_time) * 1000).to_s(:rounded, precision: 5, strip_insignificant_zeros: true)
7
+ rescue
8
+ number_with_precision((finish.to_time - start.to_time) * 1000, precision: 5, strip_insignificant_zeros: true)
9
+ end
10
+ end
11
+
12
+ ActiveSupport::Notifications.subscribe 'query.elasticsearch' do |name, start, finish, id, payload|
13
+ Rails.logger.info(["#{payload[:name]}".bright, "(#{time_diff(start,finish)}ms)",payload[:query]].join(" ").color(:yellow))
14
+ end
15
+
16
+ ActiveSupport::Notifications.subscribe 'cache.query.elasticsearch' do |name, start, finish, id, payload|
17
+ Rails.logger.info(["#{payload[:name]}".bright, "CACHE".color(:magenta).bright ,"(#{time_diff(start,finish)}ms)", payload[:query]].join(" ").color(:yellow))
18
+ end
19
+
20
+ initializer 'goodyear.set_defaults' do
21
+ config.goodyear_cache_store = :redis_store
22
+ config.goodyear_expire_cache_in = 15.minutes
23
+ #config.goodyear_perform_caching = true
24
+ end
25
+
26
+ end
27
+ end
@@ -0,0 +1,3 @@
1
+ module Goodyear
2
+ VERSION = "0.1.0"
3
+ end
data/lib/goodyear.rb ADDED
@@ -0,0 +1,28 @@
1
+ require 'goodyear/railtie' if defined?(Rails)
2
+ require "goodyear/version"
3
+ require "goodyear/query_methods"
4
+ require 'goodyear/persistence'
5
+
6
+ module Goodyear
7
+ mattr_accessor :force_cache
8
+ @@force_cache = false
9
+
10
+ module ElasticQuery
11
+
12
+ def self.included(base)
13
+ base.extend(Goodyear::QueryMethods)
14
+ end
15
+
16
+ def escape_id
17
+ id.gsub('-','\\-')
18
+ end
19
+ end
20
+
21
+ def self.cache
22
+ Goodyear.force_cache = true
23
+ lm = yield
24
+ Goodyear.force_cache = false
25
+ lm
26
+ end
27
+ end
28
+
metadata ADDED
@@ -0,0 +1,91 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: goodyear
3
+ version: !ruby/object:Gem::Version
4
+ version: 0.1.0
5
+ platform: ruby
6
+ authors:
7
+ - Spencer Markowski
8
+ autorequire:
9
+ bindir: bin
10
+ cert_chain: []
11
+ date: 2014-01-25 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.3'
20
+ type: :development
21
+ prerelease: false
22
+ version_requirements: !ruby/object:Gem::Requirement
23
+ requirements:
24
+ - - ~>
25
+ - !ruby/object:Gem::Version
26
+ version: '1.3'
27
+ - !ruby/object:Gem::Dependency
28
+ name: rake
29
+ requirement: !ruby/object:Gem::Requirement
30
+ requirements:
31
+ - - '>='
32
+ - !ruby/object:Gem::Version
33
+ version: '0'
34
+ type: :development
35
+ prerelease: false
36
+ version_requirements: !ruby/object:Gem::Requirement
37
+ requirements:
38
+ - - '>='
39
+ - !ruby/object:Gem::Version
40
+ version: '0'
41
+ description: ActiveRecord-like query interface for tire
42
+ email:
43
+ - spencer@theablefew.com
44
+ executables: []
45
+ extensions: []
46
+ extra_rdoc_files: []
47
+ files:
48
+ - .gitignore
49
+ - Gemfile
50
+ - LICENSE.txt
51
+ - README.md
52
+ - Rakefile
53
+ - goodyear.gemspec
54
+ - lib/goodyear.rb
55
+ - lib/goodyear/boolean_methods.rb
56
+ - lib/goodyear/enumerable.rb
57
+ - lib/goodyear/facet_methods.rb
58
+ - lib/goodyear/filter_methods.rb
59
+ - lib/goodyear/finder_methods.rb
60
+ - lib/goodyear/persistence.rb
61
+ - lib/goodyear/query.rb
62
+ - lib/goodyear/query_builder.rb
63
+ - lib/goodyear/query_cache.rb
64
+ - lib/goodyear/query_methods.rb
65
+ - lib/goodyear/railtie.rb
66
+ - lib/goodyear/version.rb
67
+ homepage: https://github.com/theablefew/goodyear
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.0.6
88
+ signing_key:
89
+ specification_version: 4
90
+ summary: ActiveRecord-like query interface for tire
91
+ test_files: []