2

I am fairly new to Ruby/Rails framework. I have a simple generator in my Rails application at lib/generators. The generator's function is to copy one of the files in the templates/myfile.yml directory into config/myfile.yml. Now I would like to use this generator in another app. So, I would like to package this as a gem. I have generated gem using bundler and it contains the following file structure:

lib/
  mygem/
    version.rb
  generators/
    mygem/
      install/
        templates/
          somefile.yml
        install_generator.rb
        USAGE
  mygem.rb
mygem.gemspec
Gemfile
Gemfile.lock
LICENSE.txt
Rakefile
README.md

Content of install_generator is as follows:

require 'rails/generators'
module Mygem
    module Generators
        class InstallGenerator < Rails::Generators::Base
            source_root File.expand_path('../templates', __FILE__)

            def generate_something
                copy_file "something.yml", "#{Rails.root}/config/something.yml"
            end

        end
    end
end

Following is the content of mygem.gemspec:

# coding: utf-8
lib = File.expand_path('../lib', __FILE__)
$LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
require 'mygem/version'

Gem::Specification.new do |spec|
  spec.name          = "mygem"
  spec.version       = MyGem::VERSION
  spec.authors       = ["Swaroop SM"]
  spec.email         = ["myemail@gmail.com"]
  spec.description   = %q{Something}
  spec.summary       = %q{Something}
  spec.homepage      = ""
  spec.license       = "MIT"

  spec.files        = `git ls-files`.split($/)
  spec.executables   = spec.files.grep(%r{^bin/}) { |f| File.basename(f) }
  spec.test_files    = spec.files.grep(%r{^(test|spec|features)/})
  spec.require_paths = ["lib"]

  spec.add_development_dependency "bundler", "~> 1.3"
  spec.add_development_dependency "rake"
end

I reckon there is something missing in my lib/mygem.rb

require "mygem/version"

module Mygem
  # Your code goes here...
end

I have no problem in building and pushing it to rubygems.org.

Inorder to use this in one of my rails app's, I added this to the Gemfile and run bundle install. The problem is now when I run rails g mygem:install it throws an error that says:

Could not find generator mygem:install.

What am I doing wrong?

swaroopsm
  • 1,389
  • 4
  • 18
  • 34

1 Answers1

2

I solved the issue. I had forgotten to add rails as a dependency in my gemspec file. i.e., I had to include the following in mygem.gemspec:

spec.add_development_dependency "rails", "~> RAILS_VERSION"
swaroopsm
  • 1,389
  • 4
  • 18
  • 34