After creating a new application with the rails new command, I think that the model, controller, view file, etc. are created by inputting the command once, but there were omissions and spelling mistakes when typing the command. Or ~~ And above all, it was troublesome ~~.
In this article, I will explain how to create various MVC files at once using a batch file. (I didn't have much information when I searched, so maybe it's an evil method ...)
Create a batch folder in the lib folder and create a batch file. (File example: create_mvc.rb)
Add the setting to read the batch folder in config/application.rb.
config/application.rb
module Portfolio
class Application < Rails::Application
# Initialize configuration defaults for originally generated Rails version.
config.load_defaults 5.2
#Make the files in the lib folder readable
config.paths.add 'lib', eager_load: true
# Settings in config/environments/* take precedence over those specified here.
# Application configuration can go into files in config/initializers
# -- all .rb files in that directory are automatically loaded after loading
# the framework and any gems in your application.
end
end
In order to execute the rails command in the script, it is OK to write system "command to execute".
lib/batch/create_mvc.rb
class Batch::CreateMvc
#Batch creation of files
def self.create_file
system 'rails g model Post'
system 'rails g model PostFavorite'
system 'rails g model PostComment'
system 'rails g model TagMap'
system 'rails g model Tag'
system 'rails g model Relationship'
・ ・ ・ Below, describe the commands for the file you want to create.
end
end
The execution of the batch file itself is done by entering the command directly into the console.
Execution command: bundle exec rails runner Batch :: [batch file class name]. [Method name you want to execute] Example: bundle exec rails runner Batch :: CreateMvc.create_file
This will load the batch file and execute the commands listed in the file in order from the top. Therefore, you can execute file creation commands such as rails g command in a batch.
To be honest, there is no big difference between the man-hours for creating this batch file and the man-hours for entering the rails g command once in the console. However, I think there are merits in the following points.
--Since the execution command is prepared in advance, you can check for spelling mistakes and omissions in advance. ――The batch file once created can be reused when creating a new application in the future.
In particular, I personally think that the second merit is great. I think that rails g will always be executed in every application, so if you maintain only the file name of each command in the batch file, you will be able to create the file with less man-hours.
However, since a batch file is originally intended to write a process to be executed regularly, a batch file that is used only once per application like this time may not be very effective ...
Recommended Posts