Skip to content

Instantly share code, notes, and snippets.

@letsbreelhere
Last active August 29, 2015 14:04
Show Gist options
  • Save letsbreelhere/960a5e74cf391405869f to your computer and use it in GitHub Desktop.
Save letsbreelhere/960a5e74cf391405869f to your computer and use it in GitHub Desktop.
Sketch of nested strong Rails params
# 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