Tag: singleton

Ruby元编程:初始化singleton_class变量

为什么Foo.val在调用Foo.set之前返回nil而不是”foo” ? 在课堂评估中是否有任何初始化@val机制? @val = “foo”存放在哪个范围内? class Foo class << self @val = "foo" attr_reader :val def set(val) @val = val end end end p Foo.val # nil Foo.set("bar") p Foo.val # "bar"

如何测试Singleton类?

我正在使用RSpec并且想要多次测试Singleton类的构造函数。 我怎样才能做到这一点? 最好的祝福

使用method_added了解ruby元编程以动态覆盖实例方法

我有以下来自Programming Ruby 1.9的代码(略微适应)我只是想确保我的思维过程是准确的 module Trace def self.included(culprit) #Inject existing methods with tracing code: culprit.instance_methods(false).each do |func| inject(culprit, func) end #Override the singletons method_added to ensure all future methods are injected. def culprit.method_added(meth) unless @trace_calls_internal @trace_calls_internal = true Trace.inject(self, meth) #This will call method_added itself, the condition prevents infinite recursion. @trace_calls_internal = false end end end […]

在Ruby中重置单例实例

如何在Ruby中重置单个对象? 我知道在实际代码中我们永远不想这样做但是unit testing呢? 这是我在RSpec测试中尝试做的事情 – describe MySingleton, “#not_initialised” do it “raises an exception” do expect {MySingleton.get_something}.to raise_error(RuntimeError) end end 它失败了,因为我之前的一个测试初始化​​了单例对象。 我试过从这个链接开始关注Ian White的建议,它基本上是猴子补丁Singleton来提供reset_instance方法,但我得到一个未定义的方法’reset_instance’exception。 require ‘singleton’ class <<Singleton def included_with_reset(klass) included_without_reset(klass) class <<klass def reset_instance Singleton.send :__init__, self self end end end alias_method :included_without_reset, :included alias_method :included, :included_with_reset end describe MySingleton, "#not_initialised" do it "raises an exception" […]

ruby顶层定义的方法在哪里?

在顶层,方法定义应该导致Object上的私有方法,并且测试似乎证实了这一点: def hello; “hello world”; end Object.private_instance_methods.include?(:hello) #=> true Object.new.send(:hello) #=> “hello world” 但是,以下也适用于顶层( self.meta是main本征类): self.meta.private_instance_methods(false).include?(:hello) #=> true 似乎hello方法同时在main和Object本征类上定义。 这是怎么回事? 请注意, private_instance_methods的false参数会从方法列表中排除超类方法。