module Restforce::Concerns::API

def api_path(path)

# => '/services/data/v24.0/sobjects'
api_path('sobjects')

Examples

Internal: Returns a path to an api endpoint
def api_path(path)
  "/services/data/v#{options[:api_version]}/#{path}"
end

def create(*args)

Returns false if something bad happens.
Returns the String Id of the newly created sobject.

# => '0016000000MRatd'
client.create('Account', Name: 'Foobar Inc.')
# Add a new account

Examples

attrs - Hash of attributes to set on the new record.
sobject - String name of the sobject.

Public: Insert a new record.
def create(*args)
  create!(*args)
rescue *exceptions
  false
end

def create!(sobject, attrs)

Raises exceptions if an error is returned from Salesforce.
Returns the String Id of the newly created sobject.

# => '0016000000MRatd'
client.create!('Account', Name: 'Foobar Inc.')
# Add a new account

Examples

attrs - Hash of attributes to set on the new record.
sobject - String name of the sobject.

Public: Insert a new record.
def create!(sobject, attrs)
  api_post("sobjects/#{sobject}", attrs).body['id']
end

def describe(sobject = nil)

Returns the Hash representation of the describe call.

# => { ... }
client.describe('Account')
# get the describe for the Account object

# => { ... }
client.describe
# get the global describe for all sobjects

Examples

sobject - Stringish name of the sobject (default: nil).

Public: Returns a detailed describe result for the specified sobject
def describe(sobject = nil)
  if sobject
    api_get("sobjects/#{sobject}/describe").body
  else
    api_get('sobjects').body['sobjects']
  end
end

def describe_layouts(sobject, layout_id = nil)

Returns the Hash representation of the describe_layouts result

# => { ... }
client.describe_layouts('Account', '012E0000000RHEp')
# get the layout for the specified Id for the sobject

# => { ... }
client.describe_layouts('Account')
# get the layouts for the sobject
Examples:

Only available in version 28.0 and later of the Salesforce API.

multiple Record Types.
specified sobject type, or URIs for layouts if the sobject has
Public: Returns a detailed description of the Page Layout for the
def describe_layouts(sobject, layout_id = nil)
  version_guard(28.0) do
    if layout_id
      api_get("sobjects/#{sobject}/describe/layouts/#{layout_id}").body
    else
      api_get("sobjects/#{sobject}/describe/layouts").body
    end
  end
end

def destroy(*args)

Returns false if an error is returned from Salesforce.
Returns true if the sobject was successfully deleted.

client.destroy('Account', '0016000000MRatd')
# Delete the Account with Id '0016000000MRatd'

Examples

id - The Salesforce ID of the record.
sobject - String name of the sobject.

Public: Delete a record.
def destroy(*args)
  destroy!(*args)
rescue *exceptions
  false
end

def destroy!(sobject, id)

Raises an exception if an error is returned from Salesforce.
Returns true of the sobject was successfully deleted.

client.destroy('Account', '0016000000MRatd')
# Delete the Account with Id '0016000000MRatd'

Examples

id - The Salesforce ID of the record.
sobject - String name of the sobject.

Public: Delete a record.
def destroy!(sobject, id)
  api_delete "sobjects/#{sobject}/#{id}"
  true
end

def exceptions

Internal: Errors that should be rescued from in non-bang methods
def exceptions
  [Faraday::Error::ClientError]
end

def explain(soql)

ain.htm
See: https://www.salesforce.com/us/developer/docs/api_rest/Content/dome_query_expl
Returns a Hash in the form {:plans => [Array of plan data]}

client.explain('select Name from Account')
# Find the names of all Accounts

Examples

soql - A SOQL expression.

Only available in version 30.0 and later of the Salesforce API.

Public: Explain a SOQL query execution plan.
def explain(soql)
  version_guard(30.0) { api_get("query", explain: soql).body }
end

def find(sobject, id, field = nil)

Returns the Restforce::SObject sobject record.

field - External ID field to use (default: nil).
of the external field.
id - The id of the record. If field is specified, id should be the id
sobject - The String name of the sobject.

Public: Finds a single record and returns all fields.
def find(sobject, id, field = nil)
  if field
    url = "sobjects/#{sobject}/#{field}/#{URI.encode(id)}"
  else
    url = "sobjects/#{sobject}/#{id}"
  end
  api_get(url).body
end

def get_deleted(sobject, start_time, end_time)

