shrink_wrap 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
checksums.yaml ADDED
@@ -0,0 +1,7 @@
1
+ ---
2
+ SHA1:
3
+ metadata.gz: 44c7258275698404076aaf6de1b39925aad84551
4
+ data.tar.gz: 057b2f07fae9c2bf5cc8cedfb6e5adf7e2a313c0
5
+ SHA512:
6
+ metadata.gz: ba4c353fac441540e0218f61137525370b2df55bbca6141564d76398686ee99896c6313f34d0c0c2e71ca26502568b3fff000404ee0642956a8d6f08219e7eac
7
+ data.tar.gz: baed16d8f899d79c02b3f036b2100b4f3f603785ed97793c6068282c4fd6d426d56539a4aa6ae07e5387d4009f47edb4237554997409943cc05a23c282fdeab0
data/.gitignore ADDED
@@ -0,0 +1,13 @@
1
+ /.bundle/
2
+ /.yardoc
3
+ /_yardoc/
4
+ /coverage/
5
+ /doc/
6
+ /pkg/
7
+ /spec/reports/
8
+ /tmp/
9
+ /vendor/bundle
10
+ Gemfile.lock
11
+
12
+ # rspec failure tracking
13
+ .rspec_status
data/.rspec ADDED
@@ -0,0 +1,3 @@
1
+ --format documentation
2
+ --color
3
+ --require spec_helper
data/.rubocop.yml ADDED
@@ -0,0 +1,11 @@
1
+ AllCops:
2
+ DisplayCopNames: true
3
+ TargetRubyVersion: 2.5
4
+ Exclude:
5
+ - 'bin/**/*'
6
+ - 'vendor/**/*'
7
+ Documentation:
8
+ Enabled: false
9
+ Metrics/BlockLength:
10
+ Exclude:
11
+ - 'spec/**/*'
data/.simplecov ADDED
@@ -0,0 +1,3 @@
1
+ SimpleCov.start do
2
+ SimpleCov.minimum_coverage 100.00
3
+ end
data/.travis.yml ADDED
@@ -0,0 +1,7 @@
1
+ ---
2
+ sudo: false
3
+ language: ruby
4
+ cache: bundler
5
+ rvm:
6
+ - 2.5.1
7
+ before_install: gem install bundler -v 1.16.4
data/CHANGELOG.md ADDED
@@ -0,0 +1,3 @@
1
+ # 0.1.0 - Dec. 2, 2018
2
+
3
+ * Initial release! :sparkles:
@@ -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 jdoyle@ualberta.ca. 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,8 @@
1
+ # frozen_string_literal: true
2
+
3
+ source 'https://rubygems.org'
4
+
5
+ git_source(:github) { |repo_name| "https://github.com/#{repo_name}" }
6
+
7
+ # Specify your gem's dependencies in shrink_wrap.gemspec
8
+ gemspec
data/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ The MIT License (MIT)
2
+
3
+ Copyright (c) 2018 Jesse Doyle
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,275 @@
1
+ # Shrink::Wrap
2
+
3
+ ## What is Shrink::Wrap?
4
+
5
+ Shrink::Wrap is a dead-simple framework to manipulate and map JSON data to Ruby object instances.
6
+
7
+ ## Basic Example
8
+
9
+ Imagine a JSON structure such as:
10
+
11
+ ```json
12
+ {
13
+ "name": "Milky Way",
14
+ "age": "13510000000",
15
+ "solarSystems": [
16
+ {
17
+ "name": "Sol",
18
+ "age": "4571000000",
19
+ "planets": [
20
+ {
21
+ "name": "mercury"
22
+ },
23
+ {
24
+ "name": "venus"
25
+ },
26
+ {
27
+ "name": "earth"
28
+ }
29
+ ]
30
+ }
31
+ ]
32
+ }
33
+ ```
34
+
35
+ With Shrink::Wrap, you'd be able to map the JSON data to Ruby instances as simply as:
36
+
37
+ ```ruby
38
+ data = JSON.parse(File.read('galaxy.json'))
39
+ Galaxy.shrink_wrap(data) # => #<Galaxy:0x007fec71254828
40
+ # @age=13510000000,
41
+ # @name="Milky Way",
42
+ # @solar_systems=
43
+ # [#<SolarSystem:0x007fec71254850
44
+ # @age=4571000000,
45
+ # @name="Sol",
46
+ # @planets=
47
+ # [#<Planet:0x007fec712555c0 @name="MERCURY">,
48
+ # #<Planet:0x007fec712553e0 @name="VENUS">,
49
+ # #<Planet:0x007fec71255200 @name="EARTH">>]>]>
50
+ ```
51
+
52
+ ## How Does it Work?
53
+
54
+ You must include the `Shrink::Wrap` module in your classes to gain access to the `shrink_wrap` method.
55
+
56
+ For the example above, the implementation would look like:
57
+
58
+ ```ruby
59
+ require 'shrink/wrap'
60
+
61
+ class Planet
62
+ include Shrink::Wrap
63
+
64
+ transform(Shrink::Wrap::Transformer::Symbolize)
65
+
66
+ translate(
67
+ name: { from: :name }
68
+ )
69
+
70
+ coerce(
71
+ name: ->(v) { v.upcase }
72
+ )
73
+
74
+ attr_accessor :name
75
+
76
+ def initialize(opts = {})
77
+ self.name = opts.fetch(:name)
78
+ end
79
+ end
80
+
81
+ class SolarSystem
82
+ include Shrink::Wrap
83
+
84
+ transform(Shrink::Wrap::Transformer::Symbolize)
85
+
86
+ translate(
87
+ name: { from: :name },
88
+ age: { from: :age },
89
+ planets: { from: :planets }
90
+ )
91
+
92
+ coerce(
93
+ age: ->(v) { v.to_i },
94
+ planets: Array[Planet]
95
+ )
96
+
97
+ attr_accessor :name, :age, :planets
98
+
99
+ def initialize(opts = {})
100
+ self.name = opts.fetch(:name)
101
+ self.age = opts.fetch(:age)
102
+ self.planets = opts.fetch(:planets)
103
+ end
104
+ end
105
+
106
+ class Galaxy
107
+ include Shrink::Wrap
108
+
109
+ transform(Shrink::Wrap::Transformer::Symbolize)
110
+
111
+ translate(
112
+ name: { from: :name },
113
+ age: { from: :age },
114
+ solar_systems: { from: :solarSystems }
115
+ )
116
+
117
+ coerce(
118
+ age: ->(v) { v.to_i },
119
+ solar_systems: Array[SolarSystem]
120
+ )
121
+
122
+ attr_accessor :name, :age, :solar_systems
123
+
124
+ def initialize(opts = {})
125
+ self.name = opts.fetch(:name)
126
+ self.age = opts.fetch(:age)
127
+ self.solar_systems = opts.fetch(:solar_systems)
128
+ end
129
+ end
130
+ ```
131
+
132
+ ## Order of Operations
133
+
134
+ Shrink::Wrap operations are always deterministically performed in the following order:
135
+
136
+ 1. `transform`
137
+ 2. `translate`
138
+ 3. `coerce`
139
+
140
+ Shrink::Wrap will call the `initialize` method with the data after all operations have been completed.
141
+
142
+ ## Transform
143
+
144
+ The `transform` operation accepts a transformation class as well as an options hash as parameters.
145
+
146
+ The transformation class is any Ruby class that inherits from `Shrink::Wrap::Transformer::Base`.
147
+
148
+ The class must define a `transform(data = {})` method that returns the data after transformations are applied.
149
+
150
+ You can chain transformers together by calling `transform` multiple times in your class. Transformers are always executed sequentially.
151
+
152
+ You can create your own transformer as such:
153
+
154
+ ```ruby
155
+ class FilterEmpty < Shrink::Wrap::Transformer::Base
156
+ def transform(opts = {})
157
+ data.each_with_object({}) do |(key, value), memo|
158
+ memo[key] = value unless value.empty?
159
+ end
160
+ end
161
+ end
162
+ ```
163
+
164
+ ### Built In Transformers
165
+
166
+ Shrink::Wrap provides a few built-in transformer classes for use with common transformation patterns.
167
+
168
+ #### Shrink::Wrap::Transformer::Symbolize
169
+
170
+ In Ruby, it's very common to convert Hash keys to Symbol instances.
171
+
172
+ The Symbolize transformer works similar to ActiveSupport's [`deep_symbolize_keys`](https://api.rubyonrails.org/classes/Hash.html#method-i-deep_symbolize_keys) method, but it is also able to traverse nested data structures (`Array`, `Enumerable`) and symbolize the keys of any nested elements as well.
173
+
174
+ The Symbolize transformer accepts an optional `depth` parameter that defines that maximum depth for symbolization in nested data structures.
175
+
176
+ Example:
177
+
178
+ ```ruby
179
+ class Example
180
+ include Shrink::Wrap
181
+
182
+ transform(Shrink::Wrap::Transformer::Symbolize, depth: 2)
183
+ translate_all
184
+
185
+ attr_accessor :data
186
+
187
+ def initialize(data)
188
+ self.data = data
189
+ end
190
+ end
191
+
192
+ data = { 'root' => [{ 'nested' => 'test' }] }
193
+ instance = Example.shrink_wrap(data)
194
+ instance.data # => {:root=>[{:nested=>"test"}]}
195
+ ```
196
+
197
+ #### Shrink::Wrap::Transformer::CollectionFromKey
198
+
199
+ Some data Hashes contain keys that contain relevant data for object instances.
200
+
201
+ The CollectionFromKey transformer accepts a Hash option that contains a key => attribute mapping.
202
+
203
+ The transformation then creates an Array of elements taken from the key argument and merges the key into each element in the collection.
204
+
205
+ Example:
206
+
207
+ ```ruby
208
+ class Example
209
+ include Shrink::Wrap
210
+
211
+ transform(Shrink::Wrap::Transformer::CollectionFromKey, weekends: :day)
212
+ translate_all
213
+
214
+ attr_accessor :data
215
+
216
+ def initialize(data)
217
+ self.data = data
218
+ end
219
+ end
220
+
221
+ data = {
222
+ weekends: {
223
+ saturday: {
224
+ index: 6
225
+ },
226
+ sunday: {
227
+ index: 0
228
+ }
229
+ }
230
+ }
231
+ instance = Example.shrink_wrap(data)
232
+ instance.data # => {:weekends=>[{:index=>6, :day=>:saturday}, {:index=>0, :day=>:sunday}]}
233
+ ```
234
+
235
+ ## Translate
236
+
237
+ The `translate` operation accepts a Hash that contains key/value pairs that map incoming data to attributes.
238
+
239
+ You can pass the following parameters for each attribute:
240
+
241
+ * `from` [**required**]: The input key that the attribute is mapped to.
242
+ * `allow_nil` [**optional**]: If `true`, the mapped value may be `nil`. When `false`, raises `KeyError` if the mapped value is `nil`.
243
+ * `default` [**optional**]: A `Proc` or `Lambda` that returns a particular value. This argument will be called if the value is `nil`.
244
+
245
+ ### Passing Data During Initialization
246
+
247
+ By default, any attributes not specified in a `translate` call are not passed to the underlying object during initialization.
248
+
249
+ You can call `translate_all` if you wish to pass all of the data but don't wish to explicitly define the attributes in a corresponding `translate` call.
250
+
251
+ ## Coerce
252
+
253
+ The `coerce` operation accepts a hash of attribute keys and coercion values.
254
+
255
+ Coercions must be one of the following types:
256
+
257
+ * `Class`: Tries calling `Class.shrink_wrap(data)`, `Class.coerce(data)`, then `Class.new(data)`, returning the first successful result.
258
+ * `Enumerable`: Coerces the value into the collection of type defined as the Enumerable elements. The first element of the enumerable must be a class name (eg. `Array[MyClass]`, `Hash[MyClass => MyClass]`).
259
+ * `Lambda/Proc`: Coerces the value by calling the `Proc` with the value as the only argument.
260
+
261
+ ## Contributing
262
+
263
+ Bug reports and pull requests are welcome on GitHub at https://github.com/jessedoyle/shrink_wrap.
264
+
265
+ When making code changes please fork the main repository, create a feature branch and then create a pull request with your change. All code changes must contain adequate test coverage.
266
+
267
+ This project is intended to be a safe, welcoming space for collaboration, and contributors are expected to adhere to the [Contributor Covenant](http://contributor-covenant.org) code of conduct.
268
+
269
+ ## License
270
+
271
+ The gem is available as open source under the terms of the [MIT License](https://opensource.org/licenses/MIT).
272
+
273
+ ## Code of Conduct
274
+
275
+ Everyone interacting in the ShrinkWrap project’s codebases, issue trackers, chat rooms and mailing lists is expected to follow the [code of conduct](https://github.com/jessedoyle/shrink_wrap/blob/master/CODE_OF_CONDUCT.md).
data/Rakefile ADDED
@@ -0,0 +1,11 @@
1
+ # frozen_string_literal: true
2
+
3
+ require 'bundler/gem_tasks'
4
+ require 'rspec/core/rake_task'
5
+ require 'rubocop/rake_task'
6
+
7
+ RSpec::Core::RakeTask.new(:spec)
8
+
9
+ task default: %i[spec rubocop]
10
+
11
+ RuboCop::RakeTask.new
data/bin/console ADDED
@@ -0,0 +1,14 @@
1
+ #!/usr/bin/env ruby
2
+
3
+ require 'bundler/setup'
4
+ require 'shrink_wrap'
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(__FILE__)
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
data/lib/shrink/all.rb ADDED
@@ -0,0 +1,14 @@
1
+ # frozen_string_literal: true
2
+
3
+ require 'pp'
4
+ require_relative 'wrap/version'
5
+ require_relative 'wrap/metadata'
6
+ require_relative 'wrap/support/type_check'
7
+ require_relative 'wrap/property/translation'
8
+ require_relative 'wrap/property/coercion'
9
+ require_relative 'wrap/property/coercion/class'
10
+ require_relative 'wrap/property/coercion/enumerable'
11
+ require_relative 'wrap/property/coercion/proc'
12
+ require_relative 'wrap/transformer/base'
13
+ require_relative 'wrap/transformer/symbolize'
14
+ require_relative 'wrap/transformer/collection_from_key'
@@ -0,0 +1,66 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Shrink
4
+ module Wrap
5
+ class Metadata
6
+ def add_transformer(klass, opts = {})
7
+ transformers.push(klass.new(opts))
8
+ end
9
+
10
+ def add_translation(property, opts = {})
11
+ params = { from: property }.merge(opts)
12
+ translations[property] = Shrink::Wrap::Property::Translation.new(params)
13
+ end
14
+
15
+ def add_coercion(property, coercion)
16
+ coercions[property] = Shrink::Wrap::Property::Coercion.new(coercion)
17
+ end
18
+
19
+ def transform(data)
20
+ transformers.each do |transformer|
21
+ data = transformer.transform(data)
22
+ end
23
+ data
24
+ end
25
+
26
+ def translate(data)
27
+ return data if translate_all
28
+
29
+ translations.each_with_object({}) do |(key, translation), memo|
30
+ memo[key] = translation.translate(data)
31
+ end
32
+ end
33
+
34
+ def translate_all!
35
+ @translate_all = true
36
+ end
37
+
38
+ def coerce(data)
39
+ data.each_with_object({}) do |(property, value), memo|
40
+ next if value.nil?
41
+
42
+ coercion = coercions[property]
43
+ memo[property] = coercion&.coerce(value) || value
44
+ end
45
+ end
46
+
47
+ private
48
+
49
+ def translate_all
50
+ @translate_all ||= false
51
+ end
52
+
53
+ def transformers
54
+ @transformers ||= []
55
+ end
56
+
57
+ def translations
58
+ @translations ||= {}
59
+ end
60
+
61
+ def coercions
62
+ @coercions ||= {}
63
+ end
64
+ end
65
+ end
66
+ end
@@ -0,0 +1,27 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Shrink
4
+ module Wrap
5
+ module Property
6
+ class Coercion
7
+ class Class
8
+ include Support::TypeCheck
9
+
10
+ attr_accessor :klass
11
+
12
+ def initialize(klass)
13
+ ensure_type!(::Class, klass)
14
+ self.klass = klass
15
+ end
16
+
17
+ def coerce(data)
18
+ return klass.shrink_wrap(data) if klass.respond_to?(:shrink_wrap)
19
+ return klass.coerce(data) if klass.respond_to?(:coerce)
20
+
21
+ klass.new(data)
22
+ end
23
+ end
24
+ end
25
+ end
26
+ end
27
+ end
@@ -0,0 +1,50 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Shrink
4
+ module Wrap
5
+ module Property
6
+ class Coercion
7
+ class Enumerable
8
+ include Support::TypeCheck
9
+
10
+ attr_accessor :enumerable
11
+
12
+ def initialize(enumerable)
13
+ ensure_type!(::Enumerable, enumerable)
14
+ self.enumerable = wrap(enumerable.first)
15
+ end
16
+
17
+ def coerce(data)
18
+ return coerce_hash(data) if enumerable.size > 1
19
+
20
+ coerce_enumerable(data)
21
+ end
22
+
23
+ private
24
+
25
+ def coerce_hash(data)
26
+ ensure_type!(Hash, data)
27
+ key_klass, value_klass = enumerable
28
+ data.each_with_object({}) do |(key, value), memo|
29
+ coerced_key = Class.new(key_klass).coerce(key)
30
+ coerced_value = Class.new(value_klass).coerce(value)
31
+ memo[coerced_key] = coerced_value
32
+ end
33
+ end
34
+
35
+ def coerce_enumerable(data)
36
+ ensure_type!(::Enumerable, data)
37
+ klass = enumerable.first
38
+ data.map do |element|
39
+ Class.new(klass).coerce(element)
40
+ end
41
+ end
42
+
43
+ def wrap(element)
44
+ [element].flatten
45
+ end
46
+ end
47
+ end
48
+ end
49
+ end
50
+ end
@@ -0,0 +1,24 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Shrink
4
+ module Wrap
5
+ module Property
6
+ class Coercion
7
+ class Proc
8
+ include Support::TypeCheck
9
+
10
+ attr_accessor :callable
11
+
12
+ def initialize(callable)
13
+ ensure_callable!(callable, 1)
14
+ self.callable = callable
15
+ end
16
+
17
+ def coerce(data)
18
+ callable.call(data)
19
+ end
20
+ end
21
+ end
22
+ end
23
+ end
24
+ end
@@ -0,0 +1,35 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Shrink
4
+ module Wrap
5
+ module Property
6
+ class Coercion
7
+ attr_accessor :base
8
+
9
+ def initialize(value)
10
+ case value
11
+ when ::Class
12
+ self.base = Coercion::Class.new(value)
13
+ when ::Enumerable
14
+ self.base = Coercion::Enumerable.new(value)
15
+ when ::Proc
16
+ self.base = Coercion::Proc.new(value)
17
+ else
18
+ fail!(value)
19
+ end
20
+ end
21
+
22
+ def coerce(data)
23
+ base.coerce(data)
24
+ end
25
+
26
+ private
27
+
28
+ def fail!(value)
29
+ msg = "expected Class, Enumerable or Proc, got: #{value.inspect}"
30
+ raise ArgumentError, msg
31
+ end
32
+ end
33
+ end
34
+ end
35
+ end
@@ -0,0 +1,50 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Shrink
4
+ module Wrap
5
+ module Property
6
+ class Translation
7
+ include Support::TypeCheck
8
+
9
+ ATTRIBUTES = %i[
10
+ allow_nil
11
+ default
12
+ from
13
+ ].freeze
14
+
15
+ attr_accessor(*ATTRIBUTES)
16
+
17
+ def initialize(opts = {})
18
+ self.allow_nil = opts.fetch(:allow_nil) { false }
19
+ self.default = opts[:default]
20
+ self.from = opts.fetch(:from)
21
+ end
22
+
23
+ def translate(opts = {})
24
+ ensure_type!(Hash, opts)
25
+ translate_single(opts)
26
+ end
27
+
28
+ private
29
+
30
+ def translate_single(opts)
31
+ return opts[from] if allow_nil
32
+ return opts.fetch(from) { key_error!(opts) } if default.nil?
33
+
34
+ ensure_callable!(default, 0)
35
+ opts.fetch(from) { default.call }
36
+ end
37
+
38
+ def key_error!(opts)
39
+ pretty_hash = StringIO.new
40
+ PP.pp(opts, pretty_hash)
41
+ raise KeyError, <<~MSG
42
+ Key not found `#{from.inspect}`
43
+ Searching:
44
+ #{pretty_hash.string}
45
+ MSG
46
+ end
47
+ end
48
+ end
49
+ end
50
+ end
@@ -0,0 +1,27 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Shrink
4
+ module Wrap
5
+ module Support
6
+ module TypeCheck
7
+ # rubocop:disable Style/GuardClause
8
+ def ensure_type!(klass, data)
9
+ unless data.is_a?(klass)
10
+ raise ArgumentError, "expected #{klass}, got: #{data.inspect}"
11
+ end
12
+ end
13
+
14
+ def ensure_callable!(element, arity = nil)
15
+ unless element.respond_to?(:call)
16
+ raise ArgumentError, "expected callable, got: #{element.inspect}"
17
+ end
18
+
19
+ if arity && (!element.respond_to?(:arity) || element.arity != arity)
20
+ raise ArgumentError, "expected callable with arity of #{arity}"
21
+ end
22
+ end
23
+ # rubocop:enable Style/GuardClause
24
+ end
25
+ end
26
+ end
27
+ end
@@ -0,0 +1,23 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Shrink
4
+ module Wrap
5
+ module Transformer
6
+ class Base
7
+ ATTRIBUTES = %i[
8
+ options
9
+ ].freeze
10
+
11
+ attr_accessor(*ATTRIBUTES)
12
+
13
+ def initialize(opts = {})
14
+ self.options = opts
15
+ end
16
+
17
+ def transform(_input)
18
+ raise NotImplementedError, 'must define #transform in a subclass'
19
+ end
20
+ end
21
+ end
22
+ end
23
+ end
@@ -0,0 +1,42 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Shrink
4
+ module Wrap
5
+ module Transformer
6
+ class CollectionFromKey < Base
7
+ include Support::TypeCheck
8
+
9
+ def initialize(opts = {})
10
+ unless valid_options?(opts)
11
+ raise ArgumentError, 'options must contain one key/value pair'
12
+ end
13
+
14
+ super
15
+ end
16
+
17
+ def transform(input)
18
+ ensure_type!(Hash, input)
19
+ from, to = options.first
20
+ data = input[from]
21
+ return input unless data.is_a?(Hash)
22
+
23
+ mapped = map(data, to)
24
+ input.merge(from => mapped)
25
+ end
26
+
27
+ private
28
+
29
+ def map(data, to)
30
+ data.map do |key, value|
31
+ ensure_type!(Hash, value)
32
+ value.merge(to => key)
33
+ end
34
+ end
35
+
36
+ def valid_options?(opts)
37
+ opts.is_a?(Hash) && opts.size == 1
38
+ end
39
+ end
40
+ end
41
+ end
42
+ end
@@ -0,0 +1,46 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Shrink
4
+ module Wrap
5
+ module Transformer
6
+ class Symbolize < Base
7
+ DEFAULT_DEPTH = 1
8
+
9
+ def transform(input)
10
+ symbolize(input, 0)
11
+ end
12
+
13
+ private
14
+
15
+ def symbolize(element, depth, symbolize_singular = false)
16
+ return element if depth > options.fetch(:depth) { DEFAULT_DEPTH }
17
+
18
+ case element
19
+ when Hash
20
+ symbolize_hash(element, depth + 1)
21
+ when Enumerable
22
+ symbolize_enumerable(element, depth)
23
+ else
24
+ symbolize_singular ? to_sym(element) : element
25
+ end
26
+ end
27
+
28
+ def symbolize_enumerable(array, depth)
29
+ array.map { |i| symbolize(i, depth) }
30
+ end
31
+
32
+ def symbolize_hash(hash, next_depth)
33
+ hash.each_with_object({}) do |(key, value), memo|
34
+ new_key = symbolize(key, next_depth, true)
35
+ new_value = symbolize(value, next_depth, false)
36
+ memo[new_key] = new_value
37
+ end
38
+ end
39
+
40
+ def to_sym(element)
41
+ element.respond_to?(:to_sym) ? element.to_sym : element
42
+ end
43
+ end
44
+ end
45
+ end
46
+ end
@@ -0,0 +1,7 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Shrink
4
+ module Wrap
5
+ VERSION = '0.1.0'
6
+ end
7
+ end
@@ -0,0 +1,46 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative 'all'
4
+
5
+ module Shrink
6
+ module Wrap
7
+ def self.included(base)
8
+ base.extend(ClassMethods)
9
+ end
10
+
11
+ module ClassMethods
12
+ def transform(klass, opts = {})
13
+ metadata.add_transformer(klass, opts)
14
+ end
15
+
16
+ def translate(opts = {})
17
+ opts.each do |key, value|
18
+ metadata.add_translation(key, value)
19
+ end
20
+ end
21
+
22
+ def translate_all
23
+ metadata.translate_all!
24
+ end
25
+
26
+ def coerce(opts = {})
27
+ opts.each do |key, value|
28
+ metadata.add_coercion(key, value)
29
+ end
30
+ end
31
+
32
+ def shrink_wrap(data)
33
+ transformed = metadata.transform(data)
34
+ translated = metadata.translate(transformed)
35
+ coerced = metadata.coerce(translated)
36
+ new(coerced)
37
+ end
38
+
39
+ private
40
+
41
+ def metadata
42
+ @metadata ||= Metadata.new
43
+ end
44
+ end
45
+ end
46
+ end
@@ -0,0 +1,3 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative 'shink/wrap'
@@ -0,0 +1,31 @@
1
+ # frozen_string_literal: true
2
+
3
+ lib = File.expand_path('lib', __dir__)
4
+ $LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
5
+ require 'shrink/wrap/version'
6
+
7
+ Gem::Specification.new do |spec|
8
+ spec.name = 'shrink_wrap'
9
+ spec.version = Shrink::Wrap::VERSION
10
+ spec.authors = ['Jesse Doyle']
11
+ spec.email = ['jdoyle@ualberta.ca']
12
+ spec.summary = 'Transform complex JSON data into custom Ruby objects'
13
+ spec.description = 'Shrink::Wrap is a dead-simple framework to manipulate' \
14
+ ' and map JSON data to Ruby object instances.'
15
+ spec.homepage = 'https://github.com/jessedoyle/shrink_wrap'
16
+ spec.license = 'MIT'
17
+
18
+ spec.files = Dir.chdir(File.expand_path(__dir__)) do
19
+ `git ls-files -z`
20
+ .split("\x0")
21
+ .reject { |f| f.match(%r{^(test|spec|features)/}) }
22
+ end
23
+ spec.require_paths = ['lib']
24
+
25
+ spec.add_development_dependency 'bundler', '~> 1.16'
26
+ spec.add_development_dependency 'pry'
27
+ spec.add_development_dependency 'rake', '~> 10.0'
28
+ spec.add_development_dependency 'rspec', '~> 3.0'
29
+ spec.add_development_dependency 'rubocop'
30
+ spec.add_development_dependency 'simplecov'
31
+ end
metadata ADDED
@@ -0,0 +1,157 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: shrink_wrap
3
+ version: !ruby/object:Gem::Version
4
+ version: 0.1.0
5
+ platform: ruby
6
+ authors:
7
+ - Jesse Doyle
8
+ autorequire:
9
+ bindir: bin
10
+ cert_chain: []
11
+ date: 2018-12-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.16'
20
+ type: :development
21
+ prerelease: false
22
+ version_requirements: !ruby/object:Gem::Requirement
23
+ requirements:
24
+ - - "~>"
25
+ - !ruby/object:Gem::Version
26
+ version: '1.16'
27
+ - !ruby/object:Gem::Dependency
28
+ name: pry
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
+ - !ruby/object:Gem::Dependency
42
+ name: rake
43
+ requirement: !ruby/object:Gem::Requirement
44
+ requirements:
45
+ - - "~>"
46
+ - !ruby/object:Gem::Version
47
+ version: '10.0'
48
+ type: :development
49
+ prerelease: false
50
+ version_requirements: !ruby/object:Gem::Requirement
51
+ requirements:
52
+ - - "~>"
53
+ - !ruby/object:Gem::Version
54
+ version: '10.0'
55
+ - !ruby/object:Gem::Dependency
56
+ name: rspec
57
+ requirement: !ruby/object:Gem::Requirement
58
+ requirements:
59
+ - - "~>"
60
+ - !ruby/object:Gem::Version
61
+ version: '3.0'
62
+ type: :development
63
+ prerelease: false
64
+ version_requirements: !ruby/object:Gem::Requirement
65
+ requirements:
66
+ - - "~>"
67
+ - !ruby/object:Gem::Version
68
+ version: '3.0'
69
+ - !ruby/object:Gem::Dependency
70
+ name: rubocop
71
+ requirement: !ruby/object:Gem::Requirement
72
+ requirements:
73
+ - - ">="
74
+ - !ruby/object:Gem::Version
75
+ version: '0'
76
+ type: :development
77
+ prerelease: false
78
+ version_requirements: !ruby/object:Gem::Requirement
79
+ requirements:
80
+ - - ">="
81
+ - !ruby/object:Gem::Version
82
+ version: '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
+ description: Shrink::Wrap is a dead-simple framework to manipulate and map JSON data
98
+ to Ruby object instances.
99
+ email:
100
+ - jdoyle@ualberta.ca
101
+ executables: []
102
+ extensions: []
103
+ extra_rdoc_files: []
104
+ files:
105
+ - ".gitignore"
106
+ - ".rspec"
107
+ - ".rubocop.yml"
108
+ - ".simplecov"
109
+ - ".travis.yml"
110
+ - CHANGELOG.md
111
+ - CODE_OF_CONDUCT.md
112
+ - Gemfile
113
+ - LICENSE
114
+ - README.md
115
+ - Rakefile
116
+ - bin/console
117
+ - bin/setup
118
+ - lib/shrink/all.rb
119
+ - lib/shrink/wrap.rb
120
+ - lib/shrink/wrap/metadata.rb
121
+ - lib/shrink/wrap/property/coercion.rb
122
+ - lib/shrink/wrap/property/coercion/class.rb
123
+ - lib/shrink/wrap/property/coercion/enumerable.rb
124
+ - lib/shrink/wrap/property/coercion/proc.rb
125
+ - lib/shrink/wrap/property/translation.rb
126
+ - lib/shrink/wrap/support/type_check.rb
127
+ - lib/shrink/wrap/transformer/base.rb
128
+ - lib/shrink/wrap/transformer/collection_from_key.rb
129
+ - lib/shrink/wrap/transformer/symbolize.rb
130
+ - lib/shrink/wrap/version.rb
131
+ - lib/shrink_wrap.rb
132
+ - shrink_wrap.gemspec
133
+ homepage: https://github.com/jessedoyle/shrink_wrap
134
+ licenses:
135
+ - MIT
136
+ metadata: {}
137
+ post_install_message:
138
+ rdoc_options: []
139
+ require_paths:
140
+ - lib
141
+ required_ruby_version: !ruby/object:Gem::Requirement
142
+ requirements:
143
+ - - ">="
144
+ - !ruby/object:Gem::Version
145
+ version: '0'
146
+ required_rubygems_version: !ruby/object:Gem::Requirement
147
+ requirements:
148
+ - - ">="
149
+ - !ruby/object:Gem::Version
150
+ version: '0'
151
+ requirements: []
152
+ rubyforge_project:
153
+ rubygems_version: 2.5.1
154
+ signing_key:
155
+ specification_version: 4
156
+ summary: Transform complex JSON data into custom Ruby objects
157
+ test_files: []