Class: FusionTables::Connection

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

Constant Summary collapse

URL =
URI.parse("http://tables.googlelabs.com/api/query")

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.quote(value) ⇒ Object

Safely quotes a value.



75
76
77
# File 'lib/ft.rb', line 75

def self.quote(value)
  "'#{value.to_s.gsub("'", "\\\\'")}'"
end

Instance Method Details

#authenticate(email, password) ⇒ Object

Authenticates against Google using your email and password.

Note that this method uses the ClientLogin mechanism and it only stores the resulting token as an instance variable. Your credentials are discarded after the authentication process.



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
# File 'lib/ft.rb', line 40

def authenticate(email, password)
  uri = URI.parse("https://www.google.com/accounts/ClientLogin")

  http = Net::HTTP.new(uri.host, uri.port)
  http.use_ssl = true
  http.verify_mode = OpenSSL::SSL::VERIFY_PEER

  request = Net::HTTP::Post.new(uri.request_uri)

  request.set_form_data({
    "accountType" => "GOOGLE",
    "Email" => email,
    "Passwd" => password,
    "service" => "fusiontables"
  })

  response = http.request(request)

  case response
  when Net::HTTPOK
    @token = response.body[/^Auth=(.*)$/, 1]
    return true
  else
    @token = nil
    return false
  end
end

#httpObject



11
12
13
14
15
# File 'lib/ft.rb', line 11

def http
  @http ||= Net::HTTP::Persistent.new("fusiontables").tap do |http|
    http.headers["Content-Type"] = "application/x-www-form-urlencoded"
  end
end

#inspectObject

Prevents any authorization tokens from being exposed in error logs and the like.



70
71
72
# File 'lib/ft.rb', line 70

def inspect
  "#<#{self.class}>"
end

#query(sql) ⇒ Object

Queries the Fusion Tables API with the given SQL and returns an array of arrays for rows and columns.



19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
# File 'lib/ft.rb', line 19

def query(sql)
  res = process_sql(sql)

  case res
  when Net::HTTPOK
    CSV.parse(res.body.force_encoding(Encoding::UTF_8))
  when Net::HTTPFound
    raise Error.new("Authentication required. See #{self.class}#authenticate")
  when Net::HTTPBadRequest
    message = CGI.unescapeHTML(res.body[%r[<title>(.*)</title>]i, 1])
    raise Error.new("#{message}. SQL was: #{sql}")
  else
    raise "Got #{res.class}: #{res.body}"
  end
end