gpt4 book ai didi

ruby-on-rails - 在 Rails 生成器中检索生成器名称

转载 作者:数据小太阳 更新时间:2023-10-29 07:33:32 25 4
gpt4 key购买 nike

我正在尝试设置一个 Rails 生成器,这是我的第一个生成器,在过去的两个小时里,我一直在做一些非常简单的事情——如何让用户输入生成器的名称。这是在应用程序中而不是 gem 中。

所以在下面的情况下 - 我如何让“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.

最佳答案

名称已定义 automatically :

First, notice that we are inheriting from Rails::Generators::NamedBase instead of Rails::Generators::Base. This means that our generator expects at least one argument, which will be the name of the initializer, and will be available in our code in the variable name.

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

关于ruby-on-rails - 在 Rails 生成器中检索生成器名称,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40941833/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com