NS Raghuwansi
NS Raghuwansi

Reputation: 1

Syntax for calling and how to write yaml file in ruby

Here is main.rb file (the driver of the project)

require_relative '../lib/logic'

Upvotes: 0

Views: 70

Answers (1)

max pleaner
max pleaner

Reputation: 26778

So first of all, how to make a YAML file? Well, there are many tutorials out there to teach you the basics of a format, but a little shortcut is to just use the .to_yaml method on a Ruby object, and look at the output:

require 'yaml'

checks_to_run = [
  "check_alphabetized_constants",
  "check_bfr_return_emp_line"
]

puts checks_to_run.to_yaml

Which prints

---
- check_alphabetized_constants
- check_bfr_return_emp_line

--- always goes on the first line, and then you have a list of strings (quotations are optional) - simple enough.

You can write this to a file like so:

File.open("checks.yaml", "w") { |f| f.write checks_to_run.to_yaml }

You can of course write or edit the YAML file by hand as needed.

Now, to read the YAML file:

checks_to_run = YAML.load(File.read("checks.yaml"))
# => ["check_alphabetized_constants", "check_bfr_return_emp_line"]

From this point, you can loop through the checks and call the methods. There are multiple ways to do this, for example you could use send:

checks_to_run.each do |check_to_run|
  check.send(check_to_run)
end

Or you could skip the metaprogramming and use something like if:

if checks_to_run.include?("check_alphabetized_constants")
  check.check_alphabetized_constants
end

# repeat for the other checks as well

Upvotes: 1

Related Questions