QuickBaseClient.rb: A Ruby language wrapper for the QuickBase HTTP API

This document explains what QuickBaseClient.rb is and the kinds of tasks it is suited for, and provides examples of how to accomplish those tasks. The 2/13/2006 version of this document can be considered about 3/4trs complete; some sections are obviously waiting to be filled in and a couple more sections need to be added.

What is QuickBaseClient.rb?

QuickBaseClient.rb is collection of routines written in the Ruby programming language that enable developers to create, modify and query QuickBase applications using the Ruby language. The core routines closely mimic the 'API_' items described in the QuickBase HTTP API Reference document. Additional 'helper' routines are included that reduce the amount of code developers must write to accomplish common tasks.

Also included in QuickBaseClient.rb is a simple utility that allows users to type commands at a prompt to access and manipulate QuickBase applications. Commands may be recorded into files and 'replayed' later. QuickBaseClient.rb contains a tiny web server that can 'replay' command files specified in a browser Address box or in a link in a web page.

Who is responsible for QuickBaseClient.rb?

QuickBaseClient.rb was created by Gareth Lewis who is an Intuit employee but isn't a member of the QuickBase team. It is currently maintained by Gareth outside his normal work hours.

Who should use QuickBaseClient.rb?

  1. People responsible for maintaining or enhancing QuickBase applications, especially people with programming experience.
  2. Software developers who want to include QuickBase in the 'back end' for applications.
  3. Non-programmers who use small programs written for them may find it straightforward to make minor changes to the programs that use QuickBaseClient.rb.
  4. Any QuickBase user willing to learn the commands available in the 'CommandLineClient' utility in QuickBaseClient.rb.

What kinds of things can QuickBaseClient.rb be used for?

  1. Creating large numbers of records that vary slightly. An example is creating a record for every day between two dates entered by the user.
  2. Modifying fields in a large numbers of records, especially when 'search and replace' is insufficient. An example is to prepend 'Mr. ' to a 'Name' field if a 'Male' box is checked.
  3. Setting fields based on data in multiple other records or tables. For example, a field could total the number of records in a table specifed by the user that contain a value specified by the user.
  4. Creating records automatically at specified times or when certain events occur, such as when a computer is turned on, after a particular user enters a record in another database or clicks a link field in a QuickBase record, or to make QuickBase send an email every hour until a certain time.
  5. Transforming records into useful formats not directly supported by QuickBase, such as RSS, PDF or JSON files, and storing them in QuickBase.
  6. Typing a single command instead of going through a series of steps to accomplish a daily task. For example, uploading the latest copy of a spreadsheet into particular database record by typing 'upf'.
  7. Integrating QuickBase with other applications, including applications not written in Ruby. An example might be an instant messenger written in C# that saves instant message sessions in QuickBase. Another example is to update a stock price field in QuickBase by reading it from another website.
  8. Emailing data from QuickBase using your own 'From:' email address.
  9. Triggering any of the above by clicking a link in any web page or by typing the link into a browser Address box. For example, clicking a link in a QuickBase record could upload the latest copy of a file from another user's computer into a different QuickBase table.

Like the Java, Perl and Visual Basic SDKs for QuickBase, QuickBaseClient.rb is limited by the amount of functionality that QuickBase allows external programs to access via its HTTP API. Like those SDK languages, Ruby is a full-fledged programming language with unlimited ability to create and transform data and present it in different formats. The 'sweet spot' for these SDKs and QuickBaseClient.rb is small applications and utilities that are straightforward to create, integrate with QuickBase and other applications, and manipulate QuickBase data in ways that are difficult to accomplish through the QuickBase UI. Ruby's particular sweet spot is similar to Perl's: utilities with limited UI requirements that automate tedious data manipulation tasks or that link applications together. Ruby owes a lot to Perl, but its Smalltalk heritage makes Ruby a conceptually (and visually!) cleaner language and especially pleasant to work in.

What should QuickBaseClient.rb not be used for?

  1. Anything that is much easier to do 'manually' in the browser.

What is required to get started with QuickBaseClient.rb?

  1. The Ruby language interpreter. There is a great One-click Ruby installer for Windows. For other operating systems, go to the Ruby homepage
  2. Access to QuickBase (of course!).
  3. The QuickBaseClient.rb file.
  4. QuickBaseClient.rb will make a lot more sense once you've read the QuickBase HTTP API Reference document.
  5. If you are new to Ruby, the best book to read is Programming Ruby. The first edition of the book is free online and is also installed as part of the One-click Ruby installer for Windows.
  6. Any text editor can be used to write Ruby programs, but the (free!) Scite editor installed with the One-click Ruby installer for Windows has good support for editing and running Ruby programs, and the ActiveState Komodo product is likely to be very good.

Please remember that it's always a good idea to back up important data before trying out any program or utility that modifies the data. In QuickBase, an application can be copied using the Go To menu, selecting Miscellaneous, then 'Copy with Data'. It is also possible to copy applications using this Ruby wrapper.

A simple Ruby program that uses QuickBaseClient.rb

require 'QuickBaseClient'
qbc = QuickBase::Client.new( "my_username", "my_password", "My QuickBase Database" )
qbc.makeSVFile( "MyCSVFile.csv" )
qbc.signOut

A command file that achieves the same results

signin my_username my_password
open My QuickBase Database
exportfile MyCSVFile.csv
quit

An explanation of the program and the command file

The program:

require 'QuickBaseClient'
This line tells Ruby to find QuickBaseClient.rb and make its contents available for this program.

qbc = QuickBase::Client.new( "my_username", "my_password", "My QuickBase Database" )
This line signs into QuickBase using the specified user name and password using the QuickBase API_Authenticate call, and finds the application named "My QuickBase Database" using the API_FindDBbyName call. If the username and password are valid, subsequent requests to QuickBase include a 'ticket' instead of the username and password. QuickBase::Client keeps the ticket in its @ticket variable. The active QuickBase application or table has an id, which you can see in your browser's Address box when a QuickBase application is open. QuickBase::Client keeps this id in @dbid so that it doesn't have to be specified for every request to the active table.


qbc.makeSVFile( "MyCSVFile.csv" )
This line runs a query to retrieve all the records and fields from "My QuickBase Database" and write the results to a CSV (comma-separated values) file called MyCSVFile.csv. The field names are written on the first line of the file. Fields that contain a comma are surrounded by quotes. To change the field separator from a comma to something else, a second parameter can be supplied, e.g. qbc.makeSVFile( "MyTSVFile.txt", "\t" ) will create a TAB-delimited file.

qbc.signOut
This line signs out of QuickBase.

The command file:

signin my_username my_password
This line signs into QuickBase as the user "my_username", with the password "my_password".

open My QuickBase Database
This line makes "My QuickBase Database" the active application.

exportfile MyCSVFile.csv
This line queries all the records and fields from "My QuickBase Database" and writes the results to MyCSVFile.csv.

quit
This line automatically signs out QuickBase then ends the command session.

Running the program and the command file

To run the program:-
  1. Open the qbc.makeCSVFile.rb file.
  2. Change the username, password, application name to something valid that you can access.
  3. Change 'MyCSVFile.csv' to another file name, if you prefer.
  4. At the operating system prompt, type ruby qbc.makeCSVFile.rb.
