Class: MediaWiktory::Wikipedia::Response

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

Overview

Thin wrapper around MediaWiki API response.

It provides services for separating metadata of response of its essential data, continuing multi- page responses, and converting response errors into exceptions.

You should not instantiate this class, it is obtained by some Action's #response.

Constant Summary collapse

Error =

Response fail was returned by target MediaWiki API.

Class.new(RuntimeError)

Instance Attribute Summary collapse

Instance Method Summary collapse

Instance Attribute Details

#metadataHash (readonly)

Metadata part of the response, keys like "error", "warnings", "continue".

See #to_h for content part of the response and #raw for entire response.

Returns:

  • (Hash)


36
37
38
# File 'lib/mediawiktory/wikipedia/response.rb', line 36

def 
  @metadata
end

#rawHash (readonly)

Entire response "as is", including contents and metadata parts.

See #to_h for content part of the response and #metadata for metadata part.

Returns:

  • (Hash)


29
30
31
# File 'lib/mediawiktory/wikipedia/response.rb', line 29

def raw
  @raw
end

Instance Method Details

#[](key) ⇒ Object

Fetches a key from response content.

Parameters:

  • key (String)

    Key name.



58
59
60
# File 'lib/mediawiktory/wikipedia/response.rb', line 58

def [](key)
  to_h[key]
end

#continueResponse

Continues current request and returns current & next pages merged. (Merging is necessary because MediaWiki tends to return the same object's data continued on the next request page.)

Returns:



78
79
80
81
82
83
84
# File 'lib/mediawiktory/wikipedia/response.rb', line 78

def continue
  fail 'This is the last page' unless continue?

  action = @action.merge(@metadata.fetch('continue'))

  self.class.new(action, merge_responses(JSON.parse(action.perform)))
end

#continue?Boolean

Returns true if there is next pages of response. See also #continue

Returns:

  • (Boolean)


70
71
72
# File 'lib/mediawiktory/wikipedia/response.rb', line 70

def continue?
  @metadata.key?('continue')
end

#dig(*keys) ⇒ Object

Digs for a keys from response content.

Parameters:

  • keys (Array<String>)

    Key names.



65
66
67
# File 'lib/mediawiktory/wikipedia/response.rb', line 65

def dig(*keys)
  hash_dig(to_h, *keys)
end

#inspectString

Returns:

  • (String)


87
88
89
# File 'lib/mediawiktory/wikipedia/response.rb', line 87

def inspect
  "#<#{self.class.name}(#{@action.name}): #{to_h.keys.join(', ')}#{' (can continue)' if continue?}>"
end

#to_hHash

"Content" part of the response as a plain Ruby Hash.

Returns:

  • (Hash)


49
50
51
52
53
# File 'lib/mediawiktory/wikipedia/response.rb', line 49

def to_h
  # For most of actions, like query, all response is inside additional "query" key,
  # ...but not for all.
  @data.key?(@action.name) ? @data.fetch(@action.name) : @data
end