Appirio's Tech Blog

Friday, June 3, 2011

Demo App - Ruby, Rails & Force.com REST API on Heroku

So continuing with my learning Ruby series, I finally finished my sample app using the Force.com REST API. I ran into a few issues and fortunately Quinton Wall and Heroku support came to my rescue. Apparently require 'Accounts' and require 'accounts' aren't the same when running on Heroku. Go figure.

This is a demo Rails app running on Ruby 1.9.2 and Rails 3.0.5 hosted on Heroku. It uses OAuth2 via OmniAuth to authorize access to a salesforce.com org. It uses the Force.com REST API to query for records, retreive records to display, create new records and update existing ones. It should be good sample app to get noobs (like me) up and running.

I forked Quinton Wall's (excellent) omniauth-rails3-forcedotcom project to get started. One of the things you have to do when using the Force.com REST API is to configure your server to run under SSL using WEBrick. I found some excellent instruction for OS X here.

You can run the app for yourself here.

All of the code for this app is hosted at github so feel free to fork it. I've pulled out some of the more important parts of the app for discussion after the video.


app/controllers/accounts_controller.rb

The account controller delegates authority to accounts.rb for integration with Force.com and then packages up the returns for the views.

require 'accounts'

class AccountsController < ApplicationController
  def index
  end
  
  def search
    @json = Accounts.search(params[:accountName])
  end
  
  def show
    @account = Accounts.retrieve(params[:id])
    @opportunities = Accounts.opportunities(params[:id])    
  end
  
  def create
     @account = Accounts.create
  end
  
  def edit
     @account = Accounts.retrieve(params[:id])
  end
  
  def save
    Accounts.save(params)
    redirect_to :action => :show, :id => params[:id]
  end  
  
  def new_opp 
    @account = Accounts.retrieve(params[:id])
  end
  
  def save_opp
    Accounts.create_opp(params)
    redirect_to :action => :show, :id => params[:id]
  end

end

lib/accounts.rb

Accounts.rb does most of the heavy lifting for the app. It prepares the requests to Force.com with the correct headers and makes the actual calls to Force.com with the REST API.

require 'rubygems'
require 'httparty'

class Accounts
  include HTTParty
  #doesn't seem to pick up env variable correctly if I set it here
  #headers 'Authorization' => "OAuth #{ENV['sfdc_token']}"
  format :json
  # debug_output $stderr

  def self.set_headers
    headers 'Authorization' => "OAuth #{ENV['sfdc_token']}"
  end

  def self.root_url
    @root_url = ENV['sfdc_instance_url']+"/services/data/v"+ENV['sfdc_api_version']
  end
  
  def self.search(keyword)
    Accounts.set_headers
    soql = "SELECT Id, Name, BillingCity, BillingState, Phone from Account Where Name = \'#{keyword}\'"
    get(Accounts.root_url+"/query/?q=#{CGI::escape(soql)}")
  end
  
  def self.create()
    Accounts.set_headers
    headers 'Content-Type' => "application/json"
    
    options = {
      :body => {
          :Name => "1234"
      }.to_json
    }
    response = post(Accounts.root_url+"/sobjects/Account/", options)
    # puts response.body, response.code, response.message
  end
  
  def self.save(params)
    Accounts.set_headers
    headers 'Content-Type' => "application/json"
    
    options = {
      :body => {
          :billingcity => params[:BillingCity]
      }.to_json
    }
    p options
    response = post(Accounts.root_url+"/sobjects/Account/#{params[:id]}?_HttpMethod=PATCH", options)
    # 201 response.body equals success
    # puts response.body, response.code, response.message
  end
  
  def self.retrieve(id)
    Accounts.set_headers
    get(Accounts.root_url+"/sobjects/Account/#{id}?fields=Id,Name,BillingCity,BillingState,Phone,Website") 
  end
  
  def self.opportunities(accountId)
    Accounts.set_headers
    soql = "SELECT Id, Name, Amount, StageName, Probability, CloseDate from Opportunity where AccountId = \'#{accountId}\'"
    get(Accounts.root_url+"/query/?q=#{CGI::escape(soql)}")
  end
  
  def self.create_opp(params)
    Accounts.set_headers
    headers 'Content-Type' => "application/json"
    
    options = {
      :body => {
          :name => params[:name],
          :amount => params[:amount],
          :accountId => params[:id],
          :amount => params[:amount],
          :closeDate => params[:closeDate],
          :stageName => params[:stageName]
      }.to_json
    }
    response = post(Accounts.root_url+"/sobjects/Opportunity/", options)
    # 201 response.body equals success
    # puts response.body, response.code, response.message
  end
 
end
 
2006-2012 Appirio Inc. All rights reserved.
Appirio.com | Support | Resource Center | Contact | Careers | Privacy Policy