To run the command file:-
  1. Open the qbc.makeCSVFile.qbc file.
  2. Change the username, password, application name to something valid that you can access.
  3. Change 'MyCSVFile.csv' to another file name, if you prefer.
  4. At the operating system prompt, type ruby QuickBaseClient.rb run qbc.makeCSVFile.qbc.

Running an interactive command session

To run an interactive command session:-
  1. Open the operating system prompt window
  2. Change to the folder containing the file QuickBaseClient.rb
  3. Type ruby QuickBaseClient.rb run at the operating system prompt.
You should see
 Enter a command from the list of available commands.
 The list of commands may change after each command.
 Type TABs, commas, or spaces between parts of a command.
 Use double-quotes if your commands contain TABs, commas or spaces.

 e.g. addfield "my text field" text


Commands available:

 quit(q): End this command session
 usage: Show how to use this program
 ruby 'rubycode': run a line of ruby language code
 run(r) 'filename': run the commands in a file
 record 'filename': records your commands in a file
 signin(si) 'username,password': Sign into QuickBase
 uselog(ul) 'log file': Logs requests and responses to a file

Enter a command:

You will most likely want to run 'signin username password' as the next command. After that, you will see:-
Commands available:

 quit(q): End this command session
 usage: Show how to use this program
 ruby 'rubycode': run a line of ruby language code
 run(r) 'filename': run the commands in a file
 record 'filename': records your commands in a file
 create 'application name,description': Create an application
 listapps(la) : Lists the applications you can access
 open(o) 'application name': Open an application
 print(p) : Prints the results of the last command
 signout(so) : Sign out of QuickBase
 uselog(ul) 'log file': Logs requests and responses to a file

Enter a command:
You will most likely want to run 'signin username password' as the next command. After that, you will see:-
Commands available:

 quit(q): End this command session
 usage: Show how to use this program
 ruby 'rubycode': run a line of ruby language code
 run(r) 'filename': run the commands in a file
 record 'filename': records your commands in a file
 addfield(af) 'field name,field type': Add a field to the active table
 addfieldchoices 'field name,[choice1,choice2]': Add value choices for a field
 addrecord(ar) : Add a record to the active table
 changerecords 'field,value,testfld,test,testval': Conditionally set field value
 copy 'name,desc,keep data?': Copy an application, with/out data
 create 'application name,description': Create an application
 deleteallrecords : Delete all records
 deletefield 'field name': Delete a field from the active table
 deleterecords 'test field,test,test value': Conditionally delete records
 deletetable : Delete the active table
 exportfile(ef) 'file name': Export records to a CSV file
 importfile(if) 'file name': Import records from a CSV file
 listapps(la) : Lists the applications you can access
 open(o) 'application name': Open an application
 print(p) : Prints the results of the last command
 select(sel) 'query name': Select records using a query name
 signout(so) : Sign out of QuickBase
 uploadfile(ulf) 'file name,file attachment field name': Upload a file into a new record
 uselog(ul) 'log file': Logs requests and responses to a file

Enter a command:
When a particular record is 'active', the 'setfield' and 'updatefile' commands are added to the above list.

For Ruby programmers: in addition to the above commands, any method in QuickBase::Client can be also be run as a command. e.g. typing _getRecordInfo "1" will get the details of the record from the active table that has the Record ID# of "1". The same results can be obtained by typing ruby _getRecordInfo( "1" ) .

Running a command file from a browser Address box or a link in a web page

  1. At a prompt, type ruby QuickBaseClient.rb runwebclient
  2. Open a browser and type http://127.0.0.1:2358/qbc/qbc.makeCSVFile.qbc into the Address box.
"127.0.0.1" tells a browser to look on the user's own machine for a web server. This means that people on different computers would all have to have QuickBaseClient.rb and qbc.makeCSVFile.qbc on their computer, and qbc.makeCSVFile.qbc could do different things for each user. It is more likely that everyone will expect the same behavior when a specific URL is entered or clicked, and that most people will not have QuickBaseClient.rb or Ruby on their computer. To run command files that are on a particular machine:-
  1. Find out the IP address or web-accessible name of the machine.
  2. On that machine, type ruby QuickBaseClient.rb runwebclient <IP Address>
  3. In the browser Address box or web page link, use http://<IP Address>:2358/qbc/qbc.makeCSVFile.qbc.

QuickBaseClient.rb Cookbook: Small programs for common tasks

You can find these examples and more in the QuickBase API Cookbook (Latest 'read-only' version).

Note that all the examples below can also be run by typing each line in an interactive command session. For the Program versions, simply type ruby at the beginning of each line.

-------------------------------------------------------------------------

Uploading a document into a new record

Program
Command File
require 'QuickBaseClient'
qbc = QuickBase::Client.new( "my_username", "my_password", "my_application" )
# "Documents" is a table in "my_application"
# "Author" and "Desc" are additional field values to set in the record

qbc.lookupChdbid( "Documents" )
qbc.uploadFile( qbc.dbid, "my_file.doc", "Document", { "Author" => "my_name", "Desc" => "Latest revision" } )
qbc.signOut
si my_username my_password
o my_application
use Documents
ulf my_file.doc Document
so
-------------------------------------------------------------------------

Updating a document in an existing record

Program
Command File
require 'QuickBaseClient'
qbc = QuickBase::Client.new( "my_username", "my_password", "my_application" )
qbc.lookupChdbid( "Documents" )
# "12" is the number of the record (Record ID#) to be modified
# "Document" is the name of the field containing a file attachment
# "Version" and "Date" are additional field values to modify in the record

qbc.updateFile( qbc.dbid, "12", "my_file.doc", "Document", { "Version" => "6", "Note" => "Updated 01/30/2006" } )
qbc.signOut
si my_username my_password
o my_application
use Documents
udf my_file.doc Document
so
-------------------------------------------------------------------------

Making a backup copy of an application

Program
Command File
require 'QuickBaseClient'
qbc = QuickBase::Client.new( "my_username", "my_password", "my_application" )
# "true" at the end means copy all the data, not just the structure of the database

qbc.cloneDatabase( qbc.dbid, "my_application_backup", "backup of my_application", true )
qbc.signOut
si my_username my_password
o my_application
copy my_application_backup "backup of my_application"
so
-------------------------------------------------------------------------

Deleting all the records that meet a certain condition

Program
Command File
require 'QuickBaseClient'
qbc = QuickBase::Client.new( "my_username", "my_password", "my_application" )
# delete all records with a "Status" field value equal to "closed"

qbc.deleteRecords( "Status", "==", "closed" )
qbc.signOut
si my_username my_password
o my_application
deleterecords Status == closed
so
-------------------------------------------------------------------------

Modifying all the records that meet a certain condition

Program
Command File
require 'QuickBaseClient'
qbc = QuickBase::Client.new( "my_username", "my_password", "my_application" )
# set the checkbox field "Inactive" to "true" in all records with a "Status" field value equal to "closed"

qbc.changeRecords( "Inactive", "true", "Status", "==", "closed" )
qbc.signOut
si my_username my_password
o my_application
changerecords Inactive true Status == closed
so
-------------------------------------------------------------------------

Making the records in a table match the contents of a CSV file

Program
Command File
require 'QuickBaseClient'
qbc = QuickBase::Client.new( "my_username", "my_password", "my_application" )
qbc.lookupChdbid( "Imported data" )
# delete all the records in the "Imported data" table then
# import new data from a CSV file. The field names must be at the top of the file.

