Class: Appear::Util::ValueClass

Inherits:
Object
  • Object
show all
Defined in:
lib/appear/util/value_class.rb

Overview

An immutable value type, similar to Struct, but with annotated attr_readers, that can be easily created from a Hash with the necessary fields.

Defined Under Namespace

Classes: MissingValueError

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(data) ⇒ ValueClass

Returns a new instance of ValueClass.

Parameters:

  • data (Hash)


14
15
16
17
18
19
20
21
22
# File 'lib/appear/util/value_class.rb', line 14

def initialize(data)
  self.class.properties.each do |val|
    begin
      instance_variable_set("@#{val}", data.fetch(val))
    rescue KeyError
      raise MissingValueError.new("#{self.class.name}: no value for attribute #{val.inspect}")
    end
  end
end

Class Method Details

.propertiesArray<Symbol>

Returns names of all properties.

Returns:

  • (Array<Symbol>)

    names of all properties



46
47
48
49
50
51
52
53
# File 'lib/appear/util/value_class.rb', line 46

def self.properties
  @props ||= []
  if self.superclass.respond_to?(:properties)
    self.superclass.properties + @props
  else
    @props
  end
end

.property(name, opts = {}) ⇒ Object

Define an attribute reader that can be populated by the constructor.

Parameters:

  • name (Symbol)

    define an attr_reader with this name

  • opts (Hash) (defaults to: {})

    options

Options Hash (opts):

  • :var (Symbol)

    instance variable we should read from



33
34
35
36
37
38
39
40
41
42
43
# File 'lib/appear/util/value_class.rb', line 33

def self.property(name, opts = {})
  var_name = opts.fetch(:var, name)

  @props ||= []
  @props << var_name

  # we could do super, but we want to allow defining :acttive? or so
  class_eval "def #{name}; @#{var_name}; end"

  var_name
end