Skip to content

Instantly share code, notes, and snippets.

@skojin
Created February 12, 2018 16:01
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save skojin/20f818cc3572dc7922e8cd11abe27b77 to your computer and use it in GitHub Desktop.
Save skojin/20f818cc3572dc7922e8cd11abe27b77 to your computer and use it in GitHub Desktop.
generate strong params hash rule by real request hash
def to_permit_rule(h)
scalar = []
complex = {}
h.each do |k,v|
if v.is_a? Array
complex[k.to_sym] = []
elsif v.is_a? Hash
if v.keys.all?{|vk| vk =~ /\A\d+\z/ }
complex[k.to_sym] = to_permit_rule(v.values.first)
else
complex[k.to_sym] = to_permit_rule(v)
end
else
scalar << k.to_sym
end
end
scalar.delete(:_destroy)
scalar.sort!
if !complex.empty? && scalar.empty?
complex
elsif !complex.empty? && !scalar.empty?
scalar << complex
else
scalar
end
end
require 'pp'
#pp to_permit_rule(h)
pp to_permit_rule(post: {title: 'tt', author: 'au', comments: {
'0' => {comment: 'C1', id: 1},
'1' => {comment: 'C2', id: 1},
}})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment