Module: Common::MechanizeHelper

Defined in:
lib/common/mechanize_helper.rb

Instance Method Summary collapse

Instance Method Details

#agent(force_new = false) ⇒ Object



3
4
5
6
7
8
9
10
11
12
13
14
15
16
# File 'lib/common/mechanize_helper.rb', line 3

def agent(force_new=false)
  if force_new
    @_agent = Mechanize.new
  else
    @_agent ||= Mechanize.new
  end
  @_agent.keep_alive = false
  @_agent.open_timeout = 10
  @_agent.read_timeout = 120
  @_agent.user_agent = 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10.8; rv:19.0) Gecko/20100101 Firefox/19.0'
  @_agent.ssl_version = 'SSLv3'
  # @_agent.set_proxy("localhost", 8888)
  @_agent
end

#html_page(body) ⇒ Object



22
23
24
25
# File 'lib/common/mechanize_helper.rb', line 22

def html_page body
  uri = URI 'http://example/'
  Mechanize::Page.new uri, nil, body, 200, agent
end

#post_multipart(url, post_params, headers = {}) ⇒ Object



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

def post_multipart(url, post_params, headers={})
  post_params = post_params.with_indifferent_access
  page = self.html_page <<-BODY
  <form action="#{url}" enctype="multipart/form-data" method="POST">
  </form>
  BODY

  page.forms.first.tap do |form|
    post_params.each do |key, value|
      if value.is_a?(IO)
        ul = Mechanize::Form::FileUpload.new({'name' => key.to_s},::File.basename(value.path))
        ul.file_data = value.read
        form.file_uploads << ul
      else
        form.add_field! key.to_s, value
      end
    end
  end.submit nil, headers
end

#set_timeout(seconds) ⇒ Object



18
19
20
# File 'lib/common/mechanize_helper.rb', line 18

def set_timeout(seconds)
  @_agent.open_timeout = seconds
end