Giter VIP home page Giter VIP logo

rack-params's Introduction

Rack::Params

Gem Version Build Status Coverage Status

Rack::Request.params validation and type coercion, on Rack.

Usage

Documentation

  1. Include Rack::Params to get the .validator, #validate and #validate! methods.
  2. Call .validator(name, options = {}, &code) to register a named validator for use later.
  3. Call #validate(name = nil, params = request.params, options = {}, &code) to build a new result, with the results of validation and coercion.
  4. The blocks passed to the validation methods run in the context of HashContext and ArrayContext, which is where the coercion methods are defined.

Example

# NOTE (to self) - if this changes, update `readme_spec.rb`

class SomeExampleApp
  include Rack::Params

  # create named validators that can be run at any time
  
  validator :document do
    param :id,      Integer,  required: true
    param :title,   String,   required: true
    param :created, DateTime
    
    param :tags, Array do
      every :symbol
    end
    
    param :content, Hash, required: true do
      param :header, String
      param :body,   String, required: true
    end
  end
  
  # run pre-defined or ad-hoc transforms on some hash
  # only keys in the validator blocks are copied, see #splat

  def call(env)
    request = Rack::Request.new(env)
    
    params = request.params
    params = validate(request.params, :document)
    if params.valid?
      assert params["id"].is_a? Integer
      assert (not params["content"]["body"].nil?)
    else
      assert params.errors.length > 0
      assert params.invalid?
    end

    # or
    params = { "flag" => "f", "some" => "other key", "and" => "one more" }
    params = validate(params) do
      param :flag,  :boolean, required: true
      splat :rest
    end
    
    if params.valid?
      assert [true, false].include?(params["flag"])
      assert (["some", "and"] - params["rest"]).empty?
    end

  end
end

# if you're using a framework which provides `request` as a getter method
# include the connector, which provides a `#params` override, and allows
# defaulting to request.params in validate calls

class FancyApp < Nancy::Base
  include Rack::Params::Connect

  validator :check do
    :id, Integer
  end
  
  get "/" do
    validate :check

    if params.valid?
      assert params["id"].is_a? Integer
    else
      assert params.errors.length > 0
      assert params.invalid?
    end
    
    "magic 8-ball, how's my params? << uncertan. >>"
  end

  get "/blow-up-on-failure" do
    validate! :check
    assert params.valid?

    "if I'm going down, I'm taking you all with me."
  end
end

Installation

Add this line to your application's Gemfile:

gem 'rack-params'

And then execute:

$ bundle

Or install it yourself as:

$ gem install rack-params

Development

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.

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.

Contributing

Bug reports and pull requests are welcome on GitHub at https://github.com/lygaret/rack-params.

License

The gem is available as open source under the terms of the MIT License.

Authors

rack-params's People

Contributors

lygaret avatar olleolleolle avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar

Forkers

olleolleolle

rack-params's Issues

validate additional blocks in named validator

validate :auth_code do
  param :foo, String, required: true
end

def action
  validate :auth_code do
    param :bar, String, required: true
  end
end

how does this work from the perspective of #splat which kind of has to be last?

`proc` for type coercion

it would be useful to be able to specify a proc in the type parameter to do manual type coercion.

validate params do
  param :foo, ->(f) { MyCoolParser.parse(f) }
end

things to figure out

  • pass just the value? run in a context?
  • success returns coerced value, failure... raise ArgumentError? return falsey?
    • can nil be a valid coercion?
    • raising ArgumentError would suck, ergonomics wise

`#validations` - first pass at useful validations

  • :required
  • :not_blank => true (nil or whitespace)
  • :format => /regex/
  • :in => %w(opt1 opt2) (Array, Range, anything with an #include? method)
    • aliased: :within, :range, :include
  • :min => 0 param <= value
  • :max => 10 param >= value
  • :length => { :min => 0, :max => 10, in: 0..10 }
    • implies recursive validation!
  • :proc => ->(p) { ExternalValidator.validate! p }

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.