Module: British::ClassMethods

Defined in:
lib/british.rb

Overview

Public: ClassMethods to extend in self.included Defines an?, is_an?, method_missing

Instance Method Summary collapse

Instance Method Details

#overwrite_method_missingObject

Public: method to overwrite original method_missing with magic one: this method_missing tries to translate British methods to American ones before throwing NoMethodError if neither method was found.

name - original method name
*args - original method args

Example

# with any British object
british_object.colour    # will be translated into color
british_object.magnetise # will be translated into magnetize

# all method endings age allowed
british_object.surprize!
british_object.surprize?
british_object.surprize=

# complex names are supported
british_object.initialise_something # initialize_something will be called

Returns the original method’s result Calls original method_missing (if British didn’t hook anything) Raises NoMethodError if the method cannot be found



146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
# File 'lib/british.rb', line 146

def overwrite_method_missing
  class_eval do
    unless method_defined?(:british_method_missing)
      define_method(:british_method_missing) do |name, *args|
        # do British magic
        americanised_name = name.to_s.gsub(BRITISH_ENDING_PATTERN, ENDINGS)
        return send(americanised_name, *args) if respond_to?(americanised_name)

        # call original method_missing (avoid double original method calls)
        return original_method_missing(name, *args) if caller[0] !~ /method_missing/ && defined?(:original_method_missing)

        # call original parent's method_missing
        method = self.class.superclass.instance_method(:original_method_missing)
        return method.bind(self).call(name, *args) if method
      end
    end

    if instance_method(:method_missing) != instance_method(:british_method_missing)
      alias_method :original_method_missing, :method_missing
      alias_method :method_missing, :british_method_missing
    end
  end
end