Class: Googletastic::Form

Inherits:
Base
  • Object
show all
Defined in:
lib/googletastic/form.rb

Overview

Constant Summary collapse

FORM_KEY_EXPRESSION =
/formkey["|']\s*:["|']\s*([^"|']+)"/

Constants included from Mixins::Namespaces

Mixins::Namespaces::NAMESPACES

Instance Attribute Summary collapse

Attributes inherited from Base

#acl, #attachment_path, #created_at, #etag, #head, #id, #keep_raw, #raw, #response, #synced_with, #updated_at

Attributes included from Mixins::Attributes

#attributes

Class Method Summary collapse

Instance Method Summary collapse

Methods inherited from Base

#initialize, #to_xml

Methods included from Mixins::Pagination

included

Methods included from Mixins::Finders

included

Methods included from Mixins::Parsing

included

Methods included from Mixins::Requesting

included

Methods included from Mixins::Attributes

#attribute_names, #has_attribute?, #inspect

Methods included from Mixins::Namespaces

included

Constructor Details

This class inherits a constructor from Googletastic::Base

Instance Attribute Details

#authenticity_tokenObject

Returns the value of attribute authenticity_token.



7
8
9
# File 'lib/googletastic/form.rb', line 7

def authenticity_token
  @authenticity_token
end

#bodyObject

Returns the value of attribute body.



6
7
8
# File 'lib/googletastic/form.rb', line 6

def body
  @body
end

#descriptionObject

Returns the value of attribute description.



6
7
8
# File 'lib/googletastic/form.rb', line 6

def description
  @description
end

#fieldsObject

Returns the value of attribute fields.



6
7
8
# File 'lib/googletastic/form.rb', line 6

def fields
  @fields
end

#form_keyObject

uses mechanize to hackily find form key



10
11
12
# File 'lib/googletastic/form.rb', line 10

def form_key
  @form_key
end

#form_onlyObject

Returns the value of attribute form_only.



7
8
9
# File 'lib/googletastic/form.rb', line 7

def form_only
  @form_only
end

#propertiesObject

Returns the value of attribute properties.



6
7
8
# File 'lib/googletastic/form.rb', line 6

def properties
  @properties
end

#spreadsheetObject

Returns the value of attribute spreadsheet.



7
8
9
# File 'lib/googletastic/form.rb', line 7

def spreadsheet
  @spreadsheet
end

#titleObject

Returns the value of attribute title.



6
7
8
# File 'lib/googletastic/form.rb', line 6

def title
  @title
end

Class Method Details

.add_redirect(doc, options, &block) ⇒ Object



261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
# File 'lib/googletastic/form.rb', line 261

def add_redirect(doc, options, &block)
  action = doc.xpath("//form").first
  return if action.nil?
  action = action["action"].to_s
  submit_key = action.gsub(self.submit_url, "")

  form = doc.xpath("//form").first

  form["enctype"] = "multipart/form-data"      

  # don't have time to build this correctly
  redirect = options[:redirect]
  if redirect
    form["action"] = redirect[:url]
    if redirect.has_key?(:params)
      redirect[:params].each do |k,v|
        hidden_node = doc.create_element('input')
        hidden_node["name"] = k.to_s
        hidden_node["type"] = "hidden"
        hidden_node["value"] = v.to_s
        form.children.first.add_previous_sibling(hidden_node)
      end
    end
  end

  hidden_node = doc.create_element('input')
  hidden_node["name"] = "submit_key"
  hidden_node["type"] = "hidden"
  hidden_node["value"] = submit_key
  form.children.first.add_previous_sibling(hidden_node)

  put_node = doc.create_element('input')
  put_node["name"] = "_method"
  put_node["type"] = "hidden"
  put_node["value"] = "put"
  form.children.first.add_previous_sibling(put_node)

  form
end

.agent(force = false) ⇒ Object



157
158
159
160
161
162
163
164
165
166
167
168
169
170
# File 'lib/googletastic/form.rb', line 157

def agent(force = false)
  if force || !@agent
    @agent = defined?(Mechanize) ? Mechanize.new : WWW::Mechanize.new
    # google wants recent browsers!
    # http://docs.google.com/support/bin/answer.py?answer=37560&hl=en
    @agent.user_agent = "Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10_6_2; ru-ru) AppleWebKit/533.2+ (KHTML, like Gecko) Version/4.0.4 Safari/531.21.10"
     = @agent.get(mechanize_url(id)).forms.first
    .Email = Googletastic.credentials[:username].split("@").first # don't want emails
    .Passwd = Googletastic.credentials[:password]
    @agent.submit()
  end
  
  @agent
end

.client_classObject



97
98
99
# File 'lib/googletastic/form.rb', line 97

def client_class
  "Spreadsheets"
end

.find_form_key(id, force = false) ⇒ Object

optimize this to login only once



183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
# File 'lib/googletastic/form.rb', line 183

