Class: VLC360::Resource

Inherits:
Object
  • Object
show all
Defined in:
lib/vlc360/resource.rb

Direct Known Subclasses

Injured, Session, Work

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(attributes = {}) ⇒ Resource

Returns a new instance of Resource.



28
29
30
31
# File 'lib/vlc360/resource.rb', line 28

def initialize(attributes = {})
  clear_errors
  set_attributes(attributes)
end

Instance Attribute Details

#errorsObject (readonly)

Returns the value of attribute errors.



26
27
28
# File 'lib/vlc360/resource.rb', line 26

def errors
  @errors
end

Class Method Details

.attributes(*attributes) ⇒ Object



4
5
6
7
# File 'lib/vlc360/resource.rb', line 4

def attributes(*attributes)
  attr_accessor(*attributes)
  (@attributes ||= []).push(*attributes)
end

.nested_resource(resource = nil) ⇒ Object



14
15
16
17
18
19
# File 'lib/vlc360/resource.rb', line 14

def nested_resource(resource = nil)
  return @nested_resource unless resource

  attr_accessor(resource)
  @nested_resource = resource
end

.nested_resources(*resources) ⇒ Object



9
10
11
12
# File 'lib/vlc360/resource.rb', line 9

def nested_resources(*resources)
  attr_accessor(*resources)
  (@nested_resources ||= []).push(*resources)
end

.new_from_hash(attrs, type) ⇒ Object



21
22
23
# File 'lib/vlc360/resource.rb', line 21

def new_from_hash(attrs, type)
  VLC360.const_get(type.capitalize).new(attrs)
end

Instance Method Details

#set_attributes(attributes) ⇒ Object



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

def set_attributes(attributes)
  attributes.each do |key, value|
    if self.class.attributes.include?(key.to_sym)
      send("#{key}=", value)
    elsif self.class.nested_resource == key.to_sym
      send("#{key}=", Resource.new_from_hash(value, key))
    elsif self.class.nested_resources.include?(key.to_sym)
      send("#{key}=", (value || []).map{ |attrs| Resource.new_from_hash(attrs, key) })
    end
  end
end

#to_hashObject



49
50
51
52
53
54
55
56
57
58
# File 'lib/vlc360/resource.rb', line 49

def to_hash
  hashie = Hash[self.class.attributes.map { |attribute| [attribute, send(attribute)] }]
  hashie[self.class.nested_resource] = send(self.class.nested_resource)&.to_hash if self.class.nested_resource

  self.class.nested_resources.map do |resources|
    hashie[resources] = send(resources)&.map(&:to_hash)
  end

  hashie.delete_if { |k, v| k.nil? || v.nil? }
end

#valid?Boolean

Returns:

  • (Boolean)


45
46
47
# File 'lib/vlc360/resource.rb', line 45

def valid?
  errors.empty?
end