开发者

How to use YAML in a rails way?

I am using YAML for configurations in my application. I am using configatron for general configuration. However i have private config values (account_id and password).

I could create a model in database or create a new row in my Setting model. However i prefer to maintain the information on yml

i create my.yml in config and then read on controller

yaml_config = YAML::load(ERB.new(IO.read(File.join(RAILS_ROOT, 'config', 'my.yml'))).result)[RAILS_ENV]

So i want to use my.yml file like configuratron gem does.

i.e I actually load YAML in line and 开发者_如何学JAVAI want config my.field_information.

if I express bad excuse me

Thanks in advance


I am not sure if I understood you correctly, but you want to be able to access your config with attributes?

Then you can do something like this:

class My
    def initialize
        @config = YAML::load(ERB.new(IO.read( 
                  File.join(RAILS_ROOT, 'config', 'my.yml'))).result)[RAILS_ENV]
    end

    def method_missing(name, *args, &block)
        @config[name.to_s]
    end
end

this will allow you to access the top level fields as attributes.

for instance if your my.yml file looks like

development:
    user: Me
    password: Mine

Then you can access it with

my_config = My.new
my_config.user
my_config.password    

Of course, this is just a crude example. You should add a lot of checks and error handling in case some attributes are missing in the file etc.


I just wrote something relevant in the last 5 minutes (includes checks if yml is missing / invalid):

mg_yml = YAML::load(File.open("#{RAILS_ROOT}/config/yyy.yml"))
if mg_yml
  mg_yml_env = mg_yml.with_indifferent_access[RAILS_ENV]
  if mg_yml_env
    if mg_yml_env.with_indifferent_access[:password].blank?
      flash[:error] = "<em>config/yyy.yml</em> missing password (blank / missing) for current environment.  You cannot access yyy until you set the password for this environment."
    else
      @password_from_yml = mg_yml_env.with_indifferent_access[:password]
    end
  else
    flash[:error] = "<em>config/yyy.yml</em> missing password for current environment '#{RAILS_ENV}'.  You cannot access yyy until you configure this file for this environment."
  end
else
  flash[:error] = "<em>config/yyy.yml</em> missing.  You cannot access yyy until you configure this file."
end

For yyy.yml in your /config directory:

development:
  password: my_dev_pass
test:
  password: my_test_pass
production:
  password: my_production_pass
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