Class: Manifestly::Entity::Base

Inherits:
Object
  • Object
show all
Defined in:
lib/manifestly/entity/base.rb

Direct Known Subclasses

Endpoint

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(data = {}) ⇒ Base

Returns a new instance of Base.



6
7
8
9
10
11
# File 'lib/manifestly/entity/base.rb', line 6

def initialize(data = {})
  invalids = data.keys - attributes
  raise "The following invalid #{self.class} keys were found: #{invalids}" unless invalids.empty?

  self.attributes = data
end

Class Method Details

.attr_accessor(*attrs) ⇒ Object



25
26
27
28
# File 'lib/manifestly/entity/base.rb', line 25

def self.attr_accessor(*attrs)
  attrs.each { |attr| attributes << attr }
  super
end

.attr_reader(*attrs) ⇒ Object



30
31
32
33
# File 'lib/manifestly/entity/base.rb', line 30

def self.attr_reader(*attrs)
  attrs.each { |attr| attributes << attr }
  super
end

.attributesObject



17
18
19
# File 'lib/manifestly/entity/base.rb', line 17

def self.attributes
  @attributes ||= []
end

.invalid_class_method(*names) ⇒ Object



39
40
41
# File 'lib/manifestly/entity/base.rb', line 39

def self.invalid_class_method(*names)
  names&.each { |name| define_method(name) { |*_, **_| raise 'invalid method' } }
end

.invalid_method(*names) ⇒ Object



35
36
37
# File 'lib/manifestly/entity/base.rb', line 35

def self.invalid_method(*names)
  names&.each { |name| define_method(name) { |*_, **_| raise 'invalid method' } }
end

Instance Method Details

#attributesObject



13
14
15
# File 'lib/manifestly/entity/base.rb', line 13

def attributes
  self.class.attributes
end

#attributes=(attrs) ⇒ Object



21
22
23
# File 'lib/manifestly/entity/base.rb', line 21

def attributes=(attrs)
  attrs.each { |k, v| send(:"#{k}=", v) }
end

#to_hObject



43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
# File 'lib/manifestly/entity/base.rb', line 43

def to_h
  {}.tap do |hsh|
    attributes.each do |attr|
      value = send(attr)
      if value.is_a?(Array)
        value = value.map do |it|
          next it.to_h if it.is_a?(Manifestly::Entity::Base)

          it
        end
      end
      hsh[attr] = value
    end
  end
end