greyscale_record 0.0.1

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: '04649514246f75d5ecd1d02fba8b1b773744d771'
4
+ data.tar.gz: de857e40fabfa2d27622f7f6957eed6b9602b5f3
5
+ SHA512:
6
+ metadata.gz: eb2a45fc827f0e4e1f5ea48bfd0589c1d3e9c73cf605330bc8c50e18188723759425a72d6c88bedf8b9adc9b40c33f086d36fe1b58a923f47e26f87824e95b8f
7
+ data.tar.gz: d218efe8bda685f876c4526bc58bdafaaa8b56624901225abe9a3e74c0bccd75a9970579503869837dffc78e335413da269ab0081d0c89b8136868b7c9ced85d
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/.travis.yml ADDED
@@ -0,0 +1,5 @@
1
+ sudo: false
2
+ language: ruby
3
+ rvm:
4
+ - 2.3.3
5
+ before_install: gem install bundler -v 1.13.7
@@ -0,0 +1,74 @@
1
+ # Contributor Covenant Code of Conduct
2
+
3
+ ## Our Pledge
4
+
5
+ In the interest of fostering an open and welcoming environment, we as
6
+ contributors and maintainers pledge to making participation in our project and
7
+ our community a harassment-free experience for everyone, regardless of age, body
8
+ size, disability, ethnicity, gender identity and expression, level of experience,
9
+ nationality, personal appearance, race, religion, or sexual identity and
10
+ orientation.
11
+
12
+ ## Our Standards
13
+
14
+ Examples of behavior that contributes to creating a positive environment
15
+ include:
16
+
17
+ * Using welcoming and inclusive language
18
+ * Being respectful of differing viewpoints and experiences
19
+ * Gracefully accepting constructive criticism
20
+ * Focusing on what is best for the community
21
+ * Showing empathy towards other community members
22
+
23
+ Examples of unacceptable behavior by participants include:
24
+
25
+ * The use of sexualized language or imagery and unwelcome sexual attention or
26
+ advances
27
+ * Trolling, insulting/derogatory comments, and personal or political attacks
28
+ * Public or private harassment
29
+ * Publishing others' private information, such as a physical or electronic
30
+ address, without explicit permission
31
+ * Other conduct which could reasonably be considered inappropriate in a
32
+ professional setting
33
+
34
+ ## Our Responsibilities
35
+
36
+ Project maintainers are responsible for clarifying the standards of acceptable
37
+ behavior and are expected to take appropriate and fair corrective action in
38
+ response to any instances of unacceptable behavior.
39
+
40
+ Project maintainers have the right and responsibility to remove, edit, or
41
+ reject comments, commits, code, wiki edits, issues, and other contributions
42
+ that are not aligned to this Code of Conduct, or to ban temporarily or
43
+ permanently any contributor for other behaviors that they deem inappropriate,
44
+ threatening, offensive, or harmful.
45
+
46
+ ## Scope
47
+
48
+ This Code of Conduct applies both within project spaces and in public spaces
49
+ when an individual is representing the project or its community. Examples of
50
+ representing a project or community include using an official project e-mail
51
+ address, posting via an official social media account, or acting as an appointed
52
+ representative at an online or offline event. Representation of a project may be
53
+ further defined and clarified by project maintainers.
54
+
55
+ ## Enforcement
56
+
57
+ Instances of abusive, harassing, or otherwise unacceptable behavior may be
58
+ reported by contacting the project team at gaorlov@gmail.com. All
59
+ complaints will be reviewed and investigated and will result in a response that
60
+ is deemed necessary and appropriate to the circumstances. The project team is
61
+ obligated to maintain confidentiality with regard to the reporter of an incident.
62
+ Further details of specific enforcement policies may be posted separately.
63
+
64
+ Project maintainers who do not follow or enforce the Code of Conduct in good
65
+ faith may face temporary or permanent repercussions as determined by other
66
+ members of the project's leadership.
67
+
68
+ ## Attribution
69
+
70
+ This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4,
71
+ available at [http://contributor-covenant.org/version/1/4][version]
72
+
73
+ [homepage]: http://contributor-covenant.org
74
+ [version]: http://contributor-covenant.org/version/1/4/
data/Gemfile ADDED
@@ -0,0 +1,4 @@
1
+ source 'https://rubygems.org'
2
+
3
+ # Specify your gem's dependencies in greyscale_record.gemspec
4
+ gemspec
data/LICENSE.txt ADDED
@@ -0,0 +1,21 @@
1
+ The MIT License (MIT)
2
+
3
+ Copyright (c) 2017 Greg Orlov
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,225 @@
1
+ # Greyscale Record
2
+
3
+ `GreyscaleRecord` is a simple read-only implementation of [YamlRecord](https://github.com/nicotaing/yaml_record). It's designed for users whose data is perfectly static and is stored in a flat file format (e.g. yaml files). It is a clone of [YamlBSides](https://github.com/gaorlov/yaml_b_sides), but is extended to support multiple backend drivers (YAML files, Greyscale API)
4
+
5
+ ## Installation
6
+
7
+ Add this line to your application's Gemfile:
8
+
9
+ ```ruby
10
+ gem 'greyscale_record'
11
+ ```
12
+
13
+ And then execute:
14
+
15
+ $ bundle
16
+
17
+ Or install it yourself as:
18
+
19
+ $ gem install greyscale_record
20
+
21
+ ## Usage
22
+
23
+ `Greyscale Record` acts very mich like active record. You set up your base class like you would an ActiveRecord class:
24
+
25
+ ```ruby
26
+ class Person < GreyscaleRecord::Base
27
+ ```
28
+
29
+ and your `#{FIXTURES_PATH}/people.yml` (see [Setup](#setup) for fixtures path setup):
30
+
31
+ ```yml
32
+ greg:
33
+ name: Greg Orlov
34
+ url_slug: greg
35
+ bio: |
36
+ I do stuff
37
+
38
+ john:
39
+ name: John Doe
40
+ # ... etc
41
+ ```
42
+
43
+ and you're in business. Your `Person` objects will now respond to the *present* fields as methods. (see [Properties](#property-definitions) for setting defaults)
44
+
45
+ Note: `Greyscale Record` expects your class names to match the fixture names (e.g. `Person` will want a `people.yml` file)
46
+
47
+ Your `Person` class now responds to
48
+
49
+ ### Query Methods
50
+
51
+ * `all` : will give you all of the records in the table
52
+ * `first` : wil return the first record in the table
53
+ * `find( id )` : will find a single record with the specified yaml key
54
+ * `find_by( properties = {} )` : will find all the recored that match all the proerties in the hash
55
+
56
+ ### Indexing
57
+
58
+ * `index( field )` : will add an index on that field, for faster searching
59
+
60
+ ### Property definitions
61
+
62
+ These are completely optional, but if you have a yaml file that's not uniform, and want to have some defaults, you can use
63
+
64
+ * `property( name, defaul= nil )` : will set a single field. will set defaul value to nil if omitted
65
+ * `properties( props = {})` : takes a hash; will set many defaults at once
66
+
67
+ ### Associations
68
+
69
+ You can define simple associations that behave very much like ActiveRecord associations. Once you define your association, you will have a method with that name that will do the lookups and cache the results for you.
70
+
71
+ * `belongs_to association`: the base object has to have the association id
72
+ * will return a single object or nil
73
+ * `has_one`: the assiociation object has the id of the base.
74
+ * will return a single object or nil
75
+ * `has_many`: the association object has the id of the base.
76
+ * will return an array
77
+
78
+ #### Assocaition Options
79
+
80
+ Associations have some of the standard ActiveRecord options. Namely:
81
+ * `class`: specifies the class to find the record in.
82
+
83
+ ```ruby
84
+ has_one :special_thing, class: Thing
85
+ ```
86
+
87
+ * `class_name`: specifies the class w.o having to have the class defined. Handy for circular dependencies
88
+
89
+ ```ruby
90
+ class Person < GreyscaleRecord::Base
91
+ has_one :nickname, class_name: "Pesudonym"
92
+ end
93
+
94
+ class Pseudonym < GreyscaleRecord::Base
95
+ belongs_to :bearer, class_name: "Person"
96
+ end
97
+ ```
98
+
99
+ * `through`: many to may association helper.
100
+
101
+ ```ruby
102
+ class Person < GreyscaleRecord::Base
103
+ has_many :person_foods
104
+ has_many :favorite_foods, through: :person_foods, class_name: "Food"
105
+ end
106
+
107
+ class PersonFood < GreyscaleRecord::Base
108
+ belongs_to :person
109
+ belongs_to :food
110
+ end
111
+
112
+ class Food < GreyscaleRecord::Base
113
+ end
114
+ ```
115
+
116
+ __NOTE__: only works for `has_one` and `has_many`
117
+
118
+ * `as`: specifies what the associated object calls the caller
119
+ ```ruby
120
+ class Person
121
+ has_many :images, as: :target
122
+ end
123
+
124
+ class Image
125
+ belongs_to :target, class: Person
126
+ end
127
+ ```
128
+ __NOTE__: only works for `has_one` and `has_many`
129
+
130
+ * `polymorphic`: specifies a polymorphic `belongs_to` association. Better explanation [here, on the ActiveRecord page](http://guides.rubyonrails.org/association_basics.html#polymorphic-associations)
131
+ ```ruby
132
+ class Person
133
+ has_many :images, as: :target
134
+ end
135
+
136
+ class Party
137
+ has_many :images, as: :target
138
+ end
139
+
140
+ class Image
141
+ belongs_to :target, polymorphic: true
142
+ end
143
+ ```
144
+ And then the `images.yml` looks something like
145
+ ```yml
146
+ image-1:
147
+ thing_id: a
148
+ thing_class: Person
149
+ # ...
150
+ image-2:
151
+ thing_id: a
152
+ thing_class: PArty
153
+ #...
154
+ ```
155
+
156
+ ### Example
157
+
158
+ To use the `People` class from earlier, a fully fleshed out model would look something like:
159
+
160
+ ```ruby
161
+ class Person < GreyscaleRecord::Base
162
+ property :name, ""
163
+ properties url_slug: "",
164
+ bio: ""
165
+
166
+ has_many :nicknames
167
+
168
+ index :name
169
+ index :url_slug
170
+ end
171
+
172
+ class Nickname < GreyscaleRecord::Base
173
+ belongs_to :person
174
+ end
175
+
176
+ ```
177
+
178
+ and the YAML files will look like
179
+
180
+ ```yml
181
+ # in people.yml
182
+ mark_twain:
183
+ name: Mark Twain
184
+ url_slug: mark-twain
185
+ #...
186
+
187
+ # in nicknames.yml
188
+ sam_clemmens:
189
+ name: Samuel Clemmens
190
+ person_id: mark_twain
191
+ ```
192
+
193
+
194
+ ## Setup
195
+
196
+ The setup is pretty straightforward. Greyscale Record wants a logger and a base dir to look for files in. An example config for a Rails app would look like:
197
+
198
+ ```ruby
199
+ GreyscaleRecord::logger = Rails.logger
200
+ # for now this is the only driver
201
+ GreyscaleRecord::Base.driver = GreyscaleRecord::Drivers::Yaml
202
+ GreyscaleRecord::Drivers::Yaml.root = Rails.root.join 'db', 'fixtures'
203
+
204
+
205
+ # in development.rb
206
+
207
+ # eanble reload of the data files to avoid having to restart the server for every change
208
+ GreyscaleRecord.live_reload = true
209
+ ```
210
+
211
+ ## Development
212
+
213
+ After checking out the repo, run `bin/setup` to install dependencies. Then, run `rake test` to run the tests. You can also run `bin/console` for an interactive prompt that will allow you to experiment.
214
+
215
+ 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`, which will create a git tag for the version, push git commits and tags, and push the `.gem` file to [rubygems.org](https://rubygems.org).
216
+
217
+ ## Contributing
218
+
219
+ Bug reports and pull requests are welcome on GitHub at https://github.com/gaorlov/greyscale_record.
220
+
221
+
222
+ ## License
223
+
224
+ The gem is available as open source under the terms of the [MIT License](http://opensource.org/licenses/MIT).
225
+
data/Rakefile ADDED
@@ -0,0 +1,10 @@
1
+ require "bundler/gem_tasks"
2
+ require "rake/testtask"
3
+
4
+ Rake::TestTask.new(:test) do |t|
5
+ t.libs << "test"
6
+ t.libs << "lib"
7
+ t.test_files = FileList['test/**/*_test.rb']
8
+ end
9
+
10
+ task :default => :test
data/bin/console ADDED
@@ -0,0 +1,14 @@
1
+ #!/usr/bin/env ruby
2
+
3
+ require "bundler/setup"
4
+ require "greyscale_record"
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,8 @@
1
+ #!/usr/bin/env bash
2
+ set -euo pipefail
3
+ IFS=$'\n\t'
4
+ set -vx
5
+
6
+ bundle install
7
+
8
+ # Do any other automated setup that you need to do here
@@ -0,0 +1,34 @@
1
+ # coding: utf-8
2
+ lib = File.expand_path('../lib', __FILE__)
3
+ $LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
4
+ require 'greyscale_record/version'
5
+
6
+ Gem::Specification.new do |spec|
7
+ spec.name = "greyscale_record"
8
+ spec.version = GreyscaleRecord::VERSION
9
+ spec.authors = ["Greg Orlov"]
10
+ spec.email = ["gaorlov@gmail.com"]
11
+
12
+ spec.summary = "A light AcriveRecord like wrapper for a flat data interface, such as YAML files, or the Geyscale API"
13
+ spec.description = "An ActiveRecord-like interface for reading from & queryeing flat data interfaces"
14
+ spec.homepage = "https://github.com/greyscale-io/greyscale_record"
15
+ spec.license = "MIT"
16
+
17
+ spec.files = `git ls-files -z`.split("\x0").reject do |f|
18
+ f.match(%r{^(test|spec|features)/})
19
+ end
20
+ spec.bindir = "exe"
21
+ spec.executables = spec.files.grep(%r{^exe/}) { |f| File.basename(f) }
22
+ spec.require_paths = ["lib"]
23
+
24
+
25
+ spec.add_dependency "activesupport"
26
+ spec.add_dependency "activemodel"
27
+
28
+ spec.add_development_dependency "bundler", "~> 1.13"
29
+ spec.add_development_dependency "rake", "~> 10.0"
30
+ spec.add_development_dependency "minitest", "~> 5.0"
31
+ spec.add_development_dependency "simplecov"
32
+ spec.add_development_dependency "m"
33
+
34
+ end
@@ -0,0 +1,57 @@
1
+ module GreyscaleRecord
2
+ module Associatable
3
+ extend ActiveSupport::Concern
4
+
5
+ included do
6
+ class_attribute :__associations
7
+ self.__associations = {}
8
+
9
+ attr_accessor :_cached_associations
10
+
11
+ class << self
12
+
13
+ def belongs_to( name, opts = {} )
14
+ association = Associations::BelongsTo.new( self, name, opts )
15
+ process association
16
+ index association.key
17
+ end
18
+
19
+ def has_one( name, opts = {} )
20
+ process Associations::HasOne.new( self, name, opts )
21
+ end
22
+
23
+ def has_many( name, opts = {} )
24
+ process Associations::HasMany.new( self, name, opts )
25
+ end
26
+
27
+ protected
28
+
29
+ def process( association )
30
+ associate association
31
+ methodize association
32
+ end
33
+
34
+ def associate( association )
35
+ self.__associations = __associations.merge association.name => association
36
+ end
37
+
38
+ def methodize( association )
39
+ define_method association.name do
40
+ begin
41
+ self._cached_associations ||= {}
42
+
43
+ unless self._cached_associations.has_key? association.name
44
+ result = association.klass( self ).send( association.action, association.query( self ) )
45
+
46
+ self._cached_associations[association.name] = result
47
+ end
48
+ self._cached_associations[association.name]
49
+ rescue GreyscaleRecord::Errors::RecordNotFound => e
50
+ nil
51
+ end
52
+ end
53
+ end
54
+ end
55
+ end
56
+ end
57
+ end
@@ -0,0 +1,53 @@
1
+ module GreyscaleRecord
2
+ module Associations
3
+ class Base
4
+
5
+ attr_accessor :name, :opts, :key
6
+
7
+ def initialize( base_class, name, opts = {} )
8
+ self.name = name
9
+ self.opts = opts
10
+ self.key = idify base_class
11
+
12
+ sanitize_opts( base_class )
13
+ end
14
+
15
+ def klass( instance = nil )
16
+ @klass ||= association_class name, opts
17
+ end
18
+
19
+ protected
20
+
21
+ def association_class( name, opts = {} )
22
+ a_class = opts[:class] if opts.has_key? :class
23
+ a_class_name = opts[:class_name].constantize if opts.has_key? :class_name
24
+
25
+ a_class || a_class_name || derived_class_for( name )
26
+ end
27
+
28
+ def derived_class_for( name )
29
+ name.to_s.singularize.classify.constantize
30
+ end
31
+
32
+ def idify( class_name )
33
+ "#{class_name.to_s.demodulize.underscore}_id"
34
+ end
35
+
36
+ def supported_options
37
+ [ :class, :class_name ] + additional_options
38
+ end
39
+
40
+ def sanitize_opts( base_class )
41
+ if name.to_s == "object"
42
+ raise GreyscaleRecord::Errors::AssociationError, "#{base_class}: 'object_id' is a reserved keyword in ruby and cannot be overridden"
43
+ end
44
+ invalid_options = (opts.keys - supported_options)
45
+ if invalid_options.present?
46
+ list = invalid_options.map{|o|"'#{o}'"}.to_sentence
47
+ plural = invalid_options.count > 1
48
+ raise GreyscaleRecord::Errors::AssociationError, "#{base_class}: #{list} #{plural ? "are" : "is"} not supported. Please see README for full details: http://www.github.com/greyscale-io/greyscale_record"
49
+ end
50
+ end
51
+ end
52
+ end
53
+ end
@@ -0,0 +1,36 @@
1
+ module GreyscaleRecord
2
+ module Associations
3
+ class BelongsTo < Base
4
+ def action
5
+ :find
6
+ end
7
+
8
+ def key
9
+ "#{name}_id"
10
+ end
11
+
12
+ def query( instance )
13
+ instance.send key
14
+ end
15
+
16
+ def klass( instance )
17
+ if polymorphic?
18
+ class_name = instance.send "#{name}_class"
19
+ class_name.constantize
20
+ else
21
+ super
22
+ end
23
+ end
24
+
25
+ protected
26
+
27
+ def additional_options
28
+ [ :polymorphic ]
29
+ end
30
+
31
+ def polymorphic?
32
+ opts[:polymorphic]
33
+ end
34
+ end
35
+ end
36
+ end
@@ -0,0 +1,11 @@
1
+ module GreyscaleRecord
2
+ module Associations
3
+ class HasMany < Base
4
+ include Hasable
5
+
6
+ def action
7
+ :where
8
+ end
9
+ end
10
+ end
11
+ end
@@ -0,0 +1,11 @@
1
+ module GreyscaleRecord
2
+ module Associations
3
+ class HasOne < Base
4
+ include Hasable
5
+
6
+ def action
7
+ :find_by
8
+ end
9
+ end
10
+ end
11
+ end
@@ -0,0 +1,54 @@
1
+ module GreyscaleRecord
2
+ module Associations
3
+ module Hasable
4
+ extend ActiveSupport::Concern
5
+
6
+ included do
7
+
8
+ def query( instance )
9
+ if through?
10
+ { id: target_ids( instance ) }
11
+ elsif as?
12
+ { "#{as}_id" => instance.id }
13
+ else
14
+ { key => instance.id }
15
+ end
16
+ end
17
+
18
+ def additional_options
19
+ [ :as, :through ]
20
+ end
21
+
22
+ protected
23
+
24
+ def through
25
+ opts[:through]
26
+ end
27
+
28
+ def through?
29
+ opts.has_key? :through
30
+ end
31
+
32
+ def as
33
+ opts[:as]
34
+ end
35
+
36
+ def as?
37
+ opts.has_key? :as
38
+ end
39
+
40
+ def target_ids( instance )
41
+ intermadiates = Array(instance.send( through ) )
42
+
43
+ intermadiates.map do | intermediate |
44
+ intermediate.send( through_key )
45
+ end
46
+ end
47
+
48
+ def through_key
49
+ idify klass
50
+ end
51
+ end
52
+ end
53
+ end
54
+ end
@@ -0,0 +1,9 @@
1
+ module GreyscaleRecord
2
+ module Associations
3
+ autoload :Base, 'greyscale_record/associations/base'
4
+ autoload :BelongsTo, 'greyscale_record/associations/belongs_to'
5
+ autoload :Hasable, 'greyscale_record/associations/hasable'
6
+ autoload :HasMany, 'greyscale_record/associations/has_many'
7
+ autoload :HasOne, 'greyscale_record/associations/has_one'
8
+ end
9
+ end
@@ -0,0 +1,48 @@
1
+ module GreyscaleRecord
2
+ class Base
3
+ include ActiveModel::Model
4
+ include Associatable
5
+ include Cacheable
6
+ include Propertiable
7
+ include Indexable
8
+ include Instanceable
9
+ include Queriable
10
+
11
+ class_attribute :data
12
+ class_attribute :driver
13
+
14
+ class << self
15
+
16
+ def load!
17
+ @data = driver.load!(_class_name)
18
+ return unless @data
19
+
20
+ # let's preemptively index by id so that when we do a find_by id:, or a where id: it won't table scan
21
+ idify_data!
22
+
23
+ index :id unless GreyscaleRecord.live_reload
24
+ end
25
+
26
+ def inherited(subclass)
27
+ subclass.load!
28
+ end
29
+
30
+ protected
31
+
32
+ def _class_name
33
+ self.name.pluralize.downcase
34
+ end
35
+
36
+ def idify_data!
37
+ @data.each do |k, v|
38
+ v[:id] = k
39
+ end
40
+ end
41
+
42
+ def data
43
+ load! if GreyscaleRecord.live_reload
44
+ @data
45
+ end
46
+ end
47
+ end
48
+ end
@@ -0,0 +1,17 @@
1
+ module GreyscaleRecord
2
+ module Cacheable
3
+ extend ActiveSupport::Concern
4
+
5
+ included do
6
+ class << self
7
+ def cache_key
8
+ @cache_key ||= Digest::SHA256.hexdigest(data.to_json)
9
+ end
10
+ end
11
+
12
+ def cache_key
13
+ @cache_key ||= Digest::SHA256.hexdigest(@attributes.to_json)
14
+ end
15
+ end
16
+ end
17
+ end
@@ -0,0 +1,31 @@
1
+ module GreyscaleRecord
2
+ module Drivers
3
+ class Base
4
+
5
+ class_attribute :root
6
+
7
+ class << self
8
+ def load!(class_name)
9
+
10
+ raise GreyscaleRecord::DriverError "driver needs to define a `root`" unless root
11
+
12
+ data = load_data(class_name)
13
+
14
+ GreyscaleRecord.logger.info "#{class_name} successfully loaded data"
15
+
16
+ data
17
+
18
+ rescue => e
19
+ GreyscaleRecord.logger.error "#{self} failed to load data for #{class_name}: #{e}"
20
+ return nil
21
+ end
22
+
23
+ private
24
+
25
+ def load_data
26
+ raise NotImplementedError "load_data is not implemented"
27
+ end
28
+ end
29
+ end
30
+ end
31
+ end
@@ -0,0 +1,19 @@
1
+ module GreyscaleRecord
2
+ module Drivers
3
+ class Yaml < Base
4
+
5
+ class << self
6
+
7
+ private
8
+
9
+ def load_data( class_name )
10
+ YAML.load_file( data_file( class_name ) ).with_indifferent_access
11
+ end
12
+
13
+ def data_file( class_name )
14
+ [root, "#{class_name}.yml"].compact.join("/")
15
+ end
16
+ end
17
+ end
18
+ end
19
+ end
@@ -0,0 +1,7 @@
1
+ module GreyscaleRecord
2
+ module Drivers
3
+ autoload :Base, 'greyscale_record/drivers/base'
4
+ autoload :GreyscaleAPI, 'greyscale_record/drivers/greyscale_api'
5
+ autoload :Yaml, 'greyscale_record/drivers/yaml'
6
+ end
7
+ end
@@ -0,0 +1,15 @@
1
+ module GreyscaleRecord
2
+ module Errors
3
+ class RecordNotFound < StandardError
4
+ end
5
+
6
+ class AssociationError < StandardError
7
+ end
8
+
9
+ class InvalidFieldError < StandardError
10
+ end
11
+
12
+ class DriverError < StandardError
13
+ end
14
+ end
15
+ end
@@ -0,0 +1,23 @@
1
+ module GreyscaleRecord
2
+ class Index
3
+ def initialize(field, data)
4
+ @indexed_data = {}
5
+ data.each do |id, datum|
6
+ key = datum[field]
7
+
8
+ # storing key => array of matching ids
9
+ @indexed_data[key] = Array(@indexed_data[key]) + [id]
10
+ end
11
+ end
12
+
13
+ # returns ids
14
+ def find(values)
15
+ # find all the arrays of ids for the values,
16
+ # get rid of nils (value not present),
17
+ # and compact for a single array result
18
+ values.map do |value|
19
+ @indexed_data[value]
20
+ end.compact.flatten
21
+ end
22
+ end
23
+ end
@@ -0,0 +1,35 @@
1
+ module GreyscaleRecord
2
+ module Indexable
3
+ extend ActiveSupport::Concern
4
+
5
+ included do
6
+ class_attribute :__indices
7
+ self.__indices = { }
8
+
9
+ class << self
10
+ def index(field)
11
+ return if GreyscaleRecord.live_reload
12
+ self.__indices = __indices.merge( { field => Index.new(field, data) } )
13
+ end
14
+
15
+ def find_in_index(field, values)
16
+ keys = Array(index_for(field).find(values))
17
+
18
+ keys.map do |id|
19
+ data[id]
20
+ end
21
+ end
22
+
23
+ def indexed?(field)
24
+ __indices[field].present?
25
+ end
26
+
27
+ protected
28
+
29
+ def index_for(field)
30
+ __indices[field]
31
+ end
32
+ end
33
+ end
34
+ end
35
+ end
@@ -0,0 +1,23 @@
1
+ module GreyscaleRecord
2
+ module Instanceable
3
+ extend ActiveSupport::Concern
4
+ included do
5
+ include ActiveModel::Model
6
+
7
+ def method_missing( method, *args, &block )
8
+ if @attributes.has_key? method
9
+ method = @attributes[method]
10
+ else
11
+ raise GreyscaleRecord::Errors::InvalidFieldError, "#{self.class}:#{@attributes[:id]}: Invalid field: '#{method}'"
12
+ end
13
+ end
14
+
15
+ protected
16
+
17
+ # public init really doesn't make sense for a read-only interface
18
+ def initialize( attrs = {} )
19
+ @attributes = self.class.__properties.merge( attrs ).with_indifferent_access
20
+ end
21
+ end
22
+ end
23
+ end
@@ -0,0 +1,27 @@
1
+ module GreyscaleRecord
2
+ module Propertiable
3
+ extend ActiveSupport::Concern
4
+
5
+ included do
6
+ class_attribute :__properties
7
+ self.__properties = {}
8
+
9
+ class << self
10
+ def properties( props = {} )
11
+ self.__properties = __properties.dup
12
+ merge_properties props
13
+ end
14
+
15
+ def property( prop, default = nil )
16
+ merge_properties( { prop => default } )
17
+ end
18
+
19
+ protected
20
+
21
+ def merge_properties( additional_properties = {} )
22
+ self.__properties = __properties.merge( additional_properties )
23
+ end
24
+ end
25
+ end
26
+ end
27
+ end
@@ -0,0 +1,75 @@
1
+ module GreyscaleRecord
2
+ module Queriable
3
+ extend ActiveSupport::Concern
4
+
5
+ included do
6
+ class << self
7
+ def find(id)
8
+ record = data[id]
9
+ raise Errors::RecordNotFound, "#{self}: Record not found: #{id}" unless record
10
+ new record
11
+ end
12
+
13
+ def find_by(params = {})
14
+ results = where params
15
+ raise Errors::RecordNotFound, "#{self}: Could not find record that matches: #{params.inspect}" if results.empty?
16
+ results.first
17
+ end
18
+
19
+ def all
20
+ data.values.map do |obj|
21
+ new obj
22
+ end
23
+ end
24
+
25
+ def first
26
+ new data.values.first
27
+ end
28
+
29
+ # TODO: move this into scopes
30
+ def where(params)
31
+ if all_indexed?(params.keys)
32
+ results = find_by_indexed(params)
33
+ else
34
+ results = find_by_scan(params)
35
+ end
36
+ results.map do |result|
37
+ new result
38
+ end
39
+ end
40
+
41
+ private
42
+
43
+ def find_by_scan(params)
44
+ data.values.select do |datum|
45
+ params.all? do |param, expected_value|
46
+ val = Array(expected_value).include? datum[param]
47
+ end
48
+ end
49
+ end
50
+
51
+ def find_by_indexed(params)
52
+ sets = []
53
+ params.each do |index, values|
54
+ sets << find_in_index(index, Array(values))
55
+ end
56
+
57
+ # find the intersection of all the sets
58
+ sets.inject( sets.first ) do |result, subset|
59
+ result & subset
60
+ end
61
+ end
62
+
63
+ def all_indexed?(fields)
64
+ fields.all? do |field|
65
+ indexed = indexed? field
66
+ unless indexed
67
+ GreyscaleRecord.logger.warn "You are running a query on #{self}.#{field} which is not indexed. This will perform a table scan."
68
+ end
69
+ indexed
70
+ end
71
+ end
72
+ end
73
+ end
74
+ end
75
+ end
@@ -0,0 +1,3 @@
1
+ module GreyscaleRecord
2
+ VERSION = "0.0.1"
3
+ end
@@ -0,0 +1,30 @@
1
+ require "greyscale_record/version"
2
+ require 'active_model'
3
+ require 'active_model/model'
4
+ require 'active_support'
5
+ require 'active_support/concern'
6
+ require 'active_support/core_ext/class/attribute'
7
+ require 'active_support/core_ext/hash'
8
+ require 'yaml'
9
+
10
+ module GreyscaleRecord
11
+ autoload :Associatable, 'greyscale_record/associatable'
12
+ autoload :Associations, 'greyscale_record/associations'
13
+ autoload :Base, 'greyscale_record/base'
14
+ autoload :Cacheable, 'greyscale_record/cacheable'
15
+ autoload :Drivers, 'greyscale_record/drivers'
16
+ autoload :Errors, 'greyscale_record/errors'
17
+ autoload :Instanceable, 'greyscale_record/instanceable'
18
+ autoload :Index, 'greyscale_record/index'
19
+ autoload :Indexable, 'greyscale_record/indexable'
20
+ autoload :Propertiable, 'greyscale_record/propertiable'
21
+ autoload :Queriable, 'greyscale_record/queriable'
22
+
23
+ class << self
24
+ attr_accessor :live_reload
25
+ attr_accessor :logger
26
+ end
27
+
28
+ self.live_reload = false
29
+ self.logger = Logger.new(STDOUT)
30
+ end
metadata ADDED
@@ -0,0 +1,174 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: greyscale_record
3
+ version: !ruby/object:Gem::Version
4
+ version: 0.0.1
5
+ platform: ruby
6
+ authors:
7
+ - Greg Orlov
8
+ autorequire:
9
+ bindir: exe
10
+ cert_chain: []
11
+ date: 2017-06-29 00:00:00.000000000 Z
12
+ dependencies:
13
+ - !ruby/object:Gem::Dependency
14
+ name: activesupport
15
+ requirement: !ruby/object:Gem::Requirement
16
+ requirements:
17
+ - - ">="
18
+ - !ruby/object:Gem::Version
19
+ version: '0'
20
+ type: :runtime
21
+ prerelease: false
22
+ version_requirements: !ruby/object:Gem::Requirement
23
+ requirements:
24
+ - - ">="
25
+ - !ruby/object:Gem::Version
26
+ version: '0'
27
+ - !ruby/object:Gem::Dependency
28
+ name: activemodel
29
+ requirement: !ruby/object:Gem::Requirement
30
+ requirements:
31
+ - - ">="
32
+ - !ruby/object:Gem::Version
33
+ version: '0'
34
+ type: :runtime
35
+ prerelease: false
36
+ version_requirements: !ruby/object:Gem::Requirement
37
+ requirements:
38
+ - - ">="
39
+ - !ruby/object:Gem::Version
40
+ version: '0'
41
+ - !ruby/object:Gem::Dependency
42
+ name: bundler
43
+ requirement: !ruby/object:Gem::Requirement
44
+ requirements:
45
+ - - "~>"
46
+ - !ruby/object:Gem::Version
47
+ version: '1.13'
48
+ type: :development
49
+ prerelease: false
50
+ version_requirements: !ruby/object:Gem::Requirement
51
+ requirements:
52
+ - - "~>"
53
+ - !ruby/object:Gem::Version
54
+ version: '1.13'
55
+ - !ruby/object:Gem::Dependency
56
+ name: rake
57
+ requirement: !ruby/object:Gem::Requirement
58
+ requirements:
59
+ - - "~>"
60
+ - !ruby/object:Gem::Version
61
+ version: '10.0'
62
+ type: :development
63
+ prerelease: false
64
+ version_requirements: !ruby/object:Gem::Requirement
65
+ requirements:
66
+ - - "~>"
67
+ - !ruby/object:Gem::Version
68
+ version: '10.0'
69
+ - !ruby/object:Gem::Dependency
70
+ name: minitest
71
+ requirement: !ruby/object:Gem::Requirement
72
+ requirements:
73
+ - - "~>"
74
+ - !ruby/object:Gem::Version
75
+ version: '5.0'
76
+ type: :development
77
+ prerelease: false
78
+ version_requirements: !ruby/object:Gem::Requirement
79
+ requirements:
80
+ - - "~>"
81
+ - !ruby/object:Gem::Version
82
+ version: '5.0'
83
+ - !ruby/object:Gem::Dependency
84
+ name: simplecov
85
+ requirement: !ruby/object:Gem::Requirement
86
+ requirements:
87
+ - - ">="
88
+ - !ruby/object:Gem::Version
89
+ version: '0'
90
+ type: :development
91
+ prerelease: false
92
+ version_requirements: !ruby/object:Gem::Requirement
93
+ requirements:
94
+ - - ">="
95
+ - !ruby/object:Gem::Version
96
+ version: '0'
97
+ - !ruby/object:Gem::Dependency
98
+ name: m
99
+ requirement: !ruby/object:Gem::Requirement
100
+ requirements:
101
+ - - ">="
102
+ - !ruby/object:Gem::Version
103
+ version: '0'
104
+ type: :development
105
+ prerelease: false
106
+ version_requirements: !ruby/object:Gem::Requirement
107
+ requirements:
108
+ - - ">="
109
+ - !ruby/object:Gem::Version
110
+ version: '0'
111
+ description: An ActiveRecord-like interface for reading from & queryeing flat data
112
+ interfaces
113
+ email:
114
+ - gaorlov@gmail.com
115
+ executables: []
116
+ extensions: []
117
+ extra_rdoc_files: []
118
+ files:
119
+ - ".gitignore"
120
+ - ".travis.yml"
121
+ - CODE_OF_CONDUCT.md
122
+ - Gemfile
123
+ - LICENSE.txt
124
+ - README.md
125
+ - Rakefile
126
+ - bin/console
127
+ - bin/setup
128
+ - greyscale_record.gemspec
129
+ - lib/greyscale_record.rb
130
+ - lib/greyscale_record/associatable.rb
131
+ - lib/greyscale_record/associations.rb
132
+ - lib/greyscale_record/associations/base.rb
133
+ - lib/greyscale_record/associations/belongs_to.rb
134
+ - lib/greyscale_record/associations/has_many.rb
135
+ - lib/greyscale_record/associations/has_one.rb
136
+ - lib/greyscale_record/associations/hasable.rb
137
+ - lib/greyscale_record/base.rb
138
+ - lib/greyscale_record/cacheable.rb
139
+ - lib/greyscale_record/drivers.rb
140
+ - lib/greyscale_record/drivers/base.rb
141
+ - lib/greyscale_record/drivers/yaml.rb
142
+ - lib/greyscale_record/errors.rb
143
+ - lib/greyscale_record/index.rb
144
+ - lib/greyscale_record/indexable.rb
145
+ - lib/greyscale_record/instanceable.rb
146
+ - lib/greyscale_record/propertiable.rb
147
+ - lib/greyscale_record/queriable.rb
148
+ - lib/greyscale_record/version.rb
149
+ homepage: https://github.com/greyscale-io/greyscale_record
150
+ licenses:
151
+ - MIT
152
+ metadata: {}
153
+ post_install_message:
154
+ rdoc_options: []
155
+ require_paths:
156
+ - lib
157
+ required_ruby_version: !ruby/object:Gem::Requirement
158
+ requirements:
159
+ - - ">="
160
+ - !ruby/object:Gem::Version
161
+ version: '0'
162
+ required_rubygems_version: !ruby/object:Gem::Requirement
163
+ requirements:
164
+ - - ">="
165
+ - !ruby/object:Gem::Version
166
+ version: '0'
167
+ requirements: []
168
+ rubyforge_project:
169
+ rubygems_version: 2.5.2
170
+ signing_key:
171
+ specification_version: 4
172
+ summary: A light AcriveRecord like wrapper for a flat data interface, such as YAML
173
+ files, or the Geyscale API
174
+ test_files: []