Class: JSON_ROA::Client::Relation

Inherits:
Object
  • Object
show all
Defined in:
lib/json_roa/client/relation.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(conn, key, data) ⇒ Relation

Returns a new instance of Relation.



11
12
13
14
15
16
17
18
19
20
# File 'lib/json_roa/client/relation.rb', line 11

def initialize(conn, key, data)
  @conn = conn
  @key = key
  @data = data

  Faraday::Connection::METHODS.intersection(available_methods) \
    .each do |method_name|
      define_http_method method_name
    end
end

Instance Attribute Details

#dataObject (readonly)

Returns the value of attribute data.



8
9
10
# File 'lib/json_roa/client/relation.rb', line 8

def data
  @data
end

#keyObject (readonly)

Returns the value of attribute key.



9
10
11
# File 'lib/json_roa/client/relation.rb', line 9

def key
  @key
end

Instance Method Details

#assert_proper_query_parameters!(query_parameters, template) ⇒ Object



29
30
31
32
33
34
35
# File 'lib/json_roa/client/relation.rb', line 29

def assert_proper_query_parameters!(query_parameters, template)
  unless Set.new(query_parameters.keys).subset? Set.new(template.keys)
    raise StandardError, ['query_parameters', query_parameters.keys.to_s,
                          'do not match template parameters',
                          template.keys.to_s].join(' ')
  end
end

#available_methodsObject



51
52
53
# File 'lib/json_roa/client/relation.rb', line 51

def available_methods
  available_methods_data.keys.map(&:to_sym)
end

#available_methods_dataObject



47
48
49
# File 'lib/json_roa/client/relation.rb', line 47

def available_methods_data
  @data['methods'] ||= { 'get' => {} }
end

#define_http_method(method_name) ⇒ Object



22
23
24
25
26
27
# File 'lib/json_roa/client/relation.rb', line 22

def define_http_method(method_name)
  define_singleton_method method_name \
    do |query_parameters = {}, body = nil, headers = nil, &block|
  run_request method_name, query_parameters, body, headers, &block
  end
end

#run_request(method, query_parameters, body, headers, &block) ⇒ Object



37
38
39
40
41
42
43
44
45
# File 'lib/json_roa/client/relation.rb', line 37

def run_request(method, query_parameters, body, headers, &block)
  href = @data['href']
  template = ::Addressable::Template.new(href)
  assert_proper_query_parameters! query_parameters, template
  expanded_url = template.expand(query_parameters)
  response = @conn.run_request( \
    method.to_sym, expanded_url, body, headers, &block)
  ::JSON_ROA::Client::Resource.new(@conn, response)
end

#to_sObject



55
56
57
# File 'lib/json_roa/client/relation.rb', line 55

def to_s
  "#{self.class.name}:  #{@data}"
end