Last active
July 15, 2016 14:29
-
-
Save nepalez/93253e761979ade07522a0ba32b2f48b to your computer and use it in GitHub Desktop.
Reform monkey-patching
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
require 'reform' | |
require 'reform/form/coercion' | |
require 'hashie/mash' | |
module Reform | |
module DryTypes | |
def property(name, type: nil, **options, &block) | |
super(name, **options, &block).tap do | |
if type | |
# Tries to coerce value to the necessary type | |
# Do not raise exception for the maximum coercions to be done | |
define_method("#{name}=") do |value| | |
value = type[value] rescue value | |
super(value) | |
end | |
# Checks whether a type is valid | |
validate do | |
type[send(name)] rescue errors.add(name, :invalid) | |
end | |
end | |
end | |
end | |
end | |
module SubForm | |
def property(name, **options, &block) | |
if block || options[:form] || options[:twin] | |
options[:populate_if_empty] = Hashie::Mash | |
end | |
super(name, options, &block) | |
end | |
def collection(name, **options, &block) | |
if block || options[:form] || options[:twin] | |
options[:populate_if_empty] = Hashie::Mash | |
end | |
super(name, options, &block) | |
end | |
end | |
class Contract | |
extend DryTypes | |
extend SubForm | |
# Break validation after the first type mismatch has occured | |
# | |
# Rescue from NoMethodError which can be risen when some validator | |
# calls method expected for valid structure, but we failed to | |
# coerce data to that structure. | |
# | |
def validate(*) | |
super | |
rescue TypeError, NoMethodError | |
false | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment