Module: Tree::Utils::CamelCaseMethodHandler

Included in:
TreeNode
Defined in:
lib/tree/utils/camel_case_method_handler.rb

Overview

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

Class Method Summary collapse

Dynamic Method Handling

This class handles dynamic methods through the method_missing method

#method_missing(meth, *args, &blk) ⇒ Object (private)

Allow the deprecated CamelCase method names. Display a warning. :nodoc:


50
51
52
53
54
55
56
57
58
59
# File 'lib/tree/utils/camel_case_method_handler.rb', line 50

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

Class Method Details

.included(base) ⇒ Object


46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
# 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