Class: GoogleDriveV0::Spreadsheet

Inherits:
File
  • Object
show all
Includes:
Util
Defined in:
lib/google_drive_v0/spreadsheet.rb

Overview

A spreadsheet.

Use methods in GoogleDriveV0::Session to get GoogleDriveV0::Spreadsheet object.

Constant Summary collapse

SUPPORTED_EXPORT_FORMAT =
Set.new(["xls", "csv", "pdf", "ods", "tsv", "html"])

Constants included from Util

Util::DOCS_BASE_URL, Util::EXT_TO_CONTENT_TYPE

Instance Attribute Summary collapse

Instance Method Summary collapse

Methods included from Util

concat_url, encode_query, h, to_v3_url

Methods inherited from File

#acl, #acl_feed_url, #available_content_types, #delete, #document_feed_entry_internal, #download_to_file, #download_to_string, #rename, #resource_id, #resource_type, #update_from_file, #update_from_io, #update_from_string

Constructor Details

#initialize(session, worksheets_feed_url, title = nil) ⇒ Spreadsheet

:nodoc:



25
26
27
28
29
# File 'lib/google_drive_v0/spreadsheet.rb', line 25

def initialize(session, worksheets_feed_url, title = nil) #:nodoc:
  super(session, nil)
  @worksheets_feed_url = worksheets_feed_url
  @title = title
end

Instance Attribute Details

#worksheets_feed_urlObject (readonly)

URL of worksheet-based feed of the spreadsheet.



32
33
34
# File 'lib/google_drive_v0/spreadsheet.rb', line 32

def worksheets_feed_url
  @worksheets_feed_url
end

Instance Method Details

#add_worksheet(title, max_rows = 100, max_cols = 20) ⇒ Object

Adds a new worksheet to the spreadsheet. Returns added GoogleDriveV0::Worksheet.



213
214
215
216
217
218
219
220
221
222
223
224
225
226
# File 'lib/google_drive_v0/spreadsheet.rb', line 213

def add_worksheet(title, max_rows = 100, max_cols = 20)
  xml = <<-"EOS"
    <entry xmlns='http://www.w3.org/2005/Atom'
           xmlns:gs='http://schemas.google.com/spreadsheets/2006'>
      <title>#{h(title)}</title>
      <gs:rowCount>#{h(max_rows)}</gs:rowCount>
      <gs:colCount>#{h(max_cols)}</gs:colCount>
    </entry>
  EOS
  doc = @session.request(:post, @worksheets_feed_url, :data => xml)
  url = doc.css(
    "link[rel='http://schemas.google.com/spreadsheets/2006#cellsfeed']")[0]["href"]
  return Worksheet.new(@session, self, url, title)
end

#document_feed_entry(params = {}) ⇒ Object

<entry> element of document list feed as Nokogiri::XML::Element.

Set params[:reload] to true to force reloading the feed.



104
105
106
107
108
109
110
111
112
113
# File 'lib/google_drive_v0/spreadsheet.rb', line 104

def document_feed_entry(params = {})
  warn(
      "WARNING: GoogleDriveV0::Spreadsheet\#document_feed_entry is deprecated and will be removed " +
      "in the next version.")
  if !@document_feed_entry || params[:reload]
    @document_feed_entry =
        @session.request(:get, self.document_feed_url, :auth => :writely).css("entry")[0]
  end
  return @document_feed_entry
end

#document_feed_urlObject

URL of feed used in document list feed API.



79
80
81
# File 'lib/google_drive_v0/spreadsheet.rb', line 79

def document_feed_url
  return "https://docs.google.com/feeds/documents/private/full/spreadsheet%3A#{self.key}"
end

#download_to_io(io, params = {}) ⇒ Object

Raises:

  • (NotImplementedError)


177
178
179
180
181
182
183
# File 'lib/google_drive_v0/spreadsheet.rb', line 177

def download_to_io(io, params = {})
  # General downloading API doesn't work for spreadsheets because it requires a different
  # authorization token, and it has a bug that it downloads PDF when text/html is
  # requested.
  raise(NotImplementedError,
      "Use export_as_file or export_as_string instead for GoogleDriveV0::Spreadsheet.")
end

