class Ovto::State

Attributes

values[R]

Public Class Methods

inherited(subclass) click to toggle source

(internal) initialize subclass

# File lib/ovto/state.rb, line 9
def self.inherited(subclass)
  subclass.instance_variable_set('@item_specs', [])
end
item(name, options={}) click to toggle source

Declare state item

# File lib/ovto/state.rb, line 14
def self.item(name, options={})
  unless options.is_a?(Hash)
    raise ArgumentError, "options must be a Hash: item :#{name}, #{options.inspect}"
  end
  @item_specs << [name, options]
  # Define accessor
  define_method(name){ @values[name] }
end
item_specs() click to toggle source

Return list of item specs (Array of `[name, options]`)

# File lib/ovto/state.rb, line 24
def self.item_specs
  @item_specs
end
new(hash = {}) click to toggle source
# File lib/ovto/state.rb, line 28
def initialize(hash = {})
  unknown_keys = hash.keys - self.class.item_specs.map(&:first)
  if unknown_keys.any?
    raise UnknownStateKey, "unknown key(s): #{unknown_keys.inspect}"
  end

  @values = self.class.item_specs.map{|name, options|
    if !hash.key?(name) && !options.key?(:default) && !options.key?(:default_proc)
      raise MissingValue, ":#{name} is mandatory for #{self.class.name}.new"
    end
    # Note that `hash[key]` may be false or nil
    value = if hash.key?(name) 
              hash[name] 
            elsif options.key?(:default)
              options[:default]
            elsif options.key?(:default_proc)
              options[:default_proc].call
            else
              raise "must not happen"
            end
    [name, value]
  }.to_h
end

Public Instance Methods

==(other) click to toggle source

Return true if a State object `other` has same key-value paris as `self`

# File lib/ovto/state.rb, line 68
def ==(other)
  other.is_a?(State) && self.values == other.values
end
[](key) click to toggle source

Return the value corresponds to `key`

# File lib/ovto/state.rb, line 63
def [](key)
  @values[key]
end
inspect() click to toggle source
# File lib/ovto/state.rb, line 76
def inspect
  "#<#{self.class.name}:#{object_id} #{@values.inspect}>"
end
merge(hash) click to toggle source

Create new state object from `self` and `hash`

# File lib/ovto/state.rb, line 54
def merge(hash)
  unknown_keys = hash.keys - self.class.item_specs.map(&:first)
  if unknown_keys.any?
    raise UnknownStateKey, "unknown key(s): #{unknown_keys.inspect}"
  end
  self.class.new(@values.merge(hash))
end
to_h() click to toggle source
# File lib/ovto/state.rb, line 72
def to_h
  @values
end