Last active
May 7, 2017 16:07
-
-
Save tomdalling/c6bacdac10bb70168556038c9ab60483 to your computer and use it in GitHub Desktop.
Pluggable/composable coercion upcoming in RSchema v3
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# params usually come in as strings, regardless of the actual type they are | |
params = { | |
'fruit' => 'banana', | |
'harvested_at' => '2017-05-08T01:46:16+10:00', | |
'unwanted_framework_crap' => 'DHH', | |
} | |
# you can declare what the types are _supposed_ to be with a schema | |
schema = RSchema.define {{ | |
fruit: _Symbol, | |
harvested_at: _Time, | |
is_ripe: Boolean(), | |
}} | |
# but schemas are strict by default, and will not accept the param strings | |
result = schema.call(params) | |
puts result.valid? #=> false | |
# so, to enable coercion, you can wrap coercers around the schema | |
coercing_schema = RSchema::RACK_PARAM_COERCER.wrap(schema) | |
# this new schema will coerce and accept the params | |
result = coercing_schema.call(params) | |
result.valid? #=> true | |
result.value #=> | |
# { | |
# :fruit => :banana, | |
# :harvested_at => #<Time 2017-05-08 01:46:16 +1000>, | |
# :is_ripe => false, | |
# } | |
# These coercion wrappers are composed of many small coercers, | |
# which gives fine-grained control over what does/doesn't get | |
# coerced. | |
module RSchema | |
RACK_PARAM_COERCER = CoercionWrapper.new do | |
coerce_type Symbol, with: Coercers::Symbol | |
coerce_type Integer, with: Coercers::Integer | |
coerce_type Float, with: Coercers::Float | |
coerce_type Time, with: Coercers::Time | |
coerce_type Date, with: Coercers::Date | |
coerce Schemas::Boolean, with: Coercers::Boolean | |
coerce Schemas::FixedHash, with: [ | |
Coercers::FixedHash::SymbolizeKeys, | |
Coercers::FixedHash::RemoveExtraneousAttributes, | |
Coercers::FixedHash::DefaultBooleansToFalse, | |
] | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment