2009-05-19 120 views
2

我创建了两个相关的Rails应用程序,并且我注意到很多非DRY工作。Rails应用程序设置

例如,@title领域中的各种控制器方法被设置做同样的事情,除了应用程序标题,如:

# SiteController (application 'Abc') 
def SiteController < ApplicationController 
    def index 
    @title = 'Abc' 
    end 
    def about 
    @title = 'about Abc' 
    end 
    def news 
    @title = 'Abc news' 
    end 
    def contact 
    @title = 'contact Abc' 
    end 
end 

和:

# SiteController (application 'Xyz') 
def SiteController < ApplicationController 
    def index 
    @title = 'Xyz' 
    end 
    def about 
    @title = 'about Xyz' 
    end 
    def news 
    @title = 'Xyz news' 
    end 
    def contact 
    @title = 'contact Xyz' 
    end 
end 

我”什么米寻找做的是有像

# SiteController 
def SiteController < ApplicationController 
    def index 
    @title = "#{ApplicationTitle}' 
    end 
    def about 
    @title = "about #{ApplicationTitle}" 
    end 
    def news 
    @title = "#{ApplicationTitle} news" 
    end 
    def contact 
    @title = "contact #{ApplicationTitle}" 
    end 
end 

我想图的东西是:应该在哪里定义不变的应用程序设置。它在config/* rb文件中吗?它是否在.yaml文件之一中?

在此先感谢

回答

4

对于一些基本的应用程序名称,再加上很多其他的常量,我宣布在environment.rb中的常量

常量应该使用Ruby的常量功能,而不是与访问者为markjeee类变量建议。

Ref:pg 330,“Programming Ruby”(Pickaxe)2nd Ed。

拉里

+0

谢谢。我打算它是一个常数,但不知道environment.rb(或其他地方,对于这个问题)。 – dcw 2009-05-19 06:35:11

2

您可以将它们放在app/controllers/application.rb文件中。

例如:

class ApplicationController < ActionController::Base 
    attr_accessor :application_title 

    def initialize 
    self.application_title = "Some application title" 
    end 
end 

然后在你的控制器,你可以访问标题:

class SomeController < ApplicationController 
    def some_action 
    @title = "some text with #{application_title}" 
    end 
end 

您也可以声明应用程序标题作为辅助方法,这样就可以在访问你的意见。

你也可以使用全局常量,并把它放在你的config/environment.rb文件中。把它放在environment.rb中的最下部,配置外块,像这样:

APPLICATION_TITLE = "Some title here" 

,只要你在你的控制器设置@title实例变量然后使用常量。请注意,它必须全部大写,所以Ruby会将其解释为全局常量。

+0

感谢常数。我知道ApplicationController的一个,但不知道有关environment.rb – dcw 2009-05-19 06:34:05

1

定义在config/environment.rb文件中