Rails:3.2.11
我在lib
中有此模块,application.rb
中需要此模块。我想在整个应用中提供常量FORBIDDEN_USERNAMES
。常量是从路由生成的值数组。我不能把它作为初始化器,因为尚未加载路由。
我在下面的内容不起作用,因为FORBIDDEN_USERNAMES
返回一个空数组。
# in lib
module ForbiddenUsernames
def self.names
Rails.application.reload_routes!
all_routes = Rails.application.routes.routes
all_names = Array.new
all_routes.each do |route|
# populate all_names array
end
all_names.uniq
end
end
FORBIDDEN_USERNAMES = ForbiddenUsernames.names
# when ForbiddenUsernames.names is called by itself, it does not return [] or nil
在整个应用程序中,如何制作它以便我可以使用FORBIDDEN_USERNAMES
?谢谢!
答案 0 :(得分:1)
我不明白你为什么要这个常数。在我看来,你可以使用可记忆的行为。
# Wherever in your controller. Add helper_method if you need in the view (but would seem wrong)
def forbidden_usernames
@forbidden_usernames ||= ForbiddenUsernames.names
end
helper_method :forbidden_usernames
如果@forbidden_usernames为nil,将调用ForbiddenUsernames.names,因此只发生一次。
# app/models/user.rb
def forbidden_usernames
@forbidden_usernames ||= ForbiddenUsernames.names
end
def validate_not_forbidden
!forbidden_usernames.include?(self.name)
end
如果您需要在多个模型中使用此功能,请使用模块。您还可以在模块中使用forbidden_usernames memoized方法。
module ForbiddenUsernames
def self.names
@forbidden_names ||= self.populates_all_names
end
protected
def populate_all_names
Rails.application.reload_routes!
all_routes = Rails.application.routes.routes
all_names = Array.new
all_routes.each do |route|
# populate all_names array
end
all_names.uniq
end
end