Class: JSONORM::DB
- Inherits:
-
Object
- Object
- JSONORM::DB
- Defined in:
- lib/json-orm/db.rb
Instance Attribute Summary collapse
-
#backup_path ⇒ Object
readonly
Returns the value of attribute backup_path.
-
#file_path ⇒ Object
readonly
Returns the value of attribute file_path.
-
#logger ⇒ Object
readonly
Returns the value of attribute logger.
Instance Method Summary collapse
-
#initialize(file_path, log_file) ⇒ DB
constructor
A new instance of DB.
- #read ⇒ Object
- #write(data) ⇒ Object
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_path ⇒ Object (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_path ⇒ Object (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 |
#logger ⇒ Object (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
#read ⇒ Object
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 |