All Projects → mattt → Sinatra Param

mattt / Sinatra Param

Licence: mit
Parameter Validation & Type Coercion for Sinatra

Programming Languages

ruby
36898 projects - #4 most used programming language

Projects that are alternatives of or similar to Sinatra Param

Specs
Technical specifications and guidelines for implementing Frictionless Data.
Stars: ✭ 403 (-21.9%)
Mutual labels:  validation
Phonenumberkit
A Swift framework for parsing, formatting and validating international phone numbers. Inspired by Google's libphonenumber.
Stars: ✭ 4,362 (+745.35%)
Mutual labels:  validation
Yalfield
Custom Field component with validation for creating easier form-like UI from interface builder.
Stars: ✭ 476 (-7.75%)
Mutual labels:  validation
Indicative
Indicative is a simple yet powerful data validator for Node.js and browsers. It makes it so simple to write async validations on nested set of data.
Stars: ✭ 412 (-20.16%)
Mutual labels:  validation
Graphql Query Complexity
GraphQL query complexity analysis and validation for graphql-js
Stars: ✭ 424 (-17.83%)
Mutual labels:  validation
Mimetype
A fast golang library for MIME type and file extension detection, based on magic numbers
Stars: ✭ 452 (-12.4%)
Mutual labels:  validation
V8n
☑️ JavaScript fluent validation library
Stars: ✭ 3,858 (+647.67%)
Mutual labels:  validation
Pandera
A light-weight, flexible, and expressive pandas data validation library
Stars: ✭ 506 (-1.94%)
Mutual labels:  validation
Guard
A high-performance, extensible argument validation library.
Stars: ✭ 427 (-17.25%)
Mutual labels:  validation
Bunny
BunnyJS - Lightweight native (vanilla) JavaScript (JS) and ECMAScript 6 (ES6) browser library, package of small stand-alone components without dependencies: FormData, upload, image preview, HTML5 validation, Autocomplete, Dropdown, Calendar, Datepicker, Ajax, Datatable, Pagination, URL, Template engine, Element positioning, smooth scrolling, routing, inversion of control and more. Simple syntax and architecture. Next generation jQuery and front-end framework. Documentation and examples available.
Stars: ✭ 473 (-8.33%)
Mutual labels:  validation
Lets Build A Blockchain
A mini cryptocurrency in Ruby
Stars: ✭ 416 (-19.38%)
Mutual labels:  sinatra
Dss
Digital Signature Service : creation, extension and validation of advanced electronic signatures
Stars: ✭ 415 (-19.57%)
Mutual labels:  validation
Io Ts
Runtime type system for IO decoding/encoding
Stars: ✭ 5,086 (+885.66%)
Mutual labels:  validation
Colander
A serialization/deserialization/validation library for strings, mappings and lists.
Stars: ✭ 408 (-20.93%)
Mutual labels:  validation
Validator.js
⁉️轻量级的 JavaScript 表单验证,字符串验证。没有依赖,支持 UMD ,~3kb。
Stars: ✭ 486 (-5.81%)
Mutual labels:  validation
Graphql Constraint Directive
Validate GraphQL fields
Stars: ✭ 401 (-22.29%)
Mutual labels:  validation
Async sinatra
A plugin for Sinatra to provide a DSL extension for using Thin for asynchronous responses
Stars: ✭ 434 (-15.89%)
Mutual labels:  sinatra
Govalidator
[Go] Package of validators and sanitizers for strings, numerics, slices and structs
Stars: ✭ 5,163 (+900.58%)
Mutual labels:  validation
Enforce
Python 3.5+ runtime type checking for integration testing and data validation
Stars: ✭ 502 (-2.71%)
Mutual labels:  validation
Ngx Errors
A declarative validation errors module for reactive forms.
Stars: ✭ 472 (-8.53%)
Mutual labels:  validation

sinatra-param

Parameter Validation & Type Coercion for Sinatra

REST conventions take the guesswork out of designing and consuming web APIs. Simply GET, POST, PATCH, or DELETE resource endpoints, and you get what you'd expect.

However, when it comes to figuring out what parameters are expected... well, all bets are off.

This Sinatra extension takes a first step to solving this problem on the developer side

sinatra-param allows you to declare, validate, and transform endpoint parameters as you would in frameworks like ActiveModel or DataMapper.

