Flowdock

Notes posted by kuldeepaggarwal

RSS feed
August 7, 2018
0 thanks

define_method with blocks works differently

As it is already stated that block is evaluated using instance_exec/instance_eval, so let me give you an example.

module Service
  module ClassMethods
    def endpoint_instance_exec(name, &block)
      define_method name do
        instance_exec(&block)
      end
    end

    def endpoint_block_call(name, &block)
      define_method name, &block
    end

    def endpoint_block_improper_call(name, &block)
      define_method name do
        # In this case, we called the block without "instance_eval" that
        # means block was called in the context of class MyService.
        block.call
      end
    end
  end

  def self.included(klass)
    klass.extend ClassMethods
  end

  private

    def hello
      puts 'world'
    end
end

class MyService
  include Service

  endpoint_instance_exec :foo do
    hello
  end

  endpoint_block_call :bar do
    hello
  end

  endpoint_block_improper_call :foobar do
    hello
  end
end

Now, understand how can we execute the code and understand the working of define_method and instance_exec.

MyService.new.foo # => "hello"
MyService.new.bar # => "hello"
MyService.new.foobar # => undefined local variable or method `hello' for MyService:Class