我正在构建一个gem,我想为它创建一个生成器,我有一个看起来像这样的代码:
module MagicId
module Generators
class ConfigGenerator < Rails::Generators::Base
source_root(File.expand_path(File.dirname(__FILE__)))
def copy_initializer
copy_file 'config.rb', 'config/initializers/magic_id.rb'
end
end
end
end
它的作用是将config.rb文件复制到rails app的config/initializers
,有没有办法让我在运行生成器时动态生成config.rb的代码?
答案 0 :(得分:2)
在生成器的guide上,列出了您可能感兴趣的5种方法。
class InitializerGenerator < Rails::Generators::Base def create_initializer_file create_file "config/initializers/initializer.rb", "# Add initialization content here" end end
这个实际上来自Thor,第二个参数是文件的内容,或者你可以给它一个块,返回值被用作内容
create_file "lib/fun_party.rb" do hostname = ask("What is the virtual hostname I should use?") "vhost.name = #{hostname}" end create_file "config/apache.conf", "your apache config"
将代码放在文件中的预定位置。 (guide)
inject_into_file 'name_of_file.rb', after: "#The code goes below this line. Don't forget the Line break at the end\n" do <<-'RUBY' puts "Hello World" RUBY end
基本上和上面一样,除了gsubs位置而不是在它之后添加一行。 (guide)
gsub_file 'name_of_file.rb', 'method.to_be_replaced', 'method.the_replacing_code'
添加到文件的开头并添加,这些都来自Thor documentation
append_to_file 'config/environments/test.rb', 'config.gem "rspec"' prepend_to_file 'config/environments/test.rb', 'config.gem "rspec"'
答案 1 :(得分:1)
我认为你正在寻找这个
宝石代码lib/generators/magic_id_generator.rb
中的module MagicId
module Generators
class ConfigGenerator < Rails::Generators::Base
source_root(File.expand_path(File.dirname(__FILE__)))
argument :name,
type: :string,
required: true,
banner: 'Argument name'
def copy_config_file
template 'magic_id.rb.erb', 'config/initializers/magic_id.rb'
end
end
end
end
宝石代码lib/generators/templates/magid_id.rb.erb
<%= "MagicId.config do |stuff|" %>
<%= " stuff.name = :#{name}" %>
<%= "end" %>
然后$ rails g magic_id:config is_magic
应该产生:
config/initializers/magic_id.rb
中的MagicId.config do |stuff|
stuff.name = :is_magic
end