Class: Mushbomb

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

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(file_path) ⇒ Mushbomb

Returns a new instance of Mushbomb.

Raises:



8
9
10
11
12
# File 'lib/mushbomb.rb', line 8

def initialize(file_path)
  raise NoInputFileError if file_path.nil?
  raise InvalidInputFileError if File.extname(file_path) != ".json"
  @file_path   = file_path
end

Instance Attribute Details

#file_pathObject

Returns the value of attribute file_path.



6
7
8
# File 'lib/mushbomb.rb', line 6

def file_path
  @file_path
end

#parsed_fileObject

Returns the value of attribute parsed_file.



6
7
8
# File 'lib/mushbomb.rb', line 6

def parsed_file
  @parsed_file
end

Instance Method Details

#delete(key = nil) ⇒ Object



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

def delete(key=nil)
  if key.nil?
    file = File.open(file_path, 'w+')
    file.write({}.to_json)
  else
    raise NoKeyFoundError unless parsed_file.has_key?(key)
    old_file_data = parsed_file
    file = File.open(file_path, 'w+')
    old_file_data.delete(key)
    file.write(old_file_data.to_json)
  end
  file.close
end

#get(key = nil) ⇒ Object

Raises:



18
19
20
21
22
# File 'lib/mushbomb.rb', line 18

def get(key=nil)
  return parsed_file if key.nil?
  raise NoKeyFoundError unless parsed_file.has_key?(key)
  parsed_file[key]
end

#set(key, value = nil) ⇒ Object

Raises:



24
25
26
27
28
29
30
# File 'lib/mushbomb.rb', line 24

def set(key, value=nil)
  raise InvalidInputError if key.nil?
  old_file_data = parsed_file
  file = File.open(file_path, 'w+')
  file.write(old_file_data.merge!({key => value}).to_json)
  file.close   
end