Class: Ehbrs::Observers::WithPersistence

Inherits:
Base show all
Defined in:
lib/ehbrs/observers/with_persistence.rb

Instance Attribute Summary collapse

Attributes inherited from Base

#blank_value, #last_check_time, #records

Instance Method Summary collapse

Methods inherited from Base

#changing_value?, #last_change_time, #last_value

Constructor Details

#initialize(path, options = {}) ⇒ WithPersistence

Returns a new instance of WithPersistence.



11
12
13
14
15
# File 'lib/ehbrs/observers/with_persistence.rb', line 11

def initialize(path, options = {})
  super(options)
  @path = path.to_pathname
  load
end

Instance Attribute Details

#pathObject (readonly)

Returns the value of attribute path.



9
10
11
# File 'lib/ehbrs/observers/with_persistence.rb', line 9

def path
  @path
end

Instance Method Details

#check(value, date = ::Time.zone.now) ⇒ Object



17
18
19
# File 'lib/ehbrs/observers/with_persistence.rb', line 17

def check(value, date = ::Time.zone.now)
  save if super(value, date)
end

#loadObject



21
22
23
24
25
26
# File 'lib/ehbrs/observers/with_persistence.rb', line 21

def load
  save unless path.exist?
  data = ::YAML.load_file(path.to_path)
  @records = data.fetch(:records).map { |h| ::OpenStruct.new(h) }
  @last_check_time = data.fetch(:last_check_time)
end

#saveObject



28
29
30
31
# File 'lib/ehbrs/observers/with_persistence.rb', line 28

def save
  path.parent.mkpath
  path.write({ records: records.map(&:to_h), last_check_time: last_check_time }.to_yaml)
end