Class: AdventureRL::Settings

Inherits:
Object
  • Object
show all
Includes:
Helpers::Error
Defined in:
lib/AdventureRL/Settings.rb

Constant Summary

Constants included from Helpers::Error

Helpers::Error::PADDING, Helpers::Error::STACK_TRACE_PADDING, Helpers::Error::STACK_TRACE_SIZE

Instance Attribute Summary collapse

Instance Method Summary collapse

Methods included from Helpers::Error

directory_exists?, error, error_no_directory, error_no_file, file_exists?

Constructor Details

#initialize(arg) ⇒ Settings

Initialize Settings with either a string representing a path to a YAML file, or a hash with your settings.



8
9
10
11
12
13
14
15
16
17
18
# File 'lib/AdventureRL/Settings.rb', line 8

def initialize arg
  if    ([String, Pathname].include? arg.class)
    @file = Pathname.new arg
    validate_file_exists @file
    @content = get_file_content(@file).keys_to_sym
  elsif (arg.is_a? Hash)
    @content = arg.keys_to_sym
  elsif (arg.is_a? Settings)
    @content = arg.get
  end
end

Instance Attribute Details

#contentObject (readonly)

Returns the value of attribute content.



4
5
6
# File 'lib/AdventureRL/Settings.rb', line 4

def content
  @content
end

Instance Method Details

#eachObject



57
58
59
# File 'lib/AdventureRL/Settings.rb', line 57

def each
  return get.each
end

#get(*keys) ⇒ Object

Returns the settings, following the structure of the passed keys. Similar to Hash#dig



22
23
24
25
26
27
28
29
30
31
32
33
34
# File 'lib/AdventureRL/Settings.rb', line 22

def get *keys
  current_content = @content
  keys.each do |key|
    key = key.to_sym  if (key.is_a? String)
    if (current_content.is_a?(Hash) && !current_content[key].nil?)
      current_content = current_content[key]
    else
      current_content = nil
      break
    end
  end
  return current_content
end

#merge(other_settings, *keys) ⇒ Object

Merge self Settings content with other_settings Settings content or Hash. Can pass unlimited optional arguments as keys. If keys are given, then it will only merge the content from the keys keys for both Settings instances. Returns a new Settings object where the values of the keys keys are its settings content.



42
43
44
45
46
47
48
49
50
51
52
53
54
55
# File 'lib/AdventureRL/Settings.rb', line 42

def merge other_settings, *keys
  merged_settings = nil
  if    (other_settings.is_a? Settings)
    merged_settings = Settings.new get(*keys).merge(other_settings.get(*keys))
  elsif (other_settings.is_a? Hash)
    merged_settings = Settings.new get(*keys).merge(other_settings)
  else
    error(
      "Argument needs to be an instance of `AdventureRL::Settings' or a Hash",
      "but got a `#{other_settings.class.name}'"
    )
  end
  return merged_settings
end