Method: Module#instance_function

Defined in:
lib/core/facets/module/instance_function.rb

#instance_function(*meths) ⇒ Object

Converts module methods into instance methods such that the first parameter is passed self. This promotes DRY programming when wishing to offer both inheritable and module callable procedures.

This method is modeled after module_function which essentially has the the opposite effect. Due to implementation limitations, this must use the callback #singleton_method_added to emulate module_function when no method names are given.

module MyModule
  instance_function

  def self.jumble(obj, arg)
    obj + arg
  end
end

MyModule.jumble("Try", "Me")  #=> "TryMe"

s = "Try"
s.extend MyModule
s.jumble("Me")                #=> "TryMe"

Note: This used to be a module called PromoteSelf and later Instantize, before becoming a method.

NOTE: This method is not a common core extension and is not loaded automatically when using require 'facets'.

Uncommon:

  • require ‘facets/module/instance_function’



34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
# File 'lib/core/facets/module/instance_function.rb', line 34

def instance_function(*meths)
  this = self
  if meths.empty?
    extend InstanceFunction
  else
    meths.each do |meth|
      module_eval do
        define_method(meth) do |*args|
          this.__send__(meth, self, *args)
        end
      end
      ##class_eval %{
      ##  def #{meth}(*args)
      ##    #{self.name}.#{meth}(self,*args)
      ##  end
      ##}
    end
  end
end