Restforce.configuration.mashify is false.
Returns an Array of Hash for each record in the result if
Returns a Restforce::Collection if Restforce.configuration.mashify is true.

client.get_deleted('Whizbang', startDate, endDate)
endDate = Time.new(2002, 11, 1, 2, 2, 2, "+02:00")
startDate = Time.new(2002, 10, 31, 2, 2, 2, "+02:00")
# get deleted sobject Whizbangs between yesterday and today

Examples

which have been deleted between startDateTime and endDateTime.
Public: Gets the IDs of sobjects of type [sobject]
def get_deleted(sobject, start_time, end_time)
  start_time = start_time.utc.iso8601
  end_time = end_time.utc.iso8601
  url = "/sobjects/#{sobject}/deleted/?start=#{start_time}&end=#{end_time}"
  api_get(url).body
end

def get_updated(sobject, start_time, end_time)

Restforce.configuration.mashify is false.
Returns an Array of Hash for each record in the result if
Returns a Restforce::Collection if Restforce.configuration.mashify is true.

client.get_updated('Whizbang', startDate, endDate)
endDate = Time.new(2002, 11, 1, 2, 2, 2, "+02:00")
startDate = Time.new(2002, 10, 31, 2, 2, 2, "+02:00")
# get changes for sobject Whizbang between yesterday and today

Examples

which have changed between startDateTime and endDateTime.
Public: Gets the IDs of sobjects of type [sobject]
def get_updated(sobject, start_time, end_time)
  start_time = start_time.utc.iso8601
  end_time = end_time.utc.iso8601
  url = "/sobjects/#{sobject}/updated/?start=#{start_time}&end=#{end_time}"
  api_get(url).body
end

def limits

Returns an Array of String names for each SObject.

Only available in version 29.0 and later of the Salesforce API.

Public: Get info about limits in the connected organization
def limits
  version_guard(29.0) { api_get("limits").body }
end

def list_sobjects

Returns an Array of String names for each SObject.

# => ['Account', 'Lead', ... ]
client.list_sobjects
# get the names of all sobjects on the org

Examples

Public: Get the names of all sobjects on the org.
def list_sobjects
  describe.collect { |sobject| sobject['name'] }
end

def org_id

Returns the String organization Id

# => '00Dx0000000BV7z'
client.org_id

Examples

Public: Get the current organization's Id.
def org_id
  query('select id from Organization').first['Id']
end

def query(soql)

Restforce.configuration.mashify is false.
Returns an Array of Hash for each record in the result if
Returns a Restforce::Collection if Restforce.configuration.mashify is true.

# => ['Foo Bar Inc.', 'Whizbang Corp']
client.query('select Name from Account').map(&:Name)
# Find the names of all Accounts

Examples

soql - A SOQL expression.

Public: Executs a SOQL query and returns the result.
def query(soql)
  response = api_get 'query', q: soql
  mashify? ? response.body : response.body['records']
end

def query_all(soql)

Restforce.configuration.mashify is false.
Returns an Array of Hash for each record in the result if
Returns a Restforce::Collection if Restforce.configuration.mashify is true.

# => ['Foo Bar Inc.', 'Whizbang Corp']
client.query_all('select Name from Account').map(&:Name)
# Find the names of all Accounts

Examples

soql - A SOQL expression.

Only available in version 29.0 and later of the Salesforce API.

QueryAll will also return information about archived Task and Event records.
QueryAll will return records that have been deleted because of a merge or delete.
Public: Executes a SOQL query and returns the result. Unlike the Query resource,
def query_all(soql)
  version_guard(29.0) do
    response = api_get 'queryAll', q: soql
    mashify? ? response.body : response.body['records']
  end
end

def recent(limit = nil)

Returns an array of the recently viewed Restforce::SObject records.

records per object.
returned is the maximum number of entries in RecentlyViewed, which is 200
If this parameter is not specified, the default maximum number of records
returned.
limit - An optional limit that specifies the maximum number of records to be

Public: Finds recently viewed items for the logged-in user.
def recent(limit = nil)
  path = limit ? "recent?limit=#{limit}" : "recent"
  api_get(path).body
end

def search(sosl)

Restforce.configuration.mashify is false.
Returns an Array of Hash for each record in the result if
Returns a Restforce::Collection if Restforce.configuration.mashify is true.

# => ['GenePoint']
client.search('FIND {genepoint} RETURNING Account (Name)').map(&:Name)
# Find accounts match the term 'genepoint' and return the Name field

