Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby equivalents for PHP's magic methods __call, __get and __set

I am pretty sure that Ruby has these (equivalents for __call, __get and __set), because otherwise how find_by would work in Rails? Maybe someone could give a quick example of how to define methods that act same as find_by?

Thanks

like image 872
spacemonkey Avatar asked Aug 16 '10 14:08

spacemonkey


People also ask

What is __ call () in PHP?

When you call a method on an object of the Str class and that method doesn't exist e.g., length() , PHP will invoke the __call() method. The __call() method will raise a BadMethodCallException if the method is not supported. Otherwise, it'll add the string to the argument list before calling the corresponding function.

What is __ set in PHP?

The __set() Method The __set() magic method is called when you try to set data to inaccessible or non-existent object properties. The purpose of this method is to set extra object data for which you haven't defined object properties explicitly.


1 Answers

in short you can map

  • __call to a method_missing call with arguments
  • __set to a method_missing call with method's name ending with '='
  • __get to a method_missing call without any arguments

__call

php

class MethodTest {
  public function __call($name, $arguments) {
    echo "Calling object method '$name' with " . implode(', ', $arguments) . "\n";
  }
}

$obj = new MethodTest;
$obj->runTest('arg1', 'arg2');

ruby

class MethodTest
  def method_missing(name, *arguments)
    puts "Calling object method '#{name}' with #{arguments.join(', ')}"
  end
end

obj = MethodTest.new
obj.runTest('arg1', 'arg2')

__set and __get

php

class PropertyTest {
  //  Location for overloaded data.
  private $data = array();

  public function __set($name, $value) {
    echo "Setting '$name' to '$value'\n";
    $this->data[$name] = $value;
  }

  public function __get($name) {
    echo "Getting '$name'\n";
    if (array_key_exists($name, $this->data)) {
      return $this->data[$name];
    }
  }
}

$obj = new PropertyTest;
$obj->a = 1;
echo $obj->a . "\n";

ruby

class PropertyTest

  # Location for overloaded data.
  attr_reader :data
  def initialize
    @data = {}
  end

  def method_missing(name, *arguments)
    value = arguments[0]
    name = name.to_s

    # if the method's name ends with '='
    if name[-1, 1] == "="

      method_name = name[0..-2]
      puts "Setting '#{method_name}' to '#{value}'"
      @data[method_name] = value

    else

      puts "Getting '#{name}'"
      @data[name]

    end
  end

end

obj = PropertyTest.new
obj.a = 1 # it's like calling "a=" method : obj.a=(1)
puts obj.a
like image 161
hdorio Avatar answered Nov 16 '22 02:11

hdorio