Methods

Not all ruby public instance methods are available when building connectors on Workato's SDK framework. Below we go through a list of whitelisted ruby methods that you can use in any block when building your connector.

Furthermore, you'll be able to declare personal reusable methods to use in any block when using your SDK.

Pre-defined Ruby methods

Method Description
at Creates a new time object with the given argument.
More details here.
abs Returns the absolute value of number.
ago Go back in time. Returns timestamp.
2.days.ago #2017-01-15T12:30:00.000000-07:00 if time now is 2017-01-17T12:30:00.000000-07:00
30.minutes.ago #2017-01-15T12:30:00.000000-07:00 if time now is 2017-01-15T13:00:00.000000-07:00
30.seconds.ago #2017-01-15T12:30:00.000000-07:00 if time now is 2017-01-15T12:30:30.000000-07:00
More details here.
as_string Decode byte sequence as string in given encoding
"0J/RgNC40LLQtdGC\n".decode_base64.as_string('utf-8')
as_utf8 Decode byte sequence as string in given encoding
"0J/RgNC40LLQtdGC\n".decode_base64.as_string('utf-8')
blank? Returns true if value is null or an empty string, otherwise false
binary? Returns true if value is a binary array
beginning_of_hour Returns timestamp for top-of-the-hour for given timestamp
"2017-06-01T16:56:00.000000-07:00".to_time.beginning_of_hour #2017-06-01T16:00:00.000000 +0000
beginning_of_day Returns timestamp for midnight for given timestamp
"2017-06-08T22:30:10.000000-07:00".to_time.beginning_of_day #2017-06-08T00:00:00.000000 +0000
beginning_of_week Returns timestamp for midnight for the start of the week (Mon) for given timestamp
"2017-08-18T00:00:00.000000-07:00".to_time.beginning_of_week #2017-08-14T00:00:00.000000 +0000
beginning_of_month Returns timestamp for midnight for the start of the month for given timestamp
"2017-01-30T22:35:00.000000-07:00".to_time.beginning_of_month #2017-01-01T00:00:00.000000 +0000
beginning_of_year Returns timestamp for midnight for the start of the year for given timestamp
"2017-01-30T22:35:00.000000 -07:00".to_time.beginning_of_year #2017-01-01T00:00:00.000000 +0000
capitalize Capitalizes the first character of the string
compact Returns a hash with non nil values.
More details here.
decode_base64 Decode using Base64 algorithm
decode_hex Decode hexadecimal into binary string
decode_urlsafe_base64 Decode using URL-safe modification of Base64 algorithm
decryt Decrypt the enrypted string using AES-256-CBC algorithm. Input should be in RNCryptor V3 format.
dig Retrieves the value object corresponding to the index passed in
The dig method is often used to strip away layers in nested arrays/hashes. For example, we use the dig method often when dealing with XML data formats.
More details here.
dst? Returns true if the time is within Daylight Savings Time for the specified time zone.
each Basic iterator
[1, 2, 3].each { |i| puts i }
each_with_index Iterator returned with an index
[1, 2, 3].each_with_index { |item, index| puts "#{index}:#{item}" }
More details here.
each_with_object Iterator returned with an object which you can define
[%w(foo bar).each_with_object({}) { |str, hsh| hsh[str] = str.upcase }
# => {'foo' => 'FOO', 'bar' => 'BAR'}
More details here.
encode_hex Converts binary string to its hex representation
"0J/RgNC40LLQtdGC\n".decode_base64.encode_hex
encode_sha256 Encode using SHA256 algorithm
encode_base64 Encode using Base64 algorithm
encode_url URL encode a string
'Hello World'.encode_url # 'Hello%20World'
encode_urlsafe_base64 Encode using URL-safe modification of Base64 algorithm
encode_www_form Join hash into url-encoded string of parameters
{"apple" => "red green", "2" => "3"}.encode_www_form #"apple=red+green&2=3"
ends_of_month Returns a new date/time representing the end of the month
"2017-08-18T00:00:00".to_time.end_of_month #2017-08-31 23:59:59 +0000
ends_with? Returns true if string ends with a specific pattern. False otherwise
"Hello!".ends_with?("!") #true
error raise a job error with a user-defined error body.
error("Unable to find Account with ID: 123")
even? Returns true if integer is an even number
More details here.
except Returns a hash that includes everything except given keys
{ name: "Jake", last_name: "Paul", age: "22" }.except(:name, :last_name) # { :age => "22" } 
More details here.
exclude Returns true if field does not contain a value. Case sensitive
"Partner account".exclude?("Partner") #false
More details here.
fetch Returns a value from the hash for the given key.
More details here.
first Returns the first item in a list. Can also be used to return the first n items in a list.
More details here.
flatten Flatten multi-dimensional array to simple array
[[1, 2, 3],[4,5,6]].flatten #[1, 2, 3, 4, 5, 6]
More details here.
format_json Convert request to json format and expect response body in json format
format_map Create an array of strings by formatting each row of given array
[[{name: 'Jake', age: 23}].format_map('Name: %{name}, Age: %{age}') #['Name: Jake, Age: 23']
[[22, 45], [33, 88]].format_map('Id: %s, Count: %s') #['Id: 22, Count: 45', 'Id: 33, Count: 88']
More details here.
format_xml Convert request to XML format and expect response body in XML format
from_now Go forward in time. Returns timestamp of the moment that the formula was executed with the specified time period added, in Pacific time (UTC-8/UTC-7)
4.months.from_now #2017-05-23T14:40:07.338328-07:00
2.days.from_now #2017-01-05T14:40:07.338328-07:00
30.minutes.from_now
12.seconds.from_now
group_by Group arrays into sets.
More details here.
gsub Substitute a pattern with value. Case sensitive
"Jean Marie".gsub(/J/, "M") #"Mean Marie"
More details here.
has_key? Returns true if the given key is present in hash.
More details here.
headers Add headers to a request
.headers(Authorization: "Bearer HTB674HJK1")
hmac_md5 Creates HMAC_MD5 signature
"username:password:nonce".hmac_md5("key")
hmac_sha1 Creates HMAC_SHA1 signature
"username:password:nonce".hmac_sha1("key")
hmac_sha256 Creates HMAC_SHA256 signature
"username:password:nonce".hmac_sha256("key")
hmac_sha512 Creates HMAC_SHA512 signature
"username:password:nonce".hmac_sha512("key")
ignored Ignore a comma-separate list of fields
object_definition["user"].ignored("id", "created_at")
include? Returns true if field contains a value. False otherwise
More details here.
inject Combine elements in an array using an operation.
More details here.
in_time_zone Converts the time to given time zone
"2017-09-06T18:30:15.671720-05:00".to_time.in_time_zone("America/Los_Angeles") #"2017-09-06T16:30:15.671720-07:00"
is_a? Returns true if class is the class of obj, or if class is one of the superclasses of obj or modules included in obj.
Workato currently supports the following classes - Array, Hash, Time, String, Integer, Float
More details here.
is_true? Converts a value to boolean and returns true if value is truthy.
is_not_true? Converts a value to boolean and returns true if value is not truthy.
iso8601 Convert a date/date-time variable to ISO8601 format
join Returns the last item in a list. Can also be used to return the last n items in a list. More details here.
jwt_encode_rs256 Creates JWT with RS256 - RSA using SHA-256 hash algorithm
workato.jwt_encode_rs256({ name: "John Doe" }, "PEM key") # => "eyJhbGciO..."
last Join array elements into a string More details here.
ljust Aligns string to left and pads with whitespace or pattern until string is specified length
" test".ljust(10, "*") # " test*****"
More details here.
lookup Lookup a record from your lookup tables defined in Workato.
lookup('States list', 'State code': 'AZ')['State name'] #"Arizona"
More details here.
lstrip Remove white space from the beginning of string.
"     Test     ".lstrip #"Test     "
More details here.
map Returns a new array after invoking block on each element
md5_hexdigest Creates message digest using the MD5 Message-Digest Algorith.
"hello".md5_hexdigest #5d41402abc4b2a76b9719d911017c592
match? Returns true if a string contains a pattern. Case sensitive.
"Jean Marie".match?(/Marie/) #true
merge Returns a new hash containing merged contents.
More details here.
next Returns the next object in the enumerator, and move the internal position forward.
This is often used in config_fields where you can use next as a way to add a guard clause that checks inputs before the lambda function is executed.
object_definition: {
  document: {
    fields: lambda do |connection, config_fields|
      next [] if config_fields.blank?
      get("https://www.webmerge.me/api/documents/#{config_fields["document_id"]}/fields").map {
        |field| field.slice("name")
      }
    end
  }
}
More details here.
now Returns timestamp of the moment that the formula was executed, in Pacific time (UTC-8/UTC-7)
now #2017-01-23T14:04:53.365908-08:00
now + 2.days #2017-01-25T14:04:53.365908-08:00
odd? Returns true if integer is an odd number
More details here.
only White list a comma-separate of fields
object_definition["user"].only("id", "name")
parameterize Replaces special characters in a string
"öüâ".parameterize #"oua"
params Add parameter to a request
.params(api_key: "HTB674HJK1")
parse_json Works the same way as json.parse
More details here.
parse_yaml Parse a YAML string. Supports true, false, nil, numbers, strings, arrays, hashes
workato.parse_yaml("---\nfoo: bar") # => { "foo" => "bar" }
payload Add payload to a request
.payload(id: "345")
pluck Select one or more attributes from an array of objects
[
  {"id": 1, "name": "David"},
  {"id": 2, "name": "Peter"}
].pluck("id")
returns [1, 2]
pluralize Returns the plural form of the word in the string
More details here.
pop Removes the last element from self and returns it, or nil if the array is empty.
If a number n is given, returns an array of the last n elements (or less) and removes it from array.
a = [ "a", "b", "c", "d" ]
a.pop     #=> "d"
a.pop(2)  #=> ["b", "c"]
a         #=> ["a"]
More details here<.< a="">
presence Returns the value if present. Otherwise returns nil
nil.presence #nil
"".presence #nil
0.presence #0
More details here<.< a="">
present? Returns true if the field has a value. False otherwise
nil.present? #false
"".present? #false
0.present? #true
More details here<.< a="">
puts ruby version of console.log or stdout, not the same as put method
Any outputs using the puts method shows up in the console log when testing in the code editor. Use this to aid in your debugging.
rand Random number between 0 and 1
reject Selectively returns elements for which the block returns false. Similar but opposite of select.
More details here.
render_yaml Render an object into a YAML string.
workato.render_yaml({ "foo" => "bar" }) # => "---\nfoo: bar\n"
response_format_json Expect response in json format
response_format_raw Expect response in raw format
response_format_xml Expect response in XML format
request_format_json Convert request to json format
request_format_multipart_form Convert request to multipart_form format
request_format_www_form_urlencoded Convert request to url-encoded format
request_format_xml Convert request to XML format
required Make a comma-separate list of fields required
object_definition["user"].required("id", "created_at")
reverse Reverse string or array
rjust Aligns string to right and pads with whitespace or pattern until string is specified length
"test".rjust(5) #" test"
"test".rjust(10, "*!") #"*!*!* test"
More details here<.< a="">
round Round the number by regular rounding rules
11.99.round #12
11.555.round(2) #11.56
More details here<.< a="">
rstrip Remove white space from the end of string
" Test ".rstrip #" Test"
More details here<.< a="">
scan Remove white space from the end of string
"Thu, 01/23/2014".scan(/\d+/).join("-") #01-23-2014
More details here<.< a="">
select Selectively returns elements for which the block returns true.
More details here.
SHA1 Encrypts a given string using the SHA1 encryption algorithm.
"abcdef".sha1.encode_base64 # "H4rBDyPFtbwRZ72oS4M+XAV6d9I="
More details here.
slice Returns a substring of a given string, as defined by start indexes and length
"Jean Marie\.slice(0,3) #"Jea"
More details here.
smart_join Join array to string. Removes empty and nil values. Trims the white space before joining
[nil, " ", " Hello ", "   World "].smart_join(" ") #Hello World
More details here.
sort Sort function returning new sorted array.
More details here.
sort_by Sort function returning self.
More details here.
split Split string into an array by using defined pattern as delimiter
"Split string".split() #["Split", "string"]
"Split string".split("t") #["Spli", " s", "ring"]
More details here.
strip Strip white spaces from the beginning and the end of string
"    This is an example   ".strip #"This is an example"
More details here.
strip_tags Strip html tags from the string
"Double bubble".strip_tags #"Double bubble"
strftime Format date or time using %-placeholders
tap Yields x to the block, and then returns x.
The tap method is often used for transformation. For example, we use the tap method below to transform a webhook's payload. If a webhook payload is deliever in this format.
{
  "id" => {"value" => 1},
  "name" => {"value" => 2}
}
You can use tap to transform it into a more user friendly JSON.
webhook_notification: lambda do |input, payload|
  payload.tap do |output|
    output.each { |k, v| output[k] = v["value"] }
  end
end
The final JSON will look like this {"id"=>1, "name"=>2}
More details here.
to_currency Convert to currency string
1234567890.50.to_currency    # $1,234,567,890.50
to_currency_code Convert alpha-2/3 country code or country name to ISO4217 currency code
"India".to_currency_code #INR
to_currency_name Convert alpha-2/3 country code or country name to ISO4217 currency name
"India".to_currency_name #Rupees
to_currency_symbol Convert alpha-2/3 country code or country name to ISO4217 currency symbol
"India".to_currency_symbol # ₨
to_country_alpha2 Convert alpha-3 country code or country name to alpha2 country code
"India".to_country_alpha2 #IN
"IND".to_country_alpha2 #IN
to_country_alpha3 Convert alpha-2 country code or country name to alpha2 country code
"Australia".to_country_alpha2 #AUS
"AU".to_country_alpha2 #AUS
to_country_name Convert alpha-2/3 country code or country name to ISO3166 country name
"GB".to_country_name #United Kingdom
"GBR".to_country_name #United Kingdom
to_country_number Convert alpha-2/3 country code or country name to ISO3166 country numeric code
"India".to_country_number #356
to_date Convert string or timestamp to date. Can be formatted.
"12/24/2014 10:30PM".to_date(format: "MM/DD/YYYY")
to_f Convert to float. Numbers will be rounded up or down according to regular rounding rules.
45.to_f #45.0
to_hex Converts binary string to its hex representation
to_i Convert to integer. Decimals are always rounded down.
45.67.to_i #45
to_json Converts hash or array into JSON string
{"a" => "c d", "2" => "3"}.to_json #"{"a":"c d","2":"3"}"
to_phone Convert string or number to a formatted phone number
5551234.to_phone # 555-1234
1235551234.to_phone(area_code: true) # (123) 555-1234
1235551234.to_phone(delimiter: " ") # 123 555 1234
1235551234.to_phone(country_code: 1) # +1-123-555-1234
to_param Returns a string representation for use as a URL query string
{name: 'Jake', age: '22'}.to_param #name=Jake&age=22
to_s Convert to string
45.67.to_s #"45.67"
to_state_code Convert state name to code
"California".to_state_code #CA
to_state_name Convert state code to name
"CA".to_state_name #"CALIFORNIA"
to_time Convert string or date to timestamp
"2014-11-21".to_time #2014-11-21 00:00:00 +0000
to_xml Converts hash or array into XML string
{"name" => "Ken"}.to_xml(root: "user") # <user><name>Ken</name></user>
today Date today. Returns the date of the moment that the formula was executed, in Pacific time (UTC-8/UTC-7).
today #2016-07-13
today + 2.days #2016-07-15
transliterate Replaces non-ASCII characters with an ASCII approximation, or if none exists, a replacement character which defaults to '?'
'Chloé'.transliterate #Chloe
upcase Convert string to upper case
"Convert to UPCASE".upcase #"CONVERT TO UPCASE"
uniq Return unique items in an array
[1.0, 1.5, 1.0].uniq #[1.0, 1.5]
utc Convert Time to UTC timezone.
More details here.
where Filter array by given condition
while while loop statement.
More details here.
wday Returns day of the week where 1 is Monday
wrap Wraps its argument in an array unless it is already an array
The wrap method is often used in the execute block. while loop statement.
execute: lambda do |connection, input|            More details here.
  {
    accounts: Array.wrap(get("/accounts", input)["records"])
  }
end
This ensures that the accounts variable is always an array in spite of whatever return. At Workato, we often use this to guard against unexpected returns from the various APIs we work with.
More details here.
yday Returns day of the year
"2016-07-19 10:45:30".to_time.yday #201
yweek Returns week of the year
"2016-07-19 10:45:30".to_time.yweek #29
zip Used as a method called by arrays. Converts any arguments to arrays, then merges elements of self with corresponding elements from each argument.
More details here.

This list can and will be expanded constantly, feel free to contact us to update/add to this list.

Reusable Methods

Reusable methods are supported in Workato. Reusable methods help keep your custom adapter code DRY and may be used in any code block.

Such methods are declared using the methods block. This block is a top-level block, similar to triggers and actions.

Sample code snippet

{
  title: "Math",

  connection: {...},

  methods: {
    factorial: lambda do |input|
      number = input[:number]
      if number > 1
        number * call(:factorial, { number: number - 1 })
      else
        number
      end
    end,

    hello: lambda do
      puts "Hello world"
    end
  },

  actions: {
    factorial: {
      input_fields: lambda do
        [
          { name: "number", type: :integer }
        ]
      end,

      execute: lambda do |connection, input|
        { factorial: call(:factorial, { number: input["number"] }) }
      end
    },

    say_hello: {
      execute: lambda do
        call(:hello)
      end
    }
  },

The call method

call(:name, { number: 1 })

Use the call() method to reference a method. This method takes in two parameters:

  1. Method name
    • Use the method name defined. You can use either :method_name (symbol) or "method_name" (string) representations.
  2. Input hash (optional)
    • This is a hash of input variables. Leave blank if your method does not take inputs.

The input hash is passed into the method as an argument, which you may reference as so:

methods: {
  factorial: lambda do |input|
    number = input[:number]
    ...

Recursion

Methods can also be called within method code blocks. This means that a method can be called by another method or by itself. In the case of the factorial example provided above, note that the factorial method has some degree of recursion. Be careful when writing recursive loops by setting a failsafe as in the example below:

if number > 1
  number * call(:factorial, { number: number - 1 })
else
  number
end

Testing

The SDK console only allows testing of actions and triggers. To test your reusable method, write an action that encapsulates it.

Summary

Reusable methods are powerful tools that can make development more efficient. It is especially useful when making schema introspection calls within the object_definitions or input_schema lambdas.

Next section

Find out more about how to catch and expose errors that return from the API to users configuring your connector. This makes it much easier to debug actions or triggers using your custom connector. Go to our error handling documentation.

results matching ""

    No results matching ""