在 rails 控制器中使用静态变量是一种好习惯吗?
Is it good practice to use static variables in rails controller?
我对 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中使用class变量(以@@
开头的变量); see here why
这可能看起来像一个奇怪的代码,但这是更传统的方式:
您设置了一个 "class" 实例变量,而不是设置一个 "class variable"。
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
我对 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中使用class变量(以@@
开头的变量); see here why
这可能看起来像一个奇怪的代码,但这是更传统的方式:
您设置了一个 "class" 实例变量,而不是设置一个 "class variable"。
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