qbc._purgeRecords
qbc.importCSVFile( "ImportedData.csv" )
qbc.signOut
si my_username my_password
o my_application
use Imported Data
deleteallrecords
importfile ImportedData.csv
so
-------------------------------------------------------------------------

Making the records in a table match the contents of a Microsoft Excel spreadsheet

Program
Command File
require 'QuickBaseClient'
qbc = QuickBase::Client.new( "my_username", "my_password", "my_application" )
qbc.lookupChdbid( "Imported Excel data" )
# delete all the records in the "Imported Excel data" table then
# import new data from an Excel file. The field names must be at the top of the file.
# 'h' is the letter of the last column to import.
# Note: any commas (',') in the data are converted to semi-colons (';').

qbc._purgeRecords
qbc._importFromExcel( "ImportedExcelData.xls", 'h' )
qbc.signOut
si my_username my_password
o my_application
use Imported Excel Data
deleteallrecords
importexcelfile ImportedExcelData.xls h
so
-------------------------------------------------------------------------

Deleting duplicate records from a table

Program
Command File
require 'QuickBaseClient'
qbc = QuickBase::Client.new( "my_username", "my_password", "my_application" )
# Except for the most recent records, delete all the records with
# the same values for 'First Name' and 'Last Name'

qbc.deleteDuplicateRecords( [ "First Name", "Last Name" ] )
qbc.signOut
si my_username my_password
ruby deleteDuplicateRecords( [ "First Name", "Last Name" ] )
so
-------------------------------------------------------------------------

Making multiple copies of a record

Program
Command File
require 'QuickBaseClient'
qbc = QuickBase::Client.new( "my_username", "my_password", "my_application" )
# make 6 copies of record 1

qbc.copyRecord( "1", 6 )
qbc.signOut
si my_username my_password
ruby qbc.copyRecord( "1", 6 )
so

Programs for more complex tasks

Adding records for every day between two dates


require 'QuickBaseClient'
require 'Date'

qbc = QuickBase::Client.new( "my_username", "my_password", "my_application" )

d = Date.new( 2006, 1, 1 )
d.upto( Date.new( 2007, 1, 1 ) ){ |date| 
   
    ymd = date.to_s.split( /-/ )
    mdy = "#{ymd[1]}-#{ymd[2]}-#{ymd[0]}"
   
    qbc.clearFieldValuePairList
    fvl = qbc.addFieldValuePair( "Date field", nil, nil, "#{mdy}" )

    qbc.addRecord( datefield, fvl )
}

Updating the latest copy of a file in a particular Quickbase record every hour


require 'QuickBaseClient'

loop {
  qbc = QuickBase::Client.new( "my_username", "my_password", "my_application" )
  qbc.lookupChdbid( "Documents" ) # the table containing the files

  # "12" is the number of the record (Record ID#) to be modified
  # "Document" is the name of the field containing a file attachment
  # "Version" and "Date" are additional field values to modify in the record

  qbc.updateFile( qbc.dbid, "12", "my_file.doc", "Document", { "Version" => "6",   "Note" => "Updated 01/30/2006" } )

  qbc.signOut
  qbc = nil

  # wait one hour
  sleep(60*60)
}

Automatically removing all the records from a particular Quickbase table every hour


require 'QuickBaseClient'

loop {
  qbc = QuickBase::Client.new( "my_username", "my_password", "my_application" )
  qbc.lookupChdbid( "my_table" ) # the table to empty
  qbc._purgeRecords
  qbc.signOut
  qbc = nil
  sleep(60*60)
}

Creating an RSS view of a Quickbase table and uploading it into a QuickBase record


require 'QuickBaseClient'

qbc = QuickBase::Client.new( "my_username", "my_password", "my_application" )
qbc.lookupChdbid( "my_table" ) 

# get all the records from the table using the 'List Changes' query
qbc.doQuery( qbc.dbid, nil, nil, "List Changes" )

rssText =  "<?xml version=\"1.0\" ?>\n"
rssText << " <rss version=\"2.0\">\n" 
rssText << "  <channel>\n" 

rssText << "   <title>my_table - RSS view</title>\n"

rssText << "   <link>\n"
rssText << qbc.requestURL
rssText << "\n   </link>\n"

rssText << "   <description>(#{Time.now})</description>\n"

qbc.records.each { |record| 
   if record.is_a?( REXML::Element) and record.name == "record"
   
      itemTitle = ""
      itemLink = ""
      itemText = ""
     
      record.each{ |field|
         if field.is_a?( REXML::Element)
            case field.attributes[ "id" ]
	       
	       # the field with the QuickBase id "6" contains the title for on RSS item
	       when "6" then itemTitle = field.text if field.has_text? 
	       
	       # the field with the QuickBase id "10" contains the link to the record itself
	       when "10" then itemLink = field.text if field.has_text?
	       
	       # the field with the QuickBase id "26" contains the main text from the record
	       when "26" then itemText = field.text if field.has_text?
	    end
	 end
      }
      
     # build the text for one RSS item
      rssText << "    <item>\n"
      rssText << "     <title>#{qbc.encodeXML(itemTitle)}</title>\n"
      rssText << "     <link>#{qbc.encodeXML(itemLink)}</link>\n"
      rssText << "     <description>#{qbc.encodeXML(itemText)}</description>\n"
      rssText << "    </item>"
     
   end
}

rssText << "  </channel>\n" 
rssText << " </rss>\n" 

# Write all the RSS text for the table into a file on the local hard drive
File.open( "my_table.rss.xml", "w" ) { |file| file.write( rssText ) }

# Switch to a different table in "my_application" that already contains RSS files
qbc.lookupChdbid( "rss table" )

# Put the file we've just created into record 4, into the file attachment field called "RSS File"
qbc.updateFile( qbc.dbid, "4", "my_table.rss.xml", "RSS File" )

qbc.signOut

QuickBaseClient.rb Reference

Class QuickBase::Client

API wrapper methods
These methods closely mimic the 'API_' requests as specified in the QuickBase HTTP API Reference document.
Each method expects the 'Input Parameters' of the equivalent HTTP API request.
Each method returns the 'Output Parameters' of the equivalent HTTP API response.
(Ruby methods can return multiple values)
Input and Output Parameters are all stored in '@' member variables.   
This makes it easy to reuse parameters across multiple requests.
Methods returning lists can be called with an iteration block, e.g. doQuery(){|record|, puts record } .

