Module: SFKB::REST

Extended by:
REST
Included in:
Client, Knowledge, REST
Defined in:
lib/sfkb/rest.rb

Overview

Some REST helpers

Constant Summary collapse

@@placeholder =

Used to interpolate variables into REST endpoint URIs

/[<{](.+?)[>}]/.freeze
@@url_pattern =

Used to identify URLs; %s should be the api_version

'/services/data/v%s'.freeze
@@stringify =

{ a: :b }.inject({}, &@@stringify) #=> { 'a' => :b }

lambda do |collector, kv|
  collector.tap { |h| h[kv[0].to_s] = kv[1] }
end
@@required =

{ a: 1 }.delete(:b, &@@required) # raises 'missing param: b'

-> (s) { raise(ArgumentError, "missing param: <#{s}>") }
@@parameterize =

{ a: b, c: d }.inject('x', &@@parameterize) #=> 'x?a=b&c=d'

lambda do |s, kv|
  k, *vs = *kv
  params = vs.flatten.map { |v| [k, v].join('=') }
  [s, params].flatten.compact.reject(&:empty?).join('&')
end

Instance Method Summary collapse

Instance Method Details

#apply_endpoint(obj, k, v) ⇒ Object

applies an endpoint to obj, named k, which fetches v and makes it an endpoint if it looks like a URL


53
54
55
56
57
58
59
# File 'lib/sfkb/rest.rb', line 53

def apply_endpoint(obj, k, v)
  α = -> { endpoint(get(v).body) }
  β = -> { v }
  λ = url?(v) ? -> { α.call } : -> { β.call }
  obj.define_singleton_method(k, &λ) if url?(v)
  obj
end

#endpoint(map) ⇒ Object

endpoint takes a map, and for eack key/value pair, adds a singleton method to the map which will fetch that resource (if it looks like a URL).


46
47
48
49
# File 'lib/sfkb/rest.rb', line 46

def endpoint(map)
  map.each { |k, v| apply_endpoint(map, k, v) }
  map
end

#indexObject

The REST API starts here


39
40
41
# File 'lib/sfkb/rest.rb', line 39

def index
  endpoint(get(services_url).body)
end

#services_urlObject

The starting URL


34
35
36
# File 'lib/sfkb/rest.rb', line 34

def services_url
  @@url_pattern % options[:api_version]
end

#url(path, params = {}) ⇒ Object

Converts a path and params to a Salesforce-suitable URL.


26
27
28
29
30
31
# File 'lib/sfkb/rest.rb', line 26

def url(path, params = {})
  params = params.inject({}, &@@stringify)
  path = path.gsub(@@placeholder) { params.delete($1, &@@required) }
  params = params.inject('', &@@parameterize)
  [path, params].reject(&:nil?).reject(&:empty?).join('?')
end

#url?(string) ⇒ Boolean

Identifies a valid URL for this REST instance

Returns:

  • (Boolean)

62
63
64
65
66
# File 'lib/sfkb/rest.rb', line 62

def url?(string)
  return false unless string.to_s =~ url_pattern
  return false if     string.to_s =~ @@placeholder
  true
end

#url_patternObject

Identifies a valid URL for this REST instance


69
70
71
# File 'lib/sfkb/rest.rb', line 69

def url_pattern
  %r{#{services_url}}
end