Created
          February 12, 2018 16:01 
        
      - 
      
 - 
        
Save skojin/20f818cc3572dc7922e8cd11abe27b77 to your computer and use it in GitHub Desktop.  
    generate strong params hash rule by real request hash
  
        
  
    
      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
    
  
  
    
  | 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