def find_form_key(id, force = false)
  result = nil
  begin
    page = agent(force).get(mechanize_url(id))
    match = page.body.match(FORM_KEY_EXPRESSION)
    if page.meta.first and (page.title == "Redirecting" || match.nil?)
    	page = page.meta.first.click
      match = page.body.match(FORM_KEY_EXPRESSION)
    end
    result = match.captures.first if match
  rescue Exception => e #
    puts "ERROR: #{e.to_s}"
    result = find_form_key(id, true) unless force # try again, unless we have already tried again
  end
  result
end

.find_one(id, options) ⇒ Object



91
92
93
94
95
# File 'lib/googletastic/form.rb', line 91

def find_one(id, options)
  options[:id] = id
  options[:url] = self.get_url(id)
  find_by_api(options).first
end

.from_google_tag(key) ⇒ Object



128
129
130
# File 'lib/googletastic/form.rb', line 128

def from_google_tag(key)
  tag_map[key]
end

.get_url(id) ⇒ Object



105
106
107
# File 'lib/googletastic/form.rb', line 105

def get_url(id)
  "http://spreadsheets.google.com/feeds/spreadsheets/private/full/#{id}"
end

.index_urlObject



101
102
103
# File 'lib/googletastic/form.rb', line 101

def index_url
  "http://spreadsheets.google.com/feeds/spreadsheets/private/full"
end

.mechanize_url(id) ⇒ Object



172
173
174
175
176
177
178
179
180
# File 'lib/googletastic/form.rb', line 172

def mechanize_url(id)
  url = "http://spreadsheets.google.com/"
  # for spreadsheet, we need the domain!
  if Googletastic.credentials[:domain]
    url << "a/#{Googletastic.credentials[:domain]}/"
  end
  url << "ccc?key=#{id}&hl=en&pli=1"
  url
end

.parse(html, options, &block) ⇒ Object

returns => fields, :body => body, :properties => properties, :description => description



201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
# File 'lib/googletastic/form.rb', line 201

def parse(html, options, &block)
  title = html.xpath("//h1[@class='ss-form-title']").first.text
  description = html.css(".ss-form-desc").first
  description = description ? description.children.to_html : ""
  
  properties = {}
  fields = []

  html.css("div.ss-item").each do |item|
    tag       = ""
    required  = false
    classes   = item["class"].split(/\s+/)
    classes.each do |clazz|
      if clazz =~ /ss-(text|paragraph-text|grid|scale|radio|checkbox)/
        tag = from_google_tag($1)
      elsif clazz =~ /ss-item-required/
        required = true
      end
    end
    entry     = item.xpath("div[@class='ss-form-entry']").first
    label     = entry.xpath("label[@class='ss-q-title']").first
    next unless label
    title     = label.text.gsub(/:[^:]+$/, "").gsub(/\n+.*/, "") # remove trailing :, then trailing newline stuff
    help      = entry.xpath("label[@class='ss-q-help']").first.text
    single    = (item["class"].to_s =~ /ss-(grid|scale)/).nil?
    type      = single ? "single" : "group"
    column    = label.text.downcase.gsub(/[^a-z0-9\-]/, "")
    input_name = label["for"].gsub("_", ".").squeeze("\.") + "." + type
    
    value     = []
    if tag =~ /(radio|checkbox|range|text)/
      item.css("* input[type=#{$1}]").each do |input|
        value << input["value"]
      end
    elsif tag =~ /(select)/
      item.css("* #{$1} option").each do |option|
        value << option["value"]
      end
    end
    # still need to handle defaults
    keys = {
      :id       => input_name.gsub(/[^\d]/, ""),
      :key      => column,
      :tag      => tag,
      :title    => title,
      :help     => help,
      :required => required,
      :value    => value # need defaults somehow
    }
    if tag == "range"
      keys[:left_label]   = item.css("* td.ss-leftlabel").text
      keys[:right_label]  = item.css("* td.ss-rightlabel").text
    end
    fields << keys
    properties[column] = input_name
  end

  {:fields => fields, :body => html, :properties => properties, :description => description}
end

.show_url(id) ⇒ Object



113
114
115
# File 'lib/googletastic/form.rb', line 113

def show_url(id)
  "http://spreadsheets.google.com/viewform?formkey=#{id}"
end

.submit_url(id = "") ⇒ Object



109
110
111
# File 'lib/googletastic/form.rb', line 109

def submit_url(id = "")
  "http://spreadsheets.google.com/formResponse?formkey=#{id}"
end

.tag_mapObject



117
118
119
120
121
122
123
124
125
126
# File 'lib/googletastic/form.rb', line 117

def tag_map
  @tag_map ||= {
    "text" => "text",
    "paragraph-text" => "textarea",
    "grid" => "grid",
    "scale" => "range",
    "radio" => "radio",
    "checkbox" => "checkbox"
  }
end

.to_google_tag(key) ⇒ Object



