2016-10-24 6 views
0

Wenn ich eine OpenStruct:catch-all getter-Methode auf openstruct?

require 'ostruct' 
open_struct = OpenStruct.new 

Ich kann [] überschreiben, die in einigen Fällen funktioniert

open_struct.define_singleton_method(:[]) do |*args| 
    puts args.map(&:class) 
    puts args 
end 

open_struct.a = 1 
open_struct[:a] 
# => Symbol 
# a 

Aber diese [] Methode wird nicht aufgerufen, wenn der Punkt-Methode Syntax:

open_struct.a 
# => 1 

Ich versuche, eine Klasse zu machen, die von OpenStruct erbt und mehr wie ein Javascript-Objekt funktioniert (im Grunde bin ich t rocknung die Notwendigkeit zu entfernen call auf einem proc auszuführen, die als Wert)

Antwort

1

Zunächst einmal gespeichert wird - OpenStruct bereits Funktionen sehr ähnlich wie JavaScript (vorausgesetzt, dass #[] ein Synonym für #call) ist:

JS:

foo = {} 
foo.bar = function() { console.log("Hello, world!"); }; 
foo.bar(); 
// => Hello, world! 

Rubin:

foo = OpenStruct.new 
foo.bar = proc { puts "Hello, world!" } 
foo.bar[] 
# => Hello, world! 

Wenn Sie mehr bedeuten funktionieren wie Rubin ... Sie können new_ostruct_member außer Kraft setzen:

require 'ostruct' 

class AutoCallableOpenStruct < OpenStruct 
    protected def new_ostruct_member(name) 
    name = name.to_sym 
    unless respond_to?(name) 
     define_singleton_method(name) { 
     val = @table[name] 
     if Proc === val && val.arity == 0 
      val.call 
     else 
      val 
     end 
     } 
     define_singleton_method("#{name}=") { |x| modifiable[name] = x } 
    end 
    name 
    end 
end 

a = AutoCallableOpenStruct.new 
a.name = "max" 
a.helloworld = proc { puts "Hello, world!" } 
a.hello = proc { |name| puts "Hello, #{name}!" } 

a.name    # non-Proc, retrieve 
# => max 
a.helloworld  # nullary proc, autocall 
# => Hello, world! 
a.hello[a.name]  # non-nullary Proc, retrieve (#[] invokes) 
# => Hello, max! 

sich bewusst sein, dass nur OpenStruct in Ruby Sie Ihre Programm verlangsamt, und sollte nicht verwendet werden, wenn Sie es vermeiden können.

Verwandte Themen