Гибкое конфигурирование приложения на Ruby on Rails

(Ruby & Rails) · English (26,433 views)

В моем текущем проекте на Ruby on Rails нужно хранить конфигурацию приложения. Я нашел несколько подходов к решению этой задачи: плагин AppConfig, несколько методов, описанных на странице Wiki HowtoAddYourOwnConfigInfo, но ни один из них не выглядит “похожим на конфигурационный файл”. Мы с другом, Алексеем Ковыриным, исследовали все, и решили использовать YAML-файл. Идеальной конфигурацией, как мне кажется, является следующий файл:

1
2
3
4
5
6
7
8
9
10
11
span class="re0"> common:
 support_email: admin@myhost.com
 root_url: myhost.com
 photos_max_number: 6

production:
 email_exceptions: true

development:
 root_url: localhost:3000
 photos_max_number: 10

В этом примере можно увидеть три раздела: common используется как базовая конфигурация для всех окружений, production и development – настройки, специфичные для окружения. Возможными разделами являются production, development и testing, а также любые другие пользовательские имена окружений. Я разместил этот файл в config/config.yml и добавил следующий код в config/environment.rb:

1
2
3
4
5
6
7
require 'ostruct'
require 'yaml'

config = OpenStruct.new(YAML.load_file("#{RAILS_ROOT}/config/config.yml"))
env_config = config.send(RAILS_ENV)
config.common.update(env_config) unless env_config.nil?
::AppConfig = OpenStruct.new(config.common)

Теперь я могу использовать конструкции вида AppConfig.support_email и AppConfig.root_url. Похоже на то, что мои конфигурационные файлы соответствуют принципу DRY, насколько это возможно :-)

16 Responses to this entry

Subscribe to comments with RSS

said on 17.10.2006 at 11.53 · Permalink

Во-первых, лично мне не нравится, как выглядит

1
2
3
4
5
6
7
8
9
10
11
12
13
span class="re0"> common: &common
 support_email: admin@myhost.com
 root_url: myhost.com
 photos_max_number: 6

production:
  <<: *common
 email_exceptions: true

development:
  <<: *common
 root_url: localhost:3000
 photos_max_number: 10

Во-вторых, код все равно останется в виде

1
2
config = OpenStruct.new(YAML.load_file("#{RAILS_ROOT}/config/config.yml"))
::AppConfig = OpenStruct.new(config.send(RAILS_ENV))

Имхо, уродство конфига не оправдание программисту, который сэкономил две строчки кода.

К тому же у себя я их вынес в плагин, чтоб не мешалось под ногами и можно было юзать в разных проектах.

said on 17.10.2006 at 11.54 · Permalink

Кстати, спасибо за ссылки. Очень полезно :-)

said on 25.01.2007 at 2.05 · Permalink

Небольшая модификация кода на случай, если секция common не содержит данных или отсутсвует как таковая:

1
2
3
4
5
config = OpenStruct.new(YAML.load_file("#{RAILS_ROOT}/config/config.yml"))
env_config = config.send(RAILS_ENV)
common = config.common || {}
common.update(env_config) unless env_config.nil?
::AppConfig = OpenStruct.new(common)
said on 25.01.2007 at 7.08 · Permalink

Спасибо! В некоторых проектах может быть полезно :-)

said on 25.01.2007 at 12.31 · Permalink

Да не за что, мне уже помогло :)

said on 25.04.2007 at 4.34 · Permalink

[...] solutions have been posted for handling application level config file but this solution is by far the best. It’s simple, DRY and works. Try it. You will love [...]

Eugene @
said on 26.07.2007 at 11.29 · Permalink

Many thanks for the great idea. I’ve decided to go further and now config file is parsed with ERB, one can have another file to override the values in the main file (when you place config.yml to svn and need specific values in your working copy) and config values can not be overwritten in the application (by mistake). Please check it out.

Alex
said on 21.02.2008 at 22.36 · Permalink

This code does’t work in ‘test’ environment (Rails 2.0.2).

Problem with:

1
env_config = config.send(RAILS_ENV)

It’s strange that config.test() work, but confg.send('test') not.
I don’t know why. Can anyone explain this behaivor?

said on 29.02.2008 at 6.32 · Permalink

It works for my Rails 2.0.2 project:

1
2
3
4
5
# app-specific config
require 'ostruct'
require 'yaml'
config = OpenStruct.new(YAML.load_file("#{RAILS_ROOT}/config/chef.yml"))
::AppConfig = OpenStruct.new(config.send(RAILS_ENV))

Test:

1
2
3
  def test_test_base
    assert_not_nil AppConfig.test_base
  end

Passes. When I change it to assert_nil it fails, and I see that it was actually set.

Steve C
said on 12.07.2008 at 1.48 · Permalink

If you are getting errors when using this in your test environment you forgot to add “test:” to your .yml file

The example in this article had production and dev, but for some reason omits test

Comments are closed

Comments for this entry are closed for a while. If you have anything to say – use a contact form. Thank you for your patience.