#duplicate(new_title = nil) ⇒ Object

Creates copy of this spreadsheet with the given title.



116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
# File 'lib/google_drive_v0/spreadsheet.rb', line 116

def duplicate(new_title = nil)
  new_title ||= (self.title ? "Copy of " + self.title : "Untitled")
  header = {"GData-Version" => "3.0", "Content-Type" => "application/atom+xml;charset=utf-8"}
  xml = <<-"EOS"
    <entry xmlns='http://www.w3.org/2005/Atom'>
      <id>#{h(self.document_feed_url)}</id>
      <title>#{h(new_title)}</title>
    </entry>
  EOS
  doc = @session.request(
      :post, DOCS_BASE_URL, :data => xml, :header => header, :auth => :writely)
  ss_url = doc.css(
      "link[rel='http://schemas.google.com/spreadsheets/2006#worksheetsfeed']")[0]["href"]
  return Spreadsheet.new(@session, ss_url, new_title)
end

#export_as_file(local_path, format = nil, worksheet_index = nil) ⇒ Object

Exports the spreadsheet in format as a local file.

format can be either “xls”, “csv”, “pdf”, “ods”, “tsv” or “html”. If format is nil, it is guessed from the file name. In format such as “csv”, only the worksheet specified with worksheet_index is exported.

e.g.

spreadsheet.export_as_file("hoge.ods")
spreadsheet.export_as_file("hoge.csv", nil, 0)


162
163
164
165
166
167
168
169
170
171
172
173
174
175
# File 'lib/google_drive_v0/spreadsheet.rb', line 162

def export_as_file(local_path, format = nil, worksheet_index = nil)
  if !format
    format = ::File.extname(local_path).gsub(/^\./, "")
    if !SUPPORTED_EXPORT_FORMAT.include?(format)
      raise(ArgumentError,
          ("Cannot guess format from the file name: %s\n" +
           "Specify format argument explicitly.") %
          local_path)
    end
  end
  open(local_path, "wb") do |f|
    f.write(export_as_string(format, worksheet_index))
  end
end

#export_as_string(format, worksheet_index = nil) ⇒ Object

Exports the spreadsheet in format and returns it as String.

format can be either “csv” or “pdf”. In format such as “csv”, only the worksheet specified with worksheet_index is exported.



137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
# File 'lib/google_drive_v0/spreadsheet.rb', line 137

def export_as_string(format, worksheet_index = nil)
  if ["xls", "ods", "tsv", "html"].include?(format)
    warn("WARNING: Export with format '%s' is deprecated, and will not work in the next version." % format)
  end
  gid_param = worksheet_index ? "&gid=#{worksheet_index}" : ""
  format_string = "&format=#{format}"
  if self.human_url.match("edit")
    url = self.human_url.gsub(/edit/, "export") + gid_param + format_string
  else
    url =
      "https://spreadsheets.google.com/feeds/download/spreadsheets/Export" +
      "?key=#{key}&exportFormat=#{format}#{gid_param}"
  end
  return @session.request(:get, url, :response_type => :raw)
end

#human_urlObject

URL which you can open the spreadsheet in a Web browser with.

e.g. “spreadsheets.google.com/ccc?key=pz7XtlQC-PYx-jrVMJErTcg



62
63
64
65
# File 'lib/google_drive_v0/spreadsheet.rb', line 62

def human_url
  # Uses Document feed because Spreadsheet feed returns wrong URL for Apps account.
  return self.document_feed_entry_internal.css("link[rel='alternate']")[0]["href"]
end

#inspectObject



240
241
242
243
244
# File 'lib/google_drive_v0/spreadsheet.rb', line 240

def inspect
  fields = {:worksheets_feed_url => self.worksheets_feed_url}
  fields[:title] = @title if @title
  return "\#<%p %s>" % [self.class, fields.map(){ |k, v| "%s=%p" % [k, v] }.join(", ")]
end

#keyObject

Key of the spreadsheet.



45
46
47
48
49
50
51
52
# File 'lib/google_drive_v0/spreadsheet.rb', line 45

