Is it efficient to load the YAML file as a constant in my Rails controller?

I have a couple of large arrays that need to be accessible for a specific kind. I am currently storing them in YAML files and loading them into controllers as shown below.

I'm guessing this constant is kept in memory when Rails loads the file during environment setup, but the paranoid part of me wonders if I'm hitting the filesystem every time this controller is accessed. Can anyone suggest best practices in this area?

class OnboardingController < ApplicationController

  BRANDS = YAML.load(File.open("#{Rails.root}/config/brands.yml", 'r'))
  STORES = YAML.load(File.open("#{Rails.root}/config/stores.yml", 'r'))

  # ...

      

+3


source to share


2 answers


I assume this constant is kept in memory when loading the Rails file during environment setup

Yes, when a file is loaded / required, everything in it is done and assigned. Therefore, it is loaded only once.

but the paranoid part of me is wondering if I hit the filesystem every time I access the controller.



Partially true, in design mode the constants are not set with every request, but that doesn't matter in production.

Can anyone suggest best practices in this area?

Leave it as it is, caching only forwards the parsing to the first request and not on startup where you have time, because the old worker is still running.

+6


source


You can lazily load it



class OnboardingController < ApplicationController  
  def brand_values
    @@brand_values ||= YAML.load((File.open("#{Rails.root}/config/brands.yml", 'r'))
  end

  def stores_values
    @@stores_values ||= YAML.load((File.open("#{Rails.root}/config/stores.yml", 'r'))
  end

end

      

+6


source







All Articles