Ruby Language Message Passing Interrupting Messages

Help us to keep this website almost Ad Free! It takes only 10 seconds of your time:
> Step 1: Go view our video on YouTube: EF Core Bulk Extensions
> Step 2: And Like the video. BONUS: You can also share it!

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


Got any Ruby Language Question?