Sha256: 0abc32477ebe236594f9934038f835bb6a02fd92cd7fb84531a0b446e1e34891

Contents?: true

Size: 1.65 KB

Versions: 6

Compression:

Stored size: 1.65 KB

Contents

class Module
  # 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
  #
  #   class String
  #     include MyModule
  #   end
  #
  #   MyModule.jumble( "Try", "Me" )  #=> "TryMe"
  #
  #   "Try".jumble( "Me" )            #=> 'TryMe'
  #
  # Note: This used to be a module called PromoteSelf and later Instantize,
  # before becoming a method.
  #
  def instance_function(*meths)
    if meths.empty?
      extend InstanceFunction
    else
      meths.each do |meth|
        class_eval %{
          def #{meth}(*args)
            #{self.name}.#{meth}(self,*args)
          end
        }
      end
    end
  end

  module InstanceFunction #:nodoc
    #
    def singleton_method_added(meth)
      module_eval %{
        def #{meth}(*args)
          #{self.name}.#{meth}(self,*args)
        end
      }
      #self.class_eval d
      super(meth)
    end
  end

end #class Module

=begin
module Instantize

  def self.append_features(mod)
    mod.extend self
  end

  def singleton_method_added( meth )
    d = %{
      def #{meth}(*args)
        #{self.name}.#{meth}(self,*args)
      end
    }
    self.class_eval d
    super(meth)
  end

end
=end

Version data entries

6 entries across 6 versions & 1 rubygems

Version Path
facets-2.8.4 lib/more/facets/instance_function.rb
facets-2.8.3 lib/more/facets/instance_function.rb
facets-2.8.2 lib/more/facets/instance_function.rb
facets-2.8.1 lib/more/facets/instance_function.rb
facets-2.8.0 lib/more/facets/instance_function.rb
facets-2.7.0 lib/more/facets/instance_function.rb