json_validate 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: 41f7781180656471a8e9be351a577bc223f24b06
4
+ data.tar.gz: bc42cdbbc1d98671dc3f4138d8b4a37136f33f51
5
+ SHA512:
6
+ metadata.gz: 37fe6b85028fd6dcb3a1ad05dfef180754474b71962486a27ee56a95103287784e5dcf8636689df5613ea69588910e37f7d15639d91d46eb90956e6acc1ebcc2
7
+ data.tar.gz: dc7b4a903cb744288207373c3d11cb3da3a5da23e1446fa7c2f782258c28119fdf6199b73848b38bc2157c4360d223b6aef0d25687353d79fdeeb0474a9b7efc
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/.rspec ADDED
@@ -0,0 +1,2 @@
1
+ --format documentation
2
+ --color
data/.travis.yml ADDED
@@ -0,0 +1,3 @@
1
+ language: ruby
2
+ rvm:
3
+ - 2.0.0
data/Gemfile ADDED
@@ -0,0 +1,4 @@
1
+ source 'https://rubygems.org'
2
+
3
+ # Specify your gem's dependencies in json_validate.gemspec
4
+ gemspec
data/LICENSE.txt ADDED
@@ -0,0 +1,22 @@
1
+ Copyright (c) 2015 Tomoyuki Morita
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,53 @@
1
+ # JSONValidate
2
+
3
+ This gem offers very simple way to validate parsed JSON object.
4
+ Suppose your program expect an input JSON as below.
5
+
6
+ ```json
7
+ {
8
+ "id": 100,
9
+ "title": "Some title",
10
+ "tags": ["funny", "cute"]
11
+ }
12
+ ```
13
+
14
+ It can be validated by the following code.
15
+
16
+ ```ruby
17
+ # assume json_str contains the JSON input
18
+ object = JSON.parse(json_str)
19
+ object.validate( {id: Fixnum, title: String, tags: [String]} )
20
+ ```
21
+
22
+ If the JSON doesn't have designated structure, validate method raise a ValidationError.
23
+
24
+ ```ruby
25
+ object = JSON.parse('{"hoge": 1}')
26
+ object.validate( {id:Fixnum} ) # => raise ValidationError
27
+ ```
28
+
29
+ ## Installation
30
+
31
+ Add this line to your application's Gemfile:
32
+
33
+ gem 'json_validate'
34
+
35
+ And then execute:
36
+
37
+ $ bundle
38
+
39
+ Or install it yourself as:
40
+
41
+ $ gem install json_validate
42
+
43
+ ## Usage
44
+
45
+
46
+
47
+ ## Contributing
48
+
49
+ 1. Fork it
50
+ 2. Create your feature branch (`git checkout -b my-new-feature`)
51
+ 3. Commit your changes (`git commit -am 'Add some feature'`)
52
+ 4. Push to the branch (`git push origin my-new-feature`)
53
+ 5. Create new Pull Request
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_validate/version'
5
+
6
+ Gem::Specification.new do |spec|
7
+ spec.name = "json_validate"
8
+ spec.version = JSONValidate::VERSION
9
+ spec.authors = ["Tomoyuki Morita"]
10
+ spec.email = ["ykmr1224@gmail.com"]
11
+ spec.description = %q{Offers simple way to validate JSON object having expected structure.}
12
+ spec.summary = %q{Offers simple way to validate JSON object having expected structure.}
13
+ spec.homepage = "https://github.com/ykmr1224/json_validate"
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
+ spec.add_development_dependency "rspec"
24
+ end
@@ -0,0 +1,92 @@
1
+ require "json_validate/version"
2
+
3
+ module JSONValidate
4
+ class ValidationError < RuntimeError
5
+ end
6
+
7
+ def self.pathstr(path)
8
+ "/"+path.join("/")
9
+ end
10
+
11
+ # Validate each elements of a hash by the validator.
12
+ def self.validateHash(hash, validator, path=[])
13
+ raise ValidationError.new(pathstr(path) + " : Expected to be a Hash.") unless hash.kind_of? Hash
14
+ validator.each do |key, value|
15
+ raise ValidationError.new(pathstr(path) + " : Key '#{key}' is expected to be exists.") unless hash.include? key.to_s
16
+ path.push(key.to_s)
17
+ validate(hash[key.to_s], value, path)
18
+ path.pop
19
+ end
20
+ end
21
+
22
+ # Validate each elements of an array by the first element of validator(validator[0])
23
+ # This expects validator is an array containing only one element. Other than the first element will be ignored
24
+ def self.validateArray(array, validator, path=[])
25
+ raise ValidationError.new(pathstr(path) + " : Expected to be an Array.") unless array.kind_of? Array
26
+ parent = path.pop || "" # to make the path like "/hoge/foo/parent[1]""
27
+ array.each_index do |i|
28
+ path.push(parent+"[#{i}]")
29
+ validate(array[i], validator[0], path)
30
+ path.pop
31
+ end
32
+ path.push parent
33
+ end
34
+
35
+ # Validate the parsed JSON object with the validator
36
+ # validator can be a hash or an array
37
+ # e.g. {id: Fixnum, subject: String, message: String, receipients: [{email: String, name: String}]}
38
+ # e.g. [String]
39
+ # This throws a ValidationError if the validation failed.
40
+ # If a block is given, validator is ignored and the block is evaluated as the validator to be used
41
+ def self.validate(json, validator=nil, path=[], &block)
42
+ return validate(json, JSONValidate.instance_eval(&block), path) if block_given?
43
+
44
+ case validator
45
+ when Hash # validate each pair of the hash
46
+ validateHash(json, validator, path)
47
+ when Array # validate each elements of the array
48
+ validateArray(json, validator, path)
49
+ when Class # validate the type of the value
50
+ raise ValidationError.new(pathstr(path)) unless json.kind_of? validator
51
+ when CustomValidator
52
+ raise ValidationError.new(pathstr(path)) unless validator.validate(json)
53
+ when Regexp
54
+ raise ValidationError.new(pathstr(path)) unless validator =~ json
55
+ when nil
56
+ raise ValidationError.new(pathstr(path)) unless json.nil?
57
+ else
58
+ raise ValidationError.new("Validator is expected to be Hash, Array, or Class.")
59
+ end
60
+ end
61
+
62
+ class CustomValidator
63
+ def validate(json, path=[]); false; end
64
+ def message; ""; end
65
+ end
66
+
67
+ private
68
+
69
+ class BooleanValidator < CustomValidator
70
+ def validate(json, path=[])
71
+ json.kind_of?(TrueClass) || json.kind_of?(FalseClass)
72
+ end
73
+ end
74
+
75
+ def self.boolean
76
+ BooleanValidator.new
77
+ end
78
+
79
+ end
80
+
81
+ class Hash
82
+ def validate(&block)
83
+ JSONValidate.validate(self, &block)
84
+ end
85
+ end
86
+
87
+ class Array
88
+ def validate(&block)
89
+ JSONValidate.validate(self, &block)
90
+ end
91
+ end
92
+
@@ -0,0 +1,3 @@
1
+ module JSONValidate
2
+ VERSION = "0.0.1"
3
+ end
@@ -0,0 +1,105 @@
1
+ require 'spec_helper'
2
+ require 'json'
3
+
4
+ # define an utility metod
5
+ class Array
6
+ def except(*value)
7
+ self - value
8
+ end
9
+ end
10
+
11
+ describe JSONValidate do
12
+ it 'should have a version number' do
13
+ expect(JSONValidate::VERSION).not_to be_nil
14
+ end
15
+
16
+ describe "#validate" do
17
+ it 'should not raise error for valid object types' do
18
+ json = JSON.parse('{"a":1, "b":"hoge", "c":{"c1":1}, "d":[1,2,3], "e":true, "f":false, "g":null}')
19
+ expect{
20
+ JSONValidate.validate(json, {a: Fixnum, b: String, c: Hash, d: Array, e: TrueClass, f: FalseClass, g: NilClass })
21
+ }.not_to raise_error
22
+ end
23
+
24
+ # examples for type unmatch
25
+ types = [Fixnum, String, Hash, Array, TrueClass, FalseClass, NilClass]
26
+ sample_values = {
27
+ '1' => Fixnum,
28
+ '"hoge"' => String,
29
+ '{"c1":1}' => Hash,
30
+ '[1,2,3]' => Array,
31
+ 'true' => TrueClass,
32
+ 'false' => FalseClass,
33
+ 'null' => NilClass}
34
+ sample_values.each do |value, type|
35
+ json = JSON.parse('{"a":'+value+'}')
36
+ types.except(type).each do |wrong_type|
37
+ it "should raise error for #{value} if #{wrong_type} is the expected type" do
38
+ expect{ JSONValidate.validate(json, {a: wrong_type}) }.to raise_error
39
+ end
40
+ end
41
+ end
42
+
43
+ it "should raise error for missing variable" do
44
+ json = JSON.parse('{"a": "hoge"}')
45
+ expect{ JSONValidate.validate(json, {a: String, b: String}) }.to raise_error
46
+ end
47
+
48
+ it "should handle nested hash properly" do
49
+ json = JSON.parse('{"a": {"b": "hoge", "c": {"d": "foo"}}, "e": "bar"}')
50
+ expect{ JSONValidate.validate(json, {a: {b: String, c: {d: String}}, e: String}) }.not_to raise_error
51
+ expect{ JSONValidate.validate(json, {a: {b: String, c: {d: Fixnum}}, e: String}) }.to raise_error
52
+ end
53
+
54
+ it "should validate all items in array" do
55
+ json = JSON.parse('["a", "b", "c", "d"]')
56
+ expect{ JSONValidate.validate(json, [String]) }.not_to raise_error
57
+ expect{ JSONValidate.validate(json, [Fixnum]) }.to raise_error
58
+
59
+ json = JSON.parse('["a", "b", "c", 1]')
60
+ expect{ JSONValidate.validate(json, [String]) }.to raise_error(JSONValidate::ValidationError, /\/\[3\]/)
61
+
62
+ json = JSON.parse('[{"a": 1, "b": "hoge"}, {"a": 2, "b": "foo"}]')
63
+ expect{ JSONValidate.validate(json, [{a: Fixnum, b: String}]) }.not_to raise_error
64
+
65
+ json = JSON.parse('[{"a": 1, "b": "hoge"}, {"a": 2, "b": 3}]')
66
+ expect{ JSONValidate.validate(json, [{a: Fixnum, b: String}]) }.to raise_error(JSONValidate::ValidationError, /\/\[1\]\/b/)
67
+
68
+ json = JSON.parse('[{"a": 1, "b": "hoge"}, {"a": 2, "b": "foo"}, {"a": 3}]')
69
+ expect{ JSONValidate.validate(json, [{a: Fixnum, b: String}]) }.to raise_error(JSONValidate::ValidationError, /\/\[2\]/)
70
+ end
71
+
72
+ it "should validate string by Regexp" do
73
+ json = JSON.parse('["abc", "aa", "b", "cccc"]')
74
+ expect{ JSONValidate.validate(json, [/[abc]+/])}.not_to raise_error
75
+
76
+ json = JSON.parse('["abc", "AA", "b", "cccc"]')
77
+ expect{ JSONValidate.validate(json, [/[abc]+/])}.to raise_error(JSONValidate::ValidationError, /\/\[1\]/)
78
+ end
79
+ end
80
+
81
+ describe "Hash#validate" do
82
+ it 'should add an instance method #validate to Hash' do
83
+ expect(Hash.new).to respond_to(:validate)
84
+ end
85
+
86
+ it "can be invoked via hash decoded from JSON" do
87
+ json = JSON.parse('{"a": 1, "b": "hoge"}')
88
+ expect{ json.validate{ {a: Fixnum, b: String} } }.not_to raise_error
89
+ expect{ json.validate{ {a: Fixnum, b: Fixnum} } }.to raise_error(JSONValidate::ValidationError, /\/b/)
90
+ end
91
+ end
92
+
93
+ describe "Array#validate" do
94
+ it 'should add an instance method #validate to Array' do
95
+ expect(Array.new).to respond_to(:validate)
96
+ end
97
+
98
+ it "can be invoked via array decoded from JSON" do
99
+ json = JSON.parse('[{"id": 1}, {"id": 2}, {"id": 3}]')
100
+ expect{ json.validate{ [{id: Fixnum}] } }.not_to raise_error
101
+ expect{ json.validate{ [{id: String}] } }.to raise_error(JSONValidate::ValidationError, /\/\[0\]\/id/)
102
+ end
103
+ end
104
+
105
+ end
@@ -0,0 +1,2 @@
1
+ $LOAD_PATH.unshift File.expand_path('../../lib', __FILE__)
2
+ require 'json_validate'
metadata ADDED
@@ -0,0 +1,101 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: json_validate
3
+ version: !ruby/object:Gem::Version
4
+ version: 0.0.1
5
+ platform: ruby
6
+ authors:
7
+ - Tomoyuki Morita
8
+ autorequire:
9
+ bindir: bin
10
+ cert_chain: []
11
+ date: 2015-06-21 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
+ - !ruby/object:Gem::Dependency
42
+ name: rspec
43
+ requirement: !ruby/object:Gem::Requirement
44
+ requirements:
45
+ - - '>='
46
+ - !ruby/object:Gem::Version
47
+ version: '0'
48
+ type: :development
49
+ prerelease: false
50
+ version_requirements: !ruby/object:Gem::Requirement
51
+ requirements:
52
+ - - '>='
53
+ - !ruby/object:Gem::Version
54
+ version: '0'
55
+ description: Offers simple way to validate JSON object having expected structure.
56
+ email:
57
+ - ykmr1224@gmail.com
58
+ executables: []
59
+ extensions: []
60
+ extra_rdoc_files: []
61
+ files:
62
+ - .gitignore
63
+ - .rspec
64
+ - .travis.yml
65
+ - Gemfile
66
+ - LICENSE.txt
67
+ - README.md
68
+ - Rakefile
69
+ - json_validate.gemspec
70
+ - lib/json_validate.rb
71
+ - lib/json_validate/version.rb
72
+ - spec/json_validate_spec.rb
73
+ - spec/spec_helper.rb
74
+ homepage: https://github.com/ykmr1224/json_validate
75
+ licenses:
76
+ - MIT
77
+ metadata: {}
78
+ post_install_message:
79
+ rdoc_options: []
80
+ require_paths:
81
+ - lib
82
+ required_ruby_version: !ruby/object:Gem::Requirement
83
+ requirements:
84
+ - - '>='
85
+ - !ruby/object:Gem::Version
86
+ version: '0'
87
+ required_rubygems_version: !ruby/object:Gem::Requirement
88
+ requirements:
89
+ - - '>='
90
+ - !ruby/object:Gem::Version
91
+ version: '0'
92
+ requirements: []
93
+ rubyforge_project:
94
+ rubygems_version: 2.4.5
95
+ signing_key:
96
+ specification_version: 4
97
+ summary: Offers simple way to validate JSON object having expected structure.
98
+ test_files:
99
+ - spec/json_validate_spec.rb
100
+ - spec/spec_helper.rb
101
+ has_rdoc: