重写控制器中的基类方法
我试图欺骗一个非常复杂的黑匣子,以不同的方式显示一些浮动(它是 Gruff 图形库,所以它被渲染为图像)。
在控制台中,我可以粘贴以下内容:
logger = RAILS_DEFAULT_LOGGER
logger.debug "Here's a float #{455.67.to_s}"
eval %{class Float
def to_s_with_time
h = (self / 60).to_i
m = self.to_i % 60
return h.to_s + ':' + m.to_s
end
alias_method_chain :to_s, :time
end
}
logger.debug "Here's another #{455.67.to_s}"
我会看到
Here is a float 455.67
Here is another 7:35
但是如果我将相同的代码粘贴到控制器中,我会看到
Here is a float 455.67
Here is another 455.67
为什么不能在控制器中替换 Float.to_s? 我还将接受“什么是更好的方法来完成此任务?”这个问题的答案。
I'm trying to fool a very complex black box into displaying some floats differently (it's the Gruff graphing library, so this is being rendered to an image).
In the console, I can paste this:
logger = RAILS_DEFAULT_LOGGER
logger.debug "Here's a float #{455.67.to_s}"
eval %{class Float
def to_s_with_time
h = (self / 60).to_i
m = self.to_i % 60
return h.to_s + ':' + m.to_s
end
alias_method_chain :to_s, :time
end
}
logger.debug "Here's another #{455.67.to_s}"
And I'll see
Here is a float 455.67
Here is another 7:35
But if I paste the same code into a controller, I see
Here is a float 455.67
Here is another 455.67
Why can't I replace Float.to_s within a controller? I will also accept answers to the question "What's a better way to accomplish this?"
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
如果您想替换 Float#to_s 的行为,您可以尝试将 Monkeypatch 添加到 初始化程序。 然而,这将在您的 Rails 应用程序中全局修补 Float#to_s。
config/initializers/float_patch.rb:
如果您不想太广泛地修补像 Float 这样的核心类,您也可以制作一个类似的初始化程序来修补粗暴的类/方法。
If you want to replace the behavior of Float#to_s, you could try adding your monkeypatch to the Float class in an initializer. This will however patch Float#to_s globally within your Rails app.
config/initializers/float_patch.rb:
You could also make a similar initializer to patch the gruff classes/methods if you you don't want to be so broad as to patch a core class like Float.