rack-params 0.0.1.pre1

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: a11363a7413ebf028fecf37c8844d0cabfc0db8f
4
+ data.tar.gz: d45b70dcb3c82d5fae18fcf03f616fea6b5b0ef2
5
+ SHA512:
6
+ metadata.gz: ea3fa1d609f6e647aae42865ec31fdc6b0d5b4df22164980ef61884f634b205354d2d25c9462b3ebf58b59fab1100238e9f427043cfa531f6a5ca54bae46986c
7
+ data.tar.gz: 22c7fcef94aa754b701466388c178ac390f66b468287c96a064a17064745c1930bebe5203a25267485f53c72748b06393cc2af01769849d623b0dfc4d4f9b29b
data/.gitignore ADDED
@@ -0,0 +1,14 @@
1
+ /.bundle/
2
+ /.yardoc
3
+ /_yardoc/
4
+ /coverage/
5
+ /doc/
6
+ /pkg/
7
+ /spec/reports/
8
+ /tmp/
9
+
10
+ # rspec failure tracking
11
+ .rspec_status
12
+ spec/examples.txt
13
+ /.byebug_history
14
+ /Gemfile.lock
data/.rspec ADDED
@@ -0,0 +1,3 @@
1
+ --format documentation
2
+ --color
3
+ --require spec_helper
data/.travis.yml ADDED
@@ -0,0 +1,5 @@
1
+ sudo: false
2
+ language: ruby
3
+ rvm:
4
+ - 2.4.2
5
+ before_install: gem install bundler -v 1.16.0
data/Gemfile ADDED
@@ -0,0 +1,6 @@
1
+ source "https://rubygems.org"
2
+
3
+ git_source(:github) {|repo_name| "https://github.com/#{repo_name}" }
4
+
5
+ # Specify your gem's dependencies in rack-params.gemspec
6
+ gemspec
data/LICENSE.txt ADDED
@@ -0,0 +1,21 @@
1
+ The MIT License (MIT)
2
+
3
+ Copyright (c) 2018 Jon Raphaelson
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,135 @@
1
+ # Rack::Params
2
+ [![Build Status](https://travis-ci.org/lygaret/rack-params.svg?branch=master)](https://travis-ci.org/lygaret/rack-params)
3
+
4
+ `Rack::Request.params` validation and type coercion, on Rack.
5
+
6
+ ```ruby
7
+ # NOTE (to self) - if this changes, update `readme_spec.rb`
8
+
9
+ class SomeExampleApp
10
+ include Rack::Params
11
+
12
+ # create named validators that can be run at any time
13
+
14
+ validator :document do
15
+ param :id, Integer, required: true
16
+ param :title, String, required: true
17
+ param :created, DateTime
18
+
19
+ param :tags, Array, sep: " " do
20
+ every Symbol
21
+ end
22
+
23
+ param :content, Hash, required: true do
24
+ param :header, String
25
+ param :body, String, required: true
26
+ end
27
+ end
28
+
29
+ # run pre-defined or ad-hoc transforms on some hash
30
+ # only keys in the validator blocks are copied, see #splat
31
+
32
+ def call(env)
33
+ request = Rack::Request.new(env)
34
+
35
+ params = request.params
36
+ params = validate(request.params, :document)
37
+ if params.valid?
38
+ assert params["id"].is_a? Integer
39
+ assert (not params["content"]["body"].nil?)
40
+ else
41
+ assert params.errors.length > 0
42
+ assert params.invalid?
43
+ end
44
+
45
+ # or
46
+ params = { "flag" => "f", "some" => "other key", "and" => "one more" }
47
+ params = validate(params) do
48
+ param :flag, :boolean, required: true
49
+ splat :rest
50
+ end
51
+
52
+ if params.valid?
53
+ assert [true, false].include?(params["flag"])
54
+ assert (["some", "and"] - params["rest"]).empty?
55
+ end
56
+
57
+ end
58
+ end
59
+
60
+ # if you're using a framework which provides `request` as a getter method
61
+ # include the connector, which provides a `#params` override, and allows
62
+ # defaulting to request.params in validate calls
63
+
64
+ class FancyApp < Nancy::Base
65
+ include Rack::Params::Connect
66
+
67
+ validator :check do
68
+ :id, Integer
69
+ end
70
+
71
+ get "/" do
72
+ validate :check
73
+
74
+ if params.valid?
75
+ assert params["id"].is_a? Integer
76
+ else
77
+ assert params.errors.length > 0
78
+ assert params.invalid?
79
+ end
80
+
81
+ "magic 8-ball, how's my params? << uncertan. >>"
82
+ end
83
+
84
+ get "/blow-up-on-failure" do
85
+ validate! :check
86
+ assert params.valid?
87
+
88
+ "if I'm going down, I'm taking you all with me."
89
+ end
90
+ end
91
+ ```
92
+
93
+ ## Installation
94
+
95
+ Add this line to your application's Gemfile:
96
+
97
+ ```ruby
98
+ gem 'rack-params'
99
+ ```
100
+
101
+ And then execute:
102
+
103
+ $ bundle
104
+
105
+ Or install it yourself as:
106
+
107
+ $ gem install rack-params
108
+
109
+ ## Usage
110
+
111
+ **[RDoc @ master - Rack::Params](http://www.rudydoc.info/github/lygaret/master)**
112
+
113
+ 1. Include `Rack::Params` to get the `.validator`, `#validate` and `#validate!` methods.
114
+ 2. Call `.validator(name, options = {}, &code)` to register a named validator for use later.
115
+ 3. Call `#validate(name = nil, params = request.params, options = {}, &code)` to build a new result, with the results of validation and coercion.
116
+ 4. The blocks passed to the validation methods run in the context of `HashContext` and `ArrayContext`, which is where the coercion methods are defined.
117
+
118
+ ## Development
119
+
120
+ After checking out the repo, run `bin/setup` to install dependencies. Then, run `rake spec` to run the tests. You can also run `bin/console` for an interactive prompt that will allow you to experiment.
121
+
122
+ 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).
123
+
124
+ ## Contributing
125
+
126
+ Bug reports and pull requests are welcome on GitHub at https://github.com/lygaret/rack-params.
127
+
128
+ ## License
129
+
130
+ The gem is available as open source under the terms of the [MIT License](https://opensource.org/licenses/MIT).
131
+
132
+ ## Authors
133
+
134
+ * Jon Raphaelson - https://accidental.cc
135
+ * Based heavily on [`mattt/sinatra-param`](https://github.com/mattt/sinatra-param), though diverging significantly in ways.
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
data/bin/console ADDED
@@ -0,0 +1,14 @@
1
+ #!/usr/bin/env ruby
2
+
3
+ require "bundler/setup"
4
+ require "rack/params"
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
@@ -0,0 +1,159 @@
1
+ require 'date'
2
+
3
+ module Rack
4
+ module Params
5
+
6
+ class Context
7
+ attr_reader :options
8
+ attr_reader :params
9
+ attr_reader :result
10
+
11
+ def initialize(params, options = {})
12
+ @options = options
13
+ @path = options[:path]
14
+
15
+ @params = params
16
+
17
+ @result = self.class::Result.new
18
+ @result.extend ::Rack::Params::Result
19
+ @result.errors = Hash.new { |h, k| h[k] = [] }
20
+ end
21
+
22
+ def exec(&block)
23
+ instance_exec(&block)
24
+ @result
25
+ end
26
+
27
+ def _coerce(value, type, options)
28
+ return nil if value.nil?
29
+ return value if value.is_a?(type) rescue false
30
+
31
+ return value.to_sym if type == :symbol || type == Symbol
32
+
33
+ return Integer(value, options[:base] || 0) if type == ::Integer
34
+ return Float(value) if type == ::Float
35
+
36
+ [::Date, ::Time, ::DateTime].each do |klass|
37
+ return klass.parse(value) if type == klass
38
+ end
39
+
40
+ if type == ::Array
41
+ sep = options.fetch(:sep, ',')
42
+
43
+ values = value.split(sep)
44
+ return Array(values)
45
+ end
46
+
47
+ if type == ::Hash
48
+ esep = options.fetch(:esep, ',')
49
+ fsep = options.fetch(:fsep, ':')
50
+
51
+ values = value.split(esep).map { |p| p.split(fsep) }
52
+ return ::Hash[values]
53
+ end
54
+
55
+ if type == ::TrueClass || type == ::FalseClass || type == :boolean
56
+ return false if /^(false|f|no|n|0)$/i === value
57
+ return true if /^(true|t|yes|y|1)$/i === value
58
+ raise ArgumentError # otherwise
59
+ end
60
+ rescue ArgumentError => ex
61
+ fail InvalidParameterError, ex.message
62
+ end
63
+
64
+ def _validate(name, value, validation, options)
65
+ options = {} if options == true
66
+
67
+ if validation == :oneOf
68
+ raise InvalidParameterError, "must be one of #{options}" unless options.include? value
69
+
70
+ elsif validation == :uri
71
+ uri = URI.parse(value)
72
+ schemes = options.fetch(:schemes, %w(http https))
73
+ local = options.fetch(:local, false)
74
+
75
+ unless uri && uri.host && schemes.include?(uri.scheme) && (local || uri.host.include?('.'))
76
+ raise InvalidParameterError, "must be a #{schemes.join(',')} URI"
77
+ end
78
+ end
79
+ end
80
+
81
+ def _recurse(name, type, value, &block)
82
+ path = [@path, name].reject(&:nil?).join(".")
83
+
84
+ if type == Array
85
+ ArrayContext.new(value, path: path).exec(&block)
86
+ elsif type == Hash
87
+ HashContext.new(value, path: path).exec(&block)
88
+ else
89
+ fail "can not recurse into #{type}"
90
+ end
91
+ end
92
+ end
93
+
94
+ # the DSL when validating a hash parameter (including the top-level params hash)
95
+
96
+ class HashContext < Context
97
+ Result = Hash
98
+
99
+ def param(name, type, options = {}, &block)
100
+ name = name.to_s
101
+
102
+ # default and required
103
+ value = params[name] || options[:default]
104
+ raise InvalidParameterError, "is required" if options[:required] && value.nil?
105
+
106
+ # type cast
107
+ value = _coerce(value, type, options)
108
+
109
+ # validate against rules
110
+ options.each { |v, vopts| _validate(name, value, v, vopts) }
111
+
112
+ # recurse if we've got a block
113
+ if block_given?
114
+ value = _recurse(name, type, value, &block)
115
+ result.errors.merge! value.errors
116
+ end
117
+
118
+ # return - we're good
119
+ result[name] = value
120
+ rescue InvalidParameterError => ex
121
+ path = [@path, name].reject(&:nil?).join(".")
122
+ result.errors[path] << ex.message
123
+ end
124
+
125
+ def splat(name, options = {}, &block)
126
+ name = name.to_s
127
+
128
+ # every key in params that's not already in results
129
+ value = params.reject { |k, _| result.keys.include? k }
130
+ result[name] = value
131
+ end
132
+ end
133
+
134
+ # the DSL when validating an array parameter
135
+ class ArrayContext < Context
136
+ Result = Array
137
+
138
+ # validate and coerce every element in the array to the type/options/block given
139
+ def every(type, options = {}, &block)
140
+ params.each_with_index do |value, i|
141
+ begin
142
+ value = _coerce(value, type, options)
143
+ options.each { |v, vopts| _validate(i.to_s, value, v, vopts) }
144
+ if block_given?
145
+ value = _recurse(i.to_s, type, value, &block)
146
+ result.errors.merge! value.errors
147
+ end
148
+
149
+ result[i] = value
150
+ rescue InvalidParameterError => ex
151
+ path = [@path, i].reject(&:nil?).join(".")
152
+ result.errors[path] << ex.message
153
+ end
154
+ end
155
+ end
156
+
157
+ end
158
+ end
159
+ end
@@ -0,0 +1,18 @@
1
+ module Rack
2
+ module Params
3
+
4
+ class ParameterValidationError < StandardError
5
+ attr_accessor :errors
6
+
7
+ def initialize(errors)
8
+ super("parameter validation failed, [#{errors.keys.join(', ')}] invalid.")
9
+ @errors = errors
10
+ end
11
+ end
12
+
13
+ class InvalidParameterError < StandardError
14
+ attr_accessor :name, :type, :options
15
+ end
16
+
17
+ end
18
+ end
@@ -0,0 +1,15 @@
1
+ module Rack
2
+ module Params
3
+ module Result
4
+ attr_accessor :errors
5
+
6
+ def valid?
7
+ errors.length == 0
8
+ end
9
+
10
+ def invalid?
11
+ not valid?
12
+ end
13
+ end
14
+ end
15
+ end
@@ -0,0 +1,5 @@
1
+ module Rack
2
+ module Params
3
+ VERSION = "0.0.1.pre1"
4
+ end
5
+ end
@@ -0,0 +1,65 @@
1
+ require 'rack/params/context'
2
+ require 'rack/params/errors'
3
+ require 'rack/params/result'
4
+ require 'rack/params/version'
5
+
6
+ module Rack
7
+ module Params
8
+ def self.included(base)
9
+ base.extend(ClassMethods)
10
+ end
11
+
12
+ module ClassMethods
13
+ Validator = Struct.new(:options, :code) do
14
+ def exec(values)
15
+ HashContext.new(values, options).exec(&code)
16
+ end
17
+ end
18
+
19
+ def validators
20
+ @_rp_validators ||= {}
21
+ end
22
+
23
+ def validator(name, options = {}, &code)
24
+ validators[name] = Validator.new(options, code)
25
+ end
26
+ end
27
+
28
+ # validate request.params
29
+ def validate(name = nil, params = nil, options = {}, &block)
30
+ if params.nil? && (name.class <= Hash)
31
+ params = name
32
+ name = nil
33
+ end
34
+
35
+ fail ArgumentError, "no parameters provided!" if params.nil?
36
+ if name.nil?
37
+ fail ArgumentError, "no validation block was provided!" unless block_given?
38
+ HashContext.new(params, options).exec(&block)
39
+ else
40
+ fail ArgumentError, "no validation is registered under #{name}" unless self.class.validators.key? name
41
+ self.class.validators[name].exec(params)
42
+ end
43
+ end
44
+
45
+ def validate!(name = nil, params = nil, options = {}, &block)
46
+ validate(name, params, options, &block).tap do |res|
47
+ fail ParameterValidationError, res.errors if res.invalid?
48
+ end
49
+ end
50
+
51
+ # secondary mixin for frameworks that put `request` in the scope
52
+
53
+ module Connector
54
+ def self.included(base)
55
+ base.class_eval do
56
+ attr_reader :params
57
+ end
58
+ end
59
+
60
+ def validate(name = nil, params = nil, options = {}, &block)
61
+ super(name, params || request.params, options, &block)
62
+ end
63
+ end
64
+ end
65
+ end
@@ -0,0 +1,29 @@
1
+
2
+ lib = File.expand_path("../lib", __FILE__)
3
+ $LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
4
+ require "rack/params/version"
5
+
6
+ Gem::Specification.new do |spec|
7
+ spec.name = "rack-params"
8
+ spec.version = Rack::Params::VERSION
9
+ spec.authors = ["Jon Raphaelson"]
10
+ spec.email = ["jon@accidental.cc"]
11
+
12
+ spec.summary = %q{Rack parameter validation and type coercion.}
13
+ spec.homepage = "https://accidental.cc"
14
+ spec.license = "MIT"
15
+
16
+ spec.files = `git ls-files -z`.split("\x0").reject do |f|
17
+ f.match(%r{^(test|spec|features)/})
18
+ end
19
+ spec.bindir = "exe"
20
+ spec.executables = spec.files.grep(%r{^exe/}) { |f| File.basename(f) }
21
+ spec.require_paths = ["lib"]
22
+
23
+ spec.add_dependency "rack", "~> 2.0"
24
+
25
+ spec.add_development_dependency "bundler", "~> 1.16"
26
+ spec.add_development_dependency "rake", "~> 10.0"
27
+ spec.add_development_dependency "rspec", "~> 3.0"
28
+ spec.add_development_dependency "byebug", "~> 9.0"
29
+ end
metadata ADDED
@@ -0,0 +1,129 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: rack-params
3
+ version: !ruby/object:Gem::Version
4
+ version: 0.0.1.pre1
5
+ platform: ruby
6
+ authors:
7
+ - Jon Raphaelson
8
+ autorequire:
9
+ bindir: exe
10
+ cert_chain: []
11
+ date: 2018-01-23 00:00:00.000000000 Z
12
+ dependencies:
13
+ - !ruby/object:Gem::Dependency
14
+ name: rack
15
+ requirement: !ruby/object:Gem::Requirement
16
+ requirements:
17
+ - - "~>"
18
+ - !ruby/object:Gem::Version
19
+ version: '2.0'
20
+ type: :runtime
21
+ prerelease: false
22
+ version_requirements: !ruby/object:Gem::Requirement
23
+ requirements:
24
+ - - "~>"
25
+ - !ruby/object:Gem::Version
26
+ version: '2.0'
27
+ - !ruby/object:Gem::Dependency
28
+ name: bundler
29
+ requirement: !ruby/object:Gem::Requirement
30
+ requirements:
31
+ - - "~>"
32
+ - !ruby/object:Gem::Version
33
+ version: '1.16'
34
+ type: :development
35
+ prerelease: false
36
+ version_requirements: !ruby/object:Gem::Requirement
37
+ requirements:
38
+ - - "~>"
39
+ - !ruby/object:Gem::Version
40
+ version: '1.16'
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: byebug
71
+ requirement: !ruby/object:Gem::Requirement
72
+ requirements:
73
+ - - "~>"
74
+ - !ruby/object:Gem::Version
75
+ version: '9.0'
76
+ type: :development
77
+ prerelease: false
78
+ version_requirements: !ruby/object:Gem::Requirement
79
+ requirements:
80
+ - - "~>"
81
+ - !ruby/object:Gem::Version
82
+ version: '9.0'
83
+ description:
84
+ email:
85
+ - jon@accidental.cc
86
+ executables: []
87
+ extensions: []
88
+ extra_rdoc_files: []
89
+ files:
90
+ - ".gitignore"
91
+ - ".rspec"
92
+ - ".travis.yml"
93
+ - Gemfile
94
+ - LICENSE.txt
95
+ - README.md
96
+ - Rakefile
97
+ - bin/console
98
+ - bin/setup
99
+ - lib/rack/params.rb
100
+ - lib/rack/params/context.rb
101
+ - lib/rack/params/errors.rb
102
+ - lib/rack/params/result.rb
103
+ - lib/rack/params/version.rb
104
+ - rack-params.gemspec
105
+ homepage: https://accidental.cc
106
+ licenses:
107
+ - MIT
108
+ metadata: {}
109
+ post_install_message:
110
+ rdoc_options: []
111
+ require_paths:
112
+ - lib
113
+ required_ruby_version: !ruby/object:Gem::Requirement
114
+ requirements:
115
+ - - ">="
116
+ - !ruby/object:Gem::Version
117
+ version: '0'
118
+ required_rubygems_version: !ruby/object:Gem::Requirement
119
+ requirements:
120
+ - - ">"
121
+ - !ruby/object:Gem::Version
122
+ version: 1.3.1
123
+ requirements: []
124
+ rubyforge_project:
125
+ rubygems_version: 2.6.13
126
+ signing_key:
127
+ specification_version: 4
128
+ summary: Rack parameter validation and type coercion.
129
+ test_files: []