Module: JTask::Convert

Defined in:
lib/jtask/convert.rb

Class Method Summary collapse

Class Method Details

.json_file(filename, dir = nil) ⇒ Object



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
# File 'lib/jtask/convert.rb', line 17

def self.json_file(filename, dir=nil)
  # Set the directory
  dir = JTask::Helpers.set_directory(dir)

  # Parse the file
  original_file = File.read(File.join(dir, filename))
  objects = JSON.parse(original_file)

  output = Hash.new
  objects.each_with_index do |(k, v), n|
    output["#{n + 1}"] = {k => v}
  end

  # Rename the old version
  begin
    JTask.rename(filename, "#{filename}.old", dir)
  rescue
    raise RuntimeError, "[JTask] Failed to backup original file, conversion aborted."
  end

  # Write the new version
  begin
    JTask.save(filename, output, dir)
  rescue
    raise RuntimeError, "[JTask] Failed to save the converted file. The original can be found at '#{dir}#{filename}.old'"
  end

  return true
end