Ruby Language Interrupting Messages


Example

There are two ways to interrupt messages.

  • Use method_missing to interrupt any non defined message.
  • Define a method in middle of a chain to intercept the message

After interrupting messages, it is possible to:

  • Reply to them.
  • Send them somewhere else.
  • Modify the message or its result.

Interrupting via method_missing and replying to message:

class Example
  def foo
    @foo
  end

  def method_missing name, data
    return super unless name.to_s =~ /=$/
    name = name.to_s.sub(/=$/, "")
    instance_variable_set "@#{name}", data
  end
end

e = Example.new

e.foo = :foo
e.foo # => :foo

Intercepting message and modifying it:

class Example
  def initialize title, body
  end
end

class SubExample < Example
end

Now let's imagine our data is "title:body" and we have to split them before calling Example. We can define initialize on SubExample.

class SubExample < Example
  def initialize raw_data
    processed_data = raw_data.split ":"

    super processed_data[0], processed_data[1]
  end
end

Intercepting message and sending it to another object:

class ObscureLogicProcessor
  def process data
    :ok
  end
end

class NormalLogicProcessor
  def process data
    :not_ok
  end
end

class WrapperProcessor < NormalLogicProcessor
  def process data
    return ObscureLogicProcessor.new.process data if data.obscure?

    super
  end
end