Search code examples
ruby-on-railsstatic-variables

Is it good practice to use static variables in rails controller?


I have a question concerning best practices in rails. In my rails project I have the following code:

class MyController < ApplicationController

  def some_method
    @product = MyFabricatorClass.new.create_product
  end

  ...
end

MyFabricatorClass is not dependent of some state and its behaviour is constant. I am also doing a lot of C++ stuff and to me it feels kind of unefficient to always instantiate a new MyFabricatorClass object. In a C++ project I would propably use something like:

class MyController < ApplicationController

  @@my_fabricator = nil

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

  ...
end

Is this style also legit in Rails? What would be the typical rails way to do it?

Thanks for any advice...!


Solution

  • It is a better practice to not use class variables (those that start with @@) in ruby; see here why

    This might look like a weird code, but this is the more conventional way:

    You set a "class" instance variable, instead of setting a "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
    

    About class << self, see here

    The above code is just the same as:

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

    Now you can just do:

    MyController.some_method