宝石中的Rails 3生成器 [英] Rails 3 generators in gem
问题描述
可能听起来像一个简单的问题,但我很难过.
Might sound like a simple question, but I'm stumped.
我创建了一个本质上包含生成器的 gem.
I've created a gem that essentially contains a generator.
它包含以下结构:
lib
- generators
- my_generator
my_generator_generator.rb (see below)
- templates
my_template_files...
- my_generator.rb (empty file)
test
-test files
GemFile
etc..
但是,当我将此 Gem 添加到我的 gem 文件并运行 rails g 时,它没有列出.我需要做任何额外的配置吗?
However when I add this Gem to my gem file and run rails g, it's not listed. Is there any additional config that I need to do?
我的生成器大致是这样的……
My generator roughly looks like this...
class MyGeneratorGenerator < Rails::Generators::NamedBase
source_root File.expand_path('../templates', __FILE__)
generator code....
end
奇怪的是,它在 Cygwin 中有效,但在 Ubuntu 中无效...
The strange thing is, it works in Cygwin, but not in Ubuntu...
推荐答案
我花了一点时间才弄清楚,但我遇到了同样的问题.这是我修复它的方法.
This took a little bit for me to figure out, but I've run into the same problem. Here is how I fixed it.
树形结构如下:
lib
- generators
- gemname
install_generator.rb
- templates
(template files)
这是 install_generator.rb 的代码
Here's the code for 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
您可能需要设置的其他一些东西:
Some other things you may need to setup:
#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
我在这方面找到了一些很好的参考资料:
Some good references I've found on this are:
- 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/李>
- http://textmate.rubyforge.org/thor/Thor.html (take a look at the modules, especially 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/
这篇关于宝石中的Rails 3生成器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!