benhoskings (owner)

Revisions

gist: 141305 Download_button fork
public
Public Clone URL: git://gist.github.com/141305.git
Embed All Files: show embed
Text only #
1
2
3
4
5
6
7
8
9
10
11
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
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
require 'rubygems'
require 'hpricot'
require 'net/http'
 
class Requester
 
  CookieStore = '.requester-wget-cookies'
 
  def initialize opts
    `touch #{CookieStore}`
    @opts = opts
  end
 
  def as email, pass, &block
    if login email, pass
      puts "logged in."
      puts ""
      yield self
      logout
    else
      puts 'login failed.'
    end
  end
 
  def login email = nil, pass = nil
    post '/login', 'account[email]' => email, 'account[pass]' => pass
  end
  
  def logout
    puts ""
    get '/logout'
  end
 
  def get path
    puts "GET #{path}"
    wget path
  end
 
  def post path, post_hash
    post_data = post_hash.merge('authenticity_token' => auth_token).map {|k,v| "#{k}=#{v}" }.join('&')
    puts "POST #{path}"
    wget path, %Q{--post-data="#{post_data}"}
  end
 
  private
 
  def wget path, *args
    Hpricot `wget #{File.join("http://#{@opts[:domain]}", path)} --load-cookies #{CookieStore} --save-cookies #{CookieStore} --keep-session-cookies -O - #{args.join(' ')}`
  end
 
  def auth_token
    if @auth_token
      @auth_token # already set
    elsif (auth_token_input = (get('/login') / :input).detect {|input| input.attributes['name'] == 'authenticity_token' }).nil?
      puts "Couldn't get auth_token."
    else
      @auth_token = auth_token_input.attributes['value']
    end
  end
  
end
 
req = Requester.new :domain => 'corkboard.local'
 
req.as 'ben@hoskings.net', 'sekrit' do
  puts (req.get('/transfers') / '.transfer_name').map(&:html)
end