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.



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

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

#connObject (readonly)

Returns the value of attribute conn.



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

def conn
  @conn
end

#dataObject (readonly)

Returns the value of attribute data.



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

def data
  @data
end

#keyObject (readonly)

Returns the value of attribute key.



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

def key
  @key
end

Instance Method Details

#assert_proper_query_parameters!(query_parameters, template) ⇒ Object



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

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



53
54
55
# File 'lib/json_roa/client/relation.rb', line 53

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

#available_methods_dataObject



49
50
51
# File 'lib/json_roa/client/relation.rb', line 49

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

#define_http_method(method_name) ⇒ Object



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

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



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

def run_request(method, query_parameters, body, headers, &block)
  query_parameters = query_parameters.with_indifferent_access rescue query_parameters
  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



57
58
59
# File 'lib/json_roa/client/relation.rb', line 57

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