Class: Gfrom

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

Constant Summary collapse

MATCHERS =
'//input[@type="text"] | //input[@type="radio"] | //input[@type="checkbox"] | //input[@type="hidden"] | //textarea | //form'

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(url, regenerate_cache = false, lang = 'en') ⇒ Gfrom

Returns a new instance of Gfrom.



12
13
14
15
16
17
18
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
# File 'lib/gfrom.rb', line 12

def initialize(url, regenerate_cache = false, lang = 'en')
  @form = Hash.new
  @fields = []

  uri = Addressable::URI.parse(url)
  uri.query_values ||= Hash.new
  uri.query_values = uri.query_values.merge({"hl" => lang})
  url = uri.to_s

  @cache = "#{Dir.tmpdir}/#{Digest::SHA1.hexdigest(url)}"
  if File.exists?(@cache) and regenerate_cache
    File.delete @cache
  end

  unless File.exists?(@cache)
    req = Curl.get(url)
    File.open(@cache, "w") do |f|
      f.write req.body_str
    end
  end

  keys = []

  doc = Nokogiri::XML(File.open(@cache))
  doc.search(MATCHERS).each do |node|
    case node.name
    when "form"
      @form[:action] = node.attributes["action"].value unless @form.has_key?(:action)
      @form[:title] = doc.search('//title').first.text.strip unless @form.has_key?(:title)
    else
      n = hash_it(node)
      @fields << n
      keys << n[:name]
    end
  end
  @form[:keys] = keys

end

Class Method Details

.locale_url(url, lang = 'en') ⇒ Object



51
52
53
54
55
56
57
58
59
# File 'lib/gfrom.rb', line 51

def self.locale_url(url, lang = 'en')
  uri = Addressable::URI.parse(url)
  if uri.to_hash.select{|k,v| [:scheme, :host].include? k }.values.any?{|v| v.nil? || v.length == 0}
    raise "Invalid URI"
  end
  uri.query_values ||= Hash.new
  uri.query_values = uri.query_values.merge({"hl" => lang})
  uri.to_s
end

Instance Method Details

#submit(params) ⇒ Object



61
62
63
64
65
66
67
68
69
70
71
72
73
# File 'lib/gfrom.rb', line 61

def submit(params)
  response = Curl.post(@form[:action], params)
  doc = Nokogiri::XML.parse(response.body_str)
  errorheader = doc.search('//div[@class="errorheader"]')
  success = errorheader.empty?
  out = { :success => success }
  if success
    out[:message] = doc.search('//div[@class="ss-custom-resp"]').first.text.strip rescue doc.search('//title').first.text.strip
  else
    out[:message] = errorheader.children.first.text.strip
  end
  out
end