0

导轨: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?谢谢!

4

1 回答 1

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
于 2013-02-02T14:07:41.263 回答