我希望知道何時調用任何類或任何類的方法。可能嗎?是否有可能知道何時在Ruby或Ruby on Rails中調用模型?
UPDATE
對於爲例
class Example
def obeserver_method
p "this class has been called."
end
end
UPDATE
我試圖實現一個觀察者,基於在Ruby的觀察者模式,而是返回一個錯誤...
require "observer"
class AAnyClass
extend Observable
changed
end
module AnObserver
extend self
def call constant
p "Constant #{constant} has been called."
end
def observe constant
constant.add_observer(self, call(constant))
end
end
#=> returns "Constant AAnyClass has been called."
AnObserver.observe AAnyClass
# must return "Constant AAnyClass has been called."
AAnyClass
# must return "Constant AAnyClass has been called."
AAnyClass
這是錯誤:`add_observer': observer does not respond to `Constant AAnyClass has been called.' (NoMethodError)
UPDATE
新的實現
class AAnyClass
extend Observable
changed
notify_observers self
end
module AnObserver
extend self
def call constant
p "Constant #{constant} has been called."
end
def observe constant
constant.add_observer(self, :call)
end
end
不返回一個錯誤,但沒有看到。
當你調用它,你知道吧:)添加更多信息的問題,指定它 –
@AndreyDeineko我添加了信息。 – rplaurindo
add_observer中的第二個參數是與將被調用的方法相對應的符號 - 您正在傳遞調用「call」的結果,這是字符串「Constant AAnyClass has called。」。你需要寫它'constant.add_observer(self,:call)'。但是這不會產生預期的結果。在你的類定義中,你調用'changed',這隻會在類實例化時觸發(與我其他評論中的原因相同) – sgbett