PHP的魔术方法__call,__ get和__set的Ruby等价物

时间:2010-08-16 14:36:38

标签: ruby-on-rails ruby dynamic-method

我很确定Ruby有这些(等效于 __ call,__ get __ set ),因为否则 find_by 在Rails中的作用如何?也许有人可以举例说明如何定义与 find_by 相同的方法?

由于

2 个答案:

答案 0 :(得分:14)

简而言之,你可以映射

  • __调用带参数的method_missing调用
  • __设置为方法名称以'='
  • 结尾的method_missing调用
  • __进入一个没有任何参数的method_missing调用

__呼叫

php

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

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

红宝石

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和__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";

红宝石

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

答案 1 :(得分:6)

动态查找器通过实现方法缺失

完成

http://ruby-doc.org/core/classes/Kernel.html#M005925

看一下这篇博客文章,它将为您提供有关它们如何工作的要点..

http://blog.hasmanythrough.com/2006/8/13/how-dynamic-finders-work