我对 Ruby/Rails 框架相当陌生。我的 Rails 应用程序 lib/generators 中有一个简单的生成器。生成器的功能是将 templates/myfile.yml 目录中的文件之一复制到 config/myfile.yml 中。 现在我想在另一个应用程序中使用这个生成器。所以,我想把它包装成一个 gem 。我已经使用 bundler 生成了 gem,它包含以下文件结构:
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
install_generator内容如下:
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
以下是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 = ["<a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="2b46524e464a42476b4c464a424705484446" rel="noreferrer noopener nofollow">[email protected]</a>"]
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
我认为我的 lib/mygem.rb 中缺少一些内容
require "mygem/version"
module Mygem
# Your code goes here...
end
我在构建并将其推送到 rubygems.org 方面没有任何问题。
为了在我的 Rails 应用程序之一中使用它,我将其添加到 Gemfile 中并运行 bundle 安装。问题是现在当我运行 rails g mygem:install
时它会抛出一个错误:
Could not find generator mygem:install.
我做错了什么?
最佳答案
我解决了这个问题。我忘记将 Rails 添加为 gemspec 文件中的依赖项。即,我必须在 mygem.gemspec 中包含以下内容:
spec.add_development_dependency "rails", "~> RAILS_VERSION"
关于ruby-on-rails - 将 Rails Generator 作为 Ruby Gem 分发,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18537913/