Class: Filepreviews::Response

Inherits:
OpenStruct
  • Object
show all
Defined in:
lib/filepreviews/response.rb

Overview

Response module to create callable methods from JSON response

Instance Method Summary collapse

Constructor Details

#initialize(hash = nil) ⇒ Filepreviews::Response

Overrides OpenStruct#initialize to enable deep nesting

Parameters:

  • hash (Hash<symbol>) (defaults to: nil)

    JSON response body

See Also:

  • OpenStruct#initialize


9
10
11
# File 'lib/filepreviews/response.rb', line 9

def initialize(hash = nil)
  responsify(hash)
end

Instance Method Details

#metadata(js: false) ⇒ Filepreviews::Response

Returns metadata response using the url from first response

flag is used to share this method with the CLI version (puerco, I know)

Parameters:

  • js (Boolean) (defaults to: false)

    flag to enable json response

Returns:



36
37
38
39
40
41
42
# File 'lib/filepreviews/response.rb', line 36

def (js: false)
  url = send(:url)
  response = Filepreviews::HTTP.default_connection(url).get(nil)
  json = JSON.parse(response.body)

  js ? json : self.responsify(json)
end

#responsify(hash = nil) ⇒ Filepreviews::Response

Returns inherited/hack version of OpenStruct.

Parameters:

  • hash (Hash<symbol>) (defaults to: nil)

    JSON response body

Returns:

See Also:

  • OpenStruct#initialize


21
22
23
24
25
26
27
28
29
30
# File 'lib/filepreviews/response.rb', line 21

def responsify(hash = nil)
  @table, @hash_table = {}, {}

  if hash
    hash.each do |k, v|
      @table[k.to_sym] = (v.is_a?(Hash) ? self.class.new(v) : v)
      @hash_table[k.to_sym] = v
    end
  end
end

#to_hObject

Magical method to give OpenStruct-like class deep nesting capability



14
15
16
# File 'lib/filepreviews/response.rb', line 14

def to_h
  @hash_table
end