New Force.com and Database.com Ruby gem now available

As of Aug 30, 2011 a new ruby gem, databasedotcom, is available. See the blog post announcement for more details.

Abstract

Ruby on Rails is an open source framework geared to fast, agile web development. Using the Force.com Toolkit for Ruby, it is possible to manipulate Force.com data directly from Ruby and easily integrate it with Rails applications.

The Force.com Toolkit for Ruby is built on the ASF Soap Adapter Gem, which itself is based on the earlier ActiveSalesforce-Adapter Gem, but offers more functionality and flexibility. It includes several convenience classes for standard objects, Chatter methods and more SOQL options for data queries. The RForcedotcom Gem is now a prerequisite for use, rather than being embedded, which allows for future updates to that functionality to be handled independently.

Assumptions

This article assumes Rails 2.3 development as it was the most current during the toolkit’s development. Rails 3 offers new data functionality and integration into REST APIs and will be covered in a future article.

A functional Ruby on Rails environment is also assumed. For help in getting Ruby on Rails running on your platform, see the following articles, visit the Rails Wiki.

Getting Started

The toolkit requires two other Gems, RForcedotcom and Facets. They can be installed using the gem command. At the time of this writing, toolkit requires the Facets to use 2.8.4 as opposed to the most recent version. To install these two gems, use the following commands:

sudo gem install rforcedotcom

sudo gem install facets –v=2.8.4

To install and use toolkit with your application, update the initalizer in the environment.rb file with “config.gem "asf-soap-adapter", :lib => 'asf-soap-adapter'”, such as:

Rails::Initializer.run do |config|    
  #additional or existing configuration
  config.gem "asf-soap-adapter", :lib => 'asf-soap-adapter'   
end

And then, from the project root directory, run:

sudo rake gems:install

This Gem is also backwards compatible with the original ActiveSalesforce-Adapter Gem. To use the original adapter, replace the config.gem "asf-soap-adapter", :lib => 'asf-soap-adapter' declaration with config/environment.rb with config.gem “asf-soap-adapter”, :lib => “activerecord-activesalesforce-adapter“ in theRails::Initializer.run do |config| section.

In order to access data on Force.com, add the following entry to database.yml:

salesforce-default-realm:
    adapter: activesalesforce
    url: https://www.salesforce.com
    username: <username>
    password: <password+security token>
    api_version: 20.0

Using the username and password for the Force.com user with the correct profile to access the data you need. URL and API version are optional. To use a sandbox org, enter https://test.salesforce.com for URL. API version will default to 20, update it to access a specific version of the API.

Testing The Toolkit

Once installed, the toolkit can be testing by running the console. From the project root, run...

script/console

...to enter the console. Since the toolkit comes equipped with several convenience classes which form models for the standard Force.com objects, the following can be run directly from the console without generating any new models:

>> Salesforce::Contact.first

And if everything is configured correctly, it should respond with data:

-> <Salesforce::Contact id: "003T000000GqvJsIAJ", ... >

Adding Custom Objects

To add custom objects for use with an application, generate the model using the Salesforce namespace, for instance:

script/generate model Salesforce::CustomObject

And update the resulting model file to run set_table_name:

class Salesforce::CustomObject < Salesforce::SfBase     
  set_table_name ‘CustomObject’  
  # must be a valid Salesforce Table, otherwise, it will complain.   
end

Note that the use of “__c” from the Force.com naming convention does not apply within the Ruby code. The toolkit will translate as necessary. In addition, due to a constraint imposed by the ActiveRecord, custom objects with an underscore ('_') in their name (eg: Book_Review) are not supported.

Adding Views and Controllers

It’s possible to generate scaffold from the toolkit's models with a few edits. For example, to create some baseline code for editing Contact information:

script/generate scaffold Salesforce::Contact first_name:string last_name:string phone:string

Make sure that any view is properly referring to the Salesforce namespace, for example:

<td><%= link_to 'Edit', edit_salesforce_contact_path(h contact.id) %> <%=h contact.first_name %></td>

And have routes.rb acknowledge the namespace as well, by adding:

map.namespace :salesforce do |salesforce|
  	salesforce.resources :contacts
end

Since the toolkit does not require a local database for use, some of the controller methods will need to be altered form the normal. In this example, to update a record we get the salesforce_contact param, create an instance of a standard contact object, and then save it back to Salesforce (as opposed to the normal method of updating existing attributes.

# PUT /salesforce_contacts/1
# PUT /salesforce_contacts/1.xml
  def update
    @contact = Salesforce::Contact.update(params[:id], params[:salesforce_contact]) 

    respond_to do |format|
      if @contact.update_attributes(params[:contact])
        format.html { redirect_to(@contact, :notice => 'Salesforce::Contact was successfully updated.') }
        format.xml  { head :ok }
      else
        format.html { render :action => "edit" }
        format.xml  { render :xml => @contact.errors, :status => :unprocessable_entity }
      end
    end
  end

Enabling Session Authentication

Controllers can be enabled to use session IDs for authentication. To use this feature, add the following to /app/controllers/application.rb:

class ApplicationController < ActionController::Base
  before_filter ActiveSalesforce::SessionIDAuthenticationFilter 
end

Chatter Support

To avoid repetitive queries to find the appropriate data for chatter feeds, a convenience utility has been included to simplify the process. For example:

chatter_feed_finder = Salesforce::ChatterFeed.new
 # The following two lines shows how to get the account_feed.id. You can replace it with your

account_feed = Salesforce::AccountFeed.first

object_id = account_feed.id

feed_no_attachment = chatter_feed_finder.get_all_chatter_feeds_without_attachments(object_id, 'Account', user.connection.binding, 'test-session-id')

The following methods are included:

chatter_feed_finder.get_all_chatter_feeds_with_attachments(object_id, object_type, binding, directory_name, limit, get_attachment)
chatter_feed_finder.get_all_chatter_feeds_without_attachments(object_id, object_type, binding, directory_name, limit)
chatter_feed_finder.get_single_chatter_feed_with_attachment(feedpost_id, feed_type, binding, directory_name, limit)

Summary

The Force.com Toolkit for Ruby allows a Rails developer to take a new application and integrate with Force.com data quickly and easily. It provides an update to previous GEMs by adding more flexibility and configuration and several new utilities to make development less repetitive and simplifying access.

Additionally, a new REST based adapter has been made available, which addresses the underscore "_" problem associated with this SOAP adapter. The new adapter is called asf-rest-adapter. The source code is on Github.

References

About the Authors

Raymond Gao is a Ruby expert and Cloud Computing consultant. He is a dedicated open-source project developer. Raymond developed the original asf-soap-adapter GEM from which the Ruby Toolkit sprang. (The new REST adapter is also developed by him.) Catch him on his blog or, at least at the time of this writing, in France. His organization is called Are4Us Technologies.

Josh Birk is a Developer Evangelist at salesforce.com and wrangler of code for everything from Ruby to Flex. Follow up with him on the Force.com blog or via Twitter.