Class: Bitly4R::Response

Inherits:
Object
  • Object
show all
Defined in:
lib/bitly4r/objects.rb

Overview

Response

A response from the bit.ly API.

The to_s method should always return the ‘likely’ value, assuming that there is a likely one. For example:

  • shorten => shortUrl

  • expand => longUrl

All other response values can be retrieved via method_missing.

NOTE: This is not a sophisticated XML parser. It’s just Regexp’s, with handling for CDATA blocks.

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(response, to_s_sym = nil) ⇒ Response

Constructs a bit.ly API response wrapper.

response can be:

  • a JSON String, which becomes the body

  • a Net::HTTPResponse, in which case its body is extracted and expected to be in JSON format

to_s_sym is optional, and it references the property which will become the ‘#to_s` value of this Response. It can be either camel-case or underscored. See method_missing.



77
78
79
80
81
# File 'lib/bitly4r/objects.rb', line 77

def initialize(response, to_s_sym=nil)
	response = response.body if Net::HTTPResponse === response
	@body = response
	@to_s_sym = to_s_sym
end

Dynamic Method Handling

This class handles dynamic methods through the method_missing method

#method_missing(sym, *args) ⇒ Object

Provides access to the other properties of the response body via camel-case or underscored names. For example, longUrl and long_url are equivalent. If no such property exists, you’ll get nil.



86
87
88
89
90
91
92
93
94
95
96
# File 'lib/bitly4r/objects.rb', line 86

def method_missing(sym, *args)
          begin
              json = JSON.parse(@body || '{}')
          rescue JSON::ParserError => e
              return nil
          end

          # their 'v4/*' JSON convention is snake_case
          sym = Utility::decamelize(sym.to_s)
	return json[sym]
end

Instance Attribute Details

#bodyObject (readonly)

The body of the bit.ly API response, as XML



66
67
68
# File 'lib/bitly4r/objects.rb', line 66

def body
  @body
end

Instance Method Details

#to_sObject Also known as: to_str

Provides the ‘likely’ value from the response.



99
100
101
# File 'lib/bitly4r/objects.rb', line 99

def to_s
	@to_s_sym  ? self.__send__(@to_s_sym)  : super
end

#to_symObject

Provides the ‘likely’ value from the response, as a symbol.



105
106
107
108
109
# File 'lib/bitly4r/objects.rb', line 105

def to_sym
          return super unless @to_s_sym
          value = self.to_s
          return value.nil? ? value : value.to_sym
end