Use sinatra-param in combination with Rack::PostBodyContentTypeParser and Rack::NestedParams to automatically parameterize JSON POST bodies and nested parameters.

Install

You can install sinatra-param from the command line with the following:

$ gem install sinatra-param

Alternatively, you can specify sinatra-param as a dependency in your Gemfile and run $ bundle install:

gem "sinatra-param", require: "sinatra/param"

Example

require 'sinatra/base'
require 'sinatra/param'
require 'json'

class App < Sinatra::Base
  helpers Sinatra::Param

  before do
    content_type :json
  end

  # GET /search?q=example
  # GET /search?q=example&categories=news
  # GET /search?q=example&sort=created_at&order=ASC
  get '/search' do
    param :q,           String, required: true
    param :categories,  Array
    param :sort,        String, default: "title"
    param :order,       String, in: ["ASC", "DESC"], transform: :upcase, default: "ASC"
    param :price,       String, format: /[<\=>]\s*\$\d+/

    one_of :q, :categories

    {...}.to_json
  end
end

Parameter Types

By declaring parameter types, incoming parameters will automatically be transformed into an object of that type. For instance, if a param is Boolean, values of '1', 'true', 't', 'yes', and 'y' will be automatically transformed into true.

  • String
  • Integer
  • Float
  • Boolean ("1/0", "true/false", "t/f", "yes/no", "y/n")
  • Array ("1,2,3,4,5")
  • Hash (key1:value1,key2:value2)
  • Date, Time, & DateTime

Validations

Encapsulate business logic in a consistent way with validations. If a parameter does not satisfy a particular condition, a 400 error is returned with a message explaining the failure.

  • required
  • blank
  • is
  • in, within, range
  • min / max
  • min_length / max_length
  • format

Custom Error Messages

Passing a message option allows you to customize the message for any validation error that occurs.

param :spelling,
      format: /\b(?![a-z]*cie)[a-z]*(?:cei|ie)[a-z]*/i,
      message: "'i' before 'e', except after 'c'"

Defaults and Transformations

Passing a default option will provide a default value for a parameter if none is passed. A default can defined as either a default or as a Proc:

param :attribution, String, default: "©"
param :year, Integer, default: lambda { Time.now.year }

Use the transform option to take even more of the business logic of parameter I/O out of your code. Anything that responds to to_proc (including Proc and symbols) will do.

param :order, String, in: ["ASC", "DESC"], transform: :upcase, default: "ASC"
param :offset, Integer, min: 0, transform: lambda {|n| n - (n % 10)}

One Of

Using one_of, routes can specify two or more parameters to be mutually exclusive, and fail if more than one of those parameters is provided:

param :a, String
param :b, String
param :c, String

one_of :a, :b, :c

Any Of

Using any_of, a route can specify that at least one of two or more parameters are required, and fail if none of them are provided:

param :x, String
param :y, String

any_of :x, :y

All Or None Of

Using all_or_none_of, a router can specify that all or none of a set of parameters are required, and fail if some are provided:

param :x, String
param :y, String

all_or_none_of :x,:y

Exceptions

By default, when a parameter precondition fails, Sinatra::Param will halt 400 with an error message:

{
  "message": "Parameter must be within [\"ASC\", \"DESC\"]",
  "errors": {
    "order": "Parameter must be within [\"ASC\", \"DESC\"]"
  }
}

To change this, you can set :raise_sinatra_param_exceptions to true, and intercept Sinatra::Param::InvalidParameterError with a Sinatra error do...end block. (To make this work in development, set :show_exceptions to false and :raise_errors to true):

set :raise_sinatra_param_exceptions, true

error Sinatra::Param::InvalidParameterError do
    { error: "#{env['sinatra.error'].param} is invalid" }.to_json
end

Custom exception handling can also be enabled on an individual parameter basis, by passing the raise option:

param :order, String, in: ["ASC", "DESC"], raise: true

one_of :q, :categories, raise: true

Contact

Mattt (@mattt)

License

sinatra-param is released under an MIT license. See LICENSE for more information.

Note that the project description data, including the texts, logos, images, and/or trademarks, for each open source project belongs to its rightful owner. If you wish to add or remove any projects, please contact us at [email protected].