Class: Button::Response

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

Overview

Response is a simple proxy class for easy value unpacking from an API response. It is constructed with a hash and proxies method calls on the instance down to keys in the underling hash.

## Usage

response = Button::Response.new(

prev: 'https://bloop.net/?cursor=1989',
next: 'https://bloop.net/?cursor=1991'

, :a => 1, :b => “two”)

puts response.data puts response.next_cursor puts response.prev_cursor

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(meta, response_data) ⇒ Response

Returns a new instance of Response.



21
22
23
24
# File 'lib/button/response.rb', line 21

def initialize(meta, response_data)
  @meta = meta
  @response_data = response_data
end

Class Method Details

.format_cursor(cursor_url) ⇒ Object



53
54
55
56
57
58
59
60
61
62
63
# File 'lib/button/response.rb', line 53

def format_cursor(cursor_url)
  return nil unless cursor_url

  parsed = URI(cursor_url)
  return nil unless parsed.query

  query = CGI.parse(parsed.query)
  cursor = query.fetch('cursor', [])

  cursor.empty? ? nil : cursor[0]
end

Instance Method Details

#dataObject



40
41
42
# File 'lib/button/response.rb', line 40

def data
  @response_data
end

#next_cursorObject



44
45
46
# File 'lib/button/response.rb', line 44

def next_cursor
  Response.format_cursor(@meta.fetch(:next, nil))
end

#prev_cursorObject



48
49
50
# File 'lib/button/response.rb', line 48

def prev_cursor
  Response.format_cursor(@meta.fetch(:prev, nil))
end

#to_sObject



26
27
28
29
30
31
32
33
34
35
36
37
38
# File 'lib/button/response.rb', line 26

def to_s
  repr = ''

  if @response_data.is_a?(Hash)
    repr = @response_data.reduce([]) do |acc, (name, value)|
      acc + ["#{name}: #{value || 'nil'}"]
    end.join(', ')
  elsif @response_data.is_a?(Array)
    repr = "#{@response_data.size} elements"
  end

  "Button::Response(#{repr})"
end