2013-02-19 62 views
12

我的Rails应用程序(在Heroku上运行)有一个登台和生产环境。目前,存在staging.rb和production.rb了很多东西,我不得不在每个文件中单独定义,例如:删除staging.rb和production.rb之间的重复

# Code is not reloaded between requests 
    config.cache_classes = true 

    # Full error reports are disabled and caching is turned on 
    config.consider_all_requests_local  = false 
    config.action_controller.perform_caching = true 

    # Disable Rails's static asset server (Apache or nginx will already do this) 
    config.serve_static_assets = false 

    # Compress JavaScripts and CSS 
    config.assets.compress = true 

    # Don't fallback to assets pipeline if a precompiled asset is missed 
    config.assets.compile = false 

    # Generate digests for assets URLs 
    config.assets.digest = true 

这不是DRY。有没有一种优雅的方式可以将production.rb中的设置有效地导入到staging.rb中,然后覆盖我希望为临时环境更改的设置?

回答

16

我在过去所做的是有一个文件,其中包含共享设置,然后在生产环境和临时环境文件中需要这些文件。这一直运作良好,因为它可以让你在一个地方定义常用的设置,然后在单个文件定义了独特的设置:

配置/环境/ shared_production.rb

MyApp::Application.configure do 
    # Code is not reloaded between requests 
    config.cache_classes = true 

    # Full error reports are disabled and caching is turned on 
    config.consider_all_requests_local  = false 
    config.action_controller.perform_caching = true 
end 

配置/environments/production.rb

require Rails.root.join('config/environments/shared_production') 

MyApp::Application.configure do 
    # Raise exception on mass assignment protection for Active Record models 
    config.active_record.mass_assignment_sanitizer = :logger 

    # Url to be used in mailer links 
    config.action_mailer.default_url_options = { :host => "production.com" } 
end 

配置/环境/ staging.rb

require Rails.root.join('config/environments/shared_production') 

MyApp::Application.configure do 
    # Raise exception on mass assignment protection for Active Record models 
    config.active_record.mass_assignment_sanitizer = :strict 

    # Url to be used in mailer links 
    config.action_mailer.default_url_options = { :host => "mysite-dev.com" } 
end 
+1

这正是我所期待的。 =)格拉西亚斯! – 2013-02-19 01:40:25

+1

使用ruby 1.9+你可以使用require_relative。 – codingFoo 2014-09-24 18:58:37

2

我认为这是多么好。这些是配置设置,旨在单独设置。你实际上可以定义一个函数来传递配置。在该功能上,您可以设置默认值,但我不想这样做。在项目的生命周期中,您只能在少于5个(或10个)环境下工作,因此最多只需要10个您不会一直编辑的文件。