code
stringlengths
26
124k
docstring
stringlengths
23
125k
func_name
stringlengths
1
98
language
stringclasses
1 value
repo
stringlengths
5
53
path
stringlengths
7
151
url
stringlengths
50
211
license
stringclasses
7 values
def gen_applocker_xml require 'nokogiri' # Generic XML builder function. When enabled, this produces our # XML for enabling the Applocker service. When disabled, this produces # a "clean" XML policy for Applocker configuration builder = Nokogiri::XML::Builder.new do |xml| xml.AppLockerPolicy(:Version => 1) do # Add to it each of our elements get_applocker_rules.map do |ruleset, opts| xml.RuleCollection(:Type => ruleset, :EnforcementMode => cpe_applocker_enabled? ? opts['mode'] : 'NotConfigured') do opts['rules'].each do |rule| case rule['type'] when 'path' gen_file_path_rule(rule, xml) when 'hash' gen_file_hash_rule(rule, xml) when 'certificate' gen_file_publisher_rule(rule, xml) end end # opts['rules'] end # End of RuleCollection end # End of Each Applocker ruleset, opts end # End of AppLockerPolicy end # End of Xml Builder builder.to_xml( :save_with => Nokogiri::XML::Node::SaveOptions::AS_XML | Nokogiri::XML::Node::SaveOptions::NO_DECLARATION, ).strip end
Helper function to generate our XML configuration file
gen_applocker_xml
ruby
facebook/IT-CPE
itchef/cookbooks/cpe_applocker/libraries/applocker_helpers.rb
https://github.com/facebook/IT-CPE/blob/master/itchef/cookbooks/cpe_applocker/libraries/applocker_helpers.rb
Apache-2.0
def generated_form initializer = self.instance_variables.each_with_object([]) do |v, a| value = self.instance_variable_get(v) if value.is_a?(String) a << "'#{value}'" elsif value.is_a?(Symbol) a << ":#{value}" elsif value.is_a?(NilClass) a << 'nil' elsif value.is_a?(TrueClass) || value.is_a?(FalseClass) a << value end end "#{self.class.name}.new(\n#{initializer.join(", \n")},)" end
This method is used to output a proper class constructor. The generated string is set up in such a way that the linter will properly autoformat it such that is will cooperate with our static analysis tooling.
generated_form
ruby
facebook/IT-CPE
itchef/cookbooks/cpe_chrome/libraries/windows_chrome_settingv2.rb
https://github.com/facebook/IT-CPE/blob/master/itchef/cookbooks/cpe_chrome/libraries/windows_chrome_settingv2.rb
Apache-2.0
def to_chef_reg_provider list = [] return list if @value.nil? @value.each_with_index do |entry, index| list << { :name => (index + 1).to_s, :type => @type, :data => entry } end list end
Chrome settings in the registry with multiple entries are laid out sequentially from [1...N]
to_chef_reg_provider
ruby
facebook/IT-CPE
itchef/cookbooks/cpe_chrome/libraries/windows_chrome_settingv2.rb
https://github.com/facebook/IT-CPE/blob/master/itchef/cookbooks/cpe_chrome/libraries/windows_chrome_settingv2.rb
Apache-2.0
def set_reg_settings(node) reg_settings = [] node['cpe_chrome']['profile'].each do |setting_key, setting_value| next if setting_value.nil? setting = CPE::ChromeManagement::KnownSettings::GENERATED.fetch( setting_key, nil, ) unless setting next end if setting_value.is_a?(Hash) next if setting_value.empty? setting.value = setting_value.to_json else setting.value = setting_value end reg_settings << setting end reg_settings end
Updates CPE::ChromeManagement::KnownSettings::GENERATED to contain configured values and returns a list of policies that were updated.
set_reg_settings
ruby
facebook/IT-CPE
itchef/cookbooks/cpe_chrome/libraries/windows_helpers.rb
https://github.com/facebook/IT-CPE/blob/master/itchef/cookbooks/cpe_chrome/libraries/windows_helpers.rb
Apache-2.0
def initialize(s) @string_form = s if s.nil? @arr = [] return end @arr = s.split(/[._-]/).map(&:to_i) end
This is intentional. rubocop:disable Lint/MissingSuper
initialize
ruby
facebook/IT-CPE
itchef/cookbooks/fb_helpers/libraries/fb_helpers.rb
https://github.com/facebook/IT-CPE/blob/master/itchef/cookbooks/fb_helpers/libraries/fb_helpers.rb
Apache-2.0
def el_min_version?(version, full = false) self.rhel_family? && self.os_min_version?(version, full) end
Is this a RHEL-compatible OS with a minimum major version number of `version`
el_min_version?
ruby
facebook/IT-CPE
itchef/cookbooks/fb_helpers/libraries/node_methods.rb
https://github.com/facebook/IT-CPE/blob/master/itchef/cookbooks/fb_helpers/libraries/node_methods.rb
Apache-2.0
def el_max_version?(version, full = false) self.rhel_family? && self.os_max_version?(version, full) end
Is this a RHEL-compatible OS with a maximum major version number of `version`
el_max_version?
ruby
facebook/IT-CPE
itchef/cookbooks/fb_helpers/libraries/node_methods.rb
https://github.com/facebook/IT-CPE/blob/master/itchef/cookbooks/fb_helpers/libraries/node_methods.rb
Apache-2.0
def windows1903? windows? && self['platform_version'] == '10.0.18362' end
from https://en.wikipedia.org/wiki/Windows_10_version_history
windows1903?
ruby
facebook/IT-CPE
itchef/cookbooks/fb_helpers/libraries/node_methods.rb
https://github.com/facebook/IT-CPE/blob/master/itchef/cookbooks/fb_helpers/libraries/node_methods.rb
Apache-2.0
def in_aws_account?(*accts) return false if self.quiescent? return false unless self['ec2'] accts.flatten! accts.include?(self['ec2']['account_id']) end
Takes one or more AWS account IDs as strings and return true if this node is in any of those accounts.
in_aws_account?
ruby
facebook/IT-CPE
itchef/cookbooks/fb_helpers/libraries/node_methods.rb
https://github.com/facebook/IT-CPE/blob/master/itchef/cookbooks/fb_helpers/libraries/node_methods.rb
Apache-2.0
def device_of_mount(m) fs = self.filesystem_data unless Pathname.new(m).mountpoint? Chef::Log.warn( "fb_helpers: #{m} is not a mount point - I can't determine its " + 'device.', ) return nil end unless fs && fs['by_pair'] Chef::Log.warn( 'fb_helpers: no filesystem data so no node.device_of_mount', ) return nil end fs['by_pair'].to_hash.each do |pair, info| # we skip fake filesystems 'rootfs', etc. next unless pair.start_with?('/') # is this our FS? next unless pair.end_with?(",#{m}") # make sure this isn't some fake entry next unless info['kb_size'] return info['device'] end Chef::Log.warn( "fb_helpers: #{m} shows as valid mountpoint, but Ohai can't find it.", ) nil end
Take a string representing a mount point, and return the device it resides on.
device_of_mount
ruby
facebook/IT-CPE
itchef/cookbooks/fb_helpers/libraries/node_methods.rb
https://github.com/facebook/IT-CPE/blob/master/itchef/cookbooks/fb_helpers/libraries/node_methods.rb
Apache-2.0
def fs_value(p, val) key = case val when 'size' 'kb_size' when 'used' 'kb_used' when 'available' 'kb_available' when 'percent' 'percent_used' else fail "fb_helpers: Unknown FS val #{val} for node.fs_value" end fs = self.filesystem_data # Some things like /dev/root and rootfs have same mount point... if fs && fs['by_mountpoint'] && fs['by_mountpoint'][p] && fs['by_mountpoint'][p][key] return fs['by_mountpoint'][p][key].to_f end Chef::Log.warn( "fb_helpers: Tried to get filesystem information for '#{p}', but it " + 'is not a recognized filesystem, or does not have the requested info.', ) nil end
Takes a string corresponding to a filesystem. Returns the size in GB of that filesystem.
fs_value
ruby
facebook/IT-CPE
itchef/cookbooks/fb_helpers/libraries/node_methods.rb
https://github.com/facebook/IT-CPE/blob/master/itchef/cookbooks/fb_helpers/libraries/node_methods.rb
Apache-2.0
def shard_block(threshold, &block) yield block if block_given? && in_shard?(threshold) end
This method allows you to conditionally shard chef resources @param threshold [Fixnum] An integer value that you are sharding up to. @yields The contents of the ruby block if the node is in the shard. @example This will log 'hello' during the chef run for all nodes <= shard 5 node.shard_block(5) do log 'hello' do level :info end end
shard_block
ruby
facebook/IT-CPE
itchef/cookbooks/fb_helpers/libraries/node_methods.rb
https://github.com/facebook/IT-CPE/blob/master/itchef/cookbooks/fb_helpers/libraries/node_methods.rb
Apache-2.0
def device_ssd?(device) unless self['block_device'][device] fail "fb_helpers: Device '#{device}' passed to node.device_ssd? " + "doesn't appear to be a block device!" end self['block_device'][device]['rotational'] == '0' end
is this device a SSD? If it's not rotational, then it's SSD expects a short device name, e.g. 'sda', not '/dev/sda', not '/dev/sda3'
device_ssd?
ruby
facebook/IT-CPE
itchef/cookbooks/fb_helpers/libraries/node_methods.rb
https://github.com/facebook/IT-CPE/blob/master/itchef/cookbooks/fb_helpers/libraries/node_methods.rb
Apache-2.0
def rpm_version(name) if (self.centos? && !self.centos7?) || self.fedora? || self.redhat8? || self.oracle8? || self.redhat9? || self.oracle9? || self.aristaeos_4_30_or_newer? # returns epoch.version v = Chef::Provider::Package::Dnf::PythonHelper.instance. package_query(:whatinstalled, name).version unless v.nil? v.split(':')[1] end elsif self.centos7? && (FB::Version.new(Chef::VERSION) > FB::Version.new('14')) # returns epoch.version.arch v = Chef::Provider::Package::Yum::PythonHelper.instance. package_query(:whatinstalled, name).version unless v.nil? v.split(':')[1] end else # return version Chef::Provider::Package::Yum::YumCache.instance. installed_version(name) end end
returns the version-release of an rpm installed, or nil if not present
rpm_version
ruby
facebook/IT-CPE
itchef/cookbooks/fb_helpers/libraries/node_methods.rb
https://github.com/facebook/IT-CPE/blob/master/itchef/cookbooks/fb_helpers/libraries/node_methods.rb
Apache-2.0
def attr_lookup(path, delim: '/', default: nil) return default if path.nil? node_path = path.split(delim) # implicit-begin is a function of ruby2.5 and later, but we still # support 2.4, so.... until then node_path.inject(self) do |location, key| if key.respond_to?(:to_s) && location.respond_to?(:attribute?) location.attribute?(key.to_s) ? location[key] : default else default end end end
Safely dig through the node's attributes based on the specified `path`, with the option to provide a default value in the event the key does not exist. @param path [required] [String] A string representing the path to search for the key. @param delim [opt] [String] A character that you will split the path on. @param default [opt] [Object] An object to return if the key is not found. @return [Object] Returns an arbitrary object in the event the key isn't there. @note Returns nil by default @note Returns the default value in the event of an exception @example irb> node.default.awesome = 'yup' => "yup" irb> node.attr_lookup('awesome/not_there') => nil irb> node.attr_lookup('awesome') => "yup" irb> node.override.not_cool = 'but still functional' => "but still functional" irb> node.attr_lookup('not_cool') => "but still functional" irb> node.attr_lookup('default_val', default: 'I get this back anyway') => "I get this back anyway" irb> node.automatic.a.very.deeply.nested.value = ':)' => ":)" irb> node.attr_lookup('a/very/deeply/nested/value') => ":)"
attr_lookup
ruby
facebook/IT-CPE
itchef/cookbooks/fb_helpers/libraries/node_methods.rb
https://github.com/facebook/IT-CPE/blob/master/itchef/cookbooks/fb_helpers/libraries/node_methods.rb
Apache-2.0
def interface_change_allowed?(interface) method = self['fb_helpers']['interface_change_allowed_method'] if method return method.call(self, interface) else return self.nw_changes_allowed? || ['ip6tnl0', 'tunlany0', 'tunl0'].include?(interface) || interface.match(Regexp.new('^tunlany\d+:\d+')) end end
We can change interface configs if nw_changes_allowed? or we are operating on a DSR VIP
interface_change_allowed?
ruby
facebook/IT-CPE
itchef/cookbooks/fb_helpers/libraries/node_methods.rb
https://github.com/facebook/IT-CPE/blob/master/itchef/cookbooks/fb_helpers/libraries/node_methods.rb
Apache-2.0
def files_unowned_by_pkgmgmt(files) # this uses the chef-utils helpers, which we should be moving towards # instead of the fb_helpers helpers. rpm_based is obvious, debian? # is all debian-derived distros unowned_files = [] if rpm_based? s = Mixlib::ShellOut.new(['/bin/rpm', '-qf'] + files).run_command unless s.exitstatus == 0 s.stdout.split("\n").each do |line| m = /file (.*) is not owned by any package/.match(line.strip) next unless m unowned_files << m[1] end end elsif debian? s = Mixlib::ShellOut.new(['dpkg', '-S'] + files).run_command unless s.exitstatus == 0 s.stderr.split("\n").each do |line| m = /no path found matching pattern (.*)/.match(line.strip) next unless m unowned_files << m[1] end end end unowned_files end
Given a list of files, return those that are not owned by the relevant package management for this host. Note: When using this, if you have other filters (like, "is this in my config"), use this filter last, so that you don't execute pkgmgmt stuff on files you don't need to (and hopefully not at all)
files_unowned_by_pkgmgmt
ruby
facebook/IT-CPE
itchef/cookbooks/fb_helpers/libraries/node_methods.rb
https://github.com/facebook/IT-CPE/blob/master/itchef/cookbooks/fb_helpers/libraries/node_methods.rb
Apache-2.0
def forced_why_run @saved_why_run = Chef::Config[:why_run] Chef::Config[:why_run] = true yield ensure Chef::Config[:why_run] = @saved_why_run end
Copied from lib/chef/runner.rb
forced_why_run
ruby
facebook/IT-CPE
itchef/cookbooks/fb_helpers/resources/gated_template.rb
https://github.com/facebook/IT-CPE/blob/master/itchef/cookbooks/fb_helpers/resources/gated_template.rb
Apache-2.0
def launchd_resource(label, action, attrs = {}) Chef::Log.debug( "fb_launchd: new launchd resource '#{label}' with action '#{action}' " + "and attributes #{attrs}", ) return unless label res = launchd label do action action.to_sym if attrs['only_if'] only_if { attrs['only_if'].call } end if attrs['not_if'] not_if { attrs['not_if'].call } end end attrs.each do |attribute, value| next if ['action', 'only_if', 'not_if'].include?(attribute) res.send(attribute.to_sym, value) end res end
Constructs a new launchd resource with label 'label' and action 'action'. attrs is a Hash of key/value pairs of launchd attributes and their values. Returns the new launchd resource.
launchd_resource
ruby
facebook/IT-CPE
itchef/cookbooks/fb_launchd/resources/default.rb
https://github.com/facebook/IT-CPE/blob/master/itchef/cookbooks/fb_launchd/resources/default.rb
Apache-2.0
def managed_plists(prefix) PLIST_DIRECTORIES.map do |dir| plist_glob = ::File.join(::File.expand_path(dir), "*#{prefix}*.plist") ::Dir.glob(plist_glob) end.flatten end
Finds any managed plists in the standard launchd directories with the specified prefix. Returns a list of paths to the managed plists.
managed_plists
ruby
facebook/IT-CPE
itchef/cookbooks/fb_launchd/resources/default.rb
https://github.com/facebook/IT-CPE/blob/master/itchef/cookbooks/fb_launchd/resources/default.rb
Apache-2.0
def initialize(hashed_password) @hashed_password = hashed_password end
Initializes an object of the MysqlPassword type @param [String] hashed_password mysql native hashed password @return [MysqlPassword]
initialize
ruby
sous-chefs/mysql
libraries/hashed_password.rb
https://github.com/sous-chefs/mysql/blob/master/libraries/hashed_password.rb
Apache-2.0
def hashed_password(hashed_password) HashedPassword.new hashed_password end
helper method wrappers the string into a MysqlPassword object @param [String] hashed_password mysql native hashed password @return [MysqlPassword] object
hashed_password
ruby
sous-chefs/mysql
libraries/hashed_password.rb
https://github.com/sous-chefs/mysql/blob/master/libraries/hashed_password.rb
Apache-2.0
def sql_command_string(query, database, ctrl, grep_for = nil) raw_query = query.is_a?(String) ? query : query.join(";\n") Chef::Log.debug("Control Hash: [#{ctrl.to_json}]\n") cmd = "/usr/bin/mysql -B -e \"#{raw_query}\"" cmd << " --user=#{ctrl[:user]}" if ctrl && ctrl.key?(:user) && !ctrl[:user].nil? cmd << " -p#{ctrl[:password]}" if ctrl && ctrl.key?(:password) && !ctrl[:password].nil? cmd << " -h #{ctrl[:host]}" if ctrl && ctrl.key?(:host) && !ctrl[:host].nil? && ctrl[:host] != 'localhost' cmd << " -P #{ctrl[:port]}" if ctrl && ctrl.key?(:port) && !ctrl[:port].nil? && ctrl[:host] != 'localhost' cmd << " -S #{ctrl[:socket].nil? ? default_socket_file : ctrl[:socket]}" if ctrl && ctrl.key?(:host) && !ctrl[:host].nil? && ctrl[:host] == 'localhost' cmd << " #{database}" unless database.nil? cmd << " | grep #{grep_for}" if grep_for Chef::Log.debug("Executing this command: [#{cmd}]\n") cmd end
###### Function to execute an SQL statement Input: query : Query could be a single String or an Array of String. database : a string containing the name of the database to query in, nil if no database choosen ctrl : a Hash which could contain: - user : String or nil - password : String or nil - host : String or nil - port : String or Integer or nil - socket : String or nil Output: A String with cmd to execute the query (but do not execute it!)
sql_command_string
ruby
sous-chefs/mysql
libraries/helpers.rb
https://github.com/sous-chefs/mysql/blob/master/libraries/helpers.rb
Apache-2.0
def execute_sql(query, db_name, ctrl) cmd = shell_out(sql_command_string(query, db_name, ctrl), user: 'root') if cmd.exitstatus != 0 Chef::Log.fatal("mysql failed executing this SQL statement:\n#{query}") Chef::Log.fatal(cmd.stderr) raise 'SQL ERROR' end cmd.stdout end
###### Function to execute an SQL statement in the default database. Input: Query could be a single String or an Array of String. Output: A String with <TAB>-separated columns and \n-separated rows. This is easiest for 1-field (1-row, 1-col) results, otherwise it will be complex to parse the results.
execute_sql
ruby
sous-chefs/mysql
libraries/helpers.rb
https://github.com/sous-chefs/mysql/blob/master/libraries/helpers.rb
Apache-2.0
def execute_sql_exitstatus(query, ctrl) shell_out(sql_command_string(query, nil, ctrl), user: 'root').exitstatus end
Returns status code of sql query
execute_sql_exitstatus
ruby
sous-chefs/mysql
libraries/helpers.rb
https://github.com/sous-chefs/mysql/blob/master/libraries/helpers.rb
Apache-2.0
def check_master_slave root_pass = 'MyPa$$word\Has_"Special\'Chars%!' root_pass_slave = 'An0th3r_Pa%%w0rd!' mysql_cmd_1 = mysql_query('SELECT * FROM table1', root_pass_slave, '127.0.0.1', 3307, 'databass') mysql_cmd_2 = mysql_query('SELECT * FROM table1', root_pass_slave, '127.0.0.1', 3308, 'databass') describe command(mysql_cmd_1) do its(:exit_status) { should eq 0 } its(:stdout) { should match(/awesome/) } end describe command(mysql_cmd_2) do its(:exit_status) { should eq 0 } its(:stdout) { should match(/awesome/) } end check_mysql_server_instance(3306, root_pass) check_mysql_server_instance(3307, root_pass_slave) check_mysql_server_instance(3308, root_pass_slave) end
Check Master-Slave configuration defined by test::smoke recipe
check_master_slave
ruby
sous-chefs/mysql
test/integration/spec_helper.rb
https://github.com/sous-chefs/mysql/blob/master/test/integration/spec_helper.rb
Apache-2.0
def initialize(hash, client) @client = client @raw_page = hash end
Given a hash and client, will create an Enumerator that will lazily request Salesforce for the next page of results.
initialize
ruby
restforce/restforce
lib/restforce/collection.rb
https://github.com/restforce/restforce/blob/master/lib/restforce/collection.rb
MIT
def each(&) @raw_page['records'].each { |record| yield Restforce::Mash.build(record, @client) } np = next_page while np np.current_page.each(&) np = np.next_page end end
Yield each value on each page.
each
ruby
restforce/restforce
lib/restforce/collection.rb
https://github.com/restforce/restforce/blob/master/lib/restforce/collection.rb
MIT
def size @raw_page['totalSize'] || @raw_page['size'] end
Return the number of items in the Collection without making any additional requests and going through all of the pages of results, one by one. Instead, we can rely on the total count of results which Salesforce returns. Most of the Salesforce API returns this in the `totalSize` attribute. For some reason, the [List View Results](https://developer.salesforce.com/docs/atlas.en-us.api_rest.meta/api_rest/resources_listviewresults.htm) endpoint (and maybe others?!) uses the `size` attribute.
size
ruby
restforce/restforce
lib/restforce/collection.rb
https://github.com/restforce/restforce/blob/master/lib/restforce/collection.rb
MIT
def pages [self] + (has_next_page? ? next_page.pages : []) end
Return the current and all of the following pages.
pages
ruby
restforce/restforce
lib/restforce/collection.rb
https://github.com/restforce/restforce/blob/master/lib/restforce/collection.rb
MIT
def next_page @client.get(@raw_page['nextRecordsUrl']).body if has_next_page? end
Returns the next page as a Restforce::Collection if it's available, nil otherwise.
next_page
ruby
restforce/restforce
lib/restforce/collection.rb
https://github.com/restforce/restforce/blob/master/lib/restforce/collection.rb
MIT
def configuration @configuration ||= Configuration.new end
Returns the current Configuration Example Restforce.configuration.username = "username" Restforce.configuration.password = "password"
configuration
ruby
restforce/restforce
lib/restforce/config.rb
https://github.com/restforce/restforce/blob/master/lib/restforce/config.rb
MIT
def configure yield configuration end
Yields the Configuration Example Restforce.configure do |config| config.username = "username" config.password = "password" end
configure
ruby
restforce/restforce
lib/restforce/config.rb
https://github.com/restforce/restforce/blob/master/lib/restforce/config.rb
MIT
def build(val, client) case val when Array val.collect { |a_val| self.build(a_val, client) } when Hash self.klass(val).new(val, client) else val end end
Pass in an Array or Hash and it will be recursively converted into the appropriate Restforce::Collection, Restforce::SObject and Restforce::Mash objects.
build
ruby
restforce/restforce
lib/restforce/mash.rb
https://github.com/restforce/restforce/blob/master/lib/restforce/mash.rb
MIT
def klass(val) if val.key? 'records' # When the hash has a records key, it should be considered a collection # of sobject records. Restforce::Collection elsif val.key? 'attributes' case val.dig('attributes', 'type') when "Attachment" Restforce::Attachment when "Document" Restforce::Document else # When the hash contains an attributes key, it should be considered an # sobject record Restforce::SObject end else # Fallback to a standard Restforce::Mash for everything else Restforce::Mash end end
When passed a hash, it will determine what class is appropriate to represent the data.
klass
ruby
restforce/restforce
lib/restforce/mash.rb
https://github.com/restforce/restforce/blob/master/lib/restforce/mash.rb
MIT
def convert_value(val, duping = false) case val when self.class val.dup when ::Hash val = val.dup if duping self.class.klass(val).new(val, @client) when Array val.collect { |e| convert_value(e) } else val end end
The #convert_value method and its signature are part of Hashie::Mash's API, so we can't unilaterally decide to change `duping` to be a keyword argument rubocop:disable Style/OptionalBooleanParameter
convert_value
ruby
restforce/restforce
lib/restforce/mash.rb
https://github.com/restforce/restforce/blob/master/lib/restforce/mash.rb
MIT
def decode return nil if signature != hmac JSON.parse(Base64.decode64(payload)) end
Public: Decode the signed request. Returns the parsed JSON context. Returns nil if the signed request is invalid.
decode
ruby
restforce/restforce
lib/restforce/signed_request.rb
https://github.com/restforce/restforce/blob/master/lib/restforce/signed_request.rb
MIT
def describe_layouts(layout_id = nil) @client.describe_layouts(sobject_type, layout_id) end
Public: Describe layouts for this sobject type
describe_layouts
ruby
restforce/restforce
lib/restforce/sobject.rb
https://github.com/restforce/restforce/blob/master/lib/restforce/sobject.rb
MIT
def save ensure_id @client.update(sobject_type, attrs) end
Public: Persist the attributes to Salesforce. Examples account = client.query('select Id, Name from Account').first account.Name = 'Foobar' account.save
save
ruby
restforce/restforce
lib/restforce/sobject.rb
https://github.com/restforce/restforce/blob/master/lib/restforce/sobject.rb
MIT
def destroy ensure_id @client.destroy(sobject_type, self.Id) end
Public: Destroy this record. Examples account = client.query('select Id, Name from Account').first account.destroy
destroy
ruby
restforce/restforce
lib/restforce/sobject.rb
https://github.com/restforce/restforce/blob/master/lib/restforce/sobject.rb
MIT
def attrs self.to_hash.reject { |key, _| key =~ /.*__r/ || key =~ /^attributes$/ } end
Public: Returns a hash representation of this object with the attributes key and parent/child relationships removed.
attrs
ruby
restforce/restforce
lib/restforce/sobject.rb
https://github.com/restforce/restforce/blob/master/lib/restforce/sobject.rb
MIT
def list_sobjects describe.collect { |sobject| sobject['name'] } end
Public: Get the names of all sobjects on the org. Examples # get the names of all sobjects on the org client.list_sobjects # => ['Account', 'Lead', ... ] Returns an Array of String names for each SObject.
list_sobjects
ruby
restforce/restforce
lib/restforce/concerns/api.rb
https://github.com/restforce/restforce/blob/master/lib/restforce/concerns/api.rb
MIT
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
Public: Gets the IDs of sobjects of type [sobject] which have changed between startDateTime and endDateTime. Examples # get changes for sobject Whizbang between yesterday and today startDate = Time.new(2002, 10, 31, 2, 2, 2, "+02:00") endDate = Time.new(2002, 11, 1, 2, 2, 2, "+02:00") client.get_updated('Whizbang', startDate, endDate) Returns a Restforce::Collection if Restforce.configuration.mashify is true. Returns an Array of Hash for each record in the result if Restforce.configuration.mashify is false.
get_updated
ruby
restforce/restforce
lib/restforce/concerns/api.rb
https://github.com/restforce/restforce/blob/master/lib/restforce/concerns/api.rb
MIT
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
Public: Gets the IDs of sobjects of type [sobject] which have been deleted between startDateTime and endDateTime. Examples # get deleted sobject Whizbangs between yesterday and today startDate = Time.new(2002, 10, 31, 2, 2, 2, "+02:00") endDate = Time.new(2002, 11, 1, 2, 2, 2, "+02:00") client.get_deleted('Whizbang', startDate, endDate) Returns a Restforce::Collection if Restforce.configuration.mashify is true. Returns an Array of Hash for each record in the result if Restforce.configuration.mashify is false.
get_deleted
ruby
restforce/restforce
lib/restforce/concerns/api.rb
https://github.com/restforce/restforce/blob/master/lib/restforce/concerns/api.rb
MIT
def describe(sobject = nil) if sobject api_get("sobjects/#{sobject}/describe").body else api_get('sobjects').body['sobjects'] end end
Public: Returns a detailed describe result for the specified sobject sobject - Stringish name of the sobject (default: nil). Examples # get the global describe for all sobjects client.describe # => { ... } # get the describe for the Account object client.describe('Account') # => { ... } Returns the Hash representation of the describe call.
describe
ruby
restforce/restforce
lib/restforce/concerns/api.rb
https://github.com/restforce/restforce/blob/master/lib/restforce/concerns/api.rb
MIT
def describe_layouts(sobject, layout_id = nil) version_guard(28.0) do if layout_id api_get("sobjects/#{sobject}/describe/layouts/#{CGI.escape(layout_id)}").body else api_get("sobjects/#{sobject}/describe/layouts").body end end end
Public: Returns a detailed description of the Page Layout for the specified sobject type, or URIs for layouts if the sobject has multiple Record Types. Only available in version 28.0 and later of the Salesforce API. Examples: # get the layouts for the sobject client.describe_layouts('Account') # => { ... } # get the layout for the specified Id for the sobject client.describe_layouts('Account', '012E0000000RHEp') # => { ... } Returns the Hash representation of the describe_layouts result
describe_layouts
ruby
restforce/restforce
lib/restforce/concerns/api.rb
https://github.com/restforce/restforce/blob/master/lib/restforce/concerns/api.rb
MIT
def org_id query('select id from Organization').first['Id'] end
Public: Get the current organization's Id. Examples client.org_id # => '00Dx0000000BV7z' Returns the String organization Id
org_id
ruby
restforce/restforce
lib/restforce/concerns/api.rb
https://github.com/restforce/restforce/blob/master/lib/restforce/concerns/api.rb
MIT
def query(soql) response = api_get 'query', q: soql mashify? ? response.body : response.body['records'] end
Public: Executs a SOQL query and returns the result. soql - A SOQL expression. Examples # Find the names of all Accounts client.query('select Name from Account').map(&:Name) # => ['Foo Bar Inc.', 'Whizbang Corp'] Returns a Restforce::Collection if Restforce.configuration.mashify is true. Returns an Array of Hash for each record in the result if Restforce.configuration.mashify is false.
query
ruby
restforce/restforce
lib/restforce/concerns/api.rb
https://github.com/restforce/restforce/blob/master/lib/restforce/concerns/api.rb
MIT
def explain(soql) version_guard(30.0) { api_get("query", explain: soql).body } end
Public: Explain a SOQL query execution plan. Only available in version 30.0 and later of the Salesforce API. soql - A SOQL expression. Examples # Find the names of all Accounts client.explain('select Name from Account') Returns a Hash in the form {:plans => [Array of plan data]} See: https://www.salesforce.com/us/developer/docs/api_rest/Content/dome_query_expl ain.htm
explain
ruby
restforce/restforce
lib/restforce/concerns/api.rb
https://github.com/restforce/restforce/blob/master/lib/restforce/concerns/api.rb
MIT
def query_all(soql) version_guard(29.0) do response = api_get 'queryAll', q: soql mashify? ? response.body : response.body['records'] end end
Public: Executes a SOQL query and returns the result. Unlike the Query resource, QueryAll will return records that have been deleted because of a merge or delete. QueryAll will also return information about archived Task and Event records. Only available in version 29.0 and later of the Salesforce API. soql - A SOQL expression. Examples # Find the names of all Accounts client.query_all('select Name from Account').map(&:Name) # => ['Foo Bar Inc.', 'Whizbang Corp'] Returns a Restforce::Collection if Restforce.configuration.mashify is true. Returns an Array of Hash for each record in the result if Restforce.configuration.mashify is false.
query_all
ruby
restforce/restforce
lib/restforce/concerns/api.rb
https://github.com/restforce/restforce/blob/master/lib/restforce/concerns/api.rb
MIT
def search(sosl) api_get('search', q: sosl).body end
Public: Perform a SOSL search sosl - A SOSL expression. Examples # Find all occurrences of 'bar' client.search('FIND {bar}') # => #<Restforce::Collection > # Find accounts match the term 'genepoint' and return the Name field client.search('FIND {genepoint} RETURNING Account (Name)').map(&:Name) # => ['GenePoint'] Returns a Restforce::Collection if Restforce.configuration.mashify is true. Returns an Array of Hash for each record in the result if Restforce.configuration.mashify is false.
search
ruby
restforce/restforce
lib/restforce/concerns/api.rb
https://github.com/restforce/restforce/blob/master/lib/restforce/concerns/api.rb
MIT
def create(*args) create!(*args) rescue *exceptions false end
Public: Insert a new record. sobject - String name of the sobject. attrs - Hash of attributes to set on the new record. Examples # Add a new account client.create('Account', Name: 'Foobar Inc.') # => '0016000000MRatd' Returns the String Id of the newly created sobject. Returns false if something bad happens.
create
ruby
restforce/restforce
lib/restforce/concerns/api.rb
https://github.com/restforce/restforce/blob/master/lib/restforce/concerns/api.rb
MIT
def create!(sobject, attrs) api_post("sobjects/#{sobject}", attrs).body['id'] end
Public: Insert a new record. sobject - String name of the sobject. attrs - Hash of attributes to set on the new record. Examples # Add a new account client.create!('Account', Name: 'Foobar Inc.') # => '0016000000MRatd' Returns the String Id of the newly created sobject. Raises exceptions if an error is returned from Salesforce.
create!
ruby
restforce/restforce
lib/restforce/concerns/api.rb
https://github.com/restforce/restforce/blob/master/lib/restforce/concerns/api.rb
MIT
def update(*args) update!(*args) rescue *exceptions false end
Public: Update a record. sobject - String name of the sobject. attrs - Hash of attributes to set on the record. Examples # Update the Account with Id '0016000000MRatd' client.update('Account', Id: '0016000000MRatd', Name: 'Whizbang Corp') Returns true if the sobject was successfully updated. Returns false if there was an error.
update
ruby
restforce/restforce
lib/restforce/concerns/api.rb
https://github.com/restforce/restforce/blob/master/lib/restforce/concerns/api.rb
MIT
def update!(sobject, attrs) id = attrs.fetch(attrs.keys.find { |k, v| k.to_s.casecmp('id').zero? }, nil) raise ArgumentError, 'ID field missing from provided attributes' unless id attrs_without_id = attrs.reject { |k, v| k.to_s.casecmp("id").zero? } api_patch "sobjects/#{sobject}/#{CGI.escape(id)}", attrs_without_id true end
Public: Update a record. sobject - String name of the sobject. attrs - Hash of attributes to set on the record. Examples # Update the Account with Id '0016000000MRatd' client.update!('Account', Id: '0016000000MRatd', Name: 'Whizbang Corp') Returns true if the sobject was successfully updated. Raises an exception if an error is returned from Salesforce.
update!
ruby
restforce/restforce
lib/restforce/concerns/api.rb
https://github.com/restforce/restforce/blob/master/lib/restforce/concerns/api.rb
MIT
def upsert(*args) upsert!(*args) rescue *exceptions false end
Public: Update or create a record based on an external ID sobject - The name of the sobject to created. field - The name of the external Id field to match against. attrs - Hash of attributes for the record. Examples # Update the record with external ID of 12 client.upsert('Account', 'External__c', External__c: 12, Name: 'Foobar') Returns true if the record was found and updated. Returns the Id of the newly created record if the record was created. Returns false if something bad happens (for example if the external ID matches multiple resources).
upsert
ruby
restforce/restforce
lib/restforce/concerns/api.rb
https://github.com/restforce/restforce/blob/master/lib/restforce/concerns/api.rb
MIT
def upsert!(sobject, field, attrs) attrs = attrs.dup external_id = extract_case_insensitive_string_or_symbol_key_from_hash!(attrs, field).to_s if field.to_s != "Id" && (external_id.nil? || external_id.strip.empty?) raise ArgumentError, 'Specified external ID field missing from provided ' \ 'attributes' end response = if field.to_s == "Id" && (external_id.nil? || external_id.strip.empty?) version_guard(37.0) do api_post "sobjects/#{sobject}/#{field}", attrs end else api_patch "sobjects/#{sobject}/#{field}/" \ "#{ERB::Util.url_encode(external_id)}", attrs end response.body.respond_to?(:fetch) ? response.body.fetch('id', true) : true end
Public: Update or create a record based on an external ID sobject - The name of the sobject to created. field - The name of the external Id field to match against. attrs - Hash of attributes for the record. Examples # Update the record with external ID of 12 client.upsert!('Account', 'External__c', External__c: 12, Name: 'Foobar') Returns true if the record was found and updated. Returns the Id of the newly created record if the record was created. Raises an exception if an error is returned from Salesforce, including the 300 error returned if the external ID provided matches multiple records (in which case the conflicting IDs can be found by looking at the response on the error)
upsert!
ruby
restforce/restforce
lib/restforce/concerns/api.rb
https://github.com/restforce/restforce/blob/master/lib/restforce/concerns/api.rb
MIT
def destroy(*args) destroy!(*args) rescue *exceptions false end
Public: Delete a record. sobject - String name of the sobject. id - The Salesforce ID of the record. Examples # Delete the Account with Id '0016000000MRatd' client.destroy('Account', '0016000000MRatd') Returns true if the sobject was successfully deleted. Returns false if an error is returned from Salesforce.
destroy
ruby
restforce/restforce
lib/restforce/concerns/api.rb
https://github.com/restforce/restforce/blob/master/lib/restforce/concerns/api.rb
MIT
def destroy!(sobject, id) api_delete "sobjects/#{sobject}/#{ERB::Util.url_encode(id)}" true end
Public: Delete a record. sobject - String name of the sobject. id - The Salesforce ID of the record. Examples # Delete the Account with Id '0016000000MRatd' client.destroy('Account', '0016000000MRatd') Returns true of the sobject was successfully deleted. Raises an exception if an error is returned from Salesforce.
destroy!
ruby
restforce/restforce
lib/restforce/concerns/api.rb
https://github.com/restforce/restforce/blob/master/lib/restforce/concerns/api.rb
MIT
def find(sobject, id, field = nil) url = if field "sobjects/#{sobject}/#{field}/#{ERB::Util.url_encode(id)}" else "sobjects/#{sobject}/#{ERB::Util.url_encode(id)}" end api_get(url).body end
Public: Finds a single record and returns all fields. sobject - The String name of the sobject. id - The id of the record. If field is specified, id should be the id of the external field. field - External ID field to use (default: nil). Returns the Restforce::SObject sobject record. Raises NotFoundError if nothing is found.
find
ruby
restforce/restforce
lib/restforce/concerns/api.rb
https://github.com/restforce/restforce/blob/master/lib/restforce/concerns/api.rb
MIT
def select(sobject, id, select, field = nil) path = if field "sobjects/#{sobject}/#{field}/#{ERB::Util.url_encode(id)}" else "sobjects/#{sobject}/#{ERB::Util.url_encode(id)}" end path = "#{path}?fields=#{select.join(',')}" if select&.any? api_get(path).body end
Public: Finds a single record and returns select fields. sobject - The String name of the sobject. id - The id of the record. If field is specified, id should be the id of the external field. select - A String array denoting the fields to select. If nil or empty array is passed, all fields are selected. field - External ID field to use (default: nil).
select
ruby
restforce/restforce
lib/restforce/concerns/api.rb
https://github.com/restforce/restforce/blob/master/lib/restforce/concerns/api.rb
MIT
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
Internal: Ensures that the `api_version` set for the Restforce client is at least the provided version before performing a particular action
version_guard
ruby
restforce/restforce
lib/restforce/concerns/api.rb
https://github.com/restforce/restforce/blob/master/lib/restforce/concerns/api.rb
MIT
def authentication_middleware if username_password? Restforce::Middleware::Authentication::Password elsif oauth_refresh? Restforce::Middleware::Authentication::Token elsif jwt? Restforce::Middleware::Authentication::JWTBearer elsif client_credential? Restforce::Middleware::Authentication::ClientCredential end end
Internal: Determines what middleware will be used based on the options provided
authentication_middleware
ruby
restforce/restforce
lib/restforce/concerns/authentication.rb
https://github.com/restforce/restforce/blob/master/lib/restforce/concerns/authentication.rb
MIT
def username_password? options[:username] && options[:password] && options[:client_id] && options[:client_secret] end
Internal: Returns true if username/password (autonomous) flow should be used for authentication.
username_password?
ruby
restforce/restforce
lib/restforce/concerns/authentication.rb
https://github.com/restforce/restforce/blob/master/lib/restforce/concerns/authentication.rb
MIT
def oauth_refresh? options[:refresh_token] && options[:client_id] && options[:client_secret] end
Internal: Returns true if oauth token refresh flow should be used for authentication.
oauth_refresh?
ruby
restforce/restforce
lib/restforce/concerns/authentication.rb
https://github.com/restforce/restforce/blob/master/lib/restforce/concerns/authentication.rb
MIT
def jwt? options[:jwt_key] && options[:username] && options[:client_id] end
Internal: Returns true if jwt bearer token flow should be used for authentication.
jwt?
ruby
restforce/restforce
lib/restforce/concerns/authentication.rb
https://github.com/restforce/restforce/blob/master/lib/restforce/concerns/authentication.rb
MIT
def client_credential? options[:client_id] && options[:client_secret] end
Internal: Returns true if client credential flow should be used for authentication.
client_credential?
ruby
restforce/restforce
lib/restforce/concerns/authentication.rb
https://github.com/restforce/restforce/blob/master/lib/restforce/concerns/authentication.rb
MIT
def without_caching options[:use_cache] = false yield ensure options.delete(:use_cache) end
Public: Runs the block with caching disabled. block - A query/describe/etc. Returns the result of the block
without_caching
ruby
restforce/restforce
lib/restforce/concerns/caching.rb
https://github.com/restforce/restforce/blob/master/lib/restforce/concerns/caching.rb
MIT
def connection @connection ||= Faraday.new(options[:instance_url], connection_options) do |builder| # Parses JSON into Hashie::Mash structures. unless options[:mashify] == false builder.use Restforce::Middleware::Mashify, self, options end # Handles multipart file uploads for blobs. builder.use Restforce::Middleware::Multipart # Converts the request into JSON. builder.request :restforce_json # Handles reauthentication for 403 responses. if authentication_middleware builder.use authentication_middleware, self, options end # Sets the oauth token in the headers. builder.use Restforce::Middleware::Authorization, self, options # Ensures the instance url is set. builder.use Restforce::Middleware::InstanceURL, self, options # Caches GET requests. builder.use Restforce::Middleware::Caching, cache, options if cache # Follows 30x redirects. builder.use Faraday::FollowRedirects::Middleware, { # Pass the option to clear or send the auth header on redirects through clear_authorization_header: options[:clear_authorization_header] } # Raises errors for 40x responses. builder.use Restforce::Middleware::RaiseError # Parses returned JSON response into a hash. builder.response :restforce_json, content_type: /\bjson$/ # Compress/Decompress the request/response unless adapter == :httpclient builder.use Restforce::Middleware::Gzip, self, options end # Inject custom headers into requests builder.use Restforce::Middleware::CustomHeaders, self, options # Log request/responses if Restforce.log? builder.use Restforce::Middleware::Logger, Restforce.configuration.logger, options end builder.adapter adapter end end
Internal: Internal faraday connection where all requests go through rubocop:disable Metrics/AbcSize rubocop:disable Metrics/BlockLength
connection
ruby
restforce/restforce
lib/restforce/concerns/connection.rb
https://github.com/restforce/restforce/blob/master/lib/restforce/concerns/connection.rb
MIT
def picklist_values(sobject, field, options = {}) PicklistValues.new(describe(sobject)['fields'], field, options) end
Public: Get the available picklist values for a picklist or multipicklist field. sobject - The String name of the sobject. field - The String name of the picklist/multipicklist field. options - A hash of options. (default: {}). :valid_for - If specified, will only return picklist values that are valid for the controlling picklist value Examples client.picklist_values('Account', 'Type') # => [#<Restforce::Mash label="Prospect" value="Prospect">] # Given a custom object named Automobile__c with picklist fields # Model__c and Make__c, where Model__c depends on the value of # Make__c. client.picklist_values('Automobile__c', 'Model__c', :valid_for => 'Honda') # => [#<Restforce::Mash label="Civic" value="Civic">, ... ] Returns an array of Restforce::Mash objects.
picklist_values
ruby
restforce/restforce
lib/restforce/concerns/picklists.rb
https://github.com/restforce/restforce/blob/master/lib/restforce/concerns/picklists.rb
MIT
def valid?(picklist_entry) valid_for = picklist_entry['validFor'].ljust(16, 'A').unpack1('m'). unpack('C*') valid_for[index >> 3].anybits?((0x80 >> (index % 8))) end
Returns true if the picklist entry is valid for the controlling picklist. See http://www.salesforce.com/us/developer/docs/api/Content/sforce_api_calls_des cribesobjects_describesobjectresult.htm
valid?
ruby
restforce/restforce
lib/restforce/concerns/picklists.rb
https://github.com/restforce/restforce/blob/master/lib/restforce/concerns/picklists.rb
MIT
def legacy_subscribe(topics, options = {}, &) topics = Array(topics).map { |channel| "/topic/#{channel}" } subscription(topics, options, &) end
Public: Subscribe to a PushTopic topics - The name of the PushTopic channel(s) to subscribe to. block - A block to run when a new message is received. Returns a Faye::Subscription
legacy_subscribe
ruby
restforce/restforce
lib/restforce/concerns/streaming.rb
https://github.com/restforce/restforce/blob/master/lib/restforce/concerns/streaming.rb
MIT
def subscription(channels, options = {}, &) one_or_more_channels = Array(channels) one_or_more_channels.each do |channel| replay_handlers[channel] = options[:replay] end faye.subscribe(one_or_more_channels, &) end
Public: Subscribe to one or more Streaming API channels channels - The name of the Streaming API (cometD) channel(s) to subscribe to. block - A block to run when a new message is received. Returns a Faye::Subscription
subscription
ruby
restforce/restforce
lib/restforce/concerns/streaming.rb
https://github.com/restforce/restforce/blob/master/lib/restforce/concerns/streaming.rb
MIT
def faye unless options[:instance_url] raise 'Instance URL missing. Call .authenticate! first.' end url = "#{options[:instance_url]}/cometd/#{options[:api_version]}" @faye ||= Faye::Client.new(url).tap do |client| client.set_header 'Authorization', "OAuth #{options[:oauth_token]}" client.bind 'transport:down' do Restforce.log "[COMETD DOWN]" client.set_header 'Authorization', "OAuth #{authenticate!.access_token}" end client.bind 'transport:up' do Restforce.log "[COMETD UP]" end client.add_extension ReplayExtension.new(replay_handlers) end end
Public: Faye client to use for subscribing to PushTopics
faye
ruby
restforce/restforce
lib/restforce/concerns/streaming.rb
https://github.com/restforce/restforce/blob/master/lib/restforce/concerns/streaming.rb
MIT
def define_verbs(*verbs) verbs.each do |verb| define_verb(verb) define_api_verb(verb) end end
Internal: Define methods to handle a verb. verbs - A list of verbs to define methods for. Examples define_verbs :get, :post Returns nil.
define_verbs
ruby
restforce/restforce
lib/restforce/concerns/verbs.rb
https://github.com/restforce/restforce/blob/master/lib/restforce/concerns/verbs.rb
MIT
def define_verb(verb) define_method verb do |*args, &block| retries = options[:authentication_retries] begin connection.send(verb, *args, &block) rescue Restforce::UnauthorizedError if retries.positive? retries -= 1 connection.url_prefix = options[:instance_url] retry end raise end end end
Internal: Defines a method to handle HTTP requests with the passed in verb. verb - Symbol name of the verb (e.g. :get). Examples define_verb :get # => get '/services/data/v24.0/sobjects' Returns nil.
define_verb
ruby
restforce/restforce
lib/restforce/concerns/verbs.rb
https://github.com/restforce/restforce/blob/master/lib/restforce/concerns/verbs.rb
MIT
def define_api_verb(verb) define_method :"api_#{verb}" do |*args, &block| args[0] = api_path(args[0]) send(verb, *args, &block) end end
Internal: Defines a method to handle HTTP requests with the passed in verb to a salesforce api endpoint. verb - Symbol name of the verb (e.g. :get). Examples define_api_verb :get # => api_get 'sobjects' Returns nil.
define_api_verb
ruby
restforce/restforce
lib/restforce/concerns/verbs.rb
https://github.com/restforce/restforce/blob/master/lib/restforce/concerns/verbs.rb
MIT
def url(resource) resource_name_for_url = if resource.respond_to?(:to_sparam) resource.to_sparam else resource end "#{instance_url}/#{resource_name_for_url}" end
Public: Returns a url to the resource. resource - A record that responds to to_sparam or a String/Fixnum. Returns the url to the resource.
url
ruby
restforce/restforce
lib/restforce/data/client.rb
https://github.com/restforce/restforce/blob/master/lib/restforce/data/client.rb
MIT
def call(env) @app.call(env) rescue Restforce::UnauthorizedError authenticate! raise end
Rescue from 401's, authenticate then raise the error again so the client can reissue the request.
call
ruby
restforce/restforce
lib/restforce/middleware/authentication.rb
https://github.com/restforce/restforce/blob/master/lib/restforce/middleware/authentication.rb
MIT
def authenticate! response = connection.post '/services/oauth2/token' do |req| req.body = encode_www_form(params) end if response.status >= 500 raise Restforce::ServerError, error_message(response) elsif response.status != 200 raise Restforce::AuthenticationError, error_message(response) end @options[:instance_url] = response.body['instance_url'] @options[:oauth_token] = response.body['access_token'] @options[:authentication_callback]&.call(response.body) response.body end
Internal: Performs the authentication and returns the response body.
authenticate!
ruby
restforce/restforce
lib/restforce/middleware/authentication.rb
https://github.com/restforce/restforce/blob/master/lib/restforce/middleware/authentication.rb
MIT
def params raise NotImplementedError end
Internal: The params to post to the OAuth service.
params
ruby
restforce/restforce
lib/restforce/middleware/authentication.rb
https://github.com/restforce/restforce/blob/master/lib/restforce/middleware/authentication.rb
MIT
def connection @connection ||= Faraday.new(faraday_options) do |builder| builder.use Faraday::Request::UrlEncoded builder.use Restforce::Middleware::Mashify, nil, @options builder.use Faraday::FollowRedirects::Middleware builder.response :restforce_json if Restforce.log? builder.use Restforce::Middleware::Logger, Restforce.configuration.logger, @options end builder.adapter @options[:adapter] end end
Internal: Faraday connection to use when sending an authentication request.
connection
ruby
restforce/restforce
lib/restforce/middleware/authentication.rb
https://github.com/restforce/restforce/blob/master/lib/restforce/middleware/authentication.rb
MIT
def encode_www_form(params) if URI.respond_to?(:encode_www_form) URI.encode_www_form(params) else params.map do |k, v| k = CGI.escape(k.to_s) v = CGI.escape(v.to_s) "#{k}=#{v}" end.join('&') end end
Featured detect form encoding. URI in 1.8 does not include encode_www_form
encode_www_form
ruby
restforce/restforce
lib/restforce/middleware/authentication.rb
https://github.com/restforce/restforce/blob/master/lib/restforce/middleware/authentication.rb
MIT
def initialize(app, cache = nil, options = {}) super(app) if cache.is_a?(Hash) && block_given? options = cache cache = nil end @cache = cache || yield @options = options end
Public: initialize the middleware. cache - An object that responds to read and write (default: nil). options - An options Hash (default: {}): :ignore_params - String name or Array names of query params that should be ignored when forming the cache key (default: []). :write_options - Hash of settings that should be passed as the third options parameter to the cache's #write method. If not specified, no options parameter will be passed. :full_key - Boolean - use full URL as cache key: (url.host + url.request_uri) :status_codes - Array of http status code to be cache (default: CACHEABLE_STATUS_CODE) Yields if no cache is given. The block should return a cache object.
initialize
ruby
restforce/restforce
lib/restforce/middleware/caching.rb
https://github.com/restforce/restforce/blob/master/lib/restforce/middleware/caching.rb
MIT
def gzipped?(env) env[:response_headers][CONTENT_ENCODING_HEADER] == ENCODING end
Internal: Returns true if the response is gzipped.
gzipped?
ruby
restforce/restforce
lib/restforce/middleware/gzip.rb
https://github.com/restforce/restforce/blob/master/lib/restforce/middleware/gzip.rb
MIT
def call(env) on_request(env) if respond_to?(:on_request) @app.call(env).on_complete do |environment| on_complete(environment) if respond_to?(:on_complete) end end
Required for Faraday versions pre-v1.2.0 which do not include an implementation of `#call` by default
call
ruby
restforce/restforce
lib/restforce/middleware/raise_error.rb
https://github.com/restforce/restforce/blob/master/lib/restforce/middleware/raise_error.rb
MIT
def configure MUTEX.synchronize do config = @config.dup yield config @config = config.freeze @cooldown = Cooldown[@config] end end
@example Sidekiq::Throttled.configure do |config| config.cooldown_period = nil # Disable queues cooldown manager end @yieldparam config [Config]
configure
ruby
ixti/sidekiq-throttled
lib/sidekiq/throttled.rb
https://github.com/ixti/sidekiq-throttled/blob/master/lib/sidekiq/throttled.rb
MIT
def throttled?(message) message = Message.new(message) return false unless message.job_class && message.job_id Registry.get(message.job_class) do |strategy| return strategy.throttled?(message.job_id, *message.job_args) end false rescue StandardError false end
Tells whenever job is throttled or not. @param [String] message Job's JSON payload @return [Boolean]
throttled?
ruby
ixti/sidekiq-throttled
lib/sidekiq/throttled.rb
https://github.com/ixti/sidekiq-throttled/blob/master/lib/sidekiq/throttled.rb
MIT
def requeue_throttled(work) message = JSON.parse(work.job) job_class = Object.const_get(message.fetch("wrapped") { message.fetch("class") { return false } }) Registry.get job_class do |strategy| strategy.requeue_throttled(work) end end
Return throttled job to be executed later, delegating the details of how to do that to the Strategy for that job. @return [void]
requeue_throttled
ruby
ixti/sidekiq-throttled
lib/sidekiq/throttled.rb
https://github.com/ixti/sidekiq-throttled/blob/master/lib/sidekiq/throttled.rb
MIT
def notify_throttled(queue) @queues.add(queue) if @threshold <= @tracker.merge_pair(queue, 1, &:succ) end
Notify that given queue returned job that was throttled. @param queue [String] @return [void]
notify_throttled
ruby
ixti/sidekiq-throttled
lib/sidekiq/throttled/cooldown.rb
https://github.com/ixti/sidekiq-throttled/blob/master/lib/sidekiq/throttled/cooldown.rb
MIT
def initialize(ttl) raise ArgumentError, "ttl must be positive Float" unless ttl.is_a?(Float) && ttl.positive? @elements = Concurrent::Map.new @ttl = ttl end
@param ttl [Float] expiration is seconds @raise [ArgumentError] if `ttl` is not positive Float
initialize
ruby
ixti/sidekiq-throttled
lib/sidekiq/throttled/expirable_set.rb
https://github.com/ixti/sidekiq-throttled/blob/master/lib/sidekiq/throttled/expirable_set.rb
MIT
def add(element) # cleanup expired elements to avoid mem-leak horizon = now expired = @elements.each_pair.select { |(_, sunset)| expired?(sunset, horizon) } expired.each { |pair| @elements.delete_pair(*pair) } # add new element @elements[element] = now + @ttl self end
@param element [Object] @return [ExpirableSet] self
add
ruby
ixti/sidekiq-throttled
lib/sidekiq/throttled/expirable_set.rb
https://github.com/ixti/sidekiq-throttled/blob/master/lib/sidekiq/throttled/expirable_set.rb
MIT
def each return to_enum __method__ unless block_given? horizon = now @elements.each_pair do |element, sunset| yield element unless expired?(sunset, horizon) end self end
@yield [Object] Gives each live (not expired) element to the block
each
ruby
ixti/sidekiq-throttled
lib/sidekiq/throttled/expirable_set.rb
https://github.com/ixti/sidekiq-throttled/blob/master/lib/sidekiq/throttled/expirable_set.rb
MIT
def add(name, **) name = name.to_s @strategies[name] = Strategy.new(name, **) end
Adds strategy to the registry. @param (see Strategy#initialize) @return [Strategy]
add
ruby
ixti/sidekiq-throttled
lib/sidekiq/throttled/registry.rb
https://github.com/ixti/sidekiq-throttled/blob/master/lib/sidekiq/throttled/registry.rb
MIT
def add_alias(new_name, old_name) new_name = new_name.to_s old_name = old_name.to_s raise "Strategy not found: #{old_name}" unless @strategies[old_name] @aliases[new_name] = @strategies[old_name] end
Adds alias for existing strategy. @param (#to_s) new_name @param (#to_s) old_name @raise [RuntimeError] if no strategy found with `old_name` @return [Strategy]
add_alias
ruby
ixti/sidekiq-throttled
lib/sidekiq/throttled/registry.rb
https://github.com/ixti/sidekiq-throttled/blob/master/lib/sidekiq/throttled/registry.rb
MIT
def get(name) strategy = find(name.to_s) || find_by_class(name) return yield strategy if strategy && block_given? strategy end
@overload get(name) @param [#to_s] name @return [Strategy, nil] registred strategy @overload get(name, &block) Yields control to the block if requested strategy was found. @param [#to_s] name @yieldparam [Strategy] strategy @yield [strategy] Gives found strategy to the block @return result of a block
get
ruby
ixti/sidekiq-throttled
lib/sidekiq/throttled/registry.rb
https://github.com/ixti/sidekiq-throttled/blob/master/lib/sidekiq/throttled/registry.rb
MIT
def each return to_enum(__method__) unless block_given? @strategies.each { |*args| yield(*args) } self end
@overload each() @return [Enumerator] @overload each(&block) @yieldparam [String] name @yieldparam [Strategy] strategy @yield [strategy] Gives strategy to the block @return [Registry]
each
ruby
ixti/sidekiq-throttled
lib/sidekiq/throttled/registry.rb
https://github.com/ixti/sidekiq-throttled/blob/master/lib/sidekiq/throttled/registry.rb
MIT
def each_with_static_keys return to_enum(__method__) unless block_given? @strategies.each do |name, strategy| yield(name, strategy) unless strategy.dynamic? end end
@overload each_with_static_keys() @return [Enumerator] @overload each_with_static_keys(&block) @yieldparam [String] name @yieldparam [Strategy] strategy @yield [strategy] Gives strategy to the block @return [Registry]
each_with_static_keys
ruby
ixti/sidekiq-throttled
lib/sidekiq/throttled/registry.rb
https://github.com/ixti/sidekiq-throttled/blob/master/lib/sidekiq/throttled/registry.rb
MIT
def find(name) @strategies[name] || @aliases[name] end
Find strategy by it's name. @param name [String] @return [Strategy, nil]
find
ruby
ixti/sidekiq-throttled
lib/sidekiq/throttled/registry.rb
https://github.com/ixti/sidekiq-throttled/blob/master/lib/sidekiq/throttled/registry.rb
MIT
def find_by_class(name) const = name.is_a?(Class) ? name : Object.const_get(name) return unless const.is_a?(Class) const.ancestors.each do |m| strategy = find(m.name) return strategy if strategy end nil rescue NameError nil end
Find strategy by class or it's parents. @param name [Class, #to_s] @return [Strategy, nil]
find_by_class
ruby
ixti/sidekiq-throttled
lib/sidekiq/throttled/registry.rb
https://github.com/ixti/sidekiq-throttled/blob/master/lib/sidekiq/throttled/registry.rb
MIT