2011-06-01 43 views
1

我有一個應用程序,用戶可以設置一個帳戶,該帳戶具有與之相關聯的公共URL,例如, http://myapplication.com/user_directory如何從模型中訪問應用程序常量?

爲了確保用戶不能選擇我想要保留的目錄(home,help,settings等),我有一個存儲在配置文件中並通過environment.rb加載的目錄。

的environment.rb

# Load the rails application 
require File.expand_path('../application', __FILE__) 

# Initialize the rails application 
MyApplication::Application.initialize! 

APP_CONFIG = YAML.load_file("#{Rails.root.to_s}/config/config.yml")[Rails.env] 
RESERVED_DIRECTORIES = YAML.load_file("#{Rails.root.to_s}/config/reserved_directories.yml") 

這工作得很好,我可以訪問視圖RESERVED_DIRECTORIES陣列,但是我不能從用戶模式訪問它。

用戶模式

class User < ActiveRecord::Base 

    validates_exclusion_of :user_url_dir, :in => RESERVED_DIRECTORIES 

end 

問題

uninitialized constant User::RESERVED_DIRECTORIES (NameError) 

顯然存在發生一個範圍問題,但我不知道正確的語法是從訪問RESERVED_DIRECTORIES陣列什麼這個模型。

回答

1

Urgh,我才意識到爲什麼這是行不通的。我在應用程序初始化後聲明瞭常量。

不工作

# Load the rails application 
require File.expand_path('../application', __FILE__) 

# Initialize the rails application 
MyApplication::Application.initialize! 

APP_CONFIG = YAML.load_file("#{Rails.root.to_s}/config/config.yml")[Rails.env] 
RESERVED_DIRECTORIES = YAML.load_file("#{Rails.root.to_s}/config/reserved_directories.yml") 

不工作

# Load the rails application 
require File.expand_path('../application', __FILE__) 

APP_CONFIG = YAML.load_file("#{Rails.root.to_s}/config/config.yml")[Rails.env] 
RESERVED_DIRECTORIES = YAML.load_file("# 

# Initialize the rails application 
MyApplication::Application.initialize! 
{Rails.root.to_s}/config/reserved_directories.yml") 
0

你可能會考慮移動RESERVED_DIRECTORIES到用戶模型本身,它爲您提供了一種自動命名空間,並且應該在你的代碼和規範工作

我也會考慮直接在代碼中定義保留目錄,而不是在一個yaml文件,假設你沒有500個文件,因爲這是一個常量,我不相信它在初始加載後會與文件同步。

class User 
    RESERVED_DIRECTORIES = ['app','private','admin'] 
end 

...打電話與

validates_exclusion_of :user_url_dir, :in => User::RESERVED_DIRECTORIES 
+0

謝謝。不幸的是,這些目錄有很多(〜100),我也遵循一種保持config目錄中所有app常量的模式。我只是不知道如何訪問它們:S – 2011-06-01 13:59:47

+0

將它們包裝在application.rb中的類中? AppConstants 2011-06-01 14:24:46

+0

只是想出了它(見我的答案)。令人沮喪的顯而易見! – 2011-06-01 15:11:49

0

一種方法是把這樣的常量在config/application.rb文件,例如:

module MyApplication 
    class Application < Rails::Application 
    RESERVED_DIRECTORIES = YAML.load_file("#{Rails.root.to_s}/config/reserved_directories.yml") 
    ... 
    end 
end 

通過這種方式,您的常數可以限制在您的應用程序中,並且可以像這樣(從任何地方)訪問:

MyApplication::Application::RESERVED_DIRECTORIES 
相關問題