我正在尝试设置一个rails生成器,这是我的第一个生成器,在过去的两个小时里,我一直被困在一些非常简单的东西上--如何让用户输入生成器的名称。这是一个应用程序,而不是宝石。
那么,在下面的例子中--我如何在生成器代码上打印“Foo”呢?
rails g block Foo
class BlockGenerator < Rails::Generators::NamedBase
source_root File.expand_path('../templates', __FILE__)
puts #Foo (file name)#
end我已经尝试了NamedBase和基本生成器以及我能找到的每一种方法。
任何帮助都将不胜感激!
编辑
$ rails g block Foo
class BlockGenerator < Rails::Generators::NamedBase
source_root File.expand_path('../templates', __FILE__)
argument :generator_name, type: :string
puts #Foo (file name)#
end
#result
block
No value provided for required arguments 'generator_name'
$ rails generate block :generator_name => testing
#result
is empty, nothing is printed to the console. 发布于 2016-12-02 22:46:55
名称被定义为自动:
首先,请注意,我们从Rails继承的是:生成器::NamedBase,而不是Rails::Generators::Base。这意味着我们的生成器至少需要一个参数,这将是初始化程序的名称,并且在我们的代码中可以在变量名中使用。
class BlockGenerator < Rails::Generators::NamedBase
source_root File.expand_path('../templates', __FILE__)
def display_name
puts name
end
end在此采取行动:
rails g block Foo
#=> Foo如果需要另一个参数:
class BlockGenerator < Rails::Generators::NamedBase
source_root File.expand_path('../templates', __FILE__)
argument :bar, type: :string, default: "Bar"
def display_name
puts name
puts bar
end
end它的产出如下:
rails g block Foo
#Foo
#Bar
rails g block Foo Baz
#Foo
#Baz请注意,如果在类定义中但在方法之外使用name变量,则将定义它,但使用BlockGenerator:
class BlockGenerator < Rails::Generators::NamedBase
source_root File.expand_path('../templates', __FILE__)
argument :bar, type: :string, default: "Bar"
puts name
def display_name
puts name
puts bar
end
end
rails g block Foo Baz
# BlockGenerator
# Foo
# Bazhttps://stackoverflow.com/questions/40941833
复制相似问题