[英]Ruby equivalents for PHP's magic methods __call, __get and __set
我非常確定Ruby具有這些(相當於__call,__get和__set ),因為否則find_by在Rails中將如何工作? 也許有人可以舉一個簡單的例子,說明如何定義與find_by相同的方法?
謝謝
總之你可以映射
的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')
的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
動態查找器是通過實現缺少方法來完成的
http://ruby-doc.org/core/classes/Kernel.html#M005925
看一下這篇博客文章,它將為您提供它們工作原理的要點。
http://blog.hasmanythrough.com/2006/8/13/how-dynamic-finders-work
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.