Paramnoia is a library that allows for parameter coercion into type-safe crystal structures.
Add this to your application's shard.yml
:
dependencies:
paramnoia:
github: jreinert/paramnoia
tldr; Works exactly like JSON::Serializable
. Hint: run make
in the cloned
project, start up crystal play
and play around! The following
examples are runnable in the Workbook tab!
require "paramnoia"
struct Params
include Paramnoia::Params
getter foo : String
getter bar : Int32
end
pp Params.from_urlencoded("foo=hello&bar=3")
require "paramnoia"
struct Params
include Paramnoia::Params
getter foo : Array(Float64)
end
pp Params.from_urlencoded("foo[]=1&foo[]=2.3&foo[]=-3")
require "paramnoia"
struct Params
include Paramnoia::Params
getter foo : Bool
getter bar : Bool
getter baz : Bool
getter foobar : Bool
getter foobaz : Bool
end
pp Params.from_urlencoded("foo=1&bar=2&baz=0&foobar=FALSE&foobaz=false")
require "paramnoia"
enum Foobar
Foo
Bar
Baz
end
struct Params
include Paramnoia::Params
getter foo : Foobar
end
pp Params.from_urlencoded("foo=Bar")
require "paramnoia"
struct Params
include Paramnoia::Params
getter foo : String?
getter bar : String = "bar"
getter baz : Int32
end
pp Params.from_urlencoded("baz=3")
require "paramnoia"
struct Nested
include Paramnoia::Params
getter bar : String
getter baz : Array(Int32)
end
struct Params
include Paramnoia::Params
getter foo : Nested
getter bar : String
end
pp Params.from_urlencoded("foo[bar]=nested%20bar&foo[baz][]=1&foo[baz][]=2&bar=bar")
require "paramnoia"
module BazConverter
# You will be passed all matching param values from the HTTP::Params
def self.from_params(values : Array(String))
values.last.split(",").map { |i| Int32.new(i) }
end
end
struct Params
include Paramnoia::Params
@[Paramnoia::Params::Field(key: "fooBar")]
getter foo_bar : String
@[Paramnoia::Params::Field(converter: BazConverter)]
getter baz : Array(Int32)
end
pp Params.from_urlencoded("fooBar=foo&baz=1,2,3,4")
require "paramnoia"
@[Paramnoia::Settings(strict: true)]
struct Params
include Paramnoia::Params
getter foo : String
end
begin
Params.from_urlencoded("foo=bar&baz=1")
rescue ex : Exception
puts ex.message
end
require "paramnoia"
struct Params
include Paramnoia::Params
getter foo : String
getter bar : Int32
end
pp Params.from_json(%|{"foo":"foo","bar":1}|)
- Parsing from HTTP::Params
- Parsing from JSON
- Parsing from Form Data
- Parsing from Path Params
- Specs
- CI
- Refactoring/splitting up macro code
- Fork it (https://github.com/jreinert/paramnoia/fork)
- Create your feature branch (
git checkout -b my-new-feature
) - Commit your changes (
git commit -am 'Add some feature'
) - Push to the branch (
git push origin my-new-feature
) - Create a new Pull Request
- jreinert Joakim Reinert - creator, maintainer