【问题标题】:Is it good practice to use static variables in rails controller?在 Rails 控制器中使用静态变量是一种好习惯吗?
【发布时间】:2018-02-25 03:19:34
【问题描述】:

我有一个关于 Rails 最佳实践的问题。 在我的 Rails 项目中,我有以下代码:

class MyController < ApplicationController

  def some_method
    @product = MyFabricatorClass.new.create_product
  end

  ...
end

MyFabricatorClass 不依赖于某些状态,它的行为是恒定的。我也在做很多 C++ 的东西,对我来说,总是实例化一个新的 MyFabricatorClass 对象感觉有点低效。在 C++ 项目中,我可能会使用类似的东西:

class MyController < ApplicationController

  @@my_fabricator = nil

  def some_method
    @@my_fabricator ||= MyFabricatorClass.new
    @product = @@my_fabricator.create_product
  end

  ...
end

这种风格在 Rails 中也是合法的吗?典型的 Rails 方法是什么?

感谢您的建议...!

【问题讨论】:

  • 为什么不让create_product 成为MyFabricatorClass 的类方法?
  • @jvillian:感谢您的评论。对不起,我选择了错误的命名。 MyFabricatorClass 不是真正的我的班级,而是第 3 方。因此,更改 MyFabricatorClass 不是一种选择。

标签: ruby-on-rails static-variables


【解决方案1】:

最好不要在 ruby​​ 中使用类变量(以@@ 开头的变量); see here why

这可能看起来像一个奇怪的代码,但这是更传统的方式:

您设置了一个“类”实例变量,而不是设置了一个“类变量”。

class MyController < ApplicationController
  @my_fabricator = nil

  class << self
    def some_method
      @my_fabricator ||= MyFabricatorClass.new
      @product = @my_fabricator.create_product
    end
  end
end

关于class &lt;&lt; self,见here

上面的代码就是这样的:

class MyController < ApplicationController
  @my_fabricator = nil

  def self.some_method
    @my_fabricator ||= MyFabricatorClass.new
    @product = @my_fabricator.create_product
  end
end

现在你可以这样做了:

MyController.some_method

【讨论】:

  • 感谢您的澄清和其他资源。接受并赞成。
  • 如果我在class &lt;&lt; self 块内声明@my_fabricator 有什么不同吗?谢谢
  • @hqt 是的,如果您在class &lt;&lt; self 之外声明@my_fabricator,则这些变量将成为对象MyController(它是Class 的一个实例)的实例变量。但是,如果您在其中声明它们,它们将成为对象 &lt;Class:MyController&gt;(这是 MyController 的单例类对象)的实例变量。单例类就像“为特定对象定义方法的地方”。即:puts MyController.new.singleton_class 将显示 #&lt;Class:#&lt;MyController:0x00007fa5b21ee588&gt;&gt;puts MyController.singleton_class 将显示 #&lt;Class:MyController&gt;
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2013-10-13
  • 1970-01-01
  • 2016-06-09
  • 2014-12-23
  • 2011-10-31
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多