# => #
client.search('FIND {bar}')
# Find all occurrences of 'bar'

Examples

sosl - A SOSL expression.

Public: Perform a SOSL search
def search(sosl)
  api_get('search', q: sosl).body
end

def select(sobject, id, select, field = nil)


field - External ID field to use (default: nil).
is passed, all fields are selected.
select - A String array denoting the fields to select. If nil or empty array
of the external field.
id - The id of the record. If field is specified, id should be the id
sobject - The String name of the sobject.

Public: Finds a single record and returns select fields.
def select(sobject, id, select, field = nil)
  if field
    path = "sobjects/#{sobject}/#{field}/#{URI.encode(id)}"
  else
    path = "sobjects/#{sobject}/#{id}"
  end
  path << "?fields=#{select.join(',')}" if select && select.any?
  api_get(path).body
end

def update(*args)

Returns false if there was an error.
Returns true if the sobject was successfully updated.

client.update('Account', Id: '0016000000MRatd', Name: 'Whizbang Corp')
# Update the Account with Id '0016000000MRatd'

Examples

attrs - Hash of attributes to set on the record.
sobject - String name of the sobject.

Public: Update a record.
def update(*args)
  update!(*args)
rescue *exceptions
  false
end

def update!(sobject, attrs)

Raises an exception if an error is returned from Salesforce.
Returns true if the sobject was successfully updated.

client.update!('Account', Id: '0016000000MRatd', Name: 'Whizbang Corp')
# Update the Account with Id '0016000000MRatd'

Examples

attrs - Hash of attributes to set on the record.
sobject - String name of the sobject.

Public: Update a record.
def update!(sobject, attrs)
  id = attrs.fetch(attrs.keys.find { |k, v| k.to_s.downcase == 'id' }, nil)
  raise ArgumentError, 'Id field missing from attrs.' unless id
  attrs_without_id = attrs.reject { |k, v| k.to_s.downcase == "id" }
  api_patch "sobjects/#{sobject}/#{id}", attrs_without_id
  true
end

def upsert(*args)

multiple resources).
Returns false if something bad happens (for example if the external ID matches
Returns the Id of the newly created record if the record was created.
Returns true if the record was found and updated.

client.upsert('Account', 'External__c', External__c: 12, Name: 'Foobar')
# Update the record with external ID of 12

Examples

attrs - Hash of attributes for the record.
field - The name of the external Id field to match against.
sobject - The name of the sobject to created.

Public: Update or create a record based on an external ID
def upsert(*args)
  upsert!(*args)
rescue *exceptions
  false
end

def upsert!(sobject, field, attrs)

case the conflicting IDs can be found by looking at the response on the error)
error returned if the external ID provided matches multiple records (in which
Raises an exception if an error is returned from Salesforce, including the 300
Returns the Id of the newly created record if the record was created.
Returns true if the record was found and updated.

client.upsert!('Account', 'External__c', External__c: 12, Name: 'Foobar')
# Update the record with external ID of 12

Examples

attrs - Hash of attributes for the record.
field - The name of the external Id field to match against.
sobject - The name of the sobject to created.

Public: Update or create a record based on an external ID
def upsert!(sobject, field, attrs)
  external_id = attrs.
    fetch(attrs.keys.find { |k, v| k.to_s.downcase == field.to_s.downcase }, nil)
  attrs_without_field = attrs.
    reject { |k, v| k.to_s.downcase == field.to_s.downcase }
  response = api_patch "sobjects/#{sobject}/#{field}/#{URI.encode(external_id)}",
                       attrs_without_field
  (response.body && response.body['id']) ? response.body['id'] : true
end

def user_info

Returns an Array of String names for each SObject.

# => user@example.com
client.user_info.email
# get the email of the logged-in user

Examples

Public: Get info about the logged-in user.
def user_info
  get(api_get.body.identity).body
end

def version_guard(version)

the provided version before performing a particular action
Internal: Ensures that the `api_version` set for the Restforce client is at least
def version_guard(version)
  if version.to_f <= options[:api_version].to_f
    yield
  else
    raise APIVersionError, "You must set an `api_version` of at least #{version} " \
                           "to use this feature in the Salesforce API. Set the " \
                           "`api_version` option when configuring the client - " \
                           "see https://github.com/ejholmes/restforce/blob/master" \
                           "/README.md#api-versions"
  end
end