Class: Yarrow::Schema::Entity

Inherits:
Object
  • Object
show all
Defined in:
lib/yarrow/schema/entity.rb

Overview

Entity with comparison by reference equality. Generates attribute helpers for a declared set of props. Used to replace Hashie::Mash without dragging in a whole new library.

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(config, context = nil) ⇒ Entity

Returns a new instance of Entity.



36
37
38
39
40
41
42
43
# File 'lib/yarrow/schema/entity.rb', line 36

def initialize(config, context=nil)
  converted = dictionary.cast(config)

  converted.each_pair do |key, value|
    # TODO: should we represent this as an attribute set rather than instance vars?
    instance_variable_set("@#{key}", value)
  end
end

Class Method Details

.[](label) ⇒ Object



17
18
19
20
# File 'lib/yarrow/schema/entity.rb', line 17

def [](label)
  @label = label
  self
end

.attribute(name, value_type) ⇒ Object



8
9
10
11
# File 'lib/yarrow/schema/entity.rb', line 8

def attribute(name, value_type)
  dictionary.define_attribute(name, value_type)
  attr_reader(name)
end

.dictionaryObject



13
14
15
# File 'lib/yarrow/schema/entity.rb', line 13

def dictionary
  @dictionary ||= Dictionary.new({})
end

.inherited(class_name) ⇒ Object



22
23
24
25
26
27
28
29
30
31
32
33
# File 'lib/yarrow/schema/entity.rb', line 22

def inherited(class_name)
  class_type = Yarrow::Schema::Types::Instance.of(class_name).accept(Hash)
  
  if @label
    label = @label
    @label = nil
  else
    label = Yarrow::Symbols.from_const(class_name)
  end

  Yarrow::Schema::Definitions.register(label, class_type)
end

Instance Method Details

#merge(other) ⇒ Object



67
68
69
70
71
72
73
# File 'lib/yarrow/schema/entity.rb', line 67

def merge(other)
  unless other.is_a?(self.class) || other.is_a?(Hash)
    raise ArgumentError.new("cannot merge entities that are not the same type")
  end

  self.class.new(to_h.merge(other.to_h))
end

#to_hObject



45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
# File 'lib/yarrow/schema/entity.rb', line 45

def to_h
  dictionary.attr_names.reduce({}) do |attr_dict, name|
    value = instance_variable_get("@#{name}")

    attr_dict[name] =if value.is_a?(Array)
      value.map do |entry|
        if entry.respond_to?(:to_h)
          entry.to_h
        else
          entry
        end
      end
    elsif value.respond_to?(:to_h)
      value.to_h
    else
      value
    end

    attr_dict
  end
end