Skip to content

Instantly share code, notes, and snippets.

@snusnu
Last active December 31, 2015 21:49
Show Gist options
  • Save snusnu/8049410 to your computer and use it in GitHub Desktop.
Save snusnu/8049410 to your computer and use it in GitHub Desktop.
class MethodObject < Module
DEFAULT_NAME = :call
def initialize(name = DEFAULT_NAME)
@name = name
end
def self.included(host)
host.instance_exec(@name) do |name|
define_method :call do |*args|
new(*args).public_send(name)
end
end
end
end
class Greeter
include Concord.new(:entity)
include MethodObject.new
def call
puts("Hello #{entity}")
end
end
Greeter.call('world')
class Printer
include Concord.new(:text)
include MethodObject.new(:print)
def print
puts("Hello #{text}")
end
end
Printer.print('world')
@mbj
Copy link

mbj commented Dec 20, 2013

My MethodObject is a littlebit differend:

class MethodObject < Module
  include Concord.new(:name)

  def self.included(host)
     name = self.name
     host.class_eval do
        def self.call(*arguments)
           new(*arguments).publi_send(name)
        end
     end
  end
end

class Foo
   include MethodObject.new(:bar)

   def bar
      :baz
   end
end # Foo

Foo.call # => :baz

The idea is to delegate to a public interface of the instance. While the arguments to the method object will end up as state of the method object.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment