json_array_serializer 0.0.1

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: 9691f8acb8219c2c3ae074a50330d70dd16aa570
4
+ data.tar.gz: 5a2056392495edcfc40e09833ee5880a91967f6f
5
+ SHA512:
6
+ metadata.gz: a469edf7288347abb45b33982da7b4e2985902212ff69d449397e9c0cc5d5f7b95a74b98bddba76c301714c55cca2ae9f8c5e41dfef9b4cfa142adf903120c0e
7
+ data.tar.gz: 8501d3e3829b0438f7b2fc8837a9c3b839804ba29333ecac0ad4fd9ebb067d497ee8af668230c0fd8db845b1ab1ffbebda6df295312466317c3cf4efd564030f
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 json_array_serializer.gemspec
4
+ gemspec
data/LICENSE.txt ADDED
@@ -0,0 +1,22 @@
1
+ Copyright (c) 2014 Nathan Lilienthal
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,63 @@
1
+ n# JSONArraySerializer
2
+
3
+ A class to serialize and deserialize arrays of JSON strings. This is useful when doing things like saving arrays of objects to a database or file, or sending them over the wire.
4
+
5
+ ## Installation
6
+
7
+ Add this line to your application's Gemfile:
8
+
9
+ gem 'json_array_serializer'
10
+
11
+ And then execute:
12
+
13
+ $ bundle
14
+
15
+ Or install it yourself as:
16
+
17
+ $ gem install json_array_serializer
18
+
19
+ ## Usage
20
+
21
+ You can use the `JSONArraySerizalizer` directly on a attribute of a Rails model as follows.
22
+
23
+ ```ruby
24
+ class Foo < ActiveRecord::Base
25
+ serialize :bar, JSONArraySerializer.new
26
+ end
27
+ ```
28
+
29
+ Or if you want to save object with more complexity, and custom functionality, simply extend `JSONArraySerizalizer`.
30
+
31
+ ```ruby
32
+ # A class to hold a collection of commands.
33
+ #
34
+ class CommandArray < JSONArraySerizalizer
35
+ def perform
36
+ each do |command|
37
+ result = system(command.program)
38
+ raise "Error" if !result && command.raise_exception
39
+ end
40
+ end
41
+ end
42
+ ```
43
+
44
+ You can also pass in a class to load the individual JSON objects as when extending the base `JSONArraySerizalizer`.
45
+
46
+ ```ruby
47
+ class Developer < OpenStruct
48
+ def develop(name)
49
+ # Write code.
50
+ end
51
+ end
52
+
53
+ class Company < ActiveRecord::Base
54
+ serialize :developers, JSONArraySerializer.new(Developer)
55
+ end
56
+ ```
57
+
58
+ The class you pass to `JSONArraySerializer.new` __must__ have the following two methods.
59
+
60
+ ```
61
+ # A.new : Hash -> A
62
+ # a.to_h : -> Hash (where a is an instance of A)
63
+ ```
data/Rakefile ADDED
@@ -0,0 +1,6 @@
1
+ require 'bundler/gem_tasks'
2
+ require 'rspec/core/rake_task'
3
+
4
+ RSpec::Core::RakeTask.new(:spec)
5
+
6
+ task :default => :spec
@@ -0,0 +1,24 @@
1
+ # coding: utf-8
2
+ lib = File.expand_path('../lib', __FILE__)
3
+ $LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
4
+ require 'json_array_serializer/version'
5
+
6
+ Gem::Specification.new do |spec|
7
+ spec.name = "json_array_serializer"
8
+ spec.version = JSONArraySerializer::VERSION
9
+ spec.authors = ["Nathan Lilienthal"]
10
+ spec.email = ["nathan@nixpulvis.com"]
11
+ spec.summary = %q{Simple serialization for arrays of things to arrays of JSON.}
12
+ spec.description = %q{Provides an common interface to convert between arrays of objects that implement .new and #to_h methods to arrays of JSON.}
13
+ spec.homepage = "https://github.com/Americastestkitchen/json_array_serializer"
14
+ spec.license = "MIT"
15
+
16
+ spec.files = `git ls-files -z`.split("\x0")
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.5"
22
+ spec.add_development_dependency "rake", "~> 10.3"
23
+ spec.add_development_dependency "rspec", "~> 2.14"
24
+ end
@@ -0,0 +1,3 @@
1
+ class JSONArraySerializer
2
+ VERSION = "0.0.1"
3
+ end
@@ -0,0 +1,57 @@
1
+ require 'json'
2
+ require 'json_array_serializer/version'
3
+
4
+ class JSONArraySerializer
5
+ attr_accessor :element_class
6
+
7
+ # Class -> void (hook)
8
+ # Sets up the new JSONArraySerializer with it's elements
9
+ # class. The element_class is what will be used to represent
10
+ # each element of the stored JSON.
11
+ #
12
+ # The element class MUST implement two methods:
13
+ #
14
+ # A.new : Hash -> A
15
+ # a.to_h : -> Hash (where a is an instance of A)
16
+ #
17
+ def initialize(element_class = Hash, column_type = :text)
18
+ @element_class = element_class
19
+ @column_type = column_type
20
+ end
21
+
22
+ # [JSON String] || JSON String -> [element_class]
23
+ # Takes an array of JSON strings and loads them
24
+ # into an array of element_classes.
25
+ #
26
+ def load(data)
27
+ array = case @column_type
28
+ when :array
29
+ data
30
+ when :string, :text
31
+ JSON.load(data)
32
+ end
33
+
34
+ array.map do |json|
35
+ hash = JSON.load(json)
36
+ (element_class == Hash) ? hash : element_class.new(hash)
37
+ end
38
+ end
39
+
40
+ # [element_class] -> [JSON String] || JSON String
41
+ # Takes an array of element_classes and dumps them
42
+ # into JSON Strings, and returns the array of them.
43
+ #
44
+ def dump(array)
45
+ serialized_array = array.map do |e|
46
+ hash = (element_class == Hash) ? e : e.to_h
47
+ JSON.dump(hash)
48
+ end
49
+
50
+ case @column_type
51
+ when :array
52
+ serialized_array
53
+ when :string, :text
54
+ JSON.dump(serialized_array)
55
+ end
56
+ end
57
+ end
@@ -0,0 +1,291 @@
1
+ require 'spec_helper'
2
+
3
+ describe JSONArraySerializer do
4
+
5
+ context 'text backed serialization' do
6
+ context 'default class (Hash)' do
7
+ let(:serializer) { JSONArraySerializer.new }
8
+
9
+ describe '.new' do
10
+ it 'sets it\'s element class to a Hash' do
11
+ expect(serializer.element_class).to eq(Hash)
12
+ end
13
+ end
14
+
15
+ describe '#load' do
16
+ it 'returns an empty array given an empty array' do
17
+ expect(serializer.load("[]")).to eq([])
18
+ end
19
+
20
+ it 'returns an array of the same length as it\'s given' do
21
+ array = Array.new(5, "{}")
22
+ expect(serializer.load(JSON.dump(array)).length).to eq(array.length)
23
+ end
24
+
25
+ it 'has elements that are in fact Hashs' do
26
+ array = Array.new(5, "{}")
27
+ expect(serializer.load(JSON.dump(array)).reject { |e| e.is_a? Hash }).to be_empty
28
+ end
29
+
30
+ it 'loads arrays of JSON with data' do
31
+ array = Array.new(5, "{\"foo\":\"bar\",\"baz\":1337}")
32
+ expect(serializer.load(JSON.dump(array)).first).to eq({'foo' => 'bar', 'baz' => 1337})
33
+ end
34
+ end
35
+
36
+ describe '#dump' do
37
+ it 'returns a string given an array' do
38
+ array = Array.new(5, {})
39
+ expect(serializer.dump(array)).to be_a(String)
40
+ end
41
+
42
+ it 'JSON can load it' do
43
+ array = Array.new(5, {foo: 'bar'})
44
+ expect { JSON.load(serializer.dump(array)) }.not_to raise_error
45
+ end
46
+ end
47
+
48
+ it 'dumps and loads equivalent arrays' do
49
+ array = [
50
+ { 'foo' => 'bar' },
51
+ { 'name' => 'nate', 'age' => 21 },
52
+ { 'ramble' => 'rara', 'float' => 21.13 }
53
+ ]
54
+ expect(serializer.load(serializer.dump(array))).to eq(array)
55
+ end
56
+
57
+ it 'converts symbols to strings' do
58
+ array = [
59
+ { foo: 'bar' },
60
+ { name: 'nate', age: 21 },
61
+ { ramble: 'rara', float: 21.13 },
62
+ { symbol: :very_symbol },
63
+ { hash: { 'foo' => 'bar' } },
64
+ { symbol_hash: { foo: 'bar' } }
65
+ ]
66
+ expected = array.map(&:stringify)
67
+ expect(serializer.load(serializer.dump(array))).to eq(expected)
68
+ end
69
+ end
70
+
71
+ context 'with OpenStruct class' do
72
+ let(:serializer) { JSONArraySerializer.new(OpenStruct) }
73
+
74
+ describe '.new' do
75
+ it 'sets it\'s element class to a OpenStruct' do
76
+ expect(serializer.element_class).to eq(OpenStruct)
77
+ end
78
+ end
79
+
80
+ describe '#load' do
81
+ it 'returns an empty array given an empty array' do
82
+ expect(serializer.load(JSON.dump([]))).to eq([])
83
+ end
84
+
85
+ it 'returns an array of the same length as it\'s given' do
86
+ array = Array.new(5, "{}")
87
+ expect(serializer.load(JSON.dump(array)).length).to eq(array.length)
88
+ end
89
+
90
+ it 'has elements that are in fact OpenStructs' do
91
+ array = Array.new(5, "{}")
92
+ expect(serializer.load(JSON.dump(array)).reject { |e| e.is_a? OpenStruct }).to be_empty
93
+ end
94
+
95
+ it 'loads arrays of JSON with data' do
96
+ array = Array.new(5, "{\"foo\":\"bar\",\"baz\":1337}")
97
+ expect(serializer.load(JSON.dump(array)).first).to eq(OpenStruct.new(foo: 'bar', baz: 1337))
98
+ end
99
+ end
100
+
101
+ describe '#dump' do
102
+ it 'returns a string given an array' do
103
+ array = Array.new(5, {})
104
+ expect(serializer.dump(array)).to be_a(String)
105
+ end
106
+
107
+ it 'JSON can load it' do
108
+ array = Array.new(5, {foo: 'bar'})
109
+ expect { JSON.load(serializer.dump(array)) }.not_to raise_error
110
+ end
111
+ end
112
+
113
+ it 'dumps and loads equivalent arrays' do
114
+ array = [
115
+ OpenStruct.new('foo' => 'bar'),
116
+ OpenStruct.new('name' => 'nate', 'age' => 21),
117
+ OpenStruct.new('ramble' => 'rara', 'float' => 21.13)
118
+ ]
119
+ expect(serializer.load(serializer.dump(array))).to eq(array)
120
+ end
121
+
122
+ it 'converts symbols to strings' do
123
+ array = [
124
+ OpenStruct.new(foo: 'bar'),
125
+ OpenStruct.new(name: 'nate', age: 21),
126
+ OpenStruct.new(ramble: 'rara', float: 21.13),
127
+ OpenStruct.new(symbol: :very_symbol),
128
+ OpenStruct.new(hash: { 'foo' => 'bar' }),
129
+ OpenStruct.new(symbol_hash: { foo: 'bar' })
130
+ ]
131
+ expected = array.map(&:stringify_values)
132
+ expect(serializer.load(serializer.dump(array))).to eq(expected)
133
+ end
134
+ end
135
+ end
136
+
137
+ context 'array backed serialization' do
138
+ context 'default class (Hash)' do
139
+ let(:serializer) { JSONArraySerializer.new(Hash, :array) }
140
+
141
+ describe '.new' do
142
+ it 'sets it\'s element class to a Hash' do
143
+ expect(serializer.element_class).to eq(Hash)
144
+ end
145
+ end
146
+
147
+ describe '#load' do
148
+ it 'returns an empty array given an empty array' do
149
+ expect(serializer.load([])).to eq([])
150
+ end
151
+
152
+ it 'returns an array of the same length as it\'s given' do
153
+ array = Array.new(5, "{}")
154
+ expect(serializer.load(array).length).to eq(array.length)
155
+ end
156
+
157
+ it 'has elements that are in fact Hashs' do
158
+ array = Array.new(5, "{}")
159
+ expect(serializer.load(array).reject { |e| e.is_a? Hash }).to be_empty
160
+ end
161
+
162
+ it 'loads arrays of JSON with data' do
163
+ array = Array.new(5, "{\"foo\":\"bar\",\"baz\":1337}")
164
+ expect(serializer.load(array).first).to eq({'foo' => 'bar', 'baz' => 1337})
165
+ end
166
+ end
167
+
168
+ describe '#dump' do
169
+ it 'returns an empty array given an empty array' do
170
+ expect(serializer.dump([])).to eq([])
171
+ end
172
+
173
+ it 'returns an array of the same length as it\'s given' do
174
+ array = Array.new(5, {})
175
+ expect(serializer.dump(array).length).to eq(array.length)
176
+ end
177
+
178
+ it 'has elements that are JSON strings' do
179
+ array = Array.new(5, {foo: 'bar'})
180
+ expect {
181
+ serializer.dump(array).map { |e| JSON.load(e) }
182
+ }.not_to raise_error
183
+ end
184
+
185
+ it 'dumps hashes with data' do
186
+ array = Array.new(5, {foo: 'bar', baz: 1337})
187
+ expect(serializer.dump(array).first).to eq("{\"foo\":\"bar\",\"baz\":1337}")
188
+ end
189
+ end
190
+
191
+ it 'dumps and loads equivalent arrays' do
192
+ array = [
193
+ { 'foo' => 'bar' },
194
+ { 'name' => 'nate', 'age' => 21 },
195
+ { 'ramble' => 'rara', 'float' => 21.13 }
196
+ ]
197
+ expect(serializer.load(serializer.dump(array))).to eq(array)
198
+ end
199
+
200
+ it 'converts symbols to strings' do
201
+ array = [
202
+ { foo: 'bar' },
203
+ { name: 'nate', age: 21 },
204
+ { ramble: 'rara', float: 21.13 },
205
+ { symbol: :very_symbol },
206
+ { hash: { 'foo' => 'bar' } },
207
+ { symbol_hash: { foo: 'bar' } }
208
+ ]
209
+ expected = array.map(&:stringify)
210
+ expect(serializer.load(serializer.dump(array))).to eq(expected)
211
+ end
212
+ end
213
+
214
+ context 'with OpenStruct class' do
215
+ let(:serializer) { JSONArraySerializer.new(OpenStruct, :array) }
216
+
217
+ describe '.new' do
218
+ it 'sets it\'s element class to a OpenStruct' do
219
+ expect(serializer.element_class).to eq(OpenStruct)
220
+ end
221
+ end
222
+
223
+ describe '#load' do
224
+ it 'returns an empty array given an empty array' do
225
+ expect(serializer.load([])).to eq([])
226
+ end
227
+
228
+ it 'returns an array of the same length as it\'s given' do
229
+ array = Array.new(5, "{}")
230
+ expect(serializer.load(array).length).to eq(array.length)
231
+ end
232
+
233
+ it 'has elements that are in fact OpenStructs' do
234
+ array = Array.new(5, "{}")
235
+ expect(serializer.load(array).reject { |e| e.is_a? OpenStruct }).to be_empty
236
+ end
237
+
238
+ it 'loads arrays of JSON with data' do
239
+ array = Array.new(5, "{\"foo\":\"bar\",\"baz\":1337}")
240
+ expect(serializer.load(array).first).to eq(OpenStruct.new(foo: 'bar', baz: 1337))
241
+ end
242
+ end
243
+
244
+ describe '#dump' do
245
+ it 'returns an empty array given an empty array' do
246
+ expect(serializer.dump([])).to eq([])
247
+ end
248
+
249
+ it 'returns an array of the same length as it\'s given' do
250
+ array = Array.new(5, OpenStruct.new)
251
+ expect(serializer.dump(array).length).to eq(array.length)
252
+ end
253
+
254
+ it 'has elements that are JSON strings' do
255
+ array = Array.new(5, OpenStruct.new({foo: 'bar'}))
256
+ expect {
257
+ serializer.dump(array).map { |e| JSON.load(e) }
258
+ }.not_to raise_error
259
+ end
260
+
261
+ it 'dumps OpenStructs with data' do
262
+ array = Array.new(5, OpenStruct.new(foo: 'bar', baz: 1337))
263
+ expect(serializer.dump(array).first).to eq("{\"foo\":\"bar\",\"baz\":1337}")
264
+ end
265
+ end
266
+
267
+ it 'dumps and loads equivalent arrays' do
268
+ array = [
269
+ OpenStruct.new('foo' => 'bar'),
270
+ OpenStruct.new('name' => 'nate', 'age' => 21),
271
+ OpenStruct.new('ramble' => 'rara', 'float' => 21.13),
272
+ OpenStruct.new(symbol: 'rara', 'float' => 21.13)
273
+ ]
274
+ expect(serializer.load(serializer.dump(array))).to eq(array)
275
+ end
276
+
277
+ it 'converts symbols to strings' do
278
+ array = [
279
+ OpenStruct.new(foo: 'bar'),
280
+ OpenStruct.new(name: 'nate', age: 21),
281
+ OpenStruct.new(ramble: 'rara', float: 21.13),
282
+ OpenStruct.new(symbol: :very_symbol),
283
+ OpenStruct.new(hash: { 'foo' => 'bar' }),
284
+ OpenStruct.new(symbol_hash: { foo: 'bar' })
285
+ ]
286
+ expected = array.map(&:stringify_values)
287
+ expect(serializer.load(serializer.dump(array))).to eq(expected)
288
+ end
289
+ end
290
+ end
291
+ end
@@ -0,0 +1,29 @@
1
+ require 'rspec'
2
+ require 'ostruct'
3
+ require 'json_array_serializer'
4
+
5
+ class Hash
6
+ def stringify
7
+ inject({}) do |acc, (key, value)|
8
+ acc[key.to_s] = case value
9
+ when Symbol
10
+ value.to_s
11
+ when Hash
12
+ value.stringify
13
+ else
14
+ value
15
+ end
16
+ acc
17
+ end
18
+ end
19
+ end
20
+
21
+ class OpenStruct
22
+ def stringify_values
23
+ OpenStruct.new(marshal_dump.stringify)
24
+ end
25
+ end
26
+
27
+ RSpec.configure do |config|
28
+ config.color_enabled = true
29
+ end
metadata ADDED
@@ -0,0 +1,99 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: json_array_serializer
3
+ version: !ruby/object:Gem::Version
4
+ version: 0.0.1
5
+ platform: ruby
6
+ authors:
7
+ - Nathan Lilienthal
8
+ autorequire:
9
+ bindir: bin
10
+ cert_chain: []
11
+ date: 2014-04-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.5'
20
+ type: :development
21
+ prerelease: false
22
+ version_requirements: !ruby/object:Gem::Requirement
23
+ requirements:
24
+ - - "~>"
25
+ - !ruby/object:Gem::Version
26
+ version: '1.5'
27
+ - !ruby/object:Gem::Dependency
28
+ name: rake
29
+ requirement: !ruby/object:Gem::Requirement
30
+ requirements:
31
+ - - "~>"
32
+ - !ruby/object:Gem::Version
33
+ version: '10.3'
34
+ type: :development
35
+ prerelease: false
36
+ version_requirements: !ruby/object:Gem::Requirement
37
+ requirements:
38
+ - - "~>"
39
+ - !ruby/object:Gem::Version
40
+ version: '10.3'
41
+ - !ruby/object:Gem::Dependency
42
+ name: rspec
43
+ requirement: !ruby/object:Gem::Requirement
44
+ requirements:
45
+ - - "~>"
46
+ - !ruby/object:Gem::Version
47
+ version: '2.14'
48
+ type: :development
49
+ prerelease: false
50
+ version_requirements: !ruby/object:Gem::Requirement
51
+ requirements:
52
+ - - "~>"
53
+ - !ruby/object:Gem::Version
54
+ version: '2.14'
55
+ description: 'Provides an common interface to convert between arrays of objects that
56
+ implement .new and #to_h methods to arrays of JSON.'
57
+ email:
58
+ - nathan@nixpulvis.com
59
+ executables: []
60
+ extensions: []
61
+ extra_rdoc_files: []
62
+ files:
63
+ - ".gitignore"
64
+ - Gemfile
65
+ - LICENSE.txt
66
+ - README.md
67
+ - Rakefile
68
+ - json_array_serializer.gemspec
69
+ - lib/json_array_serializer.rb
70
+ - lib/json_array_serializer/version.rb
71
+ - spec/json_array_serializer_spec.rb
72
+ - spec/spec_helper.rb
73
+ homepage: https://github.com/Americastestkitchen/json_array_serializer
74
+ licenses:
75
+ - MIT
76
+ metadata: {}
77
+ post_install_message:
78
+ rdoc_options: []
79
+ require_paths:
80
+ - lib
81
+ required_ruby_version: !ruby/object:Gem::Requirement
82
+ requirements:
83
+ - - ">="
84
+ - !ruby/object:Gem::Version
85
+ version: '0'
86
+ required_rubygems_version: !ruby/object:Gem::Requirement
87
+ requirements:
88
+ - - ">="
89
+ - !ruby/object:Gem::Version
90
+ version: '0'
91
+ requirements: []
92
+ rubyforge_project:
93
+ rubygems_version: 2.2.0
94
+ signing_key:
95
+ specification_version: 4
96
+ summary: Simple serialization for arrays of things to arrays of JSON.
97
+ test_files:
98
+ - spec/json_array_serializer_spec.rb
99
+ - spec/spec_helper.rb