Class: JSONORM::DB

Inherits:
Object
  • Object
show all
Defined in:
lib/json-orm/db.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(file_path, log_file) ⇒ DB



10
11
12
13
14
15
# File 'lib/json-orm/db.rb', line 10

def initialize(file_path, log_file)
  @file_path = file_path
  @backup_path = "#{file_path}.backup"
  @logger = Logger.new(log_file)
  initialize_file unless File.exist?(file_path)
end

Instance Attribute Details

#backup_pathObject (readonly)

Returns the value of attribute backup_path.



8
9
10
# File 'lib/json-orm/db.rb', line 8

def backup_path
  @backup_path
end

#file_pathObject (readonly)

Returns the value of attribute file_path.



8
9
10
# File 'lib/json-orm/db.rb', line 8

def file_path
  @file_path
end

#loggerObject (readonly)

Returns the value of attribute logger.



8
9
10
# File 'lib/json-orm/db.rb', line 8

def logger
  @logger
end

Instance Method Details

#readObject



17
18
19
20
21
22
23
# File 'lib/json-orm/db.rb', line 17

def read
  with_lock do
    JSON.parse(File.read(file_path), symbolize_names: true)
  rescue JSON::ParserError
    raise "Error parsing JSON data in #{file_path}"
  end
end

#write(data) ⇒ Object



25
26
27
28
29
30
31
32
33
34
35
# File 'lib/json-orm/db.rb', line 25

def write(data)
  with_lock do
    create_backup
    File.open(file_path, 'w') { |f| f.write(JSON.pretty_generate(data)) }
    logger.info('Data written successfully')
  rescue IOError => e
    restore_backup
    logger.error("Error writing to file: #{e.message}")
    raise "Error writing to file: #{e.message}"
  end
end