Last active
August 29, 2015 14:04
-
-
Save letsbreelhere/960a5e74cf391405869f to your computer and use it in GitHub Desktop.
Sketch of nested strong Rails params
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
# Like this: | |
# | |
# params.allow_nested( | |
# user: must( | |
# name: must, | |
# age: maybe, | |
# article: must( | |
# title: must, | |
# publish_at: maybe | |
# ), | |
# profile: maybe( | |
# intro: must, | |
# gender: maybe | |
# ) | |
# ) | |
# ) | |
module NestedStrongParams | |
RequiredParamsMissing = Class.new(RuntimeError) | |
WhitelistedHashError = Class.new(RuntimeError) | |
module Constants | |
MAYBE = Struct.new(:nest) | |
MUST = Struct.new(:nest) | |
end | |
def maybe(nest=nil) | |
Constants::MAYBE.new(nest) | |
end | |
def must(nest=nil) | |
Constants::MUST.new(nest) | |
end | |
end | |
# Don't actually monkey-patch Hash. Please. | |
class Hash | |
def allow_nested(allowances) | |
allowances.each do |key,value| | |
case value | |
when NestedStrongParams::Constants::MAYBE | |
raise NestedStrongParams::WhitelistedHashError.new(key) if self[key].is_a?(Hash) && value.nest.nil? | |
if value.nest | |
self[key].allow_nested(value.nest) | |
end | |
when NestedStrongParams::Constants::MUST | |
raise NestedStrongParams::RequiredParamsMissing unless has_key?(key) | |
raise NestedStrongParams::WhitelistedHashError.new(key) if self[key].is_a?(Hash) && value.nest.nil? | |
if value.nest | |
self[key].allow_nested(value.nest) | |
end | |
else | |
raise "Encountered unexpected value in nested allowances: #{value.inspect}" | |
end | |
end | |
self | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment