2009-05-19 14 views
2

私は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ファイルの1つにありますか?

ありがとうございます。

答えて

4

アプリ名などの基本的な、プラス他の定数の多くのように、何かのために、私はenvironment.rbにで定数を宣言

定数は、Rubyの定数は、アクセサを持つクラス変数ではなく、機能を使用する必要があります。

参考:pg 330「プログラミングRuby」(Pickaxe)第2版ラリー

+0

ありがとうございました。私はそれが一定であることを意図していますが、environment.rb(またはその他の点ではその点についてはっきりしません)については不明でした。 – dcw

2

これらをapp/controllers/application.rbファイルに入れることができます。例えば

:それはでアクセスすることができるように、また、ヘルパーメソッドとしてアプリケーションのタイトルを宣言することができ

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

class ApplicationController < ActionController::Base 
    attr_accessor :application_title 

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

は、その後、あなたのコントローラで、あなたは、表題にアクセスすることができますあなたの意見

グローバル定数を使用してconfig/environment.rbファイルに入れることもできます。

APPLICATION_TITLE = "Some title here" 

あなたのコントローラで@titleインスタンス変数を設定したときにその後の定数を使用します。このように、構成ブロックの外に、environment.rbにの最も下の部分でそれを入れてください。これはすべて大文字でなければならないので、Rubyはそれをグローバル定数として解釈します。 markjeeeが提案されているよう

+0

おかげで定数を定義します。私はApplicationControllerについて知っていましたが、environment.rbについてはわかりませんでした – dcw

1

は、設定/ environment.rbにファイル

関連する問題