Class: Wikipedia::Client

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

Constant Summary collapse

BASE_URL =
':protocol://:domain/:path?action=:action&format=json'.freeze

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initializeClient

Returns a new instance of Client.



8
9
10
# File 'lib/wikipedia/client.rb', line 8

def initialize
  self.follow_redirects = true
end

Instance Attribute Details

#follow_redirectsObject

Returns the value of attribute follow_redirects.



6
7
8
# File 'lib/wikipedia/client.rb', line 6

def follow_redirects
  @follow_redirects
end

Instance Method Details

#find(title, options = {}) ⇒ Object



12
13
14
15
16
17
18
19
# File 'lib/wikipedia/client.rb', line 12

def find( title, options = {} )
  title = Url.new(title).title rescue title
  page = Page.new( request_page( title, options ) )
  while follow_redirects && page.redirect?
    page = Page.new( request_page( page.redirect_title, options ) )
  end
  page
end

#find_image(title, options = {}) ⇒ Object



21
22
23
24
# File 'lib/wikipedia/client.rb', line 21

def find_image( title, options = {} )
  title = Url.new(title).title rescue title
  Page.new( request_image( title, options ) )
end

#find_random(options = {}) ⇒ Object



26
27
28
29
30
31
# File 'lib/wikipedia/client.rb', line 26

def find_random( options = {} )
  require 'json'
  data = JSON.parse( request_random( options ) )
  title = data['query']['pages'].values[0]['title']
  find( title, options )
end

#request(options) ⇒ Object



68
69
70
71
# File 'lib/wikipedia/client.rb', line 68

def request( options )
  require 'open-uri'
  URI.parse( url_for( options ) ).read( 'User-Agent' => Configuration[:user_agent] )
end

#request_image(title, options = {}) ⇒ Object



48
49
50
51
52
53
54
55
56
# File 'lib/wikipedia/client.rb', line 48

def request_image( title, options = {} )
  request( {
    action: 'query',
    prop: 'imageinfo',
    iiprop: 'url',
    iiurlwidth: options && options[:iiurlwidth] ? options[:iiurlwidth] : 200,
    titles: title
  }.merge( options ) )
end

#request_page(title, options = {}) ⇒ Object



34
35
36
37
38
39
40
41
42
43
44
45
# File 'lib/wikipedia/client.rb', line 34

def request_page( title, options = {} )
  request( {
    action: 'query',
    prop: %w[info revisions links extlinks images categories coordinates templates extracts pageimages langlinks],
    rvprop: 'content',
    inprop: 'url',
    pithumbsize: 200,
    explaintext: '',
    lllimit: 500,
    titles: title
  }.merge( options ) )
end

#request_random(options = {}) ⇒ Object



59
60
61
62
63
64
65
66
# File 'lib/wikipedia/client.rb', line 59

def request_random( options = {} )
  request( {
    action: 'query',
    generator: 'random',
    grnnamespace: '0',
    prop: 'info'
  }.merge( options ) )
end