Class: UniParser::Page

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

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(options = {}) ⇒ Page

Returns a new instance of Page.

Parameters:

  • options (Object) (defaults to: {})

Options Hash (options):

  • :source (String)

    Сырой HTML в виде строки

  • :url (String)

    Урла



26
27
28
29
# File 'lib/uni_parser/page.rb', line 26

def initialize(options = {})
  @source = options.delete(:source)
  @url = options.delete(:url)
end

Instance Attribute Details

#resultObject

Returns the value of attribute result.



5
6
7
# File 'lib/uni_parser/page.rb', line 5

def result
  @result
end

Class Method Details

.field(name, &block) ⇒ Object



7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
# File 'lib/uni_parser/page.rb', line 7

def self.field(name, &block)
  if block_given?
    attr_writer name.to_sym
    send :define_method, name.to_sym do
      unless instance_variable_defined?("@#{name}")
        value = instance_eval(&block)
        value = clean_up(value) if value.is_a?(String)
        instance_variable_set("@#{name}", value)
      end
      instance_variable_get("@#{name}")
    end
  else
    attr_accessor name.to_sym
  end
end

Instance Method Details

#agentObject



31
32
33
34
35
36
37
# File 'lib/uni_parser/page.rb', line 31

def agent
  options = {
    proxy: @proxy
  }

  @agent ||= UniParser::Agent.new options
end

#clean_up(str) ⇒ Object



60
61
62
# File 'lib/uni_parser/page.rb', line 60

def clean_up(str)
  str.strip.sub(/^\.{3}/, '').sub(/\,$/, '').gsub("\u00A0", "\u0020").strip
end

#file(file_url) ⇒ Object



56
57
58
# File 'lib/uni_parser/page.rb', line 56

def file(file_url)
  agent.get_file file_url
end

#format_date(str) ⇒ Object



64
65
66
67
68
69
# File 'lib/uni_parser/page.rb', line 64

def format_date(str)
  ['января', 'февраля', 'марта', 'апреля',
  'мая', 'июня', 'июля', 'августа', 'сентября',
  'октября', 'ноября', 'декабря'].each_with_index { |month, i| str = str.sub(month, (i + 1).to_s) }
  str.strip.gsub(/[^\d]+/, '-')
end

#jsonObject



45
46
47
48
49
50
# File 'lib/uni_parser/page.rb', line 45

def json
  return source if source.is_a?(Hash)
  @json ||= MultiJson.decode source if source
rescue Exception => e
  raise DecodeError, "#{e.to_s}, #{agent.history.inspect}", e.backtrace
end

#rootObject



52
53
54
# File 'lib/uni_parser/page.rb', line 52

def root
  @root ||= Nokogiri::HTML(source, 'utf-8')
end

#sourceObject



39
40
41
42
43
# File 'lib/uni_parser/page.rb', line 39

def source
  @source ||= agent.get(@url) || throw('Define source or url... =(')
rescue Exception => e
  raise ConnectionError, "#{e.to_s}, #{agent.history.inspect}", e.backtrace
end