Skip to content

Instantly share code, notes, and snippets.

@khalilgharbaoui
Forked from apneadiving/params_slicer.rb
Created July 17, 2021 00:02
Show Gist options
  • Save khalilgharbaoui/9f9b002e37408d180aeb33c177904e87 to your computer and use it in GitHub Desktop.
Save khalilgharbaoui/9f9b002e37408d180aeb33c177904e87 to your computer and use it in GitHub Desktop.
class ParamsSlicer
def initialize(params, *whitelist)
@params = params
@nested_whitelist = whitelist.extract_options!
@whitelist = whitelist
end
def call
params.slice(*whitelist).tap do |result|
nested_whitelist.each do |k, v|
result[k] = params[k].slice(*v)
end
end
end
private
attr_reader :params, :nested_whitelist, :whitelist
end
h = {name: 'Mike', address_attributes: {city: 'Berlin', street: 'lisenhof'}}
ParamsSlicer.new(h, :name, address_attributes: %i[city]).call
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment