class Tardvig::HashContainer
It is container for data, which is similar to Ruby's Hash, but it has more narrow purpose and corresponding changes in the list of methods. It is not Enumerable, so it has no `sort` method, `each`, `map`, etc. It allows to read, write, delete elements, save itself to/load from a file or IO, it has events and data identifier. **It is expected that you already know what is hash**.
Events:
-
`save` happen before saving data to a file. Arguments: self
-
`load` happen after loading data from a file. Arguments: self
-
`change` happen when there are some objects have been deleted from/added to this container. Arguments: self
Public Class Methods
@param hash [Hash] default Ruby's Hash.
If it is given, the container will be created from it (it will have the same key => value pairs).
# File lib/tardvig/hash_container.rb, line 21 def initialize(hash = {}) @hash = hash end
Public Instance Methods
@param key [Object] the object which you previously associated with value @return value associated with the given key through the {#[]=} method or
`nil` if there is no such value.
@see []=
@see Ruby's Hash
# File lib/tardvig/hash_container.rb, line 30 def [](key) @hash[key] end
Adds your value to this container, so you can access it through the {#[]} method later using your key. @param key [Object] object which is used as an identifier of your value @param value [Object] anything you want to store in this container @return value @see Ruby's Hash
# File lib/tardvig/hash_container.rb, line 40 def []=(key, value) @hash[key] = value trigger :change, self value end
Loads the data from the YAML file to itself. If there are old data in the hash, it overrides them. @param io [IO, String] the IO instance or the name of the file.
The data will be loaded from here.
# File lib/tardvig/hash_container.rb, line 71 def load(io) open_file io, 'r' do |f| @hash.merge! YAML.load(f.read) trigger :load, self trigger :change, self end end
Saves this container's content to the file through YAML @param io [IO, String] the IO instance or the name of the file.
The content will be saved here.
# File lib/tardvig/hash_container.rb, line 60 def save(io) open_file io, 'w' do |f| trigger :save, self f.write YAML.dump(@hash) end end
Converts current hash to JSON.
# File lib/tardvig/hash_container.rb, line 86 def to_json(*) JSON.generate @hash end
Converts current hash to YAML. Arguments are similar to standard Ruby's Object#to_yaml
# File lib/tardvig/hash_container.rb, line 81 def to_yaml(*args) @hash.to_yaml(*args) end
Private Instance Methods
# File lib/tardvig/hash_container.rb, line 92 def open_file(io, mode) if io.respond_to?(:read) && io.respond_to?(:write) yield io elsif io.is_a? String File.open(io, mode) { |f| yield f } else raise ArgumentError end end