module SnakeParams

SnakeParams helps smooth out the differences in naming conventions between the front-end (camelCase) and the back-end (snake_case). To use, just include this module in your Rails controller classes like this:

include SnakeParams

Constants

VERSION

Public Instance Methods

deep_snake_case_params!(val = params) click to toggle source

A method that recursively snake cases the camel cased params we receive from the frontend. @param val [Array/Hash] the parameters as they come from the front-end

# File lib/snake_params.rb, line 22
def deep_snake_case_params!(val = params)
  case val
  when Array
    val.map { |v| deep_snake_case_params!(v) }
  when Hash
    # We iterate the keys and then get the value, as opposed to the usual
    # val.each do |k,v| because otherwise we get an error during the
    # iteration with updates: can't add a new key into hash during iteration
    val.keys.each do |k, v = val[k]|
      val.delete k
      val[k.underscore] = deep_snake_case_params!(v)
    end
    val
  else
    val
  end
end