4
votes

I have a rails project which uses mongo db, and I wrote an mountable engine named 'report_service'.

I used it like this in main rails project:

gem 'report_service', :git => '[email protected]:report_service.git', :branch => :master, :require => false

I don't want this gem loaded when the rails project is initialized, so I added the :require => false option.

But in my rails console, after I execute require 'report_service', I cannot find models in this gem.

[1] pry(main)> ReportService
=> ReportService
[2] pry(main)> ReportService::Engine
NameError: uninitialized constant ReportService::Engine
from (pry):2:in `<main>'
[3] pry(main)> require 'report_service'
=> true
[4] pry(main)> ReportService::Engine
=> ReportService::Engine
[5] pry(main)> ReportService::RsExam
NameError: uninitialized constant ReportService::RsExam
from (pry):5:in `<main>'

Here is my report_service gem directory and code:

report_service/lib/report_service.rb

require "active_record/railtie"
require "report_service/engine"
module ReportService
end

report_service/lib/report_service/engine.rb

module ReportService
  class Engine < ::Rails::Engine
   isolate_namespace ReportService
  end
end

report_service/app/models/report_service/rs_exam.rb

module ReportService
  class RsExam < ActiveRecord::Base
  end
end
1
have you tried loading your gem at initialisation? and then trying? - SD1990
it's ok if I remove ':required => false', but this is not I want - Richie Min

1 Answers

4
votes

Scrap that update. Just add require "report_service/rs_exam" into your report_service.rb.

require "active_record/railtie"
require "report_service/engine"
require "report_service/rs_exam"
module ReportService
end

My reasoning is that what is happening is that your loading the model report_service/rs_exam which is why you will get an uninitialized constant error. Because looking at the console output.

Loading the gem works fine.

require 'report_service'
=> true

The ReportService::Engine is loaded fine.

[4] pry(main)> ReportService::Engine
=> ReportService::Engine

But then when you try to load the rs_exam

[5] pry(main)> ReportService::RsExam
NameError: uninitialized constant ReportService::RsExam
from (pry):5:in `<main>'

you get your uninitialized constant error because it has not been required. Try that and let me know how you get on