Class: DanarchyJaml::Convert

Inherits:
Object
  • Object
show all
Defined in:
lib/danarchy_jaml.rb

Instance Method Summary collapse

Constructor Details

#initialize(file) ⇒ Convert

Returns a new instance of Convert.



7
8
9
10
11
12
13
14
15
16
17
# File 'lib/danarchy_jaml.rb', line 7

def initialize(file)
  if %w[json jsn].include?(file.split('.').last)
    puts "Converting JSON to YAML..."
    json_to_yaml(file)
  elsif %w[yaml yml].include?(file.split('.').last)
    puts "Converting YAML to JSON..."
    yaml_to_json(file)
  else
    abort("Unknown file extension: #{file}")
  end
end

Instance Method Details

#json_to_yaml(file) ⇒ Object



19
20
21
22
23
24
25
26
27
28
29
30
31
# File 'lib/danarchy_jaml.rb', line 19

def json_to_yaml(file)
  outfile = file.gsub(/(json|jsn)/, 'yaml')
  hash = JSON.parse(File.read(file))

  begin
    File.write(outfile, hash.to_yaml)
  rescue StandardError => e
    puts e.message
  ensure
    File.exist?(outfile)
    puts "File written: #{outfile}"
  end
end

#yaml_to_json(file) ⇒ Object



33
34
35
36
37
38
39
40
41
42
43
44
45
# File 'lib/danarchy_jaml.rb', line 33

def yaml_to_json(file)
  outfile = file.gsub(/(yaml|yml)/, 'json')
  hash = YAML.load(File.read(file))

  begin
    File.write(outfile, JSON.pretty_generate(hash))
  rescue StandardError => e
    puts e.message
  ensure
    File.exist?(outfile)
    puts "File written: #{outfile}"
  end
end