Each method with dbid as the first parameter has a corresponding method with '_' before the name.
The '_' methods re-use @dbid instead of a requiring the dbid parameter. 
  1. def addField( dbid, label, type, mode = nil )
    Adds a new field to a table. dbid = the table ID, label = text to appear on screen for this field, type = the field type.
  2. def addRecord( dbid, fvlist = nil, disprec = nil, fform = nil, ignoreError = nil, update_id = nil )
    Adds a new record to a table. fvlist is an instance of a FieldValuePair list. Use addFieldValuePair() to build that list of fields
    to use for this parameter.
  3. def addReplaceDBPage( dbid, pageid, pagename, pagetype, pagebody, ignoreError = nil )
    Add or replace a page associated with a table.
  4. def addUserToRole( dbid, userid, roleid )
    Add a user to a role in an application. The dbid must be an application dbid, not a table dbid.
  5. def authenticate( username, password, hours = nil )
    Signs into QuickBase using the specified username and password.
    Subsequent QuickBase requests use the @ticket that is set as a result of this call.
  6. def changePermission( dbid, uname, view, modify, create, delete, saveviews, admin )
    Create, update, delete access rights for a user. NOTE: API_ChangePermission is no longer a valid QuickBase HTTP API request.
  7. def changeRecordOwner( dbid, rid, newowner )
    Change the owner of a record.
  8. def changeUserRole( dbid, userid, roleid, newroleid )
    Change the role of a user in a particular application. The dbid must be an application dbid, not a table dbid.
  9. def cloneDatabase( dbid, newdbname, newdbdesc, keepData )
    Copy an application, with ot without data.
  10. createDatabase( dbname, dbdesc )
    Create a new application.
  11. def createTable( pnoun, application_dbid = @dbid )
    Add a table to an application. pnoun should be a plural noun, such as 'Employees'. The application_dbid must be an application dbid, not a table dbid.
  12. def deleteDatabase( dbid )
    Delete an application.
  13. def deleteField( dbid, fid )
    Remove a field from a table.
  14. def deleteRecord( dbid, rid )
    Delete a record.
  15. def doQuery( dbid, query = nil, qid = nil, qname = nil, clist = nil, slist = nil, fmt = "structured", options = nil )
    Retrieve a list of records. By default, all records will be retrieved with all columns.
  16. def _doQueryName( queryName )
    This is not a direct API wrapper. It is a simple way to use a named query (e.g. 'List All') for the active table.
  17. def downLoadFile( dbid, rid, fid, vid = "0" )
    Downloads a file.
  18. def editRecord( dbid, rid, fvlist, disprec = nil, fform = nil, ignoreError = nil, update_id = nil )
    Modifies an exsiting record. fvlist is an instance of a FieldValuePair list.
    Use addFieldValuePair() to build the @fvlist list of fields to use for this parameter.
  19. def fieldAddChoices( dbid, fid, choice )
    Adds choices to a multiple-choice text field.
  20. def fieldRemoveChoices( dbid, fid, choice )
    Removes choices from a multiple-choice text field.
  21. def findDBByname( dbname )
    Set the active application using its name. e.g. 'QuickBase Community Forum'.
  22. def genAddRecordForm( dbid, fvlist = nil )
    Retrieves the HTML for adding a record to a table.
  23. def genResultsTable( dbid, query = nil, clist = nil, slist = nil, jht = nil, jsa = nil, options = nil )
    Retrieves the HTML for displaying the results of a query.
  24. def getAppDTMInfo( dbid )
    The fastest way to get the last time that an application was modified and each of its tables was last modified, or the last time one particular table was modified.
  25. def getDBInfo( dbid )
    Retrieves the properties for table.
  26. def getDBPage( dbid, pageid, pagename = nil )
    Retrieves a page associated with a table.
  27. def getDBvar( dbid, varname )
    Retrieves the value of an application variable. The dbid must be for an application , not a table.
  28. def getNumRecords( dbid )
    Retrieves the number of records in a table.
  29. def getOneTimeTicket()
    Get a QuickBase ticket that is valid only for the next 5 minutes.
  30. def getRecordAsHTML( dbid, rid, jht = nil )
    Retrieves a record in HTML format.
  31. def getRecordInfo( dbid, rid )
    Retrieves all the field values for a specified record.
  32. def getRoleInfo( dbid )
    Retrieves the list of roles defined for an application. The dbid must be for an application, not a table.
  33. def getSchema( dbid )
    Retrieves all the information about the fields in a table.
  34. getServerStatus
    Retrieves information about the QuickBase server.
  35. def getUserInfo( email = nil )
    Retrieves information about a particular user. Defaults to the user logged in via the API.
  36. def getUserRole( dbid, userid )
    Retrieves information about a particular user's role in an application. The dbid must be for an application, not a table.
  37. def grantedDBs( withembeddedtables = nil, excludeparents = nil, adminOnly = nil )
    Retrieves a list of applications accessible by the authenticated user.
  38. def importFromCSV( dbid, records_csv, clist, skipfirst = nil )
    Imports CSV data into a table. records_csv is a string containing the data.
  39. def listDBPages(dbid)
    Get the list of pages associated with an application. The dbid must be for an application, not a table.
  40. def provisionUser( dbid, roleid, email, fname, lname )
    Set up the information for a new QuickBase user, in preparation for calling sendInvitation(). The dbid must be for an application, not a table.
  41. def purgeRecords( dbid, query = nil, qid = nil, qname = nil )
    Deletes all the records from a table.
  42. def removeUserFromRole( dbid, userid, roleid )
    Removes a user from a particular role in a particular application. The dbid must be for an application, not a table.
  43. def renameApp( dbid, newappname )
    Rename an application. The dbid must be for an application, not a table.
  44. def runImport( dbid, id )
    Run a predefined QuickBase Import to get data into a particular table. The id is the numeric identifier of the import.
  45. def sendInvitation( dbid, userid )
    Send an email inviting a user to access an application. The dbid must be for an application, not a table.
  46. def setDBvar( dbid, varname, value )
    Set the value of an application variable. The dbid must be for an application, not a table.
  47. def setFieldProperties( dbid, properties, fid )
    Modifies the properties of a field in a table.
  48. def signOut()
    Signout from QuickBase.
  49. def userRoles( dbid )
    Get the list of roles for the users with access to a specific application.The dbid must be for an application, not a table.
