19

I have some rails engine 'Core', and I have:

# core/app/models/core/concerns/user_helper.rb
module Core
 module UserHelper
  extend ActiveSupport::Concern
  included do
  # some methods
  end
 end
end

# core/app/models/core/user.rb
module Core
 class User < ActiveRecord::Base
  include Core::UserHelper
 end
end

however it says uninitialized constant Core::UserHelper. So it seems engine doesn't load its concerns by default, so I added it in the autoload paths

module Core
  class Engine < ::Rails::Engine
    config.autoload_paths += %W(#{Core::Engine.root}/app/models/core/concerns)
    isolate_namespace Core
  end
end

And now I end up this error: Unable to autoload constant UserHelper, expected myapp/core/app/models/core/concerns/user_helper.rb to define it

So what is wrong here? When I checked the guide http://edgeguides.rubyonrails.org/engines.html and it didn't have the concerns in concerns directory, but rather under lib/concerns and had all reference to concern using Core::Concerns::MyConcern, so is this where to put concerns in engine?

Thanks

Edit

Yury comment explained the issue, it seems that in rails engines concerns directory don't get any special treatment, and it is treated as a normal directory under models, so modules in it must be within Concerns namespace, and when including a concern, you have to include it with Concerns namesapace as well, if I understand right. I 'm surprised this is not mentioned in the docs.

2 Answers2

30

The concern must reside inside the app/models|controllers/concerns/engine_name/concern_name.rb. This will autoload the concern.

To include the concern, include EngineName::ConcernName.

Yoganand
  • 433
  • 4
  • 7
4

I had the same issue. Your mistake is that you are putting the concerns directory in the app/{models|controllers}/core directory, when it should be the other way round.

Instead of doing

app/{models/controllers}/core/concerns/user_helper.rb

change it to be

app/{models/controllers}/concerns/core/user_helper.rb

It took me a bit to figure out, because I intuitively thought it should also be under the engine_name directory.

Hope this helps.

Theo Scholiadis
  • 2,138
  • 2
  • 19
  • 30