Getting the name of the generator in the rail generator

I am trying to set up a rail generator, my first one, and in the last two hours I have been stuck in something very simple - How do I get the username for the generator. This is an app, not a gem.

So in the example below - How do I get Foo to print the generator code?

rails g block Foo

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

  puts #Foo (file name)#
end

I tried both with NamedBase and with base generators, and every method I can find.

Any help would be greatly appreciated!

#EDIT
$ 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. 
+4
source share
1 answer

name is determined 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
+3

Source: https://habr.com/ru/post/1662696/


All Articles