可能听起来像一个简单的问题,但我被困了.
我创建了一个基本上包含生成器的gem.
它包含以下结构:
lib - generators - my_generator my_generator_generator.rb (see below) - templates my_template_files... - my_generator.rb (empty file) test -test files GemFile etc..
但是,当我将宝石添加到我的宝石文件并运行rails g时,它没有列出.有没有额外的配置,我需要做?
我的发电机大概看起来像这样
class MyGeneratorGenerator < Rails::Generators::NamedBase source_root File.expand_path('../templates',__FILE__) generator code.... end
奇怪的是,它适用于Cygwin,但不在Ubuntu中
解决方法
我花了一点时间弄清楚,但是遇到了同样的问题.这是我如何修复它.
树结构如下所示:
lib - generators - gemname install_generator.rb - templates (template files)
这是install_generator.rb的代码
#lib/generators/gemname/install_generator.rb require 'rails/generators' module Gemname class InstallGenerator < Rails::Generators::Base desc "Some description of my generator here" # Commandline options can be defined here using Thor-like options: class_option :my_opt,:type => :boolean,:default => false,:desc => "My Option" # I can later access that option using: # options[:my_opt] def self.source_root @source_root ||= File.join(File.dirname(__FILE__),'templates') end # Generator Code. Remember this is just suped-up Thor so methods are executed in order end end
当我跑
导轨g
我懂了:
Gemname gemname:install
您可能需要设置的其他一些事项:
#lib/gemname.rb module Gemname require 'gemname/engine' if defined?(Rails) # any additional requires end
和
#/lib/gemname/engine.rb require 'rails' module Gemname class Engine < Rails::Engine end end
我发现的一些很好的参考是:
> http://textmate.rubyforge.org/thor/Thor.html(看看模块,特别是Thor :: Actions)
> http://api.rubyonrails.org/classes/Rails/Generators/Base.html
> http://api.rubyonrails.org/classes/Rails/Generators/Actions.html
> https://github.com/wycats/thor/blob/master/README.md
> http://www.themodestrubyist.com/2010/03/16/rails-3-plugins—part-3—rake-tasks-generators-initializers-oh-my/