Class: YandexXml

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

Overview

Instance Method Summary collapse

Constructor Details

#initialize(args) ⇒ YandexXml

Returns a new instance of YandexXml.



12
13
14
15
16
# File 'lib/yandex_xml.rb', line 12

def initialize(args)
  @user = args[:user]
  @key = args[:key]
  @region = args.fetch(:region, '213') # Moscow
end

Instance Method Details

#get(keyword) ⇒ Object

Get data from Yandex.XML and create Hash with result



19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
# File 'lib/yandex_xml.rb', line 19

def get(keyword)
  # Create URL to Yandex.Xml
  xml_url = create_url(keyword)
  # Get data XML
  xml = Net::HTTP.get_response(URI.parse(xml_url)).body
  # Convert XML to Hash
  converter = Nori.new(:convert_dashes_to_underscores => true)
  hash = converter.parse(xml)
  # Convert Hash to OpenStruct
  data = JSON.parse(hash.to_json, object_class: OpenStruct)
  # Create short route to data
  groups = data.yandexsearch.response.results.grouping.group

  result = {}

  result[:meta] = {
    keyword: data.yandexsearch.request.query,
    timestamp: Time.now
  }

  data_array = []

  groups.each_with_index do |i, index|
    result_hash = {
      position: index + 1,
      url: i.doc.url,
      domain: i.doc.domain,
      title: i.doc.title,
      modtime: i.doc.modtime,
      size: i.doc.size,
      charset: i.doc.charset,
      # passage: i.doc.passages.passage, # TODO: not work
      passages_type: i.doc.properties._PassagesType,
      mime_type: i.doc.mime_type,
      saved_copy_url: i.doc.saved_copy_url,
      headline: i.doc.headline,
      turbo_cgi_url: i.doc.properties.TurboCgiUrl,
      turbo_fallback: i.doc.properties.TurboFallback,
      turbo_link: i.doc.properties.TurboLink
    }

    data_array << result_hash
  end

  result[:data] = data_array
  result
end

#get_limitsObject

TODO: Get information about limits in Yandex.XML service.



94
95
96
# File 'lib/yandex_xml.rb', line 94

def get_limits
  # code
end

#get_position(keyword, my_domain) ⇒ Object

Get position in Yandex Top-100 for site by keyword



78
79
80
81
82
83
84
85
86
87
88
89
90
91
# File 'lib/yandex_xml.rb', line 78

def get_position(keyword, my_domain)
  hash = get(keyword)
  struct = JSON.parse(hash.to_json, object_class: OpenStruct)

  domains = []
  struct.data.each { |i| domains << i.domain.downcase }

  position = 0
  domains.each_with_index do |domain, i|
    position = i + 1 if domain == my_domain
  end

  position
end

#get_top100_urls(keyword) ⇒ Object

Get 100 urls (Yandex Top-100) from result



68
69
70
71
72
73
74
75
# File 'lib/yandex_xml.rb', line 68

def get_top100_urls(keyword)
  hash = get(keyword)
  struct = JSON.parse(hash.to_json, object_class: OpenStruct)

  urls = []
  struct.data.each { |i| urls << i.url }
  urls
end