Search code examples
ruby-on-railsrubygemsrails-enginesgemfile

Why does my Rails engine need me to require it (unlike a typical gem) even if it's in the Gemfile and has require_paths configured?


I've written a Rails engine called annotator-store. It requires an explicit require 'annotator_store' in the /config/application.rb in the main app (even if it's in the Gemfile). This baffles me because I've written a gem before that doesn't need this to be done.

Is this behaviour by Rails engines by design or have I missed out something?

Here's my gemspec file:

$:.push File.expand_path('../lib', __FILE__)
require 'annotator_store/version'

Gem::Specification.new do |spec|
  spec.name           = 'annotator-store'
  spec.version        = AnnotatorStore::VERSION
  spec.date           = Time.new.getutc.strftime('%Y-%m-%d')
  spec.authors        = ["Job King'ori Maina"]
  spec.email          = ['[email protected]']
  spec.homepage       = 'http://itsmrwave.github.io/annotator-store'
  spec.summary        = 'Rails engine to implement a Ruby backend store implementation for Annotator.'
  spec.description    = 'Rails engine to implement a Ruby backend store implementation for Annotator, an open-source JavaScript library to easily add annotation functionality to any webpage.'
  spec.license        = 'MIT'

  spec.files          = Dir['{app,config,db,lib}/**/*', 'CHANGELOG.md', 'CONTRIBUTING.md', 'LICENSE.md', 'Rakefile', 'README.md']
  spec.require_paths  = ['lib']

  spec.required_ruby_version = '>= 1.9.3'

  # Database dependencies
  spec.add_development_dependency 'mysql2'
  spec.add_development_dependency 'pg'

  # Development dependencies
  spec.add_development_dependency 'appraisal'
  spec.add_development_dependency 'database_cleaner'
  spec.add_development_dependency 'factory_girl_rails'
  spec.add_development_dependency 'faker'
  spec.add_development_dependency 'json-schema'
  spec.add_development_dependency 'rspec-rails'

  # Runtime dependencies
  spec.add_runtime_dependency 'jbuilder'
  spec.add_runtime_dependency 'rails', '>= 4.0'
end

You can see I've added the lib folder to the require_paths. As per the rubygems.org gemspec documentation ... there's a detailed write up on what require_paths=(val) does and that is the ...

Paths in the gem to add to $LOAD_PATH when this gem is activated.

I've set up everything in the lib folder properly such that when you require 'annotator_store' everything works great.

What I'm I missing?


Solution

  • I suspect this is a '-' vs. '_' problem. In Rails gem names '-' implies subdirectories, so the natural include for your engine would be 'lib/annotator.rb' and 'lib/annotator/store.rb', not 'lib/annotator_store.rb'. So the file you expect to be required, is not.

    To confirm this you can change the name of your engine, or change the file structure under 'lib'.