我希望能够在名为 market 的文件夹中选择一个 yaml 文件。此文件夹将位于配置/市场中。在此文件夹中,我将有许多yaml文件,例如:
config/market
usa.yml
cad.yml
eur.yml
在每个 yml 文件中,我将具有相同的变量但不同的默认值。 例如在usa.yml上
---
:usa
country: "United States"
currency: "USD"
对于欧元,
---
:eur
country: "European Union"
currency: "EUR"
等等。我想使用国家和货币作为全局变量,例如在我的 rails 应用程序中。根据用户位置,我将选择 yaml 文件。
当用户登录我的应用程序时,我只想从市场文件夹中选择一个yaml文件。也许在应用程序控制器中执行before_action调用。像这样的东西
before_action :set_market
private
def set_market
if (statement)
Config[:market] = :usa
end
end
我该怎么做?请任何反馈都会有所帮助。
可以使用YAML 类打开文件。 查看此链接: https://ruby-doc.org/stdlib-2.1.3/libdoc/yaml/rdoc/YAML.html
像这样:
CONFIG = YAML.load_file("#{Rails.root.to_s}/config/market/usa.yml")
CONFIG["usa"]
希望这有帮助!
补充马库斯·文尼修斯的答案:
我建议使用一个具有不同市场/区域的yaml文件。假设您正在为使用区域的市场使用类似Spree的东西。
例如
1. 创建一个 yaml 文件 (settings.yml(:
production:
united_kingdom:
countries: ["GB", "IE"]
currency: GBP
//shipping ....
//etc
united_states:
countries: ["US", "PR"]
currency: USD
development:
united_kingdom:
countries: ["GB", "IE", "test"]
currency: GBP
//shipping ....
//etc
united_states:
countries: ["US", "PR", "test"]
currency: USD
2. 加载 yaml 文件
与前面的答案一样,在控制器操作上。
-或-
做类似的事情
使用以下命令创建初始值设定项
config/initializers/load_config.rb
:CONFIG_PATH="#{Rails.root}/config/settings.yml" APP_CONFIG = YAML.load_file(CONFIG_PATH)[Rails.env]
使用
before_filter
或after_sign_in/sign_up
: 链接执行以下操作:before_filter:set_market_spree_zone
def set_market_spree_zone market = current_user.market #or if you only have the user country do something like: get_zone_from_country(current_user.country) #convert to abrevation united_stated to us or vice-versa as needed @zone = APP_CONFIG['market'] #then use @zone for Spree or whatever you need to set globally #in the APP end
(这也可以在设备上after_sign_in或覆盖会话控制器的创建方法(
让我知道这是否有效。