Ruby equivalents for PHP magic methods __call, __get and __set

I'm sure Ruby has these (equivalents for __ call, __get and __ set ), because otherwise how will find_by work in Rails? Maybe someone can give a quick example of how to define methods that act like find_by ?

thanks

+7
ruby ruby-on-rails
source share
2 answers

Dynamic crawlers are performed by the absence of a method

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

Take a look at this blog post, it will give you the gist of how they work.

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

+5
source share

In short, you can display

  • __ method_missing method call with arguments
  • __ is set to a method_missing call with a method name ending in '='
  • __ go to 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 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 like calling "a=" method : obj.a=(1) puts obj.a 
+14
source share

All Articles