What is the best way to convert all controller params from camelCase to snake_case in Rails?

后端 未结 14 891
灰色年华
灰色年华 2020-12-23 00:02

As you already know, JSON naming convention advocates the use of camelSpace and the Rails advocates the use of snake_case for parameter names.

What is the best way t

14条回答
  •  谎友^
    谎友^ (楼主)
    2020-12-23 00:15

    You can create a filter that runs before any controller call and apply the following instructions to it:

    # transform camel case string into snake case
    snake_string  = Proc.new {|s| s.gsub(/([a-z])([A-Z])/) {|t| "#{$1}_#{$2.downcase}"}} 
    
    # transform all hash keys into snake case
    snake_hash    = Proc.new do |hash| 
      hash.inject({}) do |memo, item|
        key, value = item
    
        key = case key
              when String
                snake_string.call(key)
              when Symbol
                snake_string.call(key.to_s).to_sym
              else 
                key
              end    
    
        memo[key] = value.instance_of?(Hash) ? snake_hash.call(value) : value
        memo
      end
    end
    
    params = snake_hash.call(params)
    

    You must have to consider the above procedure will impose a small overhead on every Rails call.

    I am not convinced this is necessary, if it is just to fit in a convention.

提交回复
热议问题