Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I have a couple large arrays that need to be available to a specific view. Currently I'm storing these in YAML files and loading into controller constants, as below.

I assume that this constant is stored in memory when Rails loads the file during environment setup, but the paranoid part of me wonders if I'm hitting the filesystem each time that 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'))

  # ...
like image 931
Seth Bro Avatar asked Dec 13 '22 04:12

Seth Bro


1 Answers

I assume that this constant is stored in memory when Rails loads the file during environment setup

Yep, when the file is loaded/required, everything in there is executed and assigned. Therefore it's loaded only once.

but the paranoid part of me wonders if I'm hitting the filesystem each time that controller is accessed.

Partially true, in development mode, constants are unset with each request, but that shouldn'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 instead of at startup where you've got the time because the old worker is still running.

like image 78
Reactormonk Avatar answered May 08 '23 06:05

Reactormonk