module Tree::Utils::CamelCaseMethodHandler

Provides utility functions to handle CamelCase methods, and redirect invocation of such methods to the snake_case equivalents.

Public Class Methods

included(base) click to toggle source
# File lib/tree/utils/camel_case_method_handler.rb, line 46
def self.included(base)
  # @!visibility private
  # Allow the deprecated CamelCase method names.  Display a warning.
  # :nodoc:
  def method_missing(meth, *args, &blk)
    if self.respond_to?((new_method_name = to_snake_case(meth)))
      warn StructuredWarnings::DeprecatedMethodWarning,
           'The camelCased methods are deprecated. ' +
           "Please use #{new_method_name} instead of #{meth}"
      send(new_method_name, *args, &blk)
    else
      super
    end
  end

  protected

  # @!visibility private
  # Convert a CamelCasedWord to a underscore separated camel_cased_word.
  #
  # @param [String] camel_cased_word The word to be converted to snake_case.
  # @return [String] the snake_cased_word.
  def to_snake_case(camel_cased_word)
    word = camel_cased_word.to_s
    word.gsub!(/::/, '/')
    word.gsub!(/([A-Z]+)([A-Z][a-z])/,'\1_\2')
    word.gsub!(/([a-z\d])([A-Z])/,'\1_\2')
    word.tr!('-', '_')
    word.downcase!
    word
  end

end