2016-10-24 7 views
0

나는 OpenStruct있는 경우 :openstruct에서 catch-getter 메소드를 사용 하시겠습니까?

open_struct.a 
# => 1 
:

require 'ostruct' 
open_struct = OpenStruct.new 

나는 도트 메서드 구문을 사용하는 경우 어떤 경우

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

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

에서 작동하지만이 [] 메소드가 호출되지 않습니다 []를 덮어 쓸 수 있습니다

OpenStruct에서 상속 받고 더 자바 스크립트 개체처럼 작동하는 클래스를 만들려고합니다. (기본적으로 저는

JS : - 값으로 저장된 발동) 모든

답변

1

처음에 call를 실행하는 필요성을 제거하기 위해 rying 이미 기능이 매우 자바 스크립트와 같은 OpenStruct을 (#[]#call의 동의어) 인 것을 주어진

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

루비 :

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

더 루비 같은 기능을 의미하는 경우

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! 

그냥 루비 OpenStruct이 프로그램 속도가 느려집니다 것을 알고, 당신이 그것을 피할 수 있다면 사용하지 않아야합니다 : ... 당신은 new_ostruct_member을 대체 할 수 있습니다.