Module: Overridable::ClassMethods

Defined in:
lib/overridable.rb

Overview

:nodoc:

Instance Method Summary collapse

Instance Method Details

#overrides(*method_names) ⇒ Object

Specifies which methods can be overrided.

Parameters:

  • method_names (Symbol, String)

    specifies one or more methods which can be overrided.

Returns:

  • nil



143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
# File 'lib/overridable.rb', line 143

def overrides *method_names
  return unless self.is_a?(Class) # do nothing if it's a module
  methods =
    method_names.map { |m| instance_method m rescue nil } \
                .compact \
                .select { |m| m.owner == self }
  unless methods.empty?
    # All overrided methods are defined in the same module
    is_module_defined =
      if method(:const_defined?).arity > 0 # 1.8.x
        self.const_defined?(:OverridedMethods)
      else # 1.9
        self.const_defined?(:OverridedMethods, false)
      end

    unless is_module_defined
      self.const_set(:OverridedMethods, Module.new)
      include self.const_get(:OverridedMethods)
    end
    mod = const_get(:OverridedMethods)

    old_verbose, $VERBOSE = $VERBOSE, nil # supress warnings
    methods.each { |m|
      scope = private_instance_methods(false).include?(m.name) ?
        :private :
        protected_instance_methods(false).include?(m.name) ?
        :protected : :public
      remove_method m.name
      mod.send :define_method, m.name do |*args, &blk|
        m.bind(self).call(*args, &blk)
      end
      mod.send scope, m.name
    }
    $VERBOSE = old_verbose
  end

  nil
end