【问题标题】:How to make this an app constant?如何使它成为一个应用程序常量?
【发布时间】:2013-02-02 06:32:00
【问题描述】:

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

【问题讨论】:

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


【解决方案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

【讨论】:

  • 很好的建议。但是,我实际上需要在模型中使用它来帮助进行自定义验证。
猜你喜欢
  • 2010-11-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-04-19
  • 2018-06-12
  • 1970-01-01
  • 1970-01-01
  • 2019-08-24
相关资源
最近更新 更多