[RUBY] Insert data into DB using Yaml file

1) Background </ font>

Yaml files are often used for environment settings, but yaml files are more convenient than csv files when you want to register default data in the database in advance in your application.

If you are creating a portfolio like me, you need to set the sample data without being aware of it. I think that yaml appears in the scene where it is not written in the source, csv is not readable, and so on.

2) Environment </ font>

item Contents
OS.Catalina v10.15.4
Ruby v2.5.1
Ruby On Rails v5.2.4.3

3) Contents </ font>

** Correspondence 1) Creation of yaml file ** You can make detailed settings. I will omit it here. See the data image below.

default_user.yml


- id: 1,
  password: 111111
  name: 'Unregistered user'
  email: '[email protected]'

** Correspondence 2) Create a service that reads and outputs yaml ** It's a little long, but I created the service as follows. You need to extend it with require ('yaml').

user_insert_service.rb


 1 class MakeDefaultDataService
 2   require('yaml')
(abridgement)

 3   def insert_user_data
 4     begin
 5       default_user = User.new
 6       insert_data = YAML.load_file('app/lib/yaml/default_user.yml')
 7       insert_data.each do | data |
 8         default_user.id = data["id"]
 9         default_user.password = data["password"]
10         default_user.name = data["name"]
11       end
12       default_user.save
13     rescue
14       p "(User) Data registration failed."
15     end
16   end

When this method is executed, the data is set in the "insert_data" variable on the 4th line as follows.

[{"id"=>1, "password"=>111111, "name"=>"Unregistered user", "email"=>"[email protected]"}]

All you have to do is process the data as appropriate and set it in the database. It's convenient. that's all.