-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathRubyRubyYaml.rb
More file actions
51 lines (44 loc) · 1023 Bytes
/
RubyRubyYaml.rb
File metadata and controls
51 lines (44 loc) · 1023 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
require 'yaml'
def sort_second_level(data)
data.transform_values do |value|
if value.is_a?(Hash)
value.sort.to_h
else
value
end
end
end
while true
puts "Please enter the full file path."
path = gets.chomp
if path.empty?
puts "You need to input something!"
next
end
begin
# Read the YAML file
content = File.read(path)
data = YAML.load(content)
# Sort the data
sorted = sort_second_level(data)
# Write back to the file
yaml_options = {
indentation: 2,
line_width: -1,
canonical: false
}
File.open(path, 'w') do |file|
file.write(sorted.to_yaml(yaml_options))
end
puts "YAML file successfully sorted and saved!"
break
rescue Psych::SyntaxError => e
puts "Invalid YAML: #{e.message}"
puts "Please try again!"
rescue Errno::ENOENT
puts "File not found. Please check the path and try again."
rescue => e
puts "An error occurred: #{e.message}"
puts "Please try again!"
end
end