Module: RightScale::JsonUtilities

Defined in:
lib/instance/json_utilities.rb

Overview

collection of Json utilities

Class Method Summary collapse

Class Method Details

.merge_json(path, contents) ⇒ Object

Merges any existing JSON file with given contents or else writes a new JSON file while file is locked.

Parameters

path(String)

Path to file being written

contents(Object|String)

Object to be serialized into JSON or JSON string

Block

custom merge callback which takes (left_data, right_data) where left represents current the disk image.

Return

true

Always return true



80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
# File 'lib/instance/json_utilities.rb', line 80

def self.merge_json(path, contents)
  contents = JSON.load(contents) if contents.is_a?(String)
  dir = File.dirname(path)
  FileUtils.mkdir_p(dir) unless File.directory?(dir)
  File.open(path, 'a+') do |f|
    f.flock(File::LOCK_EX)
    if File.size(path) > 0
      begin
        previous_contents = JSON.load(f)
        yield(previous_contents, contents)
      rescue JSONError
        # ignored
      end
      f.seek(0)
      f.truncate(0)
    end
    f.write(contents.to_json)
  end
  true
end

.read_json(path) ⇒ Object

Load JSON from given file

Parameters

path(String)

Path to JSON file

Return

json(String)

Resulting JSON string

Raise

Errno::ENOENT

Invalid path

JSON Exception

Invalid JSON content



40
41
42
43
44
45
# File 'lib/instance/json_utilities.rb', line 40

def self.read_json(path)
  File.open(path, "r") do |f|
    f.flock(File::LOCK_EX)
    return JSON.load(f)
  end
end

.write_json(path, contents) ⇒ Object

Serialize object to JSON and write result to file, override existing file if any. Note: Do not serialize object if it’s a string, allows passing raw JSON.

Parameters

path(String)

Path to file being written

contents(Object|String)

Object to be serialized into JSON or JSON string

Return

true

Always return true



56
57
58
59
60
61
62
63
64
65
# File 'lib/instance/json_utilities.rb', line 56

def self.write_json(path, contents)
  contents = contents.to_json unless contents.is_a?(String)
  dir = File.dirname(path)
  FileUtils.mkdir_p(dir) unless File.directory?(dir)
  File.open(path, 'w') do |f|
    f.flock(File::LOCK_EX)
    f.write(contents)
  end
  true
end