Class: SeleniumSpider::Model

Inherits:
SeleniumStandaloneDSL::Base
  • Object
show all
Defined in:
lib/selenium_spider/model.rb

Constant Summary collapse

@@attributes =
{}

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(location: nil, driver: nil) ⇒ Model



9
10
11
12
13
14
15
16
# File 'lib/selenium_spider/model.rb', line 9

def initialize(location: nil, driver: nil)
  if driver
     @driver = driver
  else
    super()
    visit location
  end
end

Instance Attribute Details

#attributesObject

Returns the value of attribute attributes.



6
7
8
# File 'lib/selenium_spider/model.rb', line 6

def attributes
  @attributes
end

Class Method Details

.register(attr_name_sym) {|| ... } ⇒ Object

Yields:

  • ()


22
23
24
25
# File 'lib/selenium_spider/model.rb', line 22

def self.register(attr_name_sym)
  @@attributes[attr_name_sym] = SeleniumSpider::Attribute.new
  yield @@attributes[attr_name_sym] if block_given?
end

Instance Method Details

#extract(attr_name_sym) ⇒ Object



27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
# File 'lib/selenium_spider/model.rb', line 27

def extract(attr_name_sym)
  attr = @@attributes[attr_name_sym]
  return attr.value if attr.value

  element_str = search(attr.css).inner_text

  if attr.match &&(match = element_str.match(/#{attr.match}/))
    element_str = match[match.length - 1]
  end

  if attr.sub
    element_str = element_str.sub(/#{attr.sub[:replace]}/, attr.sub[:with])
  end

  if attr.lambda
    element_str = attr.lambda.call(element_str)
  end

  element_str
end

#extract_allObject



48
49
50
51
52
53
54
# File 'lib/selenium_spider/model.rb', line 48

def extract_all
  extracted = {}
  @@attributes.each do |key, value|
    extracted[key] = extract(key)
  end
  extracted
end

#output_as_jsonObject



60
61
62
# File 'lib/selenium_spider/model.rb', line 60

def output_as_json
  JSON.dump extract_all
end

#saveObject

TODO: save to database(sqlite)



57
58
# File 'lib/selenium_spider/model.rb', line 57

def save
end

#set_attributes_value(key, value) ⇒ Object



18
19
20
# File 'lib/selenium_spider/model.rb', line 18

def set_attributes_value(key, value)
  @@attributes[key].value = value
end