Class: Curl::Json

Inherits:
Object
  • Object
show all
Defined in:
lib/curly/curl/json.rb

Overview

Class for CURLing a JSON response

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(url, options = {}) ⇒ Curl::Json

Create a new Curl::Json page object

Parameters:

  • url (String)

    The url to curl

  • headers (Hash)

    The headers to send

  • compressed (Boolean)

    Expect compressed results



30
31
32
33
34
35
36
37
# File 'lib/curly/curl/json.rb', line 30

def initialize(url, options = {})
  @url = url
  @request_headers = options[:headers]
  @compressed = options[:compressed]
  @symbolize_names = options[:symbolize_names]

  @curl = TTY::Which.which('curl')
end

Instance Attribute Details

#codeObject (readonly)

Returns the value of attribute code.



10
11
12
# File 'lib/curly/curl/json.rb', line 10

def code
  @code
end

#compressed=(value) ⇒ Object (writeonly)

Sets the attribute compressed

Parameters:

  • value

    the value to set the attribute compressed to.



8
9
10
# File 'lib/curly/curl/json.rb', line 8

def compressed=(value)
  @compressed = value
end

#headersObject (readonly)

Returns the value of attribute headers.



10
11
12
# File 'lib/curly/curl/json.rb', line 10

def headers
  @headers
end

#jsonObject (readonly)

Returns the value of attribute json.



10
11
12
# File 'lib/curly/curl/json.rb', line 10

def json
  @json
end

#request_headers=(value) ⇒ Object (writeonly)

Sets the attribute request_headers

Parameters:

  • value

    the value to set the attribute request_headers to.



8
9
10
# File 'lib/curly/curl/json.rb', line 8

def request_headers=(value)
  @request_headers = value
end

#symbolize_names=(value) ⇒ Object (writeonly)

Sets the attribute symbolize_names

Parameters:

  • value

    the value to set the attribute symbolize_names to.



8
9
10
# File 'lib/curly/curl/json.rb', line 8

def symbolize_names=(value)
  @symbolize_names = value
end

#urlObject

Returns the value of attribute url.



6
7
8
# File 'lib/curly/curl/json.rb', line 6

def url
  @url
end

Instance Method Details

#curlObject



39
40
41
42
43
44
45
46
47
48
# File 'lib/curly/curl/json.rb', line 39

def curl
  page = curl_json

  raise "Error retrieving #{url}" if page.nil? || page.empty?

  @url = page[:url]
  @code = page[:code]
  @json = page[:json]
  @headers = page[:headers]
end

#path(path, json = @json) ⇒ Object



50
51
52
53
54
55
56
57
58
59
60
61
62
# File 'lib/curly/curl/json.rb', line 50

def path(path, json = @json)
  parts = path.split(/./)
  target = json
  parts.each do |part|
    if part =~ /(?<key>[^\[]+)\[(?<int>\d+)\]/
      target = target[key][int.to_i]
    else
      target = target[part]
    end
  end

  target
end

#to_dataObject



12
13
14
15
16
17
18
19
# File 'lib/curly/curl/json.rb', line 12

def to_data
  {
    url: @url,
    code: @code,
    json: @json,
    headers: @headers
  }
end