Class: ConfigFilesApi::BaseModel

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

Overview

A base class for models. Represents a configuration file as an object with domain-specific attributes/methods. For persistent storage, use load and save, Non-responsibilities: actual storage and parsing (both delegated). There is no caching involved.

Instance Method Summary collapse

Constructor Details

#initialize(parser, file_path, file_handler: File) ⇒ BaseModel

Returns a new instance of BaseModel.

Parameters:

  • parser (.parse, .serialize)

    parser that can convert object to string and vice versa. It have to provide methods ‘string #serialize(object)` and `object #parse(string)`. For example see AugeasParser

  • file_path (String)

    expected path passed to file_handler

  • file_handler (.read, .write) (defaults to: File)

    object, that can read/write string. It have to provide methods ‘string read(string)` and `write(string, string)`. For example see MemoryFile



16
17
18
19
20
21
# File 'lib/config_files_api/base_model.rb', line 16

def initialize(parser, file_path, file_handler: File)
  @file_handler = file_handler
  @parser = parser
  @file_path = file_path
  @loaded = false
end

Instance Method Details

#generic_get(key) ⇒ Object

Note:

prefer to use specialized methods of children

powerfull method that gets unformatted any value in config.



43
44
45
# File 'lib/config_files_api/base_model.rb', line 43

def generic_get(key)
  data[key]
end

#generic_set(key, value) ⇒ Object

Note:

prefer to use specialized methods of children

powerfull method that sets any value in config. It try to be smart to at first modify existing value, then replace commented out code and if even that doesn’t work, then append it at the end



37
38
39
# File 'lib/config_files_api/base_model.rb', line 37

def generic_set(key, value)
  modify(key, value) || uncomment(key, value) || add_new(key, value)
end

#loadObject



28
29
30
31
# File 'lib/config_files_api/base_model.rb', line 28

def load
  self.data = @parser.parse(@file_handler.read(@file_path))
  @loaded = true
end

#loaded?Boolean

rubocop:disable Style/TrivialAccessors Returns if configuration was already loaded

Returns:

  • (Boolean)


49
50
51
# File 'lib/config_files_api/base_model.rb', line 49

def loaded?
  @loaded
end

#save(changes_only: false) ⇒ Object



23
24
25
26
# File 'lib/config_files_api/base_model.rb', line 23

def save(changes_only: false)
  merge_changes if changes_only
  @file_handler.write(@file_path, @parser.serialize(data))
end