Create a new class and override the method_missing method : method_missing « Reflection « Ruby






Create a new class and override the method_missing method


class BackwardsString
  def initialize(s)
   @s = s
  end

  def method_missing(m, *args, &block)
    result = @s.send(m, *args, &block)
    result.respond_to?(:to_str) ? BackwardsString.new(result) : result
  end

  def to_s
    @s.reverse
  end

  def inspect
    to_s
  end
end

s = BackwardsString.new("I'm backwards.")             # => .sdrawkcab m'I
s.size                                                # => 14
s.upcase                                              # => .SDRAWKCAB M'I
s.reverse                                             # => I'm backwards.
s.no_such_method
# NoMethodError: undefined method 'no_such_method' for "I'm backwards.":String

 








Related examples in the same category

1.Convert all system command to all class method
2.Responding to Calls to Undefined Methods
3.Override method_missing method to provide meaningful error message
4.If method does not exist, call the default one
5.Create new method dynamically