Helper methods
These methods are focused on reducing the amount of code you 
have to write to get stuff done using the QuickBase::Client.
  1. def addOrEditRecord( dbid, fvlist, rid = nil, disprec = nil, fform = nil, ignoreError = nil, update_id = nil )
    Use this if you aren't sure whether a particular record already exists or not.
  2. def getRecord(rid, dbid = @dbid)
    Get a record as a Hash, using the record id and dbid .
  3. def iterateDBPages(dbid)
    Loop through the list of Pages for an application.
  4. def getDBPagesAsArray(dbid)
    Get an array Pages for an application. Each item in the array is a Hash.
  5. def Client.processDatabase( username, password, appname, chainAPIcalls = nil )
    This class method 
    
       - creates a QuickBase::Client, 
       - signs into QuickBase 
       - connects to a specific application
       - runs code in the associated block 
       - signs out of QuickBase
       
    e.g. QuickBase::Client.processDatabase( "user", "password", "my DB" ) { |qbClient,dbid| qbClient.getDBInfo( dbid ) }
    
  6. def chainAPIcallsBlock()
    This method changes all the API_ wrapper methods to return 'self' instead of their
    normal return values. The change is in effect only within the associated block.  
    This allows mutliple API_ calls to be 'chained' together without needing 'qbClient' in front of each call.  
    
    e.g. qbClient.chainAPIcallsBlock { 
              qbClient
                 .addField( @dbid, "a text field", "text" )
                 .addField( @dbid, "a choice field", "text" )
                 .fieldAddChoices( @dbid, @fid, %w{ one two three four five } )  
          }
    
  7. def setActiveRecord( dbid, rid )
    Set the active database and record for subsequent method calls.
  8. def setFieldValue( fieldName, fieldValue )
    Change a named field's value in the active record.
    e.g. setFieldValue( "Location", "Miami" )
  9. def setFieldValues( fields )
    Change several named fields' values in the active record, e.g. setFieldValue( {"Location" => "Miami", "Phone" => "343-4567" } )
  10. def changeRecords( fieldNameToSet, fieldValueToSet, fieldNameToTest, test, fieldValueToTest )
    Change a field's value in multiple records.   
    If the optional test field/operator/value are supplied, only records matching the test    
    field will be modified, otherwise all records will be modified. 
    
    e.g. changeRecords( "Status", "special", "Account Balance", ">", "100000.00" )
    
    
  11. def deleteRecords( fieldNameToTest = nil, test = nil, fieldValueToTest = nil)
    Delete all records in the active table that match 
    the field/operator/value. e.g. deleteRecords( "Status", "==", "inactive" ).
    To delete ALL records, call deleteRecords() with no parameters. 
    This is the same as calling _purgeRecords.
    
  12. def getAllValuesForFields( dbid, fieldNames, query = nil, qid = nil, qname = nil, clist = nil, slist = nil, fmt = "structured", options = nil )
    Get all the values for one or more fields from a specified table.
    e.g. getAllValuesForFields( "dhnju5y7", [ "Name", "Phone" ] )
    The results are returned in Hash, e.g. { "Name" => values[ "Name" ], "Phone" => values[ "Phone" ] }
    The parameters after 'fieldNames' are passed directly to the doQuery() API_ call.
    
  13. def getAllValuesForFieldsAsArray( dbid, fieldNames = nil, query = nil, qid = nil, qname = nil, clist = nil, slist = nil, fmt = "structured", options = nil )
    Get all the values for one or more fields from a specified table, as an Array of records.
    This also formats the field values instead of returning the raw value.
    
  14. def editRecords(dbid,fieldValuesToSet,query=nil,qid=nil,qname=nil)
    Set the values of fields in all records returned by a query.
    fieldValuesToSet must be a Hash of fieldnames+values, e.g. {"Location" => "Miami", "Phone" => "343-4567"}
    
  15. def iterateRecords( dbid, fieldNames, query = nil, qid = nil, qname = nil, clist = nil, slist = nil, fmt = "structured", options = nil )
    Loop through records returned from a query. Each record is a field+value Hash.
    e.g. iterateRecords( "dhnju5y7", ["Name","Address"] ) { |values| puts values["Name"], values["Address"] }
    
  16. def iterateFilteredRecords( dbid, fieldNames, query = nil, qid = nil, qname = nil, clist = nil, slist = nil, fmt = "structured", options = nil )
    Same as iterateRecords but with fields optionally filtered by Ruby regular expressions.
    e.g. iterateFilteredRecords( "dhnju5y7", [{"Name" => "[A-E].+}","Address"] ) { |values| puts values["Name"], values["Address"] }
    
  17. def getFilteredRecords( dbid, fieldNames, query = nil, qid = nil, qname = nil, clist = nil, slist = nil, fmt = "structured", options = nil )
    e.g. getFilteredRecords( "dhnju5y7", [{"Name" => "[A-E].+}","Address"] ) { |values| puts values["Name"], values["Address"] }
    
  18. def iterateJoinRecords(tablesAndFields)
    Get records from two or more tables and/or queries with the same value in a 
    'join' field and loop through the joined results.
    The 'joinfield' does not have to have the same name in each table.
    Fields with the same name in each table will be merged, with the value from the last 
    table being assigned. This is similar to an SQL JOIN.
    
  19. def getJoinRecords(tablesAndFields)
    Get an array of records from two or more tables and/or queries with the same value in a 'join' field.
    The 'joinfield' does not have to have the same name in each table.
    Fields with the same name in each table will be merged, with the value from the last 
    table being assigned. This is similar to an SQL JOIN.
    
  20. def iterateUnionRecords(tables,fieldNames)
    Get values from the same fields in two or more tables and/or queries and loop through the merged results.
    The merged records will be unique. This is similar to an SQL UNION.
    
  21. def getUnionRecords(tables,fieldNames)
    Returns an Array of values from the same fields in two or more tables and/or queries.
    The merged records will be unique. This is similar to an SQL UNION.
    
  22. def iterateSummaryRecords( dbid, fieldNames,query = nil, qid = nil, qname = nil, clist = nil, slist = nil, fmt = "structured", options = nil )
    (The QuickBase API does not supply a method for this.) 
    Loop through summary records, like the records in a QuickBase Summary report.
    Fields with 'Total' and 'Average' checked in the target table will be summed and/or averaged.
    Other fields with duplicate values will be merged into a single 'record'.
    The results will be sorted by the merged fields, in ascending order.
     e.g. -  
        iterateSummaryRecords( "vavaa4sdd", ["Customer", "Amount"] ) {|record| 
           puts "Customer: #{record['Customer']}, Amount #{record['Amount']}
        } 
     would print the total Amount for each Customer, sorted by Customer.
    
  23. def getSummaryRecords( dbid, fieldNames,query = nil, qid = nil, qname = nil, clist = nil, slist = nil, fmt = "structured", options = nil )
    Same as iterateSummaryRecords, but returns an array of records to be processed
    without necessarily looping through the records.
    
  24. def iterateRecordInfos(dbid, query = nil, qid = nil, qname = nil, clist = nil, slist = nil, fmt = "structured", options = nil)
    Loop through a list of records returned from a query. 
    Each record will contain all the fields with values formatted for readability by QuickBase via API_GetRecordInfo.
    This is much slower than iterateRecords() because it every record is read in a separate call to QuickBase.
    
  25. def processRESTRequest(requestString)
    Returns table or record values using REST syntax. e.g. -
    puts processRESTRequest("8emtadvk/24105") # prints record 24105 from Community Forum
    puts processRESTRequest("8emtadvk") # prints name of table with dbid of '8emtadvk'
    puts qbc.processRESTRequest("6ewwzuuj/Function Name") # prints list of QuickBase Functions
    
  26. def min( dbid, fieldNames, query = nil, qid = nil, qname = nil, clist = nil, slist = nil, fmt = "structured", options = nil )
    Find the lowest value for one or more fields in the records returned by a query.
    e.g. minimumsHash = min("dfdfafff",["Date Sent","Quantity","Part Name"])
    
  27. def max( dbid, fieldNames, query = nil, qid = nil, qname = nil, clist = nil, slist = nil, fmt = "structured", options = nil )
    Find the lowest value for one or more fields in the records returned by a query.
    e.g. minimumsHash = min("dfdfafff",["Date Sent","Quantity","Part Name"])
    
  28. def count( dbid, fieldNames, query = nil, qid = nil, qname = nil, clist = nil, slist = nil, fmt = "structured", options = nil )
    Returns the number non-null values for one or more fields in the records returned by a query.
    e.g. countsHash = count("dfdfafff",["Date Sent","Quantity","Part Name"])
    
  29. def sum( dbid, fieldNames, query = nil, qid = nil, qname = nil, clist = nil, slist = nil, fmt = "structured", options = nil )
    Returns the sum of the values for one or more fields in the records returned by a query.
    e.g. sumsHash = sum("dfdfafff",["Date Sent","Quantity","Part Name"])
    
  30. def average( dbid, fieldNames, query = nil, qid = nil, qname = nil, clist = nil, slist = nil, fmt = "structured", options = nil )
    Returns the average of the values for one or more fields in the records returned by a query.
    e.g. averagesHash = sum("dfdfafff",["Date Sent","Quantity","Part Name"])
    
  31. def applyPercentToRecords( dbid, numericField, percentField, query = nil, qid = nil, qname = nil, clist = nil, slist = nil, fmt = "structured", options = nil)
    Query records, sum the values in a numeric field, calculate each record's percentage 
    of the sum and put the percent in a percent field each record.
    
  32. def applyDeviationToRecords( dbid, numericField, deviationField,
    Query records, get the average of the values in a numeric field, calculate each record's deviation
    from the average and put the deviation in a percent field each record.
    
  33. def percent( inputValues )
    Given an array of two numbers, return the second number as a percentage of the first number
    
  34. def deviation( inputValues )
    Given an array of two numbers, return the difference between the numbers as a positive number
    
  35. def getFieldChoices(dbid,fieldName=nil,fid=nil)
    Get an array of the existing choices for a multiple-choice text field.
    
  36. def getAllRecordIDs( dbid )
    Get an array of all the record IDs for a specified table.
    e.g. IDs = getAllRecordIDs( "dhnju5y7" ){ |id| puts "Record #{id}" }
    
  37. def findDuplicateRecordIDs( fnames, fids, dbid = @dbid, ignoreCase = true )
    Finds records with the same values in a specified
    list of fields.  The field list may be a list of field IDs or a list of field names.
    Returns a hash with the structure { "duplicated values" => [ rid, rid, ... ] }
    
  38. 
    
    
    
  39. def deleteDuplicateRecords( fnames, fids = nil, options = nil, dbid = @dbid )
    Finds records with the same values in a specified
    list of fields and deletes all but the first or last duplicate record.
    The field list may be a list of field IDs or a list of field names.
    The 'options' parameter can be used to keep the oldest record instead of the
    newest record, and to control whether to ignore the case of field values when
    deciding which records are duplicates.  Returns the number of records deleted.
    
  40. def copyRecord( rid, numCopies = 1, dbid = @dbid )
    Make one or more copies of a record.
    
  41. def importFromExcel( dbid, excelFilename, lastColumn = 'j', lastDataRow = 0, worksheetNumber = 1, fieldNameRow = 1, firstDataRow = 2, firstColumn = 'a' )
    Import data directly from an Excel file into a table. The field names are expected to be on line 1 by default.
    By default, data will be read starting from row 2 and ending on the first empty row. 
    Commas in field values will be converted to semi-colons.
    e.g. importFromExcel( @dbid, "my_spreadsheet.xls", 'h' )
    
  42. def importCSVFile( filename, dbid = @dbid, targetFieldNames = nil )
    Add records from lines in a CSV file. If dbid is not specified, the active table will be used. 
    values in subsequent lines.  The file must not contain commas inside field names or values.
    
  43. def importTSVFile( filename, dbid = @dbid, targetFieldNames = nil )
    Import records from a text file in Tab-Separated-Values format.
    
  44. def importSVFile( filename, fieldSeparator = ",", dbid = @dbid, targetFieldNames = nil )
    Add records from lines in a separated values text file, using  a specified field name/value separator.
    
     e.g. importSVFile( "contacts.txt", "::", "dhnju5y7", [ "Name", "Phone", "Email" ] )
      
     If targetFieldNames is not specified, the first line in the file
     must be a list of field names that match the values in subsequent lines.  
     
     If there are no commas in any of the field names or values, the file will be 
     treated as if it were a CSV file and imported using the QuickBase importFromCSV API call.
     Otherwise, records will be added using addRecord() for each line. 
     Lines with the wrong number of fields will be skipped.
     Double-quoted fields can contain the field separator, e.g. f1,"f,2",f3
     Spaces will not be trimmed from the beginning or end of field values.
    
  45. def uploadFile( dbid, filename, fileAttachmentFieldName, additionalFieldsToSet = nil )
    Upload a file into a new record in a table. Additional field values can optionally be set.
    e.g. uploadFile( "dhnju5y7", "contacts.txt", "Contacts File", { "Notes" => "#{Time.now}" }
    
  46. def updateFile( dbid, rid, filename, fileAttachmentFieldName, additionalFieldsToSet = nil )
    Update the file attachment in an existing record in a table. Additional field values can optionally be set.
    e.g. updateFile( "dhnju5y7", "6", "contacts.txt", "Contacts File", { "Notes" => "#{Time.now}" }
    
  47. def logToFile( filename )
    Log requests to QuickBase and responses from QuickBase in a file.
    Useful for utilities that run unattended.
    
  48. def eachRecord( records = @records )
    Iterate @records XML and yield only <record> elements.
    
  49. def doSQLInsert(sqlString)
    Translate a simple SQL INSERT statement to a QuickBase addRecord call.
    Note: This method is here primarily for Rails integration.
    Note: This assumes, like SQL, that your column (i.e. field) names do not contain spaces.
    
  50. def doSQLUpdate(sqlString)
    Translate a simple SQL UPDATE statement to a QuickBase editRecord call.
    Note: This method is here primarily for Rails integration.
    Note: This assumes, like SQL, that your column (i.e. field) names do not contain spaces.
    Note: This assumes that Record ID# is the key field in your table.
    
  51. def doSQLQuery( sqlString, returnOptions = nil )
    Translate a simple SQL SELECT statement to a QuickBase query and run it.
     
    If any supplied field names are numeric, they will be treated as QuickBase field IDs if
    they aren't valid field names. 
    
    e.g. doSQLQuery( "SELECT FirstName,Salary FROM Contacts WHERE LastName = "Doe" ORDER BY FirstName )
    e.g. doSQLQuery( "SELECT * FROM Books WHERE Author = "Freud" )
    
    Note: This method is here primarily for Rails integration.
    Note: This assumes, like SQL, that your column (i.e. field) names do not contain spaces.
    
'Plumbing' methods
These methods implement the core functionality to make the API_ wrapper methods
and Helper methods work.  Most programs will not need to use these methods directly 
and should avoid doing so.
  1. def initialize( username = nil, password = nil, appname = nil, useSSL = true, printRequestsandReponses = false, stopOnError = false, showTrace = false, org = "www" )
    Set printRequestsandReponses to true to view the XML sent to QuickBase and return from QuickBase.
    This can be very useful during debugging.
    
    Set stopOnError to true to discontinue sending requests to QuickBase after an error has occured with a request.
    
    Set showTrace to true to view the complete stack trace of your running program.  This should only be
    necessary as a last resort when a low-level exception has occurred.
    
  2. def Client.init( options )
    Class method to create an instance of QuickBase::Client using a Hash of parameters. This will often be nicer to use than new().
  3. def debugHTTPConnection()
    Causes useful information to be printed to the screen for every HTTP request.
  4. def setHTTPConnection( useSSL, org = "www" )
    initializes the connection to QuickBase.
  5. def setqbhost( useSSL, org = "www" )
    sets the QuickBase URL and port to use for requests.
  6. def setHTTPConnectionAndqbhost( useSSL, org = "www" )
    initializes the connection to QuickBase and sets the QuickBase URL and port to use for requests.
  7. def clientMethods()
    Return an array of all the public methods of this class.
    Used by CommandLineClient to verify commands entered by the user.
  8. def sendRequest( api_Request, xmlRequestData = nil )
    Sends requests to QuickBase and processes the reponses.
  9. def resetErrorInfo()
    Resets error info before QuickBase requests are sent.
  10. def getDBforRequestURL( api_Request )
    Determines whether the URL for a QuickBase request
    is for a specific database table or not, and returns the appropriate string
    for that portion of the request URL.
  11. def getAuthenticationXMLforRequest()
    Returns the request XML for either a ticket or a username and password.
  12. def isHTMLRequest?( api_Request )
    Returns whether a request will return HTML rather than XML.
  13. def toggleTraceInfo( showTrace )
    Turns program stack tracing on or off. If followed by a block,
    the tracing will be toggled on or off at the end of the block.
  14. def printRequest( url, headers, xml )
    Called by sendRequest if @printRequestsandReponses is true.
  15. def printResponse( code, xml )
    Called by sendRequest if @printRequestsandReponses is true.
  16. def printLastError
    Prints the error info, if any, for the last request sent to QuickBase.
  17. def processResponse( responseXML )
    Except for requests that return HTML, called by sendRequest to process the XML responses returned from QuickBase.
  18. def getErrorInfoFromResponse()
    Extracts error info from XML responses returned by QuickBase.
  19. def parseResponseXML( xml )
    Called by processResponse to put the XML from QuickBase into a DOM tree using the REXML module that comes with Ruby.
  20. def getResponseValue( field )
    Gets the value for a specific field at the top level of the XML returned from QuickBase.
  21. def getResponsePathValue( path )
    Gets the value of a field using an XPath spec., e.g. field/name.
  22. def getResponsePathValues( path )
    Gets an array of values at an Xpath in the XML from QuickBase.
  23. def getResponseElements( path )
    Gets an array of elements at an Xpath in the XML from QuickBase.
  24. def getResponseElement( path )
    Gets the element at an Xpath in the XML from QuickBase.
  25. def getAttributeString( element )
    Returns a string representation of the attributes of an XML element.
  26. def lookupField( fid )
    Returns the XML element for a field definition.
    getSchema() or doQuery() should be called before this.
  27. def lookupFieldData( fid )
    returns the XML element for a field returned by a getRecordInfo call.
  28. def getFieldDataValue(fid)
    Returns the value for a field returned by a getRecordInfo call.
  29. def getFieldDataPrintableValue(fid)
    Returns the printable value for a field returned by a getRecordInfo call.
  30. def lookupFieldIDByName( fieldName )
    Gets the ID for a field using the QuickBase field label.
  31. def getFieldNames( dbid = nil, lowerOrUppercase = "")
    Gets an array of the field names for a table.
  32. def getFieldIDs(dbid = nil)
    Gets an array of the field IDs for a table.
  33. def getApplicationVariables( dbid = nil )
    Get a Hash of application variables.
  34. def getApplicationVariable( variableName, dbid = nil )
    Get the value of an application variable.
  35. def lookupFieldNameFromID( fid )
    Gets a field name (i.e. QuickBase field label) using a field ID.
    getSchema() or doQuery() should be called before this.
  36. def lookupFieldName( element )
    Returns the name of field given an "fid" XML element.
  37. def lookupFieldType( element )
    Returns a QuickBase field type, given an XML "fid" element.
  38. def lookupFieldsByType( type )
    Returns an array of XML field elements matching a QuickBase field type.
  39. def lookupFieldPropertyByName( fieldName, property )
    Returns the value of a field property, or nil.
  40. def isRecordidField?( fid )
    Returns whether a field ID is the ID for the key field in a QuickBase table.
  41. def isTotalField?(fieldName)
    Returns whether a field will show a Total on reports.
  42. def isAverageField?(fieldName)
    Returns whether a field will show an Average on reports.
  43. def formatFieldValue( value, type, options = nil )
    Returns a human-readable string representation of a QuickBase field value.
    Also required for subsequent requests to QuickBase.
  44. def printChildElements( element, indent = 0 )
    Recursive method to print a simplified (yaml-like) tree of any XML element returned by QuickBase.
    Translates field IDs into field names. Very useful during debugging.
  45. def processChildElements( element, leafElementsOnly, block )
    Recursive method to process leaf and (optionally) parent elements of any XML element returned by QuickBase.
  46. def findElementByAttributeValue( elements, attribute_name, attribute_value )
    Returns the first XML sub-element with the specified attribute value.
  47. def findElementsByAttributeValue( elements, attribute_name, attribute_value )
    Returns an array of XML sub-elements with the specified attribute value.
  48. def findElementsByAttributeName( elements, attribute_name )
    Returns an array of XML sub-elements with the specified attribute name.
  49. def lookupRecord( rid )
    returns the XML element for a record with the specified ID.
  50. def lookupQuery( qid )
    returns the XML element for a query with the specified ID.
  51. def formatChdbidName( tableName )
    Given the name of a QuickBase table, returns the QuickBase representation of the table name.
  52. def lookupChdbid( tableName )
    Makes the table with the specified name the active table.
  53. def getTableName(dbid)
    Get the name of a table given its id.
  54. def getTableNames(dbid, lowercaseOrUpperCase = "")
    Get a list of the names of the child tables of an application.
  55. def getTableIDs(dbid)
    Get a list of the dbid's of the child tables of an application.
  56. def getNumTables(dbid)
    Get the number of child tables of an application.
  57. def getReportNames(dbid = @dbid)
    Get a list of the names of the reports (i.e. queries) for a table
  58. def toXML( tag, value = nil )
    Returns the XML for a specific item included in a request to QuickBase.
  59. def isValidFieldType?( type )
    Returns whether a given string represents a valid QuickBase field type.
  60. def isValidFieldProperty?( property )
    Returns whether a given string represents a valid QuickBase field property.
  61. def addFieldValuePair( name, fid, filename, value )
    Adds a field value to the list of fields to be set by the next addRecord() or editRecord() call to QuickBase.
    name - label of the field value to be set
    fid - id of the field to be set
    filename - if the field is a file attachment field, the name of the file that should be displayed in QuickBase.
    value - the value to set in this field. If the field is a file attachment field, the name of the file that should be uploaded into QuickBase.
  62. def replaceFieldValuePair( name, fid, filename, value )
    Replaces a field value in the list of fields to be set by the next addRecord() or editRecord() call to QuickBase.
  63. def clearFieldValuePairList
    clearFieldValuePairList: empty the list of field values used for the next addRecord() or editRecord() call to QuickBase.
  64. def verifyFieldList( fnames, fids = nil, dbid = @dbid )
    Given an array of field names or field IDs and a table ID, builds an array of valid field IDs and field names.
    Throws an exception when an invalid name or ID is encountered.
  65. def getQueryRequestXML( query = nil, qid = nil, qname = nil )
    Builds the request XML for retrieving the results of a query.
  66. getColumnListForQuery( id, name )
    Returns the clist associated with a query.
  67. def getSortListForQuery( id, name )
    Returns the slist associated with a query.
  68. verifyQueryOperator( operator, fieldType )
    Returns a valid query operator.
  69. def lookupBaseFieldTypeByName( fieldName )
    Get a field's base type using its name.
  70. def lookupFieldTypeByName( fieldName )
    Get a field's type using its name.
  71. def formatImportCSV( csv )
    Returns the string required for emebedding CSV data in a request.
  72. def formatDate( milliseconds, fmtString = nil, addDay = false )
    Returns the humad-readable string represntation of a date, given the milliseconds version of the date.
    Also needed for requests to QuickBase.
  73. def formatDuration( value, option = "hours" )
    Converts milliseconds to hours and returns the value as a string.
  74. def formatTimeOfDay(milliseconds, format = "%I:%M %p" )
    Returns a string format for a time of day value.
  75. def formatCurrency( value, options = nil )
    Returns a string format for a currency value.
  76. def formatPercent( value, options = nil )
    Returns a string format for a percent value, given the data from QuickBase.
  77. def dateToMS( dateString )
    Returns the milliseconds representation of a date specified in mm-dd-yyyy format.
  78. def splitString( string, fieldSeparator = "," )
    Converts a string into an array, given a field separator.
    '"' followed by the field separator are treated the same way as just the field separator.
  79. def escapeXML( char )
    returns the URL-encoded version of a non-printing character.
  80. def encodingStrings( reverse = false )
  81. Returns the list of string substitutions to make to encode or decode field values used in XML.
  82. def encodeXML( text, doNPChars = false )
    Modify the given string for use as a XML field value.
  83. def decodeXML( text )
    Modify the given XML field value for use as a string.
  84. def resetrid
    Set the @rid (active record ID) member variable to nil.
  85. def resetfid
    set the @fid (active field ID) member variable to nil.
  86. def onChangedDbid
    Reset appropriate member variables after a different table is accessed.
  87. def subscribe( event, handler )
    Subscribe to a specified event published by QuickBase::Client.
  88. def setLogger( logger )
    Set the instance of a QuickBase::Logger to be used by QuickBase::Client.
    Closes the open log file if necessary.

Nested class

class FieldValuePairXML
Encapsulates field values to be set and file uploads to be made during addRecord() and editRecord() calls.

Class QuickBase::EventHandler

To subscribe to events fired by the Client class, derive from this 
class, override handle( event ), and call subscribe( event, self ).  
See Client.subscribe() for a list of events.

Methods

  1. def handle( event )
    Override this method to be notified of events fired by QuickBase::Client. Events fired are :-
    1. onSendRequest
    2. onProcessResponse
    3. onSetActiveTable
    4. onRequestSucceeded
    5. onRequestFailed
    6. onSetActiveRecord
    7. onSetActiveField

Class QuickBase::Logger

To log QuickBase requests and responses to a file, make an instance
of this class and call Client.setLogger( loggerInstance ).
Call Client.setLogger( nil ) to turn logging off.
The log file is written in CSV format to make it importable by QuickBase.
Methods
  1. def initialize( filename, append = true )
    Opens filename as a log file. filename will be appended to if it already exists, unless append is false.
  2. def closeLogFile()
    Closes the log file and resets all variables.
  3. def changeLogFile( filename, append = true )
    Closes a log file that may already be open and opens filename. filename will be appended to if it already exists, unless append is false.
  4. def logRequest( dbidForRequestURL, api_Request, requestXML )
    Called by QuickBase::Client to log requests to QuickBase.
  5. def logResponse( error, responseXML )
    Called by QuickBase::Client to log responses from QuickBase.
  6. def getTimeString()
    Called by the logger to format a timestamp string to write to the log file.

Class QuickBase::CommandLineClient < Client

This implements an extensible command line interface to QuickBase.
Use setCommand() and setCommandAlias() to extend or modify the interface. 

Call run() to use the command line interactively.
Call run( filename ) to run the commands in a file.  
Commands entered during an interactive session can be recorded to a file.

In addition to the @commands loaded in initialize(), any public method 
from class Client can be used as a command, and any line of ruby code 
can be executed.

Nested class

class Command

Contains the data for commands:-
  1. name - name of the command shown to the user
  2. desc - description of the command shown to the user
  3. prerequisite - boolean expression controlling the availability of the command
  4. args - list of required parameters displayed to the user
  5. code - array of methods to call to run when this command is selected. Only the first method can expect any parameters.
  6. prompt - a prompt string that should accompany the command. nil by default.

Methods
  1. def initialize()
    Loads the default list of commands and their aliases.
  2. def showUsage()
    Displays a usage message.
  3. def setCommand( name, desc, prerequisite, args, code, prompt = nil )
    Add a command to the list of commands avaliable to the user.
  4. def setCommandAlias( anAlias, cmd )
    Sets the alias (abbreviation) for a command.
  5. def evalAvailableCommands()
    Build the list of available commands by testing the boolean expression associated with each command.
  6. def cmdString( command, include_desc = true )
    Builds the representation of a command displayed to the user.
  7. def showAvailableCommands()
    Builds the list of available commands and displays them.
  8. def prompt( promptString )
    If promptString is not nil, display the prompt string and wait for input from the user.
  9. def run( filename = nil )
    Runs the commands in a file, or runs a loop that displays the list of available commands and processes the user's input.

Class QuickBase::WebClient < CommandLineClient

A web server that responds to requests to run command files 
present on the local machine. This extends QuickBase via URLs on web pages.

e.g. if there is an 'uploadSpreadsheet.qbc' command file next to this QuickBaseClient.rb 
file on your machine, it can be run from a web page by starting 'WebClient.new' on your 
machine and placing 'http://127.0.0.1:2358/qbc/uploadSpreadsheet.qbc' in a link on the
web page.
  
Any request that does not include "/qbc/" will shut down the server.   
Methods
  1. def initialize( runNow = true, ipAddress = 'localhost', port = 2358 )
    Set the IP address and port, on which to run the web server, and optionally start the server. The IP address must be a valid address for the machine on which this server is run.
  2. def stop()
    Stops the web server.
  3. def start( ipAddress = 'localhost', port = 2358 )
    Starts the web server on a separate thread and processes requests to run command files. If the server is already running, it will be restarted.

Additional Ruby classes that build on QuickBase::Client

  1. QuickBaseEventNotifier.rb
  2. QuickBaseRSSGenerator.rb
  3. QuickBaseTwitterConnector.rb
  4. QuickBaseMisc.rb
  5. QuickBaseTextData.rb
  6. QuickBaseEmailer.rb

Appendices

Appendix 1: Submitting enhancement requests and bugs

Please submit enhancement requests in the QuickBase Community Forum.

Appendix 2: To Do List and future directions

To Do:-
  1. Expand test code to cover all methods and the most common cases.
  2. Make it as easy as possible for people to get started with QuickBaseClient.rb.
Future directions:-
  1. Add extensible classes to convert response XML to other formats. Start with the most useful formats.
  2. Add extensible classes to convert data and code into requests. Start with the most useful formats.
  3. Write a QuickBase adapter for Rails - DONE! Please see quickbase_adapter.rb.htm.

Appendix 3: Design goals behind the creation of QuickBaseClient.rb

  1. Since this project is being done outside normal work hours, the work is prioritized as if it will have to stop at any time.
  2. The first goal was to wrap the QuickBase HTTP API in a Ruby class in a way that minimizes the amount of additional documentation needed by users of the Ruby class. The assumption is that many developers will prefer working in Ruby to working in the other QuickBase SDK languages.
  3. The second goal is to write test code that reduces the need for manual regression testing of the Ruby class.
  4. Next is the addition of methods that reduce the amount of code developers have to write to perform common tasks using QuickBaseClient.rb. This will be ongoing.
  5. Next is the implementation of a small program that provides almost immediate benefit to users. The QuickBase::CommandLineClient serves this purpose and also helps in testing QuickBase::Client and understanding what additional functionality would be worth developing.