将 YAML 文件作为常量加载到 Rails 控制器中是否有效? [英] Is it efficient to load a YAML file as a constant in my Rails controller?

查看:42
本文介绍了将 YAML 文件作为常量加载到 Rails 控制器中是否有效?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有几个大型数组需要供特定视图使用.目前我将这些存储在 YAML 文件中并加载到控制器常量中,如下所示.

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.

我假设在环境设置期间 Rails 加载文件时,这个常量存储在内存中,但我的偏执部分想知道每次访问控制器时我是否都在访问文件系统.谁能建议这方面的最佳做法?

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'))

  # ...

推荐答案

我假设这个常量在 Rails 加载时存储在内存中环境设置过程中的文件

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.

这篇关于将 YAML 文件作为常量加载到 Rails 控制器中是否有效?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