简体   繁体   English

如何在Rails初始化程序中使用关注点?

[英]How to use a concern in a Rails initializer?

In my Ruby on Rails project I have a concern app/controllers/concerns/common.rb : 在我的Ruby on Rails项目中,我有一个担忧app/controllers/concerns/common.rb

module Common
  extend ActiveSupport::Concern

  private

  def foo
  end

end

I want to use its foo function inside config/initializers/devise.rb : 我想在config/initializers/devise.rb使用它的foo函数:

Devise.setup do |config|
  ...
  foo
  ...
end

For now I failed to somehow load common.rb inside config/initializers/devise.rb - how to do it? 现在,我无法以某种方式在config/initializers/devise.rb加载common.rb怎么做?

Currently I'm using a workaround - I define the foo function inside config/application.rb and it works, but it breaks the DRY principles. 当前,我正在使用一种解决方法-我在config/application.rb定义了foo函数,它可以工作,但它违反了DRY原则。

Theoretically you could include your concern inside the devise config: 理论上,您可以在devise配置中包含您的关注点:

Devise.setup do |config|
  include Common
  foo
  # ...
end

That way how ever you're including the method on ruby's main object / top level context. 这样,您如何在ruby的主要对象/顶级上下文中包含该方法。

Alternatively you could extend 'config' (= Devise) with your module, and call the method foo on config. 或者,您可以使用模块扩展'config'(= Devise),然后在config上调用方法foo。

Devise.setup do |config|
  config.send(:extend, Common)
  config.foo
  # ...
end

To make this work however you would need to make foo a public method, otherwise you won't be able to call it like that. 但是,要使此工作有效,您需要使foo为公共方法,否则您将无法像这样调用它。

If you're overall goal is to avoid code duplication it is hard to tell you what the best solution would be, without knowing more about what you want to achieve, eg what shared code you want to extract from your devise config. 如果您的总体目标是避免代码重复,那么就很难告诉您最佳的解决方案是什么,而又不知道要实现的目标,例如,您想从设计配置中提取哪些共享代码。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM