重写控制器中的基类方法

发布于 2024-07-25 16:01:20 字数 685 浏览 2 评论 0原文

我试图欺骗一个非常复杂的黑匣子,以不同的方式显示一些浮动(它是 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

俏︾媚 2024-08-01 16:01:21

如果您想替换 Float#to_s 的行为,您可以尝试将 Monkeypatch 添加到 初始化程序。 然而,这将在您的 Rails 应用程序中全局修补 Float#to_s。

config/initializers/float_patch.rb:

class Float
  def to_s
    h = (self / 60).to_i
    m = self.to_i % 60
    h.to_s + ':' + m.to_s
  end
end

如果您不想太广泛地修补像 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:

class Float
  def to_s
    h = (self / 60).to_i
    m = self.to_i % 60
    h.to_s + ':' + m.to_s
  end
end

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文