Class: ElasticWeb::Resource

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

Direct Known Subclasses

ResourceCollection

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(original_data) ⇒ Resource

Returns a new instance of Resource.



5
6
7
8
9
10
11
12
13
14
15
16
17
# File 'lib/elasticweb/resource.rb', line 5

def initialize(original_data)
  @status = original_data.dig(:status)
  @message = original_data.dig(:message)

  original_data = {} unless original_data.dig(:data).is_a?(Hash)

  references = original_data.delete(:references)
  refs_collection = parse_references(references)
  @refs = refs_collection.present? ? OpenStruct.new(refs_collection) : nil

  data = original_data.dig(:data)
  @data = OpenStruct.new(data.with_indifferent_access)
end

Dynamic Method Handling

This class handles dynamic methods through the method_missing method

#method_missing(method_sym, *arguments, &block) ⇒ Object



28
29
30
31
32
33
34
# File 'lib/elasticweb/resource.rb', line 28

def method_missing(method_sym, *arguments, &block)
  if @data.respond_to?(method_sym)
    @data.send(method_sym)
  else
    super
  end
end

Instance Attribute Details

#dataObject (readonly)

Returns the value of attribute data.



3
4
5
# File 'lib/elasticweb/resource.rb', line 3

def data
  @data
end

#messageObject (readonly)

Returns the value of attribute message.



3
4
5
# File 'lib/elasticweb/resource.rb', line 3

def message
  @message
end

#refsObject (readonly)

Returns the value of attribute refs.



3
4
5
# File 'lib/elasticweb/resource.rb', line 3

def refs
  @refs
end

#statusObject (readonly)

Returns the value of attribute status.



3
4
5
# File 'lib/elasticweb/resource.rb', line 3

def status
  @status
end

Instance Method Details

#parse_references(references) ⇒ Object



19
20
21
22
23
24
25
26
# File 'lib/elasticweb/resource.rb', line 19

def parse_references(references)
  (references || {}).each_with_object({}) do |(reference, value), result|
    case value
      when Hash then result[reference] = Relation.new(value)
      when Array then result[reference] = RelationCollection.new(value)
    end
  end
end