spa*_*key 7 ruby ruby-on-rails dynamic-method
我很确定Ruby有这些(__ call ,__ get和__set的等价物),因为否则find_by如何在Rails中工作?也许有人可以举例说明如何定义与find_by相同的方法?
谢谢
hdo*_*rio 14
总之,你可以映射
PHP
class MethodTest {
public function __call($name, $arguments) {
echo "Calling object method '$name' with " . implode(', ', $arguments) . "\n";
}
}
$obj = new MethodTest;
$obj->runTest('arg1', 'arg2');
Run Code Online (Sandbox Code Playgroud)
红宝石
class MethodTest
def method_missing(name, *arguments)
puts "Calling object method '#{name}' with #{arguments.join(', ')}"
end
end
obj = MethodTest.new
obj.runTest('arg1', 'arg2')
Run Code Online (Sandbox Code Playgroud)
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";
Run Code Online (Sandbox Code Playgroud)
红宝石
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
Run Code Online (Sandbox Code Playgroud)
动态查找器通过实现方法缺失来完成
http://ruby-doc.org/core/classes/Kernel.html#M005925
看一下这篇博文,它将为您提供有关它们如何工作的要点.
http://blog.hasmanythrough.com/2006/8/13/how-dynamic-finders-work
| 归档时间: |
|
| 查看次数: |
4014 次 |
| 最近记录: |