【问题标题】:Retrieving generator name in a rails generator在 Rails 生成器中检索生成器名称
【发布时间】:2016-12-02 22:29:40
【问题描述】:

我正在尝试设置一个 rails 生成器,这是我的第一个,在过去的两个小时里,我一直被困在一个非常简单的事情上 - 如何让用户输入生成器的名称。这是在应用程序中,而不是宝石。

那么在下面的情况下 - 我如何让 'Foo' 在生成器代码上打印?

rails g block Foo

class BlockGenerator < Rails::Generators::NamedBase
  source_root File.expand_path('../templates', __FILE__)

  puts #Foo (file name)#
end

我已经尝试过 NamedBase 和 base 生成器以及我能找到的所有方法。

任何帮助将不胜感激!

# 编辑
$ 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. 

【问题讨论】:

  • 您应该能够指定将映射到用户输入的参数。您可以在source_root 行之后插入它,如下所示:argument :generator_name, type: :string。然后它将在您的生成器中以generator_name 的形式提供。希望对您有所帮助!
  • 感谢您的回复。我已经修改了您对 NamedBase 和 base 的建议,并为参数提供了一个键,但每次它只响应生成器名称作为值。在这种情况下,“阻止”。我已经编辑了问题以进行演示。再次感谢您的意见

标签: ruby-on-rails ruby


【解决方案1】:

名称定义为automatically

首先,请注意我们继承自 Rails::Generators::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
# Baz

【讨论】:

  • 非常感谢您的详细回答。但是,当我尝试此操作时,它会返回 ClassName。所以在这种情况下 BlockGenerator
  • name 变量应该在方法中使用。我将添加一个示例。
  • Ahhhhhh- 当然,因为它会触发所有方法。非常感谢埃里克!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-04-01
  • 2016-01-09
  • 2016-12-05
  • 2023-03-30
  • 2011-12-01
  • 2013-01-19
相关资源
最近更新 更多