def key
  if !(@worksheets_feed_url =~
      %r{^https?://spreadsheets.google.com/feeds/worksheets/(.*)/private/.*$})
    raise(GoogleDriveV0::Error,
      "Worksheets feed URL is in unknown format: #{@worksheets_feed_url}")
  end
  return $1
end

#spreadsheet_feed_entry(params = {}) ⇒ Object

<entry> element of spreadsheet feed as Nokogiri::XML::Element.

Set params[:reload] to true to force reloading the feed.



86
87
88
89
90
91
# File 'lib/google_drive_v0/spreadsheet.rb', line 86

def spreadsheet_feed_entry(params = {})
  warn(
      "WARNING: GoogleDriveV0::Spreadsheet\#spreadsheet_feed_entry is deprecated and will be removed " +
      "in the next version.")
  return spreadsheet_feed_entry_internal(params)
end

#spreadsheet_feed_entry_internal(params = {}) ⇒ Object

:nodoc



93
94
95
96
97
98
99
# File 'lib/google_drive_v0/spreadsheet.rb', line 93

def spreadsheet_feed_entry_internal(params = {}) #:nodoc
  if !@spreadsheet_feed_entry || params[:reload]
    @spreadsheet_feed_entry =
        @session.request(:get, self.spreadsheet_feed_url).css("entry")[0]
  end
  return @spreadsheet_feed_entry
end

#spreadsheet_feed_urlObject

Spreadsheet feed URL of the spreadsheet.



55
56
57
# File 'lib/google_drive_v0/spreadsheet.rb', line 55

def spreadsheet_feed_url
  return "https://spreadsheets.google.com/feeds/spreadsheets/private/full/#{self.key}"
end

#tablesObject

DEPRECATED: Table and Record feeds are deprecated and they will not be available after March 2012.

Returns list of tables in the spreadsheet.



232
233
234
235
236
237
238
# File 'lib/google_drive_v0/spreadsheet.rb', line 232

def tables
  warn(
      "DEPRECATED: Google Spreadsheet Table and Record feeds are deprecated and they " +
      "will not be available after March 2012.")
  doc = @session.request(:get, self.tables_feed_url)
  return doc.css("entry").map(){ |e| Table.new(@session, e) }.freeze()
end

#tables_feed_urlObject

DEPRECATED: Table and Record feeds are deprecated and they will not be available after March 2012.

Tables feed URL of the spreadsheet.



71
72
73
74
75
76
# File 'lib/google_drive_v0/spreadsheet.rb', line 71

def tables_feed_url
  warn(
      "DEPRECATED: Google Spreadsheet Table and Record feeds are deprecated and they " +
      "will not be available after March 2012.")
  return "https://spreadsheets.google.com/feeds/#{self.key}/tables"
end

#title(params = {}) ⇒ Object

Title of the spreadsheet.

Set params[:reload] to true to force reloading the title.



37
38
39
40
41
42
# File 'lib/google_drive_v0/spreadsheet.rb', line 37

def title(params = {})
  if !@title || params[:reload]
    @title = spreadsheet_feed_entry_internal(params).css("title").text
  end
  return @title
end

#worksheet_by_title(title) ⇒ Object

Returns a GoogleDriveV0::Worksheet with the given title in the spreadsheet.

Returns nil if not found. Returns the first one when multiple worksheets with the title are found.



208
209
210
# File 'lib/google_drive_v0/spreadsheet.rb', line 208

def worksheet_by_title(title)
  return self.worksheets.find(){ |ws| ws.title == title }
end

#worksheetsObject

Returns worksheets of the spreadsheet as array of GoogleDriveV0::Worksheet.



186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
# File 'lib/google_drive_v0/spreadsheet.rb', line 186

def worksheets
  doc = @session.request(:get, @worksheets_feed_url)
  if doc.root.name != "feed"
    raise(GoogleDriveV0::Error,
        "%s doesn't look like a worksheets feed URL because its root is not <feed>." %
        @worksheets_feed_url)
  end
  result = []
  doc.css("entry").each() do |entry|
    title = entry.css("title").text
    updated = Time.parse(entry.css("updated").text)
    url = entry.css(
      "link[rel='http://schemas.google.com/spreadsheets/2006#cellsfeed']")[0]["href"]
    result.push(Worksheet.new(@session, self, url, title, updated))
  end
  return result.freeze()
end