我有一个关于 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 方法是什么?
感谢您的任何建议...!
最佳答案
在 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 << 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
关于ruby-on-rails - 在 Rails Controller 中使用静态变量是个好习惯吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46247915/