132
133
134
# File 'lib/googletastic/form.rb', line 132

def to_google_tag(key)
  tag_map[tag_map.values.detect {|i| i == key.to_s}]
end

.unmarshall(xml) ⇒ Object



136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
# File 'lib/googletastic/form.rb', line 136

def unmarshall(xml)
  records = xml.xpath("//atom:entry", ns_tag("atom")).collect do |record|
    #id          = record.xpath("atom:id", ns_tag("atom")).first.text.gsub("http://spreadsheets.google.com/feeds/spreadsheets/", "")
    id          = record.xpath("atom:link[@rel='alternate']", ns_tag("atom")).first
    if id
      id = id["href"].gsub("http://spreadsheets.google.com/ccc?key=", "")
    end
    title       = record.xpath("atom:title", ns_tag("atom")).first.text
    created_at  = record.xpath("atom:published", ns_tag("atom")).text
    updated_at  = record.xpath("atom:updated", ns_tag("atom")).text
            
    # same as spreadsheet
    Googletastic::Form.new(
      :id         => id,
      :title      => title,
      :updated_at => DateTime.parse(updated_at)
    )
  end
  records
end

Instance Method Details

#construct(options = {}, &block) ⇒ Object

construct(:redirect => => “/our-forms”, :params => {:one => “hello”})



304
305
306
307
308
309
310
311
312
313
314
315
# File 'lib/googletastic/form.rb', line 304

def construct(options = {}, &block)
  return if body
  raise "I NEED A FORM KEY (#{self.title.to_s})!" unless self.form_key
  parts = fetch(options, &block)
  parts.each do |k, v|
    self.send("#{k}=", v)
  end
  parts.delete(:body)
  parts[:form_key] = form_key
  self.attributes.merge!(parts)
  body
end

#fetch(options = {}, &block) ⇒ Object



317
318
319
320
321
322
323
324
# File 'lib/googletastic/form.rb', line 317

def fetch(options = {}, &block)
  response = client.get(show_url)
  if response.is_a?(Net::HTTPSuccess) || response.is_a?(GData::HTTP::Response)
    self.class.parse(Nokogiri::HTML(response.body), options, &block)
  else
    response
  end
end

#from_google_tag(key) ⇒ Object



27
28
29
# File 'lib/googletastic/form.rb', line 27

def from_google_tag(key)
  self.class.from_google_tag(key)
end

#renderObject

this you want to call JUST BEFORE you render in the view body still gives you the nokogiri element



37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
# File 'lib/googletastic/form.rb', line 37

def render
  add_redirect(body, options, &block)
  
  body.xpath("//textarea").each do |node|
    node.add_child Nokogiri::XML::Text.new("\n", body)
    node.remove_attribute("rows")
    node.remove_attribute("cols")
  end
  
  if self.form_only
    result = body.xpath("//form").first.unlink
  else
    body.xpath("//div[@class='ss-footer']").first.unlink
    body.xpath("//script").each {|x| x.unlink }
    result = body.xpath("//div[@class='ss-form-container']").first.unlink
  end
  result.to_html
end

#set_defaults(hash) ⇒ Object

=> value



57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
# File 'lib/googletastic/form.rb', line 57

def set_defaults(hash)
  hash.each do |column, value|
    entry = properties[column]
    next unless entry and !entry.empty?
    nodes = body.xpath("//*[@name='#{entry}']")
    if entry =~ /group/
      nodes.each do |node|
        if node["value"] == value
          node["checked"] = "checked"
          break
        end
      end
    else
      node = nodes.first
      next unless node
      case node.name.to_s
      when "input"
        node["value"] = value
      when "textarea"
        node.content = value
      when "select"
        node.xpath("option").each do |option|
          if option["value"] == value
            option["selected"] = "selected"
            break
          end
        end
      end
    end
  end
end

#show_urlObject



23
24
25
# File 'lib/googletastic/form.rb', line 23

def show_url
  self.class.show_url(self.form_key)
end

#submit(form_key, params, options) ⇒ Object



326
327
328
329
330
331
332
333
334
335
336
# File 'lib/googletastic/form.rb', line 326

def submit(form_key, params, options)
  uri = URI.parse(submit_url)
  req = Net::HTTP::Post.new("#{uri.path}?#{uri.query}")
  req.form_data = params
  response = Net::HTTP.new(uri.host).start {|h| h.request(req)}
  if response.is_a?(Net::HTTPSuccess) || response.is_a?(GData::HTTP::Response)
    self.class.parse(Nokogiri::HTML(response.body), options).to_html
  else
    response.body
  end
end

#submit_urlObject



19
20
21
# File 'lib/googletastic/form.rb', line 19

def submit_url
  self.class.submit_url(self.form_key)
end

#to_google_tag(key) ⇒ Object



31
32
33
# File 'lib/googletastic/form.rb', line 31

def to_google_tag(key)
  self.class.to_google_tag(key)
end