如何让这个应用程序保持不变?

时间:2013-02-02 06:32:01

标签: ruby-on-rails ruby ruby-on-rails-3

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?谢谢!

1 个答案:

答案 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