id
int32
0
24.9k
repo
stringlengths
5
58
path
stringlengths
9
168
func_name
stringlengths
9
130
original_string
stringlengths
66
10.5k
language
stringclasses
1 value
code
stringlengths
66
10.5k
code_tokens
list
docstring
stringlengths
8
16k
docstring_tokens
list
sha
stringlengths
40
40
url
stringlengths
94
266
17,700
brynary/webrat
lib/webrat/adapters/rails.rb
Webrat.RailsAdapter.normalize_url
def normalize_url(href) #:nodoc: uri = URI.parse(href) normalized_url = [] normalized_url << "#{uri.scheme}://" if uri.scheme normalized_url << uri.host if uri.host normalized_url << ":#{uri.port}" if uri.port && ![80,443].include?(uri.port) normalized_url << uri.path if uri.path normalized_url << "?#{uri.query}" if uri.query normalized_url.join end
ruby
def normalize_url(href) #:nodoc: uri = URI.parse(href) normalized_url = [] normalized_url << "#{uri.scheme}://" if uri.scheme normalized_url << uri.host if uri.host normalized_url << ":#{uri.port}" if uri.port && ![80,443].include?(uri.port) normalized_url << uri.path if uri.path normalized_url << "?#{uri.query}" if uri.query normalized_url.join end
[ "def", "normalize_url", "(", "href", ")", "#:nodoc:", "uri", "=", "URI", ".", "parse", "(", "href", ")", "normalized_url", "=", "[", "]", "normalized_url", "<<", "\"#{uri.scheme}://\"", "if", "uri", ".", "scheme", "normalized_url", "<<", "uri", ".", "host", "if", "uri", ".", "host", "normalized_url", "<<", "\":#{uri.port}\"", "if", "uri", ".", "port", "&&", "!", "[", "80", ",", "443", "]", ".", "include?", "(", "uri", ".", "port", ")", "normalized_url", "<<", "uri", ".", "path", "if", "uri", ".", "path", "normalized_url", "<<", "\"?#{uri.query}\"", "if", "uri", ".", "query", "normalized_url", ".", "join", "end" ]
remove protocol, host and anchor
[ "remove", "protocol", "host", "and", "anchor" ]
1263639e24ce0f5e2eeeae614f10f900f498d92a
https://github.com/brynary/webrat/blob/1263639e24ce0f5e2eeeae614f10f900f498d92a/lib/webrat/adapters/rails.rb#L54-L63
17,701
brynary/webrat
lib/webrat/core/elements/form.rb
Webrat.Form.params
def params query_string = [] replaces = {} fields.each do |field| next if field.to_query_string.nil? replaces.merge!({field.digest_value => field.test_uploaded_file}) if field.is_a?(FileField) query_string << field.to_query_string end query_params = self.class.query_string_to_params(query_string.join('&')) query_params = self.class.replace_params_values(query_params, replaces) self.class.unescape_params(query_params) end
ruby
def params query_string = [] replaces = {} fields.each do |field| next if field.to_query_string.nil? replaces.merge!({field.digest_value => field.test_uploaded_file}) if field.is_a?(FileField) query_string << field.to_query_string end query_params = self.class.query_string_to_params(query_string.join('&')) query_params = self.class.replace_params_values(query_params, replaces) self.class.unescape_params(query_params) end
[ "def", "params", "query_string", "=", "[", "]", "replaces", "=", "{", "}", "fields", ".", "each", "do", "|", "field", "|", "next", "if", "field", ".", "to_query_string", ".", "nil?", "replaces", ".", "merge!", "(", "{", "field", ".", "digest_value", "=>", "field", ".", "test_uploaded_file", "}", ")", "if", "field", ".", "is_a?", "(", "FileField", ")", "query_string", "<<", "field", ".", "to_query_string", "end", "query_params", "=", "self", ".", "class", ".", "query_string_to_params", "(", "query_string", ".", "join", "(", "'&'", ")", ")", "query_params", "=", "self", ".", "class", ".", "replace_params_values", "(", "query_params", ",", "replaces", ")", "self", ".", "class", ".", "unescape_params", "(", "query_params", ")", "end" ]
iterate over all form fields to build a request querystring to get params from it, for file_field we made a work around to pass a digest as value to later replace it in params hash with the real file.
[ "iterate", "over", "all", "form", "fields", "to", "build", "a", "request", "querystring", "to", "get", "params", "from", "it", "for", "file_field", "we", "made", "a", "work", "around", "to", "pass", "a", "digest", "as", "value", "to", "later", "replace", "it", "in", "params", "hash", "with", "the", "real", "file", "." ]
1263639e24ce0f5e2eeeae614f10f900f498d92a
https://github.com/brynary/webrat/blob/1263639e24ce0f5e2eeeae614f10f900f498d92a/lib/webrat/core/elements/form.rb#L44-L59
17,702
brynary/webrat
lib/webrat/core/matchers/have_selector.rb
Webrat.Matchers.assert_have_selector
def assert_have_selector(name, attributes = {}, &block) matcher = HaveSelector.new(name, attributes, &block) assert matcher.matches?(response_body), matcher.failure_message end
ruby
def assert_have_selector(name, attributes = {}, &block) matcher = HaveSelector.new(name, attributes, &block) assert matcher.matches?(response_body), matcher.failure_message end
[ "def", "assert_have_selector", "(", "name", ",", "attributes", "=", "{", "}", ",", "&", "block", ")", "matcher", "=", "HaveSelector", ".", "new", "(", "name", ",", "attributes", ",", "block", ")", "assert", "matcher", ".", "matches?", "(", "response_body", ")", ",", "matcher", ".", "failure_message", "end" ]
Asserts that the body of the response contains the supplied selector
[ "Asserts", "that", "the", "body", "of", "the", "response", "contains", "the", "supplied", "selector" ]
1263639e24ce0f5e2eeeae614f10f900f498d92a
https://github.com/brynary/webrat/blob/1263639e24ce0f5e2eeeae614f10f900f498d92a/lib/webrat/core/matchers/have_selector.rb#L72-L75
17,703
CocoaPods/cocoapods-try
lib/pod/try_settings.rb
Pod.TrySettings.prompt_for_permission
def prompt_for_permission UI.titled_section 'Running Pre-Install Commands' do commands = pre_install_commands.length > 1 ? 'commands' : 'command' UI.puts "In order to try this pod, CocoaPods-Try needs to run the following #{commands}:" pre_install_commands.each { |command| UI.puts " - #{command}" } UI.puts "\nPress return to run these #{commands}, or press `ctrl + c` to stop trying this pod." end # Give an elegant exit point. UI.gets.chomp end
ruby
def prompt_for_permission UI.titled_section 'Running Pre-Install Commands' do commands = pre_install_commands.length > 1 ? 'commands' : 'command' UI.puts "In order to try this pod, CocoaPods-Try needs to run the following #{commands}:" pre_install_commands.each { |command| UI.puts " - #{command}" } UI.puts "\nPress return to run these #{commands}, or press `ctrl + c` to stop trying this pod." end # Give an elegant exit point. UI.gets.chomp end
[ "def", "prompt_for_permission", "UI", ".", "titled_section", "'Running Pre-Install Commands'", "do", "commands", "=", "pre_install_commands", ".", "length", ">", "1", "?", "'commands'", ":", "'command'", "UI", ".", "puts", "\"In order to try this pod, CocoaPods-Try needs to run the following #{commands}:\"", "pre_install_commands", ".", "each", "{", "|", "command", "|", "UI", ".", "puts", "\" - #{command}\"", "}", "UI", ".", "puts", "\"\\nPress return to run these #{commands}, or press `ctrl + c` to stop trying this pod.\"", "end", "# Give an elegant exit point.", "UI", ".", "gets", ".", "chomp", "end" ]
If we need to run commands from pod-try we should let the users know what is going to be running on their device.
[ "If", "we", "need", "to", "run", "commands", "from", "pod", "-", "try", "we", "should", "let", "the", "users", "know", "what", "is", "going", "to", "be", "running", "on", "their", "device", "." ]
2c0840a6ba64056931622abc1d11479ffcc4a31b
https://github.com/CocoaPods/cocoapods-try/blob/2c0840a6ba64056931622abc1d11479ffcc4a31b/lib/pod/try_settings.rb#L29-L39
17,704
CocoaPods/cocoapods-try
lib/pod/try_settings.rb
Pod.TrySettings.run_pre_install_commands
def run_pre_install_commands(prompt) if pre_install_commands prompt_for_permission if prompt pre_install_commands.each { |command| Executable.execute_command('bash', ['-ec', command], true) } end end
ruby
def run_pre_install_commands(prompt) if pre_install_commands prompt_for_permission if prompt pre_install_commands.each { |command| Executable.execute_command('bash', ['-ec', command], true) } end end
[ "def", "run_pre_install_commands", "(", "prompt", ")", "if", "pre_install_commands", "prompt_for_permission", "if", "prompt", "pre_install_commands", ".", "each", "{", "|", "command", "|", "Executable", ".", "execute_command", "(", "'bash'", ",", "[", "'-ec'", ",", "command", "]", ",", "true", ")", "}", "end", "end" ]
Runs the pre_install_commands from @param [Bool] prompt Should CocoaPods-Try show a prompt with the commands to the user.
[ "Runs", "the", "pre_install_commands", "from" ]
2c0840a6ba64056931622abc1d11479ffcc4a31b
https://github.com/CocoaPods/cocoapods-try/blob/2c0840a6ba64056931622abc1d11479ffcc4a31b/lib/pod/try_settings.rb#L46-L51
17,705
torquebox/torquebox
core/lib/torquebox/logger.rb
TorqueBox.Logger.level=
def level=(new_level) if new_level.respond_to?(:to_int) new_level = STD_LOGGER_LEVELS[new_level] end LogbackUtil.set_log_level(@logger, new_level) end
ruby
def level=(new_level) if new_level.respond_to?(:to_int) new_level = STD_LOGGER_LEVELS[new_level] end LogbackUtil.set_log_level(@logger, new_level) end
[ "def", "level", "=", "(", "new_level", ")", "if", "new_level", ".", "respond_to?", "(", ":to_int", ")", "new_level", "=", "STD_LOGGER_LEVELS", "[", "new_level", "]", "end", "LogbackUtil", ".", "set_log_level", "(", "@logger", ",", "new_level", ")", "end" ]
Sets current logger's level @params [String] log level @returns [String] log level
[ "Sets", "current", "logger", "s", "level" ]
db885c118f27441a4f0d9736c193870ee046f343
https://github.com/torquebox/torquebox/blob/db885c118f27441a4f0d9736c193870ee046f343/core/lib/torquebox/logger.rb#L168-L174
17,706
torquebox/torquebox
core/lib/torquebox/daemon.rb
TorqueBox.Daemon.start
def start @java_daemon.set_action do action end @java_daemon.set_error_callback do |_, err| on_error(err) end @java_daemon.set_stop_callback do |_| on_stop end @java_daemon.start self end
ruby
def start @java_daemon.set_action do action end @java_daemon.set_error_callback do |_, err| on_error(err) end @java_daemon.set_stop_callback do |_| on_stop end @java_daemon.start self end
[ "def", "start", "@java_daemon", ".", "set_action", "do", "action", "end", "@java_daemon", ".", "set_error_callback", "do", "|", "_", ",", "err", "|", "on_error", "(", "err", ")", "end", "@java_daemon", ".", "set_stop_callback", "do", "|", "_", "|", "on_stop", "end", "@java_daemon", ".", "start", "self", "end" ]
Creates a daemon object. Optionally takes a block that is the action of the daemon. If not provided, you must extend this class and override {#action} if you want the daemon to actually do anything. The block will be passed the daemon object. @param name [String] The name of this daemon. Needs to be the same across a cluster for :singleton to work, and must be unique. @param options [Hash] Options for the daemon. @option options :singleton [true, false] (true) @option options :on_error [Proc] A custom error handler, will be passed the daemon object and the error (see {#on_error}) @option options :on_stop [Proc] A custom stop handler, will be passed the daemon object (see {#on_stop}) @option options :stop_timeout [Number] (30_000) Milliseconds to wait for the daemon thread to exit when stopping. Starts the daemon. If :singleton and in a cluster, the daemon may not be running on the current node after calling start. @return [Daemon] self
[ "Creates", "a", "daemon", "object", "." ]
db885c118f27441a4f0d9736c193870ee046f343
https://github.com/torquebox/torquebox/blob/db885c118f27441a4f0d9736c193870ee046f343/core/lib/torquebox/daemon.rb#L89-L105
17,707
sorentwo/readthis
lib/readthis/entity.rb
Readthis.Entity.load
def load(string) marshal, compress, value = decompose(string) marshal.load(inflate(value, compress)) rescue TypeError, NoMethodError string end
ruby
def load(string) marshal, compress, value = decompose(string) marshal.load(inflate(value, compress)) rescue TypeError, NoMethodError string end
[ "def", "load", "(", "string", ")", "marshal", ",", "compress", ",", "value", "=", "decompose", "(", "string", ")", "marshal", ".", "load", "(", "inflate", "(", "value", ",", "compress", ")", ")", "rescue", "TypeError", ",", "NoMethodError", "string", "end" ]
Parse a dumped value using the embedded options. @param [String] string Option embedded string to load @return [String] The original dumped string, restored @example entity.load(dumped)
[ "Parse", "a", "dumped", "value", "using", "the", "embedded", "options", "." ]
2bdf79329f2de437664ed74b2152b329f1b20704
https://github.com/sorentwo/readthis/blob/2bdf79329f2de437664ed74b2152b329f1b20704/lib/readthis/entity.rb#L78-L84
17,708
sorentwo/readthis
lib/readthis/entity.rb
Readthis.Entity.decompose
def decompose(string) flags = string[0].unpack('C').first if flags < 16 marshal = serializers.rassoc(flags) compress = (flags & COMPRESSED_FLAG) != 0 [marshal, compress, string[1..-1]] else [@options[:marshal], @options[:compress], string] end end
ruby
def decompose(string) flags = string[0].unpack('C').first if flags < 16 marshal = serializers.rassoc(flags) compress = (flags & COMPRESSED_FLAG) != 0 [marshal, compress, string[1..-1]] else [@options[:marshal], @options[:compress], string] end end
[ "def", "decompose", "(", "string", ")", "flags", "=", "string", "[", "0", "]", ".", "unpack", "(", "'C'", ")", ".", "first", "if", "flags", "<", "16", "marshal", "=", "serializers", ".", "rassoc", "(", "flags", ")", "compress", "=", "(", "flags", "&", "COMPRESSED_FLAG", ")", "!=", "0", "[", "marshal", ",", "compress", ",", "string", "[", "1", "..", "-", "1", "]", "]", "else", "[", "@options", "[", ":marshal", "]", ",", "@options", "[", ":compress", "]", ",", "string", "]", "end", "end" ]
Decompose an option embedded string into marshal, compression and value. @param [String] string Option embedded string to @return [Array<Module, Boolean, String>] An array comprised of the marshal, compression flag, and the base string.
[ "Decompose", "an", "option", "embedded", "string", "into", "marshal", "compression", "and", "value", "." ]
2bdf79329f2de437664ed74b2152b329f1b20704
https://github.com/sorentwo/readthis/blob/2bdf79329f2de437664ed74b2152b329f1b20704/lib/readthis/entity.rb#L117-L128
17,709
sorentwo/readthis
lib/readthis/cache.rb
Readthis.Cache.write
def write(key, value, options = {}) options = merged_options(options) invoke(:write, key) do |store| write_entity(key, value, store, options) end end
ruby
def write(key, value, options = {}) options = merged_options(options) invoke(:write, key) do |store| write_entity(key, value, store, options) end end
[ "def", "write", "(", "key", ",", "value", ",", "options", "=", "{", "}", ")", "options", "=", "merged_options", "(", "options", ")", "invoke", "(", ":write", ",", "key", ")", "do", "|", "store", "|", "write_entity", "(", "key", ",", "value", ",", "store", ",", "options", ")", "end", "end" ]
Writes data to the cache using the given key. Will overwrite whatever value is already stored at that key. @param [String] key Key for lookup @param [Hash] options Optional overrides @example cache.write('some-key', 'a bunch of text') # => 'OK' cache.write('some-key', 'short lived', expires_in: 60) # => 'OK' cache.write('some-key', 'lives elsehwere', namespace: 'cache') # => 'OK'
[ "Writes", "data", "to", "the", "cache", "using", "the", "given", "key", ".", "Will", "overwrite", "whatever", "value", "is", "already", "stored", "at", "that", "key", "." ]
2bdf79329f2de437664ed74b2152b329f1b20704
https://github.com/sorentwo/readthis/blob/2bdf79329f2de437664ed74b2152b329f1b20704/lib/readthis/cache.rb#L107-L113
17,710
sorentwo/readthis
lib/readthis/cache.rb
Readthis.Cache.delete
def delete(key, options = {}) namespaced = namespaced_key(key, merged_options(options)) invoke(:delete, key) do |store| store.del(namespaced) > 0 end end
ruby
def delete(key, options = {}) namespaced = namespaced_key(key, merged_options(options)) invoke(:delete, key) do |store| store.del(namespaced) > 0 end end
[ "def", "delete", "(", "key", ",", "options", "=", "{", "}", ")", "namespaced", "=", "namespaced_key", "(", "key", ",", "merged_options", "(", "options", ")", ")", "invoke", "(", ":delete", ",", "key", ")", "do", "|", "store", "|", "store", ".", "del", "(", "namespaced", ")", ">", "0", "end", "end" ]
Delete the value stored at the specified key. Returns `true` if anything was deleted, `false` otherwise. @param [String] key The key for lookup @param [Hash] options Optional overrides @example cache.delete('existing-key') # => true cache.delete('random-key') # => false
[ "Delete", "the", "value", "stored", "at", "the", "specified", "key", ".", "Returns", "true", "if", "anything", "was", "deleted", "false", "otherwise", "." ]
2bdf79329f2de437664ed74b2152b329f1b20704
https://github.com/sorentwo/readthis/blob/2bdf79329f2de437664ed74b2152b329f1b20704/lib/readthis/cache.rb#L126-L132
17,711
sorentwo/readthis
lib/readthis/cache.rb
Readthis.Cache.fetch
def fetch(key, options = {}) options ||= {} value = read(key, options) unless options[:force] if value.nil? && block_given? value = yield(key) write(key, value, options) end value end
ruby
def fetch(key, options = {}) options ||= {} value = read(key, options) unless options[:force] if value.nil? && block_given? value = yield(key) write(key, value, options) end value end
[ "def", "fetch", "(", "key", ",", "options", "=", "{", "}", ")", "options", "||=", "{", "}", "value", "=", "read", "(", "key", ",", "options", ")", "unless", "options", "[", ":force", "]", "if", "value", ".", "nil?", "&&", "block_given?", "value", "=", "yield", "(", "key", ")", "write", "(", "key", ",", "value", ",", "options", ")", "end", "value", "end" ]
Fetches data from the cache, using the given key. If there is data in the cache with the given key, then that data is returned. If there is no such data in the cache (a cache miss), then `nil` will be returned. However, if a block has been passed, that block will be passed the key and executed in the event of a cache miss. The return value of the block will be written to the cache under the given cache key, and that return value will be returned. @param [String] key Key for lookup @param options [Hash] Optional overrides @option options [Boolean] :force Force a cache miss @yield [String] Gives a missing key to the block, which is used to generate the missing value @example Typical cache.write('today', 'Monday') cache.fetch('today') # => "Monday" cache.fetch('city') # => nil @example With a block cache.fetch('city') do 'Duckburgh' end cache.fetch('city') # => "Duckburgh" @example Cache Miss cache.write('today', 'Monday') cache.fetch('today', force: true) # => nil
[ "Fetches", "data", "from", "the", "cache", "using", "the", "given", "key", ".", "If", "there", "is", "data", "in", "the", "cache", "with", "the", "given", "key", "then", "that", "data", "is", "returned", "." ]
2bdf79329f2de437664ed74b2152b329f1b20704
https://github.com/sorentwo/readthis/blob/2bdf79329f2de437664ed74b2152b329f1b20704/lib/readthis/cache.rb#L211-L221
17,712
sorentwo/readthis
lib/readthis/cache.rb
Readthis.Cache.increment
def increment(key, amount = 1, options = {}) invoke(:increment, key) do |store| alter(store, key, amount, options) end end
ruby
def increment(key, amount = 1, options = {}) invoke(:increment, key) do |store| alter(store, key, amount, options) end end
[ "def", "increment", "(", "key", ",", "amount", "=", "1", ",", "options", "=", "{", "}", ")", "invoke", "(", ":increment", ",", "key", ")", "do", "|", "store", "|", "alter", "(", "store", ",", "key", ",", "amount", ",", "options", ")", "end", "end" ]
Increment a key in the store. If the key doesn't exist it will be initialized at 0. If the key exists but it isn't a Fixnum it will be coerced to 0. Note that this method does *not* use Redis' native `incr` or `incrby` commands. Those commands only work with number-like strings, and are incompatible with the encoded values Readthis writes to the store. The behavior of `incrby` is preserved as much as possible, but incrementing is not an atomic action. If multiple clients are incrementing the same key there will be a "last write wins" race condition, causing incorrect counts. If you absolutely require correct counts it is better to use the Redis client directly. @param [String] key Key for lookup @param [Fixnum] amount Value to increment by @param [Hash] options Optional overrides @example cache.increment('counter') # => 1 cache.increment('counter', 2) # => 3
[ "Increment", "a", "key", "in", "the", "store", "." ]
2bdf79329f2de437664ed74b2152b329f1b20704
https://github.com/sorentwo/readthis/blob/2bdf79329f2de437664ed74b2152b329f1b20704/lib/readthis/cache.rb#L248-L252
17,713
sorentwo/readthis
lib/readthis/cache.rb
Readthis.Cache.decrement
def decrement(key, amount = 1, options = {}) invoke(:decrement, key) do |store| alter(store, key, -amount, options) end end
ruby
def decrement(key, amount = 1, options = {}) invoke(:decrement, key) do |store| alter(store, key, -amount, options) end end
[ "def", "decrement", "(", "key", ",", "amount", "=", "1", ",", "options", "=", "{", "}", ")", "invoke", "(", ":decrement", ",", "key", ")", "do", "|", "store", "|", "alter", "(", "store", ",", "key", ",", "-", "amount", ",", "options", ")", "end", "end" ]
Decrement a key in the store. If the key doesn't exist it will be initialized at 0. If the key exists but it isn't a Fixnum it will be coerced to 0. Like `increment`, this does not make use of the native `decr` or `decrby` commands. @param [String] key Key for lookup @param [Fixnum] amount Value to decrement by @param [Hash] options Optional overrides @example cache.write('counter', 20) # => 20 cache.decrement('counter') # => 19 cache.decrement('counter', 2) # => 17
[ "Decrement", "a", "key", "in", "the", "store", "." ]
2bdf79329f2de437664ed74b2152b329f1b20704
https://github.com/sorentwo/readthis/blob/2bdf79329f2de437664ed74b2152b329f1b20704/lib/readthis/cache.rb#L270-L274
17,714
sorentwo/readthis
lib/readthis/cache.rb
Readthis.Cache.read_multi
def read_multi(*keys) options = merged_options(extract_options!(keys)) mapping = keys.map { |key| namespaced_key(key, options) } return {} if keys.empty? invoke(:read_multi, keys) do |store| values = store.mget(*mapping).map { |value| entity.load(value) } refresh_entity(mapping, store, options) zipped_results(keys, values, options) end end
ruby
def read_multi(*keys) options = merged_options(extract_options!(keys)) mapping = keys.map { |key| namespaced_key(key, options) } return {} if keys.empty? invoke(:read_multi, keys) do |store| values = store.mget(*mapping).map { |value| entity.load(value) } refresh_entity(mapping, store, options) zipped_results(keys, values, options) end end
[ "def", "read_multi", "(", "*", "keys", ")", "options", "=", "merged_options", "(", "extract_options!", "(", "keys", ")", ")", "mapping", "=", "keys", ".", "map", "{", "|", "key", "|", "namespaced_key", "(", "key", ",", "options", ")", "}", "return", "{", "}", "if", "keys", ".", "empty?", "invoke", "(", ":read_multi", ",", "keys", ")", "do", "|", "store", "|", "values", "=", "store", ".", "mget", "(", "mapping", ")", ".", "map", "{", "|", "value", "|", "entity", ".", "load", "(", "value", ")", "}", "refresh_entity", "(", "mapping", ",", "store", ",", "options", ")", "zipped_results", "(", "keys", ",", "values", ",", "options", ")", "end", "end" ]
Efficiently read multiple values at once from the cache. Options can be passed in the last argument. @overload read_multi(keys) Return all values for the given keys. @param [String] One or more keys to fetch @param [Hash] options Configuration to override @return [Hash] A hash mapping keys to the values found. @example cache.read_multi('a', 'b') # => { 'a' => 1 } cache.read_multi('a', 'b', retain_nils: true) # => { 'a' => 1, 'b' => nil }
[ "Efficiently", "read", "multiple", "values", "at", "once", "from", "the", "cache", ".", "Options", "can", "be", "passed", "in", "the", "last", "argument", "." ]
2bdf79329f2de437664ed74b2152b329f1b20704
https://github.com/sorentwo/readthis/blob/2bdf79329f2de437664ed74b2152b329f1b20704/lib/readthis/cache.rb#L291-L304
17,715
sorentwo/readthis
lib/readthis/cache.rb
Readthis.Cache.write_multi
def write_multi(hash, options = {}) options = merged_options(options) invoke(:write_multi, hash.keys) do |store| store.multi do hash.each { |key, value| write_entity(key, value, store, options) } end end end
ruby
def write_multi(hash, options = {}) options = merged_options(options) invoke(:write_multi, hash.keys) do |store| store.multi do hash.each { |key, value| write_entity(key, value, store, options) } end end end
[ "def", "write_multi", "(", "hash", ",", "options", "=", "{", "}", ")", "options", "=", "merged_options", "(", "options", ")", "invoke", "(", ":write_multi", ",", "hash", ".", "keys", ")", "do", "|", "store", "|", "store", ".", "multi", "do", "hash", ".", "each", "{", "|", "key", ",", "value", "|", "write_entity", "(", "key", ",", "value", ",", "store", ",", "options", ")", "}", "end", "end", "end" ]
Write multiple key value pairs simultaneously. This is an atomic operation that will always succeed and will overwrite existing values. This is a non-standard, but useful, cache method. @param [Hash] hash Key value hash to write @param [Hash] options Optional overrides @example cache.write_multi({ 'a' => 1, 'b' => 2 }) # => true
[ "Write", "multiple", "key", "value", "pairs", "simultaneously", ".", "This", "is", "an", "atomic", "operation", "that", "will", "always", "succeed", "and", "will", "overwrite", "existing", "values", "." ]
2bdf79329f2de437664ed74b2152b329f1b20704
https://github.com/sorentwo/readthis/blob/2bdf79329f2de437664ed74b2152b329f1b20704/lib/readthis/cache.rb#L319-L327
17,716
sorentwo/readthis
lib/readthis/cache.rb
Readthis.Cache.fetch_multi
def fetch_multi(*keys) options = extract_options!(keys).merge(retain_nils: true) results = read_multi(*keys, options) missing = {} invoke(:fetch_multi, keys) do |_store| results.each do |key, value| next unless value.nil? value = yield(key) missing[key] = value results[key] = value end end write_multi(missing, options) if missing.any? results end
ruby
def fetch_multi(*keys) options = extract_options!(keys).merge(retain_nils: true) results = read_multi(*keys, options) missing = {} invoke(:fetch_multi, keys) do |_store| results.each do |key, value| next unless value.nil? value = yield(key) missing[key] = value results[key] = value end end write_multi(missing, options) if missing.any? results end
[ "def", "fetch_multi", "(", "*", "keys", ")", "options", "=", "extract_options!", "(", "keys", ")", ".", "merge", "(", "retain_nils", ":", "true", ")", "results", "=", "read_multi", "(", "keys", ",", "options", ")", "missing", "=", "{", "}", "invoke", "(", ":fetch_multi", ",", "keys", ")", "do", "|", "_store", "|", "results", ".", "each", "do", "|", "key", ",", "value", "|", "next", "unless", "value", ".", "nil?", "value", "=", "yield", "(", "key", ")", "missing", "[", "key", "]", "=", "value", "results", "[", "key", "]", "=", "value", "end", "end", "write_multi", "(", "missing", ",", "options", ")", "if", "missing", ".", "any?", "results", "end" ]
Fetches multiple keys from the cache using a single call to the server and filling in any cache misses. All read and write operations are executed atomically. @overload fetch_multi(keys) Return all values for the given keys, applying the block to the key when a value is missing. @param [String] One or more keys to fetch @example cache.fetch_multi('alpha', 'beta') do |key| "#{key}-was-missing" end cache.fetch_multi('a', 'b', expires_in: 60) do |key| key * 2 end
[ "Fetches", "multiple", "keys", "from", "the", "cache", "using", "a", "single", "call", "to", "the", "server", "and", "filling", "in", "any", "cache", "misses", ".", "All", "read", "and", "write", "operations", "are", "executed", "atomically", "." ]
2bdf79329f2de437664ed74b2152b329f1b20704
https://github.com/sorentwo/readthis/blob/2bdf79329f2de437664ed74b2152b329f1b20704/lib/readthis/cache.rb#L348-L366
17,717
sorentwo/readthis
lib/readthis/cache.rb
Readthis.Cache.exist?
def exist?(key, options = {}) invoke(:exist?, key) do |store| store.exists(namespaced_key(key, merged_options(options))) end end
ruby
def exist?(key, options = {}) invoke(:exist?, key) do |store| store.exists(namespaced_key(key, merged_options(options))) end end
[ "def", "exist?", "(", "key", ",", "options", "=", "{", "}", ")", "invoke", "(", ":exist?", ",", "key", ")", "do", "|", "store", "|", "store", ".", "exists", "(", "namespaced_key", "(", "key", ",", "merged_options", "(", "options", ")", ")", ")", "end", "end" ]
Returns `true` if the cache contains an entry for the given key. @param [String] key Key for lookup @param [Hash] options Optional overrides @example cache.exist?('some-key') # => false cache.exist?('some-key', namespace: 'cache') # => true
[ "Returns", "true", "if", "the", "cache", "contains", "an", "entry", "for", "the", "given", "key", "." ]
2bdf79329f2de437664ed74b2152b329f1b20704
https://github.com/sorentwo/readthis/blob/2bdf79329f2de437664ed74b2152b329f1b20704/lib/readthis/cache.rb#L378-L382
17,718
sorentwo/readthis
lib/readthis/cache.rb
Readthis.Cache.clear
def clear(options = {}) invoke(:clear, '*') do |store| if options[:async] store.flushdb(async: true) else store.flushdb end end end
ruby
def clear(options = {}) invoke(:clear, '*') do |store| if options[:async] store.flushdb(async: true) else store.flushdb end end end
[ "def", "clear", "(", "options", "=", "{", "}", ")", "invoke", "(", ":clear", ",", "'*'", ")", "do", "|", "store", "|", "if", "options", "[", ":async", "]", "store", ".", "flushdb", "(", "async", ":", "true", ")", "else", "store", ".", "flushdb", "end", "end", "end" ]
Clear the entire cache by flushing the current database. This flushes everything in the current database, with no globbing applied. Data in other numbered databases will be preserved. @option options [Hash] :async Flush the database asynchronously, only supported in Redis 4.0+ @example cache.clear #=> 'OK' cache.clear(async: true) #=> 'OK'
[ "Clear", "the", "entire", "cache", "by", "flushing", "the", "current", "database", "." ]
2bdf79329f2de437664ed74b2152b329f1b20704
https://github.com/sorentwo/readthis/blob/2bdf79329f2de437664ed74b2152b329f1b20704/lib/readthis/cache.rb#L397-L405
17,719
binarylogic/searchlogic
lib/searchlogic/rails_helpers.rb
Searchlogic.RailsHelpers.fields_for
def fields_for(*args, &block) if search_obj = args.find { |arg| arg.is_a?(Searchlogic::Search) } args.unshift(:search) if args.first == search_obj options = args.extract_options! if !options[:skip_order_field] concat(content_tag("div", hidden_field_tag("#{args.first}[order]", search_obj.order), :style => "display: inline")) end args << options super else super end end
ruby
def fields_for(*args, &block) if search_obj = args.find { |arg| arg.is_a?(Searchlogic::Search) } args.unshift(:search) if args.first == search_obj options = args.extract_options! if !options[:skip_order_field] concat(content_tag("div", hidden_field_tag("#{args.first}[order]", search_obj.order), :style => "display: inline")) end args << options super else super end end
[ "def", "fields_for", "(", "*", "args", ",", "&", "block", ")", "if", "search_obj", "=", "args", ".", "find", "{", "|", "arg", "|", "arg", ".", "is_a?", "(", "Searchlogic", "::", "Search", ")", "}", "args", ".", "unshift", "(", ":search", ")", "if", "args", ".", "first", "==", "search_obj", "options", "=", "args", ".", "extract_options!", "if", "!", "options", "[", ":skip_order_field", "]", "concat", "(", "content_tag", "(", "\"div\"", ",", "hidden_field_tag", "(", "\"#{args.first}[order]\"", ",", "search_obj", ".", "order", ")", ",", ":style", "=>", "\"display: inline\"", ")", ")", "end", "args", "<<", "options", "super", "else", "super", "end", "end" ]
Automatically adds an "order" hidden field in your form to preserve how the data is being ordered.
[ "Automatically", "adds", "an", "order", "hidden", "field", "in", "your", "form", "to", "preserve", "how", "the", "data", "is", "being", "ordered", "." ]
074c9334df5fac4041224accb40191f46814f8c5
https://github.com/binarylogic/searchlogic/blob/074c9334df5fac4041224accb40191f46814f8c5/lib/searchlogic/rails_helpers.rb#L69-L81
17,720
petrovich/petrovich-ruby
lib/petrovich/rule_set.rb
Petrovich.RuleSet.load_case_rules!
def load_case_rules!(rules) [:lastname, :firstname, :middlename].each do |name_part| [:exceptions, :suffixes].each do |section| entries = rules[name_part.to_s][section.to_s] next if entries.nil? entries.each do |entry| load_case_entry(name_part, section, entry) end end end end
ruby
def load_case_rules!(rules) [:lastname, :firstname, :middlename].each do |name_part| [:exceptions, :suffixes].each do |section| entries = rules[name_part.to_s][section.to_s] next if entries.nil? entries.each do |entry| load_case_entry(name_part, section, entry) end end end end
[ "def", "load_case_rules!", "(", "rules", ")", "[", ":lastname", ",", ":firstname", ",", ":middlename", "]", ".", "each", "do", "|", "name_part", "|", "[", ":exceptions", ",", ":suffixes", "]", ".", "each", "do", "|", "section", "|", "entries", "=", "rules", "[", "name_part", ".", "to_s", "]", "[", "section", ".", "to_s", "]", "next", "if", "entries", ".", "nil?", "entries", ".", "each", "do", "|", "entry", "|", "load_case_entry", "(", "name_part", ",", "section", ",", "entry", ")", "end", "end", "end", "end" ]
Load rules for names
[ "Load", "rules", "for", "names" ]
567628988d2c0c87fe5137066cefe22acbc1c5af
https://github.com/petrovich/petrovich-ruby/blob/567628988d2c0c87fe5137066cefe22acbc1c5af/lib/petrovich/rule_set.rb#L50-L61
17,721
petrovich/petrovich-ruby
lib/petrovich/rule_set.rb
Petrovich.RuleSet.load_gender_rules!
def load_gender_rules!(rules) [:lastname, :firstname, :middlename].each do |name_part| Petrovich::GENDERS.each do |section| entries = rules['gender'][name_part.to_s]['suffixes'][section.to_s] Array(entries).each do |entry| load_gender_entry(name_part, section, entry) end exceptions = rules['gender'][name_part.to_s]['exceptions'] @gender_exceptions[name_part] ||= {} next if exceptions.nil? Array(exceptions[section.to_s]).each do |exception| @gender_exceptions[name_part][exception] = Gender::Rule.new(as: name_part, gender: section, suffix: exception) end end end @gender_rules.each do |_, gender_rules| gender_rules.sort_by!{ |rule| -rule.accuracy } end end
ruby
def load_gender_rules!(rules) [:lastname, :firstname, :middlename].each do |name_part| Petrovich::GENDERS.each do |section| entries = rules['gender'][name_part.to_s]['suffixes'][section.to_s] Array(entries).each do |entry| load_gender_entry(name_part, section, entry) end exceptions = rules['gender'][name_part.to_s]['exceptions'] @gender_exceptions[name_part] ||= {} next if exceptions.nil? Array(exceptions[section.to_s]).each do |exception| @gender_exceptions[name_part][exception] = Gender::Rule.new(as: name_part, gender: section, suffix: exception) end end end @gender_rules.each do |_, gender_rules| gender_rules.sort_by!{ |rule| -rule.accuracy } end end
[ "def", "load_gender_rules!", "(", "rules", ")", "[", ":lastname", ",", ":firstname", ",", ":middlename", "]", ".", "each", "do", "|", "name_part", "|", "Petrovich", "::", "GENDERS", ".", "each", "do", "|", "section", "|", "entries", "=", "rules", "[", "'gender'", "]", "[", "name_part", ".", "to_s", "]", "[", "'suffixes'", "]", "[", "section", ".", "to_s", "]", "Array", "(", "entries", ")", ".", "each", "do", "|", "entry", "|", "load_gender_entry", "(", "name_part", ",", "section", ",", "entry", ")", "end", "exceptions", "=", "rules", "[", "'gender'", "]", "[", "name_part", ".", "to_s", "]", "[", "'exceptions'", "]", "@gender_exceptions", "[", "name_part", "]", "||=", "{", "}", "next", "if", "exceptions", ".", "nil?", "Array", "(", "exceptions", "[", "section", ".", "to_s", "]", ")", ".", "each", "do", "|", "exception", "|", "@gender_exceptions", "[", "name_part", "]", "[", "exception", "]", "=", "Gender", "::", "Rule", ".", "new", "(", "as", ":", "name_part", ",", "gender", ":", "section", ",", "suffix", ":", "exception", ")", "end", "end", "end", "@gender_rules", ".", "each", "do", "|", "_", ",", "gender_rules", "|", "gender_rules", ".", "sort_by!", "{", "|", "rule", "|", "-", "rule", ".", "accuracy", "}", "end", "end" ]
Load rules for genders
[ "Load", "rules", "for", "genders" ]
567628988d2c0c87fe5137066cefe22acbc1c5af
https://github.com/petrovich/petrovich-ruby/blob/567628988d2c0c87fe5137066cefe22acbc1c5af/lib/petrovich/rule_set.rb#L64-L83
17,722
pact-foundation/pact-support
lib/pact/consumer_contract/query_hash.rb
Pact.QueryHash.difference
def difference(other) require 'pact/matchers' # avoid recursive loop between this file, pact/reification and pact/matchers Pact::Matchers.diff(query, symbolize_keys(CGI::parse(other.query)), allow_unexpected_keys: false) end
ruby
def difference(other) require 'pact/matchers' # avoid recursive loop between this file, pact/reification and pact/matchers Pact::Matchers.diff(query, symbolize_keys(CGI::parse(other.query)), allow_unexpected_keys: false) end
[ "def", "difference", "(", "other", ")", "require", "'pact/matchers'", "# avoid recursive loop between this file, pact/reification and pact/matchers", "Pact", "::", "Matchers", ".", "diff", "(", "query", ",", "symbolize_keys", "(", "CGI", "::", "parse", "(", "other", ".", "query", ")", ")", ",", "allow_unexpected_keys", ":", "false", ")", "end" ]
other will always be a QueryString, not a QueryHash, as it will have ben created from the actual query string.
[ "other", "will", "always", "be", "a", "QueryString", "not", "a", "QueryHash", "as", "it", "will", "have", "ben", "created", "from", "the", "actual", "query", "string", "." ]
be6d29cbe37cb1559aff787f17a9da78f173927b
https://github.com/pact-foundation/pact-support/blob/be6d29cbe37cb1559aff787f17a9da78f173927b/lib/pact/consumer_contract/query_hash.rb#L33-L36
17,723
alphagov/govuk_publishing_components
app/models/govuk_publishing_components/component_example.rb
GovukPublishingComponents.ComponentExample.html_safe_strings
def html_safe_strings(obj) if obj.is_a?(String) obj.html_safe elsif obj.is_a?(Hash) obj.each do |key, value| obj[key] = html_safe_strings(value) end elsif obj.is_a?(Array) obj.map! { |e| html_safe_strings(e) } else obj end end
ruby
def html_safe_strings(obj) if obj.is_a?(String) obj.html_safe elsif obj.is_a?(Hash) obj.each do |key, value| obj[key] = html_safe_strings(value) end elsif obj.is_a?(Array) obj.map! { |e| html_safe_strings(e) } else obj end end
[ "def", "html_safe_strings", "(", "obj", ")", "if", "obj", ".", "is_a?", "(", "String", ")", "obj", ".", "html_safe", "elsif", "obj", ".", "is_a?", "(", "Hash", ")", "obj", ".", "each", "do", "|", "key", ",", "value", "|", "obj", "[", "key", "]", "=", "html_safe_strings", "(", "value", ")", "end", "elsif", "obj", ".", "is_a?", "(", "Array", ")", "obj", ".", "map!", "{", "|", "e", "|", "html_safe_strings", "(", "e", ")", "}", "else", "obj", "end", "end" ]
Iterate through data object and recursively mark any found string as html_safe Safe HTML can be passed to components, simulate by marking any string that comes from YAML as safe
[ "Iterate", "through", "data", "object", "and", "recursively", "mark", "any", "found", "string", "as", "html_safe" ]
928efa7fb82cf78a465b8eb6a4c555e9d54b8069
https://github.com/alphagov/govuk_publishing_components/blob/928efa7fb82cf78a465b8eb6a4c555e9d54b8069/app/models/govuk_publishing_components/component_example.rb#L48-L60
17,724
vmware/rvc
lib/rvc/command_slate.rb
RVC.CommandSlate.opts
def opts name, &b fail "command name must be a symbol" unless name.is_a? Symbol if name.to_s =~ /[A-Z]/ fail "Camel-casing is not allowed (#{name})" end parser = OptionParser.new name.to_s, @ns.shell.fs, &b summary = parser.summary? parser.specs.each do |opt_name,spec| if opt_name.to_s =~ /[A-Z]/ fail "Camel-casing is not allowed (#{name} option #{opt_name})" end end @ns.commands[name] = Command.new @ns, name, summary, parser end
ruby
def opts name, &b fail "command name must be a symbol" unless name.is_a? Symbol if name.to_s =~ /[A-Z]/ fail "Camel-casing is not allowed (#{name})" end parser = OptionParser.new name.to_s, @ns.shell.fs, &b summary = parser.summary? parser.specs.each do |opt_name,spec| if opt_name.to_s =~ /[A-Z]/ fail "Camel-casing is not allowed (#{name} option #{opt_name})" end end @ns.commands[name] = Command.new @ns, name, summary, parser end
[ "def", "opts", "name", ",", "&", "b", "fail", "\"command name must be a symbol\"", "unless", "name", ".", "is_a?", "Symbol", "if", "name", ".", "to_s", "=~", "/", "/", "fail", "\"Camel-casing is not allowed (#{name})\"", "end", "parser", "=", "OptionParser", ".", "new", "name", ".", "to_s", ",", "@ns", ".", "shell", ".", "fs", ",", "b", "summary", "=", "parser", ".", "summary?", "parser", ".", "specs", ".", "each", "do", "|", "opt_name", ",", "spec", "|", "if", "opt_name", ".", "to_s", "=~", "/", "/", "fail", "\"Camel-casing is not allowed (#{name} option #{opt_name})\"", "end", "end", "@ns", ".", "commands", "[", "name", "]", "=", "Command", ".", "new", "@ns", ",", "name", ",", "summary", ",", "parser", "end" ]
Command definition functions
[ "Command", "definition", "functions" ]
acac697bd732fc8b9266aca9018ff844ecf62238
https://github.com/vmware/rvc/blob/acac697bd732fc8b9266aca9018ff844ecf62238/lib/rvc/command_slate.rb#L37-L54
17,725
GetStream/stream-ruby
lib/stream/activities.rb
Stream.Activities.get_activities
def get_activities(params = {}) if params[:foreign_id_times] foreign_ids = [] timestamps = [] params[:foreign_id_times].each{|e| foreign_ids << e[:foreign_id] timestamps << e[:time] } params = { foreign_ids: foreign_ids, timestamps: timestamps, } end signature = Stream::Signer.create_jwt_token('activities', '*', @api_secret, '*') make_request(:get, '/activities/', signature, params) end
ruby
def get_activities(params = {}) if params[:foreign_id_times] foreign_ids = [] timestamps = [] params[:foreign_id_times].each{|e| foreign_ids << e[:foreign_id] timestamps << e[:time] } params = { foreign_ids: foreign_ids, timestamps: timestamps, } end signature = Stream::Signer.create_jwt_token('activities', '*', @api_secret, '*') make_request(:get, '/activities/', signature, params) end
[ "def", "get_activities", "(", "params", "=", "{", "}", ")", "if", "params", "[", ":foreign_id_times", "]", "foreign_ids", "=", "[", "]", "timestamps", "=", "[", "]", "params", "[", ":foreign_id_times", "]", ".", "each", "{", "|", "e", "|", "foreign_ids", "<<", "e", "[", ":foreign_id", "]", "timestamps", "<<", "e", "[", ":time", "]", "}", "params", "=", "{", "foreign_ids", ":", "foreign_ids", ",", "timestamps", ":", "timestamps", ",", "}", "end", "signature", "=", "Stream", "::", "Signer", ".", "create_jwt_token", "(", "'activities'", ",", "'*'", ",", "@api_secret", ",", "'*'", ")", "make_request", "(", ":get", ",", "'/activities/'", ",", "signature", ",", "params", ")", "end" ]
Get activities directly, via ID or Foreign ID + timestamp @param [Hash<:ids, :foreign_id_times>] params the request params (ids or list of <:foreign_id, :time> objects) @return the found activities, if any. @example Retrieve by activity IDs @client.get_activities( ids: [ '4b39fda2-d6e2-42c9-9abf-5301ef071b12', '89b910d3-1ef5-44f8-914e-e7735d79e817' ] ) @example Retrieve by Foreign IDs + timestamps @client.get_activities( foreign_id_times: [ { foreign_id: 'post:1000', time: '2016-11-10T13:20:00.000000' }, { foreign_id: 'like:2000', time: '2018-01-07T09:15:59.123456' } ] )
[ "Get", "activities", "directly", "via", "ID", "or", "Foreign", "ID", "+", "timestamp" ]
5586784079f00d60e0701512184ae821b906b176
https://github.com/GetStream/stream-ruby/blob/5586784079f00d60e0701512184ae821b906b176/lib/stream/activities.rb#L27-L42
17,726
vmware/rvc
lib/rvc/fs.rb
RVC.FS.traverse
def traverse base, arcs objs = [base] arcs.each_with_index do |arc,i| objs.map! { |obj| traverse_one obj, arc, i==0 } objs.flatten! end objs end
ruby
def traverse base, arcs objs = [base] arcs.each_with_index do |arc,i| objs.map! { |obj| traverse_one obj, arc, i==0 } objs.flatten! end objs end
[ "def", "traverse", "base", ",", "arcs", "objs", "=", "[", "base", "]", "arcs", ".", "each_with_index", "do", "|", "arc", ",", "i", "|", "objs", ".", "map!", "{", "|", "obj", "|", "traverse_one", "obj", ",", "arc", ",", "i", "==", "0", "}", "objs", ".", "flatten!", "end", "objs", "end" ]
Starting from base, traverse each path element in arcs. Since the path may contain wildcards, this function returns a list of matches.
[ "Starting", "from", "base", "traverse", "each", "path", "element", "in", "arcs", ".", "Since", "the", "path", "may", "contain", "wildcards", "this", "function", "returns", "a", "list", "of", "matches", "." ]
acac697bd732fc8b9266aca9018ff844ecf62238
https://github.com/vmware/rvc/blob/acac697bd732fc8b9266aca9018ff844ecf62238/lib/rvc/fs.rb#L55-L62
17,727
GetStream/stream-ruby
lib/stream/batch.rb
Stream.Batch.follow_many
def follow_many(follows, activity_copy_limit = nil) query_params = {} unless activity_copy_limit.nil? query_params['activity_copy_limit'] = activity_copy_limit end signature = Stream::Signer.create_jwt_token('follower', '*', @api_secret, '*') make_request(:post, '/follow_many/', signature, query_params, follows) end
ruby
def follow_many(follows, activity_copy_limit = nil) query_params = {} unless activity_copy_limit.nil? query_params['activity_copy_limit'] = activity_copy_limit end signature = Stream::Signer.create_jwt_token('follower', '*', @api_secret, '*') make_request(:post, '/follow_many/', signature, query_params, follows) end
[ "def", "follow_many", "(", "follows", ",", "activity_copy_limit", "=", "nil", ")", "query_params", "=", "{", "}", "unless", "activity_copy_limit", ".", "nil?", "query_params", "[", "'activity_copy_limit'", "]", "=", "activity_copy_limit", "end", "signature", "=", "Stream", "::", "Signer", ".", "create_jwt_token", "(", "'follower'", ",", "'*'", ",", "@api_secret", ",", "'*'", ")", "make_request", "(", ":post", ",", "'/follow_many/'", ",", "signature", ",", "query_params", ",", "follows", ")", "end" ]
Follows many feeds in one single request @param [Array<Hash<:source, :target>>] follows the list of follows @return [nil] @example follows = [ {:source => 'flat:1', :target => 'user:1'}, {:source => 'flat:1', :target => 'user:3'} ] @client.follow_many(follows)
[ "Follows", "many", "feeds", "in", "one", "single", "request" ]
5586784079f00d60e0701512184ae821b906b176
https://github.com/GetStream/stream-ruby/blob/5586784079f00d60e0701512184ae821b906b176/lib/stream/batch.rb#L17-L24
17,728
GetStream/stream-ruby
lib/stream/batch.rb
Stream.Batch.add_to_many
def add_to_many(activity_data, feeds) data = { :feeds => feeds, :activity => activity_data } signature = Stream::Signer.create_jwt_token('feed', '*', @api_secret, '*') make_request(:post, '/feed/add_to_many/', signature, {}, data) end
ruby
def add_to_many(activity_data, feeds) data = { :feeds => feeds, :activity => activity_data } signature = Stream::Signer.create_jwt_token('feed', '*', @api_secret, '*') make_request(:post, '/feed/add_to_many/', signature, {}, data) end
[ "def", "add_to_many", "(", "activity_data", ",", "feeds", ")", "data", "=", "{", ":feeds", "=>", "feeds", ",", ":activity", "=>", "activity_data", "}", "signature", "=", "Stream", "::", "Signer", ".", "create_jwt_token", "(", "'feed'", ",", "'*'", ",", "@api_secret", ",", "'*'", ")", "make_request", "(", ":post", ",", "'/feed/add_to_many/'", ",", "signature", ",", "{", "}", ",", "data", ")", "end" ]
Adds an activity to many feeds in one single request @param [Hash] activity_data the activity do add @param [Array<string>] feeds list of feeds (eg. 'user:1', 'flat:2') @return [nil]
[ "Adds", "an", "activity", "to", "many", "feeds", "in", "one", "single", "request" ]
5586784079f00d60e0701512184ae821b906b176
https://github.com/GetStream/stream-ruby/blob/5586784079f00d60e0701512184ae821b906b176/lib/stream/batch.rb#L53-L60
17,729
bhollis/maruku
lib/maruku/input/html_helper.rb
MaRuKu::In::Markdown::SpanLevelParser.HTMLHelper.close_script_style
def close_script_style tag = @tag_stack.last # See http://www.w3.org/TR/xhtml1/#C_4 for character sequences not allowed within an element body. if @already =~ /<|&|\]\]>|--/ new_already = script_style_cdata_start(tag) new_already << "\n" unless @already.start_with?("\n") new_already << @already new_already << "\n" unless @already.end_with?("\n") new_already << script_style_cdata_end(tag) @already = new_already end @before_already << @already @already = @before_already end
ruby
def close_script_style tag = @tag_stack.last # See http://www.w3.org/TR/xhtml1/#C_4 for character sequences not allowed within an element body. if @already =~ /<|&|\]\]>|--/ new_already = script_style_cdata_start(tag) new_already << "\n" unless @already.start_with?("\n") new_already << @already new_already << "\n" unless @already.end_with?("\n") new_already << script_style_cdata_end(tag) @already = new_already end @before_already << @already @already = @before_already end
[ "def", "close_script_style", "tag", "=", "@tag_stack", ".", "last", "# See http://www.w3.org/TR/xhtml1/#C_4 for character sequences not allowed within an element body.", "if", "@already", "=~", "/", "\\]", "\\]", "/", "new_already", "=", "script_style_cdata_start", "(", "tag", ")", "new_already", "<<", "\"\\n\"", "unless", "@already", ".", "start_with?", "(", "\"\\n\"", ")", "new_already", "<<", "@already", "new_already", "<<", "\"\\n\"", "unless", "@already", ".", "end_with?", "(", "\"\\n\"", ")", "new_already", "<<", "script_style_cdata_end", "(", "tag", ")", "@already", "=", "new_already", "end", "@before_already", "<<", "@already", "@already", "=", "@before_already", "end" ]
Finish script or style tag content, wrapping it in CDATA if necessary, and add it to our original @already buffer.
[ "Finish", "script", "or", "style", "tag", "content", "wrapping", "it", "in", "CDATA", "if", "necessary", "and", "add", "it", "to", "our", "original" ]
ec44b2709d6c617f6c5f7d79caec9b40570cdd68
https://github.com/bhollis/maruku/blob/ec44b2709d6c617f6c5f7d79caec9b40570cdd68/lib/maruku/input/html_helper.rb#L209-L223
17,730
bhollis/maruku
lib/maruku/errors.rb
MaRuKu.Errors.maruku_error
def maruku_error(s, src=nil, con=nil, recover=nil) policy = get_setting(:on_error) case policy when :ignore when :raise raise_error create_frame(describe_error(s, src, con, recover)) when :warning tell_user create_frame(describe_error(s, src, con, recover)) else raise "Unknown on_error policy: #{policy.inspect}" end end
ruby
def maruku_error(s, src=nil, con=nil, recover=nil) policy = get_setting(:on_error) case policy when :ignore when :raise raise_error create_frame(describe_error(s, src, con, recover)) when :warning tell_user create_frame(describe_error(s, src, con, recover)) else raise "Unknown on_error policy: #{policy.inspect}" end end
[ "def", "maruku_error", "(", "s", ",", "src", "=", "nil", ",", "con", "=", "nil", ",", "recover", "=", "nil", ")", "policy", "=", "get_setting", "(", ":on_error", ")", "case", "policy", "when", ":ignore", "when", ":raise", "raise_error", "create_frame", "(", "describe_error", "(", "s", ",", "src", ",", "con", ",", "recover", ")", ")", "when", ":warning", "tell_user", "create_frame", "(", "describe_error", "(", "s", ",", "src", ",", "con", ",", "recover", ")", ")", "else", "raise", "\"Unknown on_error policy: #{policy.inspect}\"", "end", "end" ]
Properly handles a formatting error. All such errors go through this method. The behavior depends on {MaRuKu::Globals `MaRuKu::Globals[:on_error]`}. If this is `:warning`, this prints the error to stderr (or `@error_stream` if it's defined) and tries to continue. If `:on_error` is `:ignore`, this doesn't print anything and tries to continue. If it's `:raise`, this raises a {MaRuKu::Exception}. By default, `:on_error` is set to `:warning`. @overload def maruku_error(s, src = nil, con = nil) @param s [String] The text of the error @param src [#describe, nil] The source of the error @param con [#describe, nil] The context of the error @param recover [String, nil] Recovery text @raise [MaRuKu::Exception] If `:on_error` is set to `:raise`
[ "Properly", "handles", "a", "formatting", "error", ".", "All", "such", "errors", "go", "through", "this", "method", "." ]
ec44b2709d6c617f6c5f7d79caec9b40570cdd68
https://github.com/bhollis/maruku/blob/ec44b2709d6c617f6c5f7d79caec9b40570cdd68/lib/maruku/errors.rb#L24-L36
17,731
bhollis/maruku
lib/maruku/string_utils.rb
MaRuKu.Strings.spaces_before_first_char
def spaces_before_first_char(s) s = MaRuKu::MDLine.new(s.gsub(/([^\t]*)(\t)/) { $1 + " " * (TAB_SIZE - $1.length % TAB_SIZE) }) match = case s.md_type when :ulist # whitespace, followed by ('*'|'+'|'-') followed by # more whitespace, followed by an optional IAL, followed # by yet more whitespace s[/^\s*(\*|\+|\-)\s*(\{[:#\.].*?\})?\s*/] when :olist # whitespace, followed by a number, followed by a period, # more whitespace, an optional IAL, and more whitespace s[/^\s*\d+\.\s*(\{[:#\.].*?\})?\s*/] else tell_user "BUG (my bad): '#{s}' is not a list" '' end f = /\{(.*?)\}/.match(match) ial = f[1] if f [match.length, ial] end
ruby
def spaces_before_first_char(s) s = MaRuKu::MDLine.new(s.gsub(/([^\t]*)(\t)/) { $1 + " " * (TAB_SIZE - $1.length % TAB_SIZE) }) match = case s.md_type when :ulist # whitespace, followed by ('*'|'+'|'-') followed by # more whitespace, followed by an optional IAL, followed # by yet more whitespace s[/^\s*(\*|\+|\-)\s*(\{[:#\.].*?\})?\s*/] when :olist # whitespace, followed by a number, followed by a period, # more whitespace, an optional IAL, and more whitespace s[/^\s*\d+\.\s*(\{[:#\.].*?\})?\s*/] else tell_user "BUG (my bad): '#{s}' is not a list" '' end f = /\{(.*?)\}/.match(match) ial = f[1] if f [match.length, ial] end
[ "def", "spaces_before_first_char", "(", "s", ")", "s", "=", "MaRuKu", "::", "MDLine", ".", "new", "(", "s", ".", "gsub", "(", "/", "\\t", "\\t", "/", ")", "{", "$1", "+", "\" \"", "*", "(", "TAB_SIZE", "-", "$1", ".", "length", "%", "TAB_SIZE", ")", "}", ")", "match", "=", "case", "s", ".", "md_type", "when", ":ulist", "# whitespace, followed by ('*'|'+'|'-') followed by", "# more whitespace, followed by an optional IAL, followed", "# by yet more whitespace", "s", "[", "/", "\\s", "\\*", "\\+", "\\-", "\\s", "\\{", "\\.", "\\}", "\\s", "/", "]", "when", ":olist", "# whitespace, followed by a number, followed by a period,", "# more whitespace, an optional IAL, and more whitespace", "s", "[", "/", "\\s", "\\d", "\\.", "\\s", "\\{", "\\.", "\\}", "\\s", "/", "]", "else", "tell_user", "\"BUG (my bad): '#{s}' is not a list\"", "''", "end", "f", "=", "/", "\\{", "\\}", "/", ".", "match", "(", "match", ")", "ial", "=", "f", "[", "1", "]", "if", "f", "[", "match", ".", "length", ",", "ial", "]", "end" ]
This returns the position of the first non-list character in a list item. @example spaces_before_first_char('*Hello') #=> 1 spaces_before_first_char('* Hello') #=> 2 spaces_before_first_char(' * Hello') #=> 3 spaces_before_first_char(' * Hello') #=> 5 spaces_before_first_char('1.Hello') #=> 2 spaces_before_first_char(' 1. Hello') #=> 5 @param s [String] @return [Fixnum]
[ "This", "returns", "the", "position", "of", "the", "first", "non", "-", "list", "character", "in", "a", "list", "item", "." ]
ec44b2709d6c617f6c5f7d79caec9b40570cdd68
https://github.com/bhollis/maruku/blob/ec44b2709d6c617f6c5f7d79caec9b40570cdd68/lib/maruku/string_utils.rb#L59-L78
17,732
bhollis/maruku
lib/maruku/input_textile2/t2_parser.rb
MaRuKu.MDDocument.t2_parse_blocks
def t2_parse_blocks(src, output) while src.cur_line l = src.shift_line # ignore empty line if l.t2_empty? then src.shift_line next end # TODO: lists # TODO: xml # TODO: `==` signature, l = if l.t2_contains_signature? l.t2_get_signature else [Textile2Signature.new, l] end if handling = T2_Handling.has_key?(signature.block_name) if self.responds_to? handling.method # read as many non-empty lines that you can lines = [l] if handling.parse_lines while not src.cur_line.t2_empty? lines.push src.shift_line end end self.send(handling.method, src, output, signature, lines) else maruku_error("We don't know about method #{handling.method.inspect}") next end end end end
ruby
def t2_parse_blocks(src, output) while src.cur_line l = src.shift_line # ignore empty line if l.t2_empty? then src.shift_line next end # TODO: lists # TODO: xml # TODO: `==` signature, l = if l.t2_contains_signature? l.t2_get_signature else [Textile2Signature.new, l] end if handling = T2_Handling.has_key?(signature.block_name) if self.responds_to? handling.method # read as many non-empty lines that you can lines = [l] if handling.parse_lines while not src.cur_line.t2_empty? lines.push src.shift_line end end self.send(handling.method, src, output, signature, lines) else maruku_error("We don't know about method #{handling.method.inspect}") next end end end end
[ "def", "t2_parse_blocks", "(", "src", ",", "output", ")", "while", "src", ".", "cur_line", "l", "=", "src", ".", "shift_line", "# ignore empty line", "if", "l", ".", "t2_empty?", "then", "src", ".", "shift_line", "next", "end", "# TODO: lists", "# TODO: xml", "# TODO: `==`", "signature", ",", "l", "=", "if", "l", ".", "t2_contains_signature?", "l", ".", "t2_get_signature", "else", "[", "Textile2Signature", ".", "new", ",", "l", "]", "end", "if", "handling", "=", "T2_Handling", ".", "has_key?", "(", "signature", ".", "block_name", ")", "if", "self", ".", "responds_to?", "handling", ".", "method", "# read as many non-empty lines that you can", "lines", "=", "[", "l", "]", "if", "handling", ".", "parse_lines", "while", "not", "src", ".", "cur_line", ".", "t2_empty?", "lines", ".", "push", "src", ".", "shift_line", "end", "end", "self", ".", "send", "(", "handling", ".", "method", ",", "src", ",", "output", ",", "signature", ",", "lines", ")", "else", "maruku_error", "(", "\"We don't know about method #{handling.method.inspect}\"", ")", "next", "end", "end", "end", "end" ]
Input is a LineSource
[ "Input", "is", "a", "LineSource" ]
ec44b2709d6c617f6c5f7d79caec9b40570cdd68
https://github.com/bhollis/maruku/blob/ec44b2709d6c617f6c5f7d79caec9b40570cdd68/lib/maruku/input_textile2/t2_parser.rb#L109-L149
17,733
bhollis/maruku
lib/maruku/html.rb
MaRuKu.NokogiriHTMLFragment.to_html
def to_html output_options = Nokogiri::XML::Node::SaveOptions::DEFAULT_XHTML ^ Nokogiri::XML::Node::SaveOptions::FORMAT @fragment.children.inject("") do |out, child| out << child.serialize(:save_with => output_options, :encoding => 'UTF-8') end end
ruby
def to_html output_options = Nokogiri::XML::Node::SaveOptions::DEFAULT_XHTML ^ Nokogiri::XML::Node::SaveOptions::FORMAT @fragment.children.inject("") do |out, child| out << child.serialize(:save_with => output_options, :encoding => 'UTF-8') end end
[ "def", "to_html", "output_options", "=", "Nokogiri", "::", "XML", "::", "Node", "::", "SaveOptions", "::", "DEFAULT_XHTML", "^", "Nokogiri", "::", "XML", "::", "Node", "::", "SaveOptions", "::", "FORMAT", "@fragment", ".", "children", ".", "inject", "(", "\"\"", ")", "do", "|", "out", ",", "child", "|", "out", "<<", "child", ".", "serialize", "(", ":save_with", "=>", "output_options", ",", ":encoding", "=>", "'UTF-8'", ")", "end", "end" ]
Convert this fragment to an HTML or XHTML string. @return [String]
[ "Convert", "this", "fragment", "to", "an", "HTML", "or", "XHTML", "string", "." ]
ec44b2709d6c617f6c5f7d79caec9b40570cdd68
https://github.com/bhollis/maruku/blob/ec44b2709d6c617f6c5f7d79caec9b40570cdd68/lib/maruku/html.rb#L121-L127
17,734
bhollis/maruku
lib/maruku/html.rb
MaRuKu.NokogiriHTMLFragment.span_descendents
def span_descendents(e) ns = Nokogiri::XML::NodeSet.new(Nokogiri::XML::Document.new) e.element_children.inject(ns) do |descendents, c| if HTML_INLINE_ELEMS.include?(c.name) descendents << c descendents += span_descendents(c) end descendents end end
ruby
def span_descendents(e) ns = Nokogiri::XML::NodeSet.new(Nokogiri::XML::Document.new) e.element_children.inject(ns) do |descendents, c| if HTML_INLINE_ELEMS.include?(c.name) descendents << c descendents += span_descendents(c) end descendents end end
[ "def", "span_descendents", "(", "e", ")", "ns", "=", "Nokogiri", "::", "XML", "::", "NodeSet", ".", "new", "(", "Nokogiri", "::", "XML", "::", "Document", ".", "new", ")", "e", ".", "element_children", ".", "inject", "(", "ns", ")", "do", "|", "descendents", ",", "c", "|", "if", "HTML_INLINE_ELEMS", ".", "include?", "(", "c", ".", "name", ")", "descendents", "<<", "c", "descendents", "+=", "span_descendents", "(", "c", ")", "end", "descendents", "end", "end" ]
Get all span-level descendents of the given element, recursively, as a flat NodeSet. @param e [Nokogiri::XML::Node] An element. @return [Nokogiri::XML::NodeSet]
[ "Get", "all", "span", "-", "level", "descendents", "of", "the", "given", "element", "recursively", "as", "a", "flat", "NodeSet", "." ]
ec44b2709d6c617f6c5f7d79caec9b40570cdd68
https://github.com/bhollis/maruku/blob/ec44b2709d6c617f6c5f7d79caec9b40570cdd68/lib/maruku/html.rb#L136-L145
17,735
bhollis/maruku
lib/maruku/html.rb
MaRuKu.REXMLHTMLFragment.span_descendents
def span_descendents(e) descendents = [] e.each_element do |c| name = c.respond_to?(:name) ? c.name : nil if name && HTML_INLINE_ELEMS.include?(c.name) descendents << c descendents += span_descendents(c) end end end
ruby
def span_descendents(e) descendents = [] e.each_element do |c| name = c.respond_to?(:name) ? c.name : nil if name && HTML_INLINE_ELEMS.include?(c.name) descendents << c descendents += span_descendents(c) end end end
[ "def", "span_descendents", "(", "e", ")", "descendents", "=", "[", "]", "e", ".", "each_element", "do", "|", "c", "|", "name", "=", "c", ".", "respond_to?", "(", ":name", ")", "?", "c", ".", "name", ":", "nil", "if", "name", "&&", "HTML_INLINE_ELEMS", ".", "include?", "(", "c", ".", "name", ")", "descendents", "<<", "c", "descendents", "+=", "span_descendents", "(", "c", ")", "end", "end", "end" ]
Get all span-level descendents of the given element, recursively, as an Array. @param e [REXML::Element] An element. @return [Array]
[ "Get", "all", "span", "-", "level", "descendents", "of", "the", "given", "element", "recursively", "as", "an", "Array", "." ]
ec44b2709d6c617f6c5f7d79caec9b40570cdd68
https://github.com/bhollis/maruku/blob/ec44b2709d6c617f6c5f7d79caec9b40570cdd68/lib/maruku/html.rb#L240-L249
17,736
tpitale/staccato
lib/staccato/timing.rb
Staccato.Timing.track!
def track!(&block) if block_given? start_at = Time.now block.call end_at = Time.now self.options.time = (end_at - start_at).to_i*1000 end super end
ruby
def track!(&block) if block_given? start_at = Time.now block.call end_at = Time.now self.options.time = (end_at - start_at).to_i*1000 end super end
[ "def", "track!", "(", "&", "block", ")", "if", "block_given?", "start_at", "=", "Time", ".", "now", "block", ".", "call", "end_at", "=", "Time", ".", "now", "self", ".", "options", ".", "time", "=", "(", "end_at", "-", "start_at", ")", ".", "to_i", "1000", "end", "super", "end" ]
tracks the timing hit type @param block [#call] block is executed and time recorded
[ "tracks", "the", "timing", "hit", "type" ]
fb79fa0e95474cc13c5981f852ce7b3f2de44822
https://github.com/tpitale/staccato/blob/fb79fa0e95474cc13c5981f852ce7b3f2de44822/lib/staccato/timing.rb#L30-L40
17,737
tpitale/staccato
lib/staccato/hit.rb
Staccato.Hit.params
def params {}. merge!(base_params). merge!(tracker_default_params). merge!(global_options_params). merge!(hit_params). merge!(custom_dimensions). merge!(custom_metrics). merge!(measurement_params). reject {|_,v| v.nil?} end
ruby
def params {}. merge!(base_params). merge!(tracker_default_params). merge!(global_options_params). merge!(hit_params). merge!(custom_dimensions). merge!(custom_metrics). merge!(measurement_params). reject {|_,v| v.nil?} end
[ "def", "params", "{", "}", ".", "merge!", "(", "base_params", ")", ".", "merge!", "(", "tracker_default_params", ")", ".", "merge!", "(", "global_options_params", ")", ".", "merge!", "(", "hit_params", ")", ".", "merge!", "(", "custom_dimensions", ")", ".", "merge!", "(", "custom_metrics", ")", ".", "merge!", "(", "measurement_params", ")", ".", "reject", "{", "|", "_", ",", "v", "|", "v", ".", "nil?", "}", "end" ]
collects the parameters from options for this hit type
[ "collects", "the", "parameters", "from", "options", "for", "this", "hit", "type" ]
fb79fa0e95474cc13c5981f852ce7b3f2de44822
https://github.com/tpitale/staccato/blob/fb79fa0e95474cc13c5981f852ce7b3f2de44822/lib/staccato/hit.rb#L103-L113
17,738
tpitale/staccato
lib/staccato/hit.rb
Staccato.Hit.add_measurement
def add_measurement(key, options = {}) if options.is_a?(Hash) self.measurements << Measurement.lookup(key).new(options) else self.measurements << options end end
ruby
def add_measurement(key, options = {}) if options.is_a?(Hash) self.measurements << Measurement.lookup(key).new(options) else self.measurements << options end end
[ "def", "add_measurement", "(", "key", ",", "options", "=", "{", "}", ")", "if", "options", ".", "is_a?", "(", "Hash", ")", "self", ".", "measurements", "<<", "Measurement", ".", "lookup", "(", "key", ")", ".", "new", "(", "options", ")", "else", "self", ".", "measurements", "<<", "options", "end", "end" ]
Add a measurement by its symbol name with options @param key [Symbol] any one of the measurable classes lookup key @param options [Hash or Object] for the measurement
[ "Add", "a", "measurement", "by", "its", "symbol", "name", "with", "options" ]
fb79fa0e95474cc13c5981f852ce7b3f2de44822
https://github.com/tpitale/staccato/blob/fb79fa0e95474cc13c5981f852ce7b3f2de44822/lib/staccato/hit.rb#L145-L151
17,739
tpitale/staccato
lib/staccato/measurable.rb
Staccato.Measurable.params
def params {}. merge!(measurable_params). merge!(custom_dimensions). merge!(custom_metrics). reject {|_,v| v.nil?} end
ruby
def params {}. merge!(measurable_params). merge!(custom_dimensions). merge!(custom_metrics). reject {|_,v| v.nil?} end
[ "def", "params", "{", "}", ".", "merge!", "(", "measurable_params", ")", ".", "merge!", "(", "custom_dimensions", ")", ".", "merge!", "(", "custom_metrics", ")", ".", "reject", "{", "|", "_", ",", "v", "|", "v", ".", "nil?", "}", "end" ]
collects the parameters from options for this measurement @return [Hash]
[ "collects", "the", "parameters", "from", "options", "for", "this", "measurement" ]
fb79fa0e95474cc13c5981f852ce7b3f2de44822
https://github.com/tpitale/staccato/blob/fb79fa0e95474cc13c5981f852ce7b3f2de44822/lib/staccato/measurable.rb#L38-L44
17,740
devlocker/breakfast
lib/breakfast/manifest.rb
Breakfast.Manifest.clean!
def clean! files_to_keep = cache.keys.concat(cache.values) if (sprockets_manifest = Dir.entries("#{base_dir}").detect { |entry| entry =~ SPROCKETS_MANIFEST_REGEX }) files_to_keep.concat(JSON.parse(File.read("#{base_dir}/#{sprockets_manifest}")).fetch("files", {}).keys) end Dir["#{base_dir}/**/*"].each do |path| next if File.directory?(path) || files_to_keep.include?(Pathname(path).relative_path_from(base_dir).to_s) FileUtils.rm(path) end end
ruby
def clean! files_to_keep = cache.keys.concat(cache.values) if (sprockets_manifest = Dir.entries("#{base_dir}").detect { |entry| entry =~ SPROCKETS_MANIFEST_REGEX }) files_to_keep.concat(JSON.parse(File.read("#{base_dir}/#{sprockets_manifest}")).fetch("files", {}).keys) end Dir["#{base_dir}/**/*"].each do |path| next if File.directory?(path) || files_to_keep.include?(Pathname(path).relative_path_from(base_dir).to_s) FileUtils.rm(path) end end
[ "def", "clean!", "files_to_keep", "=", "cache", ".", "keys", ".", "concat", "(", "cache", ".", "values", ")", "if", "(", "sprockets_manifest", "=", "Dir", ".", "entries", "(", "\"#{base_dir}\"", ")", ".", "detect", "{", "|", "entry", "|", "entry", "=~", "SPROCKETS_MANIFEST_REGEX", "}", ")", "files_to_keep", ".", "concat", "(", "JSON", ".", "parse", "(", "File", ".", "read", "(", "\"#{base_dir}/#{sprockets_manifest}\"", ")", ")", ".", "fetch", "(", "\"files\"", ",", "{", "}", ")", ".", "keys", ")", "end", "Dir", "[", "\"#{base_dir}/**/*\"", "]", ".", "each", "do", "|", "path", "|", "next", "if", "File", ".", "directory?", "(", "path", ")", "||", "files_to_keep", ".", "include?", "(", "Pathname", "(", "path", ")", ".", "relative_path_from", "(", "base_dir", ")", ".", "to_s", ")", "FileUtils", ".", "rm", "(", "path", ")", "end", "end" ]
Remove any files not directly referenced by the manifest.
[ "Remove", "any", "files", "not", "directly", "referenced", "by", "the", "manifest", "." ]
bdb7a9d034d4a769a02815ba4e19973265f1d4cb
https://github.com/devlocker/breakfast/blob/bdb7a9d034d4a769a02815ba4e19973265f1d4cb/lib/breakfast/manifest.rb#L67-L79
17,741
devlocker/breakfast
lib/breakfast/manifest.rb
Breakfast.Manifest.nuke!
def nuke! Dir["#{base_dir}/**/*"] .select { |path| path =~ FINGERPRINT_REGEX } .each { |file| FileUtils.rm(file) } FileUtils.rm(manifest_path) end
ruby
def nuke! Dir["#{base_dir}/**/*"] .select { |path| path =~ FINGERPRINT_REGEX } .each { |file| FileUtils.rm(file) } FileUtils.rm(manifest_path) end
[ "def", "nuke!", "Dir", "[", "\"#{base_dir}/**/*\"", "]", ".", "select", "{", "|", "path", "|", "path", "=~", "FINGERPRINT_REGEX", "}", ".", "each", "{", "|", "file", "|", "FileUtils", ".", "rm", "(", "file", ")", "}", "FileUtils", ".", "rm", "(", "manifest_path", ")", "end" ]
Remove manifest, any fingerprinted files.
[ "Remove", "manifest", "any", "fingerprinted", "files", "." ]
bdb7a9d034d4a769a02815ba4e19973265f1d4cb
https://github.com/devlocker/breakfast/blob/bdb7a9d034d4a769a02815ba4e19973265f1d4cb/lib/breakfast/manifest.rb#L82-L88
17,742
xero-gateway/xero_gateway
lib/xero_gateway/line_item.rb
XeroGateway.LineItem.valid?
def valid? @errors = [] if !line_item_id.nil? && line_item_id !~ GUID_REGEX @errors << ['line_item_id', 'must be blank or a valid Xero GUID'] end unless description @errors << ['description', "can't be blank"] end if tax_type && !TAX_TYPE[tax_type] @errors << ['tax_type', "must be one of #{TAX_TYPE.keys.join('/')}"] end @errors.size == 0 end
ruby
def valid? @errors = [] if !line_item_id.nil? && line_item_id !~ GUID_REGEX @errors << ['line_item_id', 'must be blank or a valid Xero GUID'] end unless description @errors << ['description', "can't be blank"] end if tax_type && !TAX_TYPE[tax_type] @errors << ['tax_type', "must be one of #{TAX_TYPE.keys.join('/')}"] end @errors.size == 0 end
[ "def", "valid?", "@errors", "=", "[", "]", "if", "!", "line_item_id", ".", "nil?", "&&", "line_item_id", "!~", "GUID_REGEX", "@errors", "<<", "[", "'line_item_id'", ",", "'must be blank or a valid Xero GUID'", "]", "end", "unless", "description", "@errors", "<<", "[", "'description'", ",", "\"can't be blank\"", "]", "end", "if", "tax_type", "&&", "!", "TAX_TYPE", "[", "tax_type", "]", "@errors", "<<", "[", "'tax_type'", ",", "\"must be one of #{TAX_TYPE.keys.join('/')}\"", "]", "end", "@errors", ".", "size", "==", "0", "end" ]
Validate the LineItem record according to what will be valid by the gateway. Usage: line_item.valid? # Returns true/false Additionally sets line_item.errors array to an array of field/error.
[ "Validate", "the", "LineItem", "record", "according", "to", "what", "will", "be", "valid", "by", "the", "gateway", "." ]
6f0afbc3ebb756b66c7eff6c37f77f1e33bd07c5
https://github.com/xero-gateway/xero_gateway/blob/6f0afbc3ebb756b66c7eff6c37f77f1e33bd07c5/lib/xero_gateway/line_item.rb#L32-L48
17,743
xero-gateway/xero_gateway
lib/xero_gateway/accounts_list.rb
XeroGateway.AccountsList.find_all_by_type
def find_all_by_type(account_type) raise AccountsListNotLoadedError unless loaded? @accounts.inject([]) do | list, account | list << account if account.type == account_type list end end
ruby
def find_all_by_type(account_type) raise AccountsListNotLoadedError unless loaded? @accounts.inject([]) do | list, account | list << account if account.type == account_type list end end
[ "def", "find_all_by_type", "(", "account_type", ")", "raise", "AccountsListNotLoadedError", "unless", "loaded?", "@accounts", ".", "inject", "(", "[", "]", ")", "do", "|", "list", ",", "account", "|", "list", "<<", "account", "if", "account", ".", "type", "==", "account_type", "list", "end", "end" ]
Return a list of all accounts matching account_type.
[ "Return", "a", "list", "of", "all", "accounts", "matching", "account_type", "." ]
6f0afbc3ebb756b66c7eff6c37f77f1e33bd07c5
https://github.com/xero-gateway/xero_gateway/blob/6f0afbc3ebb756b66c7eff6c37f77f1e33bd07c5/lib/xero_gateway/accounts_list.rb#L55-L61
17,744
xero-gateway/xero_gateway
lib/xero_gateway/accounts_list.rb
XeroGateway.AccountsList.find_all_by_tax_type
def find_all_by_tax_type(tax_type) raise AccountsListNotLoadedError unless loaded? @accounts.inject([]) do | list, account | list << account if account.tax_type == tax_type list end end
ruby
def find_all_by_tax_type(tax_type) raise AccountsListNotLoadedError unless loaded? @accounts.inject([]) do | list, account | list << account if account.tax_type == tax_type list end end
[ "def", "find_all_by_tax_type", "(", "tax_type", ")", "raise", "AccountsListNotLoadedError", "unless", "loaded?", "@accounts", ".", "inject", "(", "[", "]", ")", "do", "|", "list", ",", "account", "|", "list", "<<", "account", "if", "account", ".", "tax_type", "==", "tax_type", "list", "end", "end" ]
Return a list of all accounts matching tax_type.
[ "Return", "a", "list", "of", "all", "accounts", "matching", "tax_type", "." ]
6f0afbc3ebb756b66c7eff6c37f77f1e33bd07c5
https://github.com/xero-gateway/xero_gateway/blob/6f0afbc3ebb756b66c7eff6c37f77f1e33bd07c5/lib/xero_gateway/accounts_list.rb#L64-L70
17,745
xero-gateway/xero_gateway
lib/xero_gateway/contact.rb
XeroGateway.Contact.valid?
def valid? @errors = [] if !contact_id.nil? && contact_id !~ GUID_REGEX @errors << ['contact_id', 'must be blank or a valid Xero GUID'] end if status && !CONTACT_STATUS[status] @errors << ['status', "must be one of #{CONTACT_STATUS.keys.join('/')}"] end unless name @errors << ['name', "can't be blank"] end # Make sure all addresses are correct. unless addresses.all? { | address | address.valid? } @errors << ['addresses', 'at least one address is invalid'] end # Make sure all phone numbers are correct. unless phones.all? { | phone | phone.valid? } @errors << ['phones', 'at least one phone is invalid'] end @errors.size == 0 end
ruby
def valid? @errors = [] if !contact_id.nil? && contact_id !~ GUID_REGEX @errors << ['contact_id', 'must be blank or a valid Xero GUID'] end if status && !CONTACT_STATUS[status] @errors << ['status', "must be one of #{CONTACT_STATUS.keys.join('/')}"] end unless name @errors << ['name', "can't be blank"] end # Make sure all addresses are correct. unless addresses.all? { | address | address.valid? } @errors << ['addresses', 'at least one address is invalid'] end # Make sure all phone numbers are correct. unless phones.all? { | phone | phone.valid? } @errors << ['phones', 'at least one phone is invalid'] end @errors.size == 0 end
[ "def", "valid?", "@errors", "=", "[", "]", "if", "!", "contact_id", ".", "nil?", "&&", "contact_id", "!~", "GUID_REGEX", "@errors", "<<", "[", "'contact_id'", ",", "'must be blank or a valid Xero GUID'", "]", "end", "if", "status", "&&", "!", "CONTACT_STATUS", "[", "status", "]", "@errors", "<<", "[", "'status'", ",", "\"must be one of #{CONTACT_STATUS.keys.join('/')}\"", "]", "end", "unless", "name", "@errors", "<<", "[", "'name'", ",", "\"can't be blank\"", "]", "end", "# Make sure all addresses are correct.", "unless", "addresses", ".", "all?", "{", "|", "address", "|", "address", ".", "valid?", "}", "@errors", "<<", "[", "'addresses'", ",", "'at least one address is invalid'", "]", "end", "# Make sure all phone numbers are correct.", "unless", "phones", ".", "all?", "{", "|", "phone", "|", "phone", ".", "valid?", "}", "@errors", "<<", "[", "'phones'", ",", "'at least one phone is invalid'", "]", "end", "@errors", ".", "size", "==", "0", "end" ]
Validate the Contact record according to what will be valid by the gateway. Usage: contact.valid? # Returns true/false Additionally sets contact.errors array to an array of field/error.
[ "Validate", "the", "Contact", "record", "according", "to", "what", "will", "be", "valid", "by", "the", "gateway", "." ]
6f0afbc3ebb756b66c7eff6c37f77f1e33bd07c5
https://github.com/xero-gateway/xero_gateway/blob/6f0afbc3ebb756b66c7eff6c37f77f1e33bd07c5/lib/xero_gateway/contact.rb#L113-L139
17,746
xero-gateway/xero_gateway
lib/xero_gateway/gateway.rb
XeroGateway.Gateway.get_contacts
def get_contacts(options = {}) request_params = {} if !options[:updated_after].nil? warn '[warning] :updated_after is depracated in XeroGateway#get_contacts. Use :modified_since' options[:modified_since] = options.delete(:updated_after) end request_params[:ContactID] = options[:contact_id] if options[:contact_id] request_params[:ContactNumber] = options[:contact_number] if options[:contact_number] request_params[:order] = options[:order] if options[:order] request_params[:ModifiedAfter] = options[:modified_since] if options[:modified_since] request_params[:where] = options[:where] if options[:where] request_params[:page] = options[:page] if options[:page] response_xml = http_get(@client, "#{@xero_url}/Contacts", request_params) parse_response(response_xml, {:request_params => request_params}, {:request_signature => 'GET/contacts'}) end
ruby
def get_contacts(options = {}) request_params = {} if !options[:updated_after].nil? warn '[warning] :updated_after is depracated in XeroGateway#get_contacts. Use :modified_since' options[:modified_since] = options.delete(:updated_after) end request_params[:ContactID] = options[:contact_id] if options[:contact_id] request_params[:ContactNumber] = options[:contact_number] if options[:contact_number] request_params[:order] = options[:order] if options[:order] request_params[:ModifiedAfter] = options[:modified_since] if options[:modified_since] request_params[:where] = options[:where] if options[:where] request_params[:page] = options[:page] if options[:page] response_xml = http_get(@client, "#{@xero_url}/Contacts", request_params) parse_response(response_xml, {:request_params => request_params}, {:request_signature => 'GET/contacts'}) end
[ "def", "get_contacts", "(", "options", "=", "{", "}", ")", "request_params", "=", "{", "}", "if", "!", "options", "[", ":updated_after", "]", ".", "nil?", "warn", "'[warning] :updated_after is depracated in XeroGateway#get_contacts. Use :modified_since'", "options", "[", ":modified_since", "]", "=", "options", ".", "delete", "(", ":updated_after", ")", "end", "request_params", "[", ":ContactID", "]", "=", "options", "[", ":contact_id", "]", "if", "options", "[", ":contact_id", "]", "request_params", "[", ":ContactNumber", "]", "=", "options", "[", ":contact_number", "]", "if", "options", "[", ":contact_number", "]", "request_params", "[", ":order", "]", "=", "options", "[", ":order", "]", "if", "options", "[", ":order", "]", "request_params", "[", ":ModifiedAfter", "]", "=", "options", "[", ":modified_since", "]", "if", "options", "[", ":modified_since", "]", "request_params", "[", ":where", "]", "=", "options", "[", ":where", "]", "if", "options", "[", ":where", "]", "request_params", "[", ":page", "]", "=", "options", "[", ":page", "]", "if", "options", "[", ":page", "]", "response_xml", "=", "http_get", "(", "@client", ",", "\"#{@xero_url}/Contacts\"", ",", "request_params", ")", "parse_response", "(", "response_xml", ",", "{", ":request_params", "=>", "request_params", "}", ",", "{", ":request_signature", "=>", "'GET/contacts'", "}", ")", "end" ]
The consumer key and secret here correspond to those provided to you by Xero inside the API Previewer. Retrieve all contacts from Xero Usage : get_contacts(:order => :name) get_contacts(:modified_since => Time) Note : modified_since is in UTC format (i.e. Brisbane is UTC+10)
[ "The", "consumer", "key", "and", "secret", "here", "correspond", "to", "those", "provided", "to", "you", "by", "Xero", "inside", "the", "API", "Previewer", "." ]
6f0afbc3ebb756b66c7eff6c37f77f1e33bd07c5
https://github.com/xero-gateway/xero_gateway/blob/6f0afbc3ebb756b66c7eff6c37f77f1e33bd07c5/lib/xero_gateway/gateway.rb#L28-L46
17,747
xero-gateway/xero_gateway
lib/xero_gateway/gateway.rb
XeroGateway.Gateway.build_contact
def build_contact(contact = {}) case contact when Contact then contact.gateway = self when Hash then contact = Contact.new(contact.merge({:gateway => self})) end contact end
ruby
def build_contact(contact = {}) case contact when Contact then contact.gateway = self when Hash then contact = Contact.new(contact.merge({:gateway => self})) end contact end
[ "def", "build_contact", "(", "contact", "=", "{", "}", ")", "case", "contact", "when", "Contact", "then", "contact", ".", "gateway", "=", "self", "when", "Hash", "then", "contact", "=", "Contact", ".", "new", "(", "contact", ".", "merge", "(", "{", ":gateway", "=>", "self", "}", ")", ")", "end", "contact", "end" ]
Factory method for building new Contact objects associated with this gateway.
[ "Factory", "method", "for", "building", "new", "Contact", "objects", "associated", "with", "this", "gateway", "." ]
6f0afbc3ebb756b66c7eff6c37f77f1e33bd07c5
https://github.com/xero-gateway/xero_gateway/blob/6f0afbc3ebb756b66c7eff6c37f77f1e33bd07c5/lib/xero_gateway/gateway.rb#L61-L67
17,748
xero-gateway/xero_gateway
lib/xero_gateway/gateway.rb
XeroGateway.Gateway.update_contact
def update_contact(contact) raise "contact_id or contact_number is required for updating contacts" if contact.contact_id.nil? and contact.contact_number.nil? save_contact(contact) end
ruby
def update_contact(contact) raise "contact_id or contact_number is required for updating contacts" if contact.contact_id.nil? and contact.contact_number.nil? save_contact(contact) end
[ "def", "update_contact", "(", "contact", ")", "raise", "\"contact_id or contact_number is required for updating contacts\"", "if", "contact", ".", "contact_id", ".", "nil?", "and", "contact", ".", "contact_number", ".", "nil?", "save_contact", "(", "contact", ")", "end" ]
Updates an existing Xero contact Usage : contact = xero_gateway.get_contact(some_contact_id) contact.email = "a_new_email_ddress" xero_gateway.update_contact(contact)
[ "Updates", "an", "existing", "Xero", "contact" ]
6f0afbc3ebb756b66c7eff6c37f77f1e33bd07c5
https://github.com/xero-gateway/xero_gateway/blob/6f0afbc3ebb756b66c7eff6c37f77f1e33bd07c5/lib/xero_gateway/gateway.rb#L100-L103
17,749
xero-gateway/xero_gateway
lib/xero_gateway/gateway.rb
XeroGateway.Gateway.update_contacts
def update_contacts(contacts) b = Builder::XmlMarkup.new request_xml = b.Contacts { contacts.each do | contact | contact.to_xml(b) end } response_xml = http_post(@client, "#{@xero_url}/Contacts", request_xml, {}) response = parse_response(response_xml, {:request_xml => request_xml}, {:request_signature => 'POST/contacts'}) response.contacts.each_with_index do | response_contact, index | contacts[index].contact_id = response_contact.contact_id if response_contact && response_contact.contact_id end response end
ruby
def update_contacts(contacts) b = Builder::XmlMarkup.new request_xml = b.Contacts { contacts.each do | contact | contact.to_xml(b) end } response_xml = http_post(@client, "#{@xero_url}/Contacts", request_xml, {}) response = parse_response(response_xml, {:request_xml => request_xml}, {:request_signature => 'POST/contacts'}) response.contacts.each_with_index do | response_contact, index | contacts[index].contact_id = response_contact.contact_id if response_contact && response_contact.contact_id end response end
[ "def", "update_contacts", "(", "contacts", ")", "b", "=", "Builder", "::", "XmlMarkup", ".", "new", "request_xml", "=", "b", ".", "Contacts", "{", "contacts", ".", "each", "do", "|", "contact", "|", "contact", ".", "to_xml", "(", "b", ")", "end", "}", "response_xml", "=", "http_post", "(", "@client", ",", "\"#{@xero_url}/Contacts\"", ",", "request_xml", ",", "{", "}", ")", "response", "=", "parse_response", "(", "response_xml", ",", "{", ":request_xml", "=>", "request_xml", "}", ",", "{", ":request_signature", "=>", "'POST/contacts'", "}", ")", "response", ".", "contacts", ".", "each_with_index", "do", "|", "response_contact", ",", "index", "|", "contacts", "[", "index", "]", ".", "contact_id", "=", "response_contact", ".", "contact_id", "if", "response_contact", "&&", "response_contact", ".", "contact_id", "end", "response", "end" ]
Updates an array of contacts in a single API operation. Usage : contacts = [XeroGateway::Contact.new(:name => 'Joe Bloggs'), XeroGateway::Contact.new(:name => 'Jane Doe')] result = gateway.update_contacts(contacts) Will update contacts with matching contact_id, contact_number or name or create if they don't exist.
[ "Updates", "an", "array", "of", "contacts", "in", "a", "single", "API", "operation", "." ]
6f0afbc3ebb756b66c7eff6c37f77f1e33bd07c5
https://github.com/xero-gateway/xero_gateway/blob/6f0afbc3ebb756b66c7eff6c37f77f1e33bd07c5/lib/xero_gateway/gateway.rb#L114-L129
17,750
xero-gateway/xero_gateway
lib/xero_gateway/gateway.rb
XeroGateway.Gateway.get_contact_groups
def get_contact_groups(options = {}) request_params = {} request_params[:ContactGroupID] = options[:contact_group_id] if options[:contact_group_id] request_params[:order] = options[:order] if options[:order] request_params[:where] = options[:where] if options[:where] response_xml = http_get(@client, "#{@xero_url}/ContactGroups", request_params) parse_response(response_xml, {:request_params => request_params}, {:request_signature => 'GET/contactgroups'}) end
ruby
def get_contact_groups(options = {}) request_params = {} request_params[:ContactGroupID] = options[:contact_group_id] if options[:contact_group_id] request_params[:order] = options[:order] if options[:order] request_params[:where] = options[:where] if options[:where] response_xml = http_get(@client, "#{@xero_url}/ContactGroups", request_params) parse_response(response_xml, {:request_params => request_params}, {:request_signature => 'GET/contactgroups'}) end
[ "def", "get_contact_groups", "(", "options", "=", "{", "}", ")", "request_params", "=", "{", "}", "request_params", "[", ":ContactGroupID", "]", "=", "options", "[", ":contact_group_id", "]", "if", "options", "[", ":contact_group_id", "]", "request_params", "[", ":order", "]", "=", "options", "[", ":order", "]", "if", "options", "[", ":order", "]", "request_params", "[", ":where", "]", "=", "options", "[", ":where", "]", "if", "options", "[", ":where", "]", "response_xml", "=", "http_get", "(", "@client", ",", "\"#{@xero_url}/ContactGroups\"", ",", "request_params", ")", "parse_response", "(", "response_xml", ",", "{", ":request_params", "=>", "request_params", "}", ",", "{", ":request_signature", "=>", "'GET/contactgroups'", "}", ")", "end" ]
Retreives all contact groups from Xero Usage: groups = gateway.get_contact_groups()
[ "Retreives", "all", "contact", "groups", "from", "Xero" ]
6f0afbc3ebb756b66c7eff6c37f77f1e33bd07c5
https://github.com/xero-gateway/xero_gateway/blob/6f0afbc3ebb756b66c7eff6c37f77f1e33bd07c5/lib/xero_gateway/gateway.rb#L136-L146
17,751
xero-gateway/xero_gateway
lib/xero_gateway/gateway.rb
XeroGateway.Gateway.get_contact_group_by_id
def get_contact_group_by_id(contact_group_id) request_params = { :ContactGroupID => contact_group_id } response_xml = http_get(@client, "#{@xero_url}/ContactGroups/#{CGI.escape(contact_group_id)}", request_params) parse_response(response_xml, {:request_params => request_params}, {:request_signature => 'GET/contactgroup'}) end
ruby
def get_contact_group_by_id(contact_group_id) request_params = { :ContactGroupID => contact_group_id } response_xml = http_get(@client, "#{@xero_url}/ContactGroups/#{CGI.escape(contact_group_id)}", request_params) parse_response(response_xml, {:request_params => request_params}, {:request_signature => 'GET/contactgroup'}) end
[ "def", "get_contact_group_by_id", "(", "contact_group_id", ")", "request_params", "=", "{", ":ContactGroupID", "=>", "contact_group_id", "}", "response_xml", "=", "http_get", "(", "@client", ",", "\"#{@xero_url}/ContactGroups/#{CGI.escape(contact_group_id)}\"", ",", "request_params", ")", "parse_response", "(", "response_xml", ",", "{", ":request_params", "=>", "request_params", "}", ",", "{", ":request_signature", "=>", "'GET/contactgroup'", "}", ")", "end" ]
Retreives a contact group by its id.
[ "Retreives", "a", "contact", "group", "by", "its", "id", "." ]
6f0afbc3ebb756b66c7eff6c37f77f1e33bd07c5
https://github.com/xero-gateway/xero_gateway/blob/6f0afbc3ebb756b66c7eff6c37f77f1e33bd07c5/lib/xero_gateway/gateway.rb#L149-L154
17,752
xero-gateway/xero_gateway
lib/xero_gateway/gateway.rb
XeroGateway.Gateway.get_invoices
def get_invoices(options = {}) request_params = {} request_params[:InvoiceID] = options[:invoice_id] if options[:invoice_id] request_params[:InvoiceNumber] = options[:invoice_number] if options[:invoice_number] request_params[:order] = options[:order] if options[:order] request_params[:ModifiedAfter] = options[:modified_since] if options[:modified_since] request_params[:IDs] = Array(options[:invoice_ids]).join(",") if options[:invoice_ids] request_params[:InvoiceNumbers] = Array(options[:invoice_numbers]).join(",") if options[:invoice_numbers] request_params[:ContactIDs] = Array(options[:contact_ids]).join(",") if options[:contact_ids] request_params[:page] = options[:page] if options[:page] request_params[:where] = options[:where] if options[:where] response_xml = http_get(@client, "#{@xero_url}/Invoices", request_params) parse_response(response_xml, {:request_params => request_params}, {:request_signature => 'GET/Invoices'}) end
ruby
def get_invoices(options = {}) request_params = {} request_params[:InvoiceID] = options[:invoice_id] if options[:invoice_id] request_params[:InvoiceNumber] = options[:invoice_number] if options[:invoice_number] request_params[:order] = options[:order] if options[:order] request_params[:ModifiedAfter] = options[:modified_since] if options[:modified_since] request_params[:IDs] = Array(options[:invoice_ids]).join(",") if options[:invoice_ids] request_params[:InvoiceNumbers] = Array(options[:invoice_numbers]).join(",") if options[:invoice_numbers] request_params[:ContactIDs] = Array(options[:contact_ids]).join(",") if options[:contact_ids] request_params[:page] = options[:page] if options[:page] request_params[:where] = options[:where] if options[:where] response_xml = http_get(@client, "#{@xero_url}/Invoices", request_params) parse_response(response_xml, {:request_params => request_params}, {:request_signature => 'GET/Invoices'}) end
[ "def", "get_invoices", "(", "options", "=", "{", "}", ")", "request_params", "=", "{", "}", "request_params", "[", ":InvoiceID", "]", "=", "options", "[", ":invoice_id", "]", "if", "options", "[", ":invoice_id", "]", "request_params", "[", ":InvoiceNumber", "]", "=", "options", "[", ":invoice_number", "]", "if", "options", "[", ":invoice_number", "]", "request_params", "[", ":order", "]", "=", "options", "[", ":order", "]", "if", "options", "[", ":order", "]", "request_params", "[", ":ModifiedAfter", "]", "=", "options", "[", ":modified_since", "]", "if", "options", "[", ":modified_since", "]", "request_params", "[", ":IDs", "]", "=", "Array", "(", "options", "[", ":invoice_ids", "]", ")", ".", "join", "(", "\",\"", ")", "if", "options", "[", ":invoice_ids", "]", "request_params", "[", ":InvoiceNumbers", "]", "=", "Array", "(", "options", "[", ":invoice_numbers", "]", ")", ".", "join", "(", "\",\"", ")", "if", "options", "[", ":invoice_numbers", "]", "request_params", "[", ":ContactIDs", "]", "=", "Array", "(", "options", "[", ":contact_ids", "]", ")", ".", "join", "(", "\",\"", ")", "if", "options", "[", ":contact_ids", "]", "request_params", "[", ":page", "]", "=", "options", "[", ":page", "]", "if", "options", "[", ":page", "]", "request_params", "[", ":where", "]", "=", "options", "[", ":where", "]", "if", "options", "[", ":where", "]", "response_xml", "=", "http_get", "(", "@client", ",", "\"#{@xero_url}/Invoices\"", ",", "request_params", ")", "parse_response", "(", "response_xml", ",", "{", ":request_params", "=>", "request_params", "}", ",", "{", ":request_signature", "=>", "'GET/Invoices'", "}", ")", "end" ]
Retrieves all invoices from Xero Usage : get_invoices get_invoices(:invoice_id => "297c2dc5-cc47-4afd-8ec8-74990b8761e9") get_invoices(:invoice_number => "175") get_invoices(:contact_ids => ["297c2dc5-cc47-4afd-8ec8-74990b8761e9"] ) Note : modified_since is in UTC format (i.e. Brisbane is UTC+10)
[ "Retrieves", "all", "invoices", "from", "Xero" ]
6f0afbc3ebb756b66c7eff6c37f77f1e33bd07c5
https://github.com/xero-gateway/xero_gateway/blob/6f0afbc3ebb756b66c7eff6c37f77f1e33bd07c5/lib/xero_gateway/gateway.rb#L164-L182
17,753
xero-gateway/xero_gateway
lib/xero_gateway/gateway.rb
XeroGateway.Gateway.get_invoice
def get_invoice(invoice_id_or_number, format = :xml) request_params = {} headers = {} headers.merge!("Accept" => "application/pdf") if format == :pdf url = "#{@xero_url}/Invoices/#{CGI.escape(invoice_id_or_number)}" response = http_get(@client, url, request_params, headers) if format == :pdf Tempfile.open(invoice_id_or_number) do |f| f.write(response) f end else parse_response(response, {:request_params => request_params}, {:request_signature => 'GET/Invoice'}) end end
ruby
def get_invoice(invoice_id_or_number, format = :xml) request_params = {} headers = {} headers.merge!("Accept" => "application/pdf") if format == :pdf url = "#{@xero_url}/Invoices/#{CGI.escape(invoice_id_or_number)}" response = http_get(@client, url, request_params, headers) if format == :pdf Tempfile.open(invoice_id_or_number) do |f| f.write(response) f end else parse_response(response, {:request_params => request_params}, {:request_signature => 'GET/Invoice'}) end end
[ "def", "get_invoice", "(", "invoice_id_or_number", ",", "format", "=", ":xml", ")", "request_params", "=", "{", "}", "headers", "=", "{", "}", "headers", ".", "merge!", "(", "\"Accept\"", "=>", "\"application/pdf\"", ")", "if", "format", "==", ":pdf", "url", "=", "\"#{@xero_url}/Invoices/#{CGI.escape(invoice_id_or_number)}\"", "response", "=", "http_get", "(", "@client", ",", "url", ",", "request_params", ",", "headers", ")", "if", "format", "==", ":pdf", "Tempfile", ".", "open", "(", "invoice_id_or_number", ")", "do", "|", "f", "|", "f", ".", "write", "(", "response", ")", "f", "end", "else", "parse_response", "(", "response", ",", "{", ":request_params", "=>", "request_params", "}", ",", "{", ":request_signature", "=>", "'GET/Invoice'", "}", ")", "end", "end" ]
Retrieves a single invoice You can get a PDF-formatted invoice by specifying :pdf as the format argument Usage : get_invoice("297c2dc5-cc47-4afd-8ec8-74990b8761e9") # By ID get_invoice("OIT-12345") # By number
[ "Retrieves", "a", "single", "invoice" ]
6f0afbc3ebb756b66c7eff6c37f77f1e33bd07c5
https://github.com/xero-gateway/xero_gateway/blob/6f0afbc3ebb756b66c7eff6c37f77f1e33bd07c5/lib/xero_gateway/gateway.rb#L190-L208
17,754
xero-gateway/xero_gateway
lib/xero_gateway/gateway.rb
XeroGateway.Gateway.build_invoice
def build_invoice(invoice = {}) case invoice when Invoice then invoice.gateway = self when Hash then invoice = Invoice.new(invoice.merge(:gateway => self)) end invoice end
ruby
def build_invoice(invoice = {}) case invoice when Invoice then invoice.gateway = self when Hash then invoice = Invoice.new(invoice.merge(:gateway => self)) end invoice end
[ "def", "build_invoice", "(", "invoice", "=", "{", "}", ")", "case", "invoice", "when", "Invoice", "then", "invoice", ".", "gateway", "=", "self", "when", "Hash", "then", "invoice", "=", "Invoice", ".", "new", "(", "invoice", ".", "merge", "(", ":gateway", "=>", "self", ")", ")", "end", "invoice", "end" ]
Factory method for building new Invoice objects associated with this gateway.
[ "Factory", "method", "for", "building", "new", "Invoice", "objects", "associated", "with", "this", "gateway", "." ]
6f0afbc3ebb756b66c7eff6c37f77f1e33bd07c5
https://github.com/xero-gateway/xero_gateway/blob/6f0afbc3ebb756b66c7eff6c37f77f1e33bd07c5/lib/xero_gateway/gateway.rb#L211-L217
17,755
xero-gateway/xero_gateway
lib/xero_gateway/gateway.rb
XeroGateway.Gateway.create_invoices
def create_invoices(invoices) b = Builder::XmlMarkup.new request_xml = b.Invoices { invoices.each do | invoice | invoice.to_xml(b) end } response_xml = http_put(@client, "#{@xero_url}/Invoices?SummarizeErrors=false", request_xml, {}) response = parse_response(response_xml, {:request_xml => request_xml}, {:request_signature => 'PUT/invoices'}) response.invoices.each_with_index do | response_invoice, index | invoices[index].invoice_id = response_invoice.invoice_id if response_invoice && response_invoice.invoice_id end response end
ruby
def create_invoices(invoices) b = Builder::XmlMarkup.new request_xml = b.Invoices { invoices.each do | invoice | invoice.to_xml(b) end } response_xml = http_put(@client, "#{@xero_url}/Invoices?SummarizeErrors=false", request_xml, {}) response = parse_response(response_xml, {:request_xml => request_xml}, {:request_signature => 'PUT/invoices'}) response.invoices.each_with_index do | response_invoice, index | invoices[index].invoice_id = response_invoice.invoice_id if response_invoice && response_invoice.invoice_id end response end
[ "def", "create_invoices", "(", "invoices", ")", "b", "=", "Builder", "::", "XmlMarkup", ".", "new", "request_xml", "=", "b", ".", "Invoices", "{", "invoices", ".", "each", "do", "|", "invoice", "|", "invoice", ".", "to_xml", "(", "b", ")", "end", "}", "response_xml", "=", "http_put", "(", "@client", ",", "\"#{@xero_url}/Invoices?SummarizeErrors=false\"", ",", "request_xml", ",", "{", "}", ")", "response", "=", "parse_response", "(", "response_xml", ",", "{", ":request_xml", "=>", "request_xml", "}", ",", "{", ":request_signature", "=>", "'PUT/invoices'", "}", ")", "response", ".", "invoices", ".", "each_with_index", "do", "|", "response_invoice", ",", "index", "|", "invoices", "[", "index", "]", ".", "invoice_id", "=", "response_invoice", ".", "invoice_id", "if", "response_invoice", "&&", "response_invoice", ".", "invoice_id", "end", "response", "end" ]
Creates an array of invoices with a single API request. Usage : invoices = [XeroGateway::Invoice.new(...), XeroGateway::Invoice.new(...)] result = gateway.create_invoices(invoices)
[ "Creates", "an", "array", "of", "invoices", "with", "a", "single", "API", "request", "." ]
6f0afbc3ebb756b66c7eff6c37f77f1e33bd07c5
https://github.com/xero-gateway/xero_gateway/blob/6f0afbc3ebb756b66c7eff6c37f77f1e33bd07c5/lib/xero_gateway/gateway.rb#L270-L285
17,756
xero-gateway/xero_gateway
lib/xero_gateway/gateway.rb
XeroGateway.Gateway.get_credit_notes
def get_credit_notes(options = {}) request_params = {} request_params[:CreditNoteID] = options[:credit_note_id] if options[:credit_note_id] request_params[:CreditNoteNumber] = options[:credit_note_number] if options[:credit_note_number] request_params[:order] = options[:order] if options[:order] request_params[:ModifiedAfter] = options[:modified_since] if options[:modified_since] request_params[:where] = options[:where] if options[:where] response_xml = http_get(@client, "#{@xero_url}/CreditNotes", request_params) parse_response(response_xml, {:request_params => request_params}, {:request_signature => 'GET/CreditNotes'}) end
ruby
def get_credit_notes(options = {}) request_params = {} request_params[:CreditNoteID] = options[:credit_note_id] if options[:credit_note_id] request_params[:CreditNoteNumber] = options[:credit_note_number] if options[:credit_note_number] request_params[:order] = options[:order] if options[:order] request_params[:ModifiedAfter] = options[:modified_since] if options[:modified_since] request_params[:where] = options[:where] if options[:where] response_xml = http_get(@client, "#{@xero_url}/CreditNotes", request_params) parse_response(response_xml, {:request_params => request_params}, {:request_signature => 'GET/CreditNotes'}) end
[ "def", "get_credit_notes", "(", "options", "=", "{", "}", ")", "request_params", "=", "{", "}", "request_params", "[", ":CreditNoteID", "]", "=", "options", "[", ":credit_note_id", "]", "if", "options", "[", ":credit_note_id", "]", "request_params", "[", ":CreditNoteNumber", "]", "=", "options", "[", ":credit_note_number", "]", "if", "options", "[", ":credit_note_number", "]", "request_params", "[", ":order", "]", "=", "options", "[", ":order", "]", "if", "options", "[", ":order", "]", "request_params", "[", ":ModifiedAfter", "]", "=", "options", "[", ":modified_since", "]", "if", "options", "[", ":modified_since", "]", "request_params", "[", ":where", "]", "=", "options", "[", ":where", "]", "if", "options", "[", ":where", "]", "response_xml", "=", "http_get", "(", "@client", ",", "\"#{@xero_url}/CreditNotes\"", ",", "request_params", ")", "parse_response", "(", "response_xml", ",", "{", ":request_params", "=>", "request_params", "}", ",", "{", ":request_signature", "=>", "'GET/CreditNotes'", "}", ")", "end" ]
Retrieves all credit_notes from Xero Usage : get_credit_notes get_credit_notes(:credit_note_id => " 297c2dc5-cc47-4afd-8ec8-74990b8761e9") Note : modified_since is in UTC format (i.e. Brisbane is UTC+10)
[ "Retrieves", "all", "credit_notes", "from", "Xero" ]
6f0afbc3ebb756b66c7eff6c37f77f1e33bd07c5
https://github.com/xero-gateway/xero_gateway/blob/6f0afbc3ebb756b66c7eff6c37f77f1e33bd07c5/lib/xero_gateway/gateway.rb#L293-L307
17,757
xero-gateway/xero_gateway
lib/xero_gateway/gateway.rb
XeroGateway.Gateway.get_credit_note
def get_credit_note(credit_note_id_or_number) request_params = {} url = "#{@xero_url}/CreditNotes/#{CGI.escape(credit_note_id_or_number)}" response_xml = http_get(@client, url, request_params) parse_response(response_xml, {:request_params => request_params}, {:request_signature => 'GET/CreditNote'}) end
ruby
def get_credit_note(credit_note_id_or_number) request_params = {} url = "#{@xero_url}/CreditNotes/#{CGI.escape(credit_note_id_or_number)}" response_xml = http_get(@client, url, request_params) parse_response(response_xml, {:request_params => request_params}, {:request_signature => 'GET/CreditNote'}) end
[ "def", "get_credit_note", "(", "credit_note_id_or_number", ")", "request_params", "=", "{", "}", "url", "=", "\"#{@xero_url}/CreditNotes/#{CGI.escape(credit_note_id_or_number)}\"", "response_xml", "=", "http_get", "(", "@client", ",", "url", ",", "request_params", ")", "parse_response", "(", "response_xml", ",", "{", ":request_params", "=>", "request_params", "}", ",", "{", ":request_signature", "=>", "'GET/CreditNote'", "}", ")", "end" ]
Retrieves a single credit_note Usage : get_credit_note("297c2dc5-cc47-4afd-8ec8-74990b8761e9") # By ID get_credit_note("OIT-12345") # By number
[ "Retrieves", "a", "single", "credit_note" ]
6f0afbc3ebb756b66c7eff6c37f77f1e33bd07c5
https://github.com/xero-gateway/xero_gateway/blob/6f0afbc3ebb756b66c7eff6c37f77f1e33bd07c5/lib/xero_gateway/gateway.rb#L313-L321
17,758
xero-gateway/xero_gateway
lib/xero_gateway/gateway.rb
XeroGateway.Gateway.build_credit_note
def build_credit_note(credit_note = {}) case credit_note when CreditNote then credit_note.gateway = self when Hash then credit_note = CreditNote.new(credit_note.merge(:gateway => self)) end credit_note end
ruby
def build_credit_note(credit_note = {}) case credit_note when CreditNote then credit_note.gateway = self when Hash then credit_note = CreditNote.new(credit_note.merge(:gateway => self)) end credit_note end
[ "def", "build_credit_note", "(", "credit_note", "=", "{", "}", ")", "case", "credit_note", "when", "CreditNote", "then", "credit_note", ".", "gateway", "=", "self", "when", "Hash", "then", "credit_note", "=", "CreditNote", ".", "new", "(", "credit_note", ".", "merge", "(", ":gateway", "=>", "self", ")", ")", "end", "credit_note", "end" ]
Factory method for building new CreditNote objects associated with this gateway.
[ "Factory", "method", "for", "building", "new", "CreditNote", "objects", "associated", "with", "this", "gateway", "." ]
6f0afbc3ebb756b66c7eff6c37f77f1e33bd07c5
https://github.com/xero-gateway/xero_gateway/blob/6f0afbc3ebb756b66c7eff6c37f77f1e33bd07c5/lib/xero_gateway/gateway.rb#L324-L330
17,759
xero-gateway/xero_gateway
lib/xero_gateway/gateway.rb
XeroGateway.Gateway.create_credit_note
def create_credit_note(credit_note) request_xml = credit_note.to_xml response_xml = http_put(@client, "#{@xero_url}/CreditNotes", request_xml) response = parse_response(response_xml, {:request_xml => request_xml}, {:request_signature => 'PUT/credit_note'}) # Xero returns credit_notes inside an <CreditNotes> tag, even though there's only ever # one for this request response.response_item = response.credit_notes.first if response.success? && response.credit_note && response.credit_note.credit_note_id credit_note.credit_note_id = response.credit_note.credit_note_id end response end
ruby
def create_credit_note(credit_note) request_xml = credit_note.to_xml response_xml = http_put(@client, "#{@xero_url}/CreditNotes", request_xml) response = parse_response(response_xml, {:request_xml => request_xml}, {:request_signature => 'PUT/credit_note'}) # Xero returns credit_notes inside an <CreditNotes> tag, even though there's only ever # one for this request response.response_item = response.credit_notes.first if response.success? && response.credit_note && response.credit_note.credit_note_id credit_note.credit_note_id = response.credit_note.credit_note_id end response end
[ "def", "create_credit_note", "(", "credit_note", ")", "request_xml", "=", "credit_note", ".", "to_xml", "response_xml", "=", "http_put", "(", "@client", ",", "\"#{@xero_url}/CreditNotes\"", ",", "request_xml", ")", "response", "=", "parse_response", "(", "response_xml", ",", "{", ":request_xml", "=>", "request_xml", "}", ",", "{", ":request_signature", "=>", "'PUT/credit_note'", "}", ")", "# Xero returns credit_notes inside an <CreditNotes> tag, even though there's only ever", "# one for this request", "response", ".", "response_item", "=", "response", ".", "credit_notes", ".", "first", "if", "response", ".", "success?", "&&", "response", ".", "credit_note", "&&", "response", ".", "credit_note", ".", "credit_note_id", "credit_note", ".", "credit_note_id", "=", "response", ".", "credit_note", ".", "credit_note_id", "end", "response", "end" ]
Creates an credit_note in Xero based on an credit_note object. CreditNote and line item totals are calculated automatically. Usage : credit_note = XeroGateway::CreditNote.new({ :credit_note_type => "ACCREC", :due_date => 1.month.from_now, :credit_note_number => "YOUR CREDIT_NOTE NUMBER", :reference => "YOUR REFERENCE (NOT NECESSARILY UNIQUE!)", :line_amount_types => "Inclusive" }) credit_note.contact = XeroGateway::Contact.new(:name => "THE NAME OF THE CONTACT") credit_note.contact.phone.number = "12345" credit_note.contact.address.line_1 = "LINE 1 OF THE ADDRESS" credit_note.line_items << XeroGateway::LineItem.new( :description => "THE DESCRIPTION OF THE LINE ITEM", :unit_amount => 100, :tax_amount => 12.5, :tracking_category => "THE TRACKING CATEGORY FOR THE LINE ITEM", :tracking_option => "THE TRACKING OPTION FOR THE LINE ITEM" ) create_credit_note(credit_note)
[ "Creates", "an", "credit_note", "in", "Xero", "based", "on", "an", "credit_note", "object", "." ]
6f0afbc3ebb756b66c7eff6c37f77f1e33bd07c5
https://github.com/xero-gateway/xero_gateway/blob/6f0afbc3ebb756b66c7eff6c37f77f1e33bd07c5/lib/xero_gateway/gateway.rb#L357-L371
17,760
xero-gateway/xero_gateway
lib/xero_gateway/gateway.rb
XeroGateway.Gateway.create_credit_notes
def create_credit_notes(credit_notes) b = Builder::XmlMarkup.new request_xml = b.CreditNotes { credit_notes.each do | credit_note | credit_note.to_xml(b) end } response_xml = http_put(@client, "#{@xero_url}/CreditNotes", request_xml, {}) response = parse_response(response_xml, {:request_xml => request_xml}, {:request_signature => 'PUT/credit_notes'}) response.credit_notes.each_with_index do | response_credit_note, index | credit_notes[index].credit_note_id = response_credit_note.credit_note_id if response_credit_note && response_credit_note.credit_note_id end response end
ruby
def create_credit_notes(credit_notes) b = Builder::XmlMarkup.new request_xml = b.CreditNotes { credit_notes.each do | credit_note | credit_note.to_xml(b) end } response_xml = http_put(@client, "#{@xero_url}/CreditNotes", request_xml, {}) response = parse_response(response_xml, {:request_xml => request_xml}, {:request_signature => 'PUT/credit_notes'}) response.credit_notes.each_with_index do | response_credit_note, index | credit_notes[index].credit_note_id = response_credit_note.credit_note_id if response_credit_note && response_credit_note.credit_note_id end response end
[ "def", "create_credit_notes", "(", "credit_notes", ")", "b", "=", "Builder", "::", "XmlMarkup", ".", "new", "request_xml", "=", "b", ".", "CreditNotes", "{", "credit_notes", ".", "each", "do", "|", "credit_note", "|", "credit_note", ".", "to_xml", "(", "b", ")", "end", "}", "response_xml", "=", "http_put", "(", "@client", ",", "\"#{@xero_url}/CreditNotes\"", ",", "request_xml", ",", "{", "}", ")", "response", "=", "parse_response", "(", "response_xml", ",", "{", ":request_xml", "=>", "request_xml", "}", ",", "{", ":request_signature", "=>", "'PUT/credit_notes'", "}", ")", "response", ".", "credit_notes", ".", "each_with_index", "do", "|", "response_credit_note", ",", "index", "|", "credit_notes", "[", "index", "]", ".", "credit_note_id", "=", "response_credit_note", ".", "credit_note_id", "if", "response_credit_note", "&&", "response_credit_note", ".", "credit_note_id", "end", "response", "end" ]
Creates an array of credit_notes with a single API request. Usage : credit_notes = [XeroGateway::CreditNote.new(...), XeroGateway::CreditNote.new(...)] result = gateway.create_credit_notes(credit_notes)
[ "Creates", "an", "array", "of", "credit_notes", "with", "a", "single", "API", "request", "." ]
6f0afbc3ebb756b66c7eff6c37f77f1e33bd07c5
https://github.com/xero-gateway/xero_gateway/blob/6f0afbc3ebb756b66c7eff6c37f77f1e33bd07c5/lib/xero_gateway/gateway.rb#L380-L395
17,761
xero-gateway/xero_gateway
lib/xero_gateway/gateway.rb
XeroGateway.Gateway.get_bank_transactions
def get_bank_transactions(options = {}) request_params = {} request_params[:BankTransactionID] = options[:bank_transaction_id] if options[:bank_transaction_id] request_params[:ModifiedAfter] = options[:modified_since] if options[:modified_since] request_params[:order] = options[:order] if options[:order] request_params[:where] = options[:where] if options[:where] request_params[:page] = options[:page] if options[:page] response_xml = http_get(@client, "#{@xero_url}/BankTransactions", request_params) parse_response(response_xml, {:request_params => request_params}, {:request_signature => 'GET/BankTransactions'}) end
ruby
def get_bank_transactions(options = {}) request_params = {} request_params[:BankTransactionID] = options[:bank_transaction_id] if options[:bank_transaction_id] request_params[:ModifiedAfter] = options[:modified_since] if options[:modified_since] request_params[:order] = options[:order] if options[:order] request_params[:where] = options[:where] if options[:where] request_params[:page] = options[:page] if options[:page] response_xml = http_get(@client, "#{@xero_url}/BankTransactions", request_params) parse_response(response_xml, {:request_params => request_params}, {:request_signature => 'GET/BankTransactions'}) end
[ "def", "get_bank_transactions", "(", "options", "=", "{", "}", ")", "request_params", "=", "{", "}", "request_params", "[", ":BankTransactionID", "]", "=", "options", "[", ":bank_transaction_id", "]", "if", "options", "[", ":bank_transaction_id", "]", "request_params", "[", ":ModifiedAfter", "]", "=", "options", "[", ":modified_since", "]", "if", "options", "[", ":modified_since", "]", "request_params", "[", ":order", "]", "=", "options", "[", ":order", "]", "if", "options", "[", ":order", "]", "request_params", "[", ":where", "]", "=", "options", "[", ":where", "]", "if", "options", "[", ":where", "]", "request_params", "[", ":page", "]", "=", "options", "[", ":page", "]", "if", "options", "[", ":page", "]", "response_xml", "=", "http_get", "(", "@client", ",", "\"#{@xero_url}/BankTransactions\"", ",", "request_params", ")", "parse_response", "(", "response_xml", ",", "{", ":request_params", "=>", "request_params", "}", ",", "{", ":request_signature", "=>", "'GET/BankTransactions'", "}", ")", "end" ]
Retrieves all bank transactions from Xero Usage : get_bank_transactions get_bank_transactions(:bank_transaction_id => " 297c2dc5-cc47-4afd-8ec8-74990b8761e9") Note : modified_since is in UTC format (i.e. Brisbane is UTC+10)
[ "Retrieves", "all", "bank", "transactions", "from", "Xero" ]
6f0afbc3ebb756b66c7eff6c37f77f1e33bd07c5
https://github.com/xero-gateway/xero_gateway/blob/6f0afbc3ebb756b66c7eff6c37f77f1e33bd07c5/lib/xero_gateway/gateway.rb#L445-L456
17,762
xero-gateway/xero_gateway
lib/xero_gateway/gateway.rb
XeroGateway.Gateway.get_bank_transaction
def get_bank_transaction(bank_transaction_id) request_params = {} url = "#{@xero_url}/BankTransactions/#{CGI.escape(bank_transaction_id)}" response_xml = http_get(@client, url, request_params) parse_response(response_xml, {:request_params => request_params}, {:request_signature => 'GET/BankTransaction'}) end
ruby
def get_bank_transaction(bank_transaction_id) request_params = {} url = "#{@xero_url}/BankTransactions/#{CGI.escape(bank_transaction_id)}" response_xml = http_get(@client, url, request_params) parse_response(response_xml, {:request_params => request_params}, {:request_signature => 'GET/BankTransaction'}) end
[ "def", "get_bank_transaction", "(", "bank_transaction_id", ")", "request_params", "=", "{", "}", "url", "=", "\"#{@xero_url}/BankTransactions/#{CGI.escape(bank_transaction_id)}\"", "response_xml", "=", "http_get", "(", "@client", ",", "url", ",", "request_params", ")", "parse_response", "(", "response_xml", ",", "{", ":request_params", "=>", "request_params", "}", ",", "{", ":request_signature", "=>", "'GET/BankTransaction'", "}", ")", "end" ]
Retrieves a single bank transaction Usage : get_bank_transaction("297c2dc5-cc47-4afd-8ec8-74990b8761e9") # By ID get_bank_transaction("OIT-12345") # By number
[ "Retrieves", "a", "single", "bank", "transaction" ]
6f0afbc3ebb756b66c7eff6c37f77f1e33bd07c5
https://github.com/xero-gateway/xero_gateway/blob/6f0afbc3ebb756b66c7eff6c37f77f1e33bd07c5/lib/xero_gateway/gateway.rb#L462-L467
17,763
xero-gateway/xero_gateway
lib/xero_gateway/gateway.rb
XeroGateway.Gateway.get_manual_journals
def get_manual_journals(options = {}) request_params = {} request_params[:ManualJournalID] = options[:manual_journal_id] if options[:manual_journal_id] request_params[:ModifiedAfter] = options[:modified_since] if options[:modified_since] response_xml = http_get(@client, "#{@xero_url}/ManualJournals", request_params) parse_response(response_xml, {:request_params => request_params}, {:request_signature => 'GET/ManualJournals'}) end
ruby
def get_manual_journals(options = {}) request_params = {} request_params[:ManualJournalID] = options[:manual_journal_id] if options[:manual_journal_id] request_params[:ModifiedAfter] = options[:modified_since] if options[:modified_since] response_xml = http_get(@client, "#{@xero_url}/ManualJournals", request_params) parse_response(response_xml, {:request_params => request_params}, {:request_signature => 'GET/ManualJournals'}) end
[ "def", "get_manual_journals", "(", "options", "=", "{", "}", ")", "request_params", "=", "{", "}", "request_params", "[", ":ManualJournalID", "]", "=", "options", "[", ":manual_journal_id", "]", "if", "options", "[", ":manual_journal_id", "]", "request_params", "[", ":ModifiedAfter", "]", "=", "options", "[", ":modified_since", "]", "if", "options", "[", ":modified_since", "]", "response_xml", "=", "http_get", "(", "@client", ",", "\"#{@xero_url}/ManualJournals\"", ",", "request_params", ")", "parse_response", "(", "response_xml", ",", "{", ":request_params", "=>", "request_params", "}", ",", "{", ":request_signature", "=>", "'GET/ManualJournals'", "}", ")", "end" ]
Retrieves all manual journals from Xero Usage : get_manual_journal getmanual_journal(:manual_journal_id => " 297c2dc5-cc47-4afd-8ec8-74990b8761e9") Note : modified_since is in UTC format (i.e. Brisbane is UTC+10)
[ "Retrieves", "all", "manual", "journals", "from", "Xero" ]
6f0afbc3ebb756b66c7eff6c37f77f1e33bd07c5
https://github.com/xero-gateway/xero_gateway/blob/6f0afbc3ebb756b66c7eff6c37f77f1e33bd07c5/lib/xero_gateway/gateway.rb#L498-L506
17,764
xero-gateway/xero_gateway
lib/xero_gateway/gateway.rb
XeroGateway.Gateway.get_manual_journal
def get_manual_journal(manual_journal_id) request_params = {} url = "#{@xero_url}/ManualJournals/#{CGI.escape(manual_journal_id)}" response_xml = http_get(@client, url, request_params) parse_response(response_xml, {:request_params => request_params}, {:request_signature => 'GET/ManualJournal'}) end
ruby
def get_manual_journal(manual_journal_id) request_params = {} url = "#{@xero_url}/ManualJournals/#{CGI.escape(manual_journal_id)}" response_xml = http_get(@client, url, request_params) parse_response(response_xml, {:request_params => request_params}, {:request_signature => 'GET/ManualJournal'}) end
[ "def", "get_manual_journal", "(", "manual_journal_id", ")", "request_params", "=", "{", "}", "url", "=", "\"#{@xero_url}/ManualJournals/#{CGI.escape(manual_journal_id)}\"", "response_xml", "=", "http_get", "(", "@client", ",", "url", ",", "request_params", ")", "parse_response", "(", "response_xml", ",", "{", ":request_params", "=>", "request_params", "}", ",", "{", ":request_signature", "=>", "'GET/ManualJournal'", "}", ")", "end" ]
Retrieves a single manual journal Usage : get_manual_journal("297c2dc5-cc47-4afd-8ec8-74990b8761e9") # By ID get_manual_journal("OIT-12345") # By number
[ "Retrieves", "a", "single", "manual", "journal" ]
6f0afbc3ebb756b66c7eff6c37f77f1e33bd07c5
https://github.com/xero-gateway/xero_gateway/blob/6f0afbc3ebb756b66c7eff6c37f77f1e33bd07c5/lib/xero_gateway/gateway.rb#L512-L517
17,765
xero-gateway/xero_gateway
lib/xero_gateway/gateway.rb
XeroGateway.Gateway.create_payment
def create_payment(payment) b = Builder::XmlMarkup.new request_xml = b.Payments do payment.to_xml(b) end response_xml = http_put(@client, "#{xero_url}/Payments", request_xml) parse_response(response_xml, {:request_xml => request_xml}, {:request_signature => 'PUT/payments'}) end
ruby
def create_payment(payment) b = Builder::XmlMarkup.new request_xml = b.Payments do payment.to_xml(b) end response_xml = http_put(@client, "#{xero_url}/Payments", request_xml) parse_response(response_xml, {:request_xml => request_xml}, {:request_signature => 'PUT/payments'}) end
[ "def", "create_payment", "(", "payment", ")", "b", "=", "Builder", "::", "XmlMarkup", ".", "new", "request_xml", "=", "b", ".", "Payments", "do", "payment", ".", "to_xml", "(", "b", ")", "end", "response_xml", "=", "http_put", "(", "@client", ",", "\"#{xero_url}/Payments\"", ",", "request_xml", ")", "parse_response", "(", "response_xml", ",", "{", ":request_xml", "=>", "request_xml", "}", ",", "{", ":request_signature", "=>", "'PUT/payments'", "}", ")", "end" ]
Create Payment record in Xero
[ "Create", "Payment", "record", "in", "Xero" ]
6f0afbc3ebb756b66c7eff6c37f77f1e33bd07c5
https://github.com/xero-gateway/xero_gateway/blob/6f0afbc3ebb756b66c7eff6c37f77f1e33bd07c5/lib/xero_gateway/gateway.rb#L579-L588
17,766
xero-gateway/xero_gateway
lib/xero_gateway/gateway.rb
XeroGateway.Gateway.get_payments
def get_payments(options = {}) request_params = {} request_params[:PaymentID] = options[:payment_id] if options[:payment_id] request_params[:ModifiedAfter] = options[:modified_since] if options[:modified_since] request_params[:order] = options[:order] if options[:order] request_params[:where] = options[:where] if options[:where] response_xml = http_get(@client, "#{@xero_url}/Payments", request_params) parse_response(response_xml, {:request_params => request_params}, {:request_signature => 'GET/payments'}) end
ruby
def get_payments(options = {}) request_params = {} request_params[:PaymentID] = options[:payment_id] if options[:payment_id] request_params[:ModifiedAfter] = options[:modified_since] if options[:modified_since] request_params[:order] = options[:order] if options[:order] request_params[:where] = options[:where] if options[:where] response_xml = http_get(@client, "#{@xero_url}/Payments", request_params) parse_response(response_xml, {:request_params => request_params}, {:request_signature => 'GET/payments'}) end
[ "def", "get_payments", "(", "options", "=", "{", "}", ")", "request_params", "=", "{", "}", "request_params", "[", ":PaymentID", "]", "=", "options", "[", ":payment_id", "]", "if", "options", "[", ":payment_id", "]", "request_params", "[", ":ModifiedAfter", "]", "=", "options", "[", ":modified_since", "]", "if", "options", "[", ":modified_since", "]", "request_params", "[", ":order", "]", "=", "options", "[", ":order", "]", "if", "options", "[", ":order", "]", "request_params", "[", ":where", "]", "=", "options", "[", ":where", "]", "if", "options", "[", ":where", "]", "response_xml", "=", "http_get", "(", "@client", ",", "\"#{@xero_url}/Payments\"", ",", "request_params", ")", "parse_response", "(", "response_xml", ",", "{", ":request_params", "=>", "request_params", "}", ",", "{", ":request_signature", "=>", "'GET/payments'", "}", ")", "end" ]
Gets all Payments for a specific organisation in Xero
[ "Gets", "all", "Payments", "for", "a", "specific", "organisation", "in", "Xero" ]
6f0afbc3ebb756b66c7eff6c37f77f1e33bd07c5
https://github.com/xero-gateway/xero_gateway/blob/6f0afbc3ebb756b66c7eff6c37f77f1e33bd07c5/lib/xero_gateway/gateway.rb#L593-L602
17,767
xero-gateway/xero_gateway
lib/xero_gateway/gateway.rb
XeroGateway.Gateway.get_payment
def get_payment(payment_id, options = {}) request_params = {} response_xml = http_get(client, "#{@xero_url}/Payments/#{payment_id}", request_params) parse_response(response_xml, {:request_params => request_params}, {:request_signature => 'GET/payments'}) end
ruby
def get_payment(payment_id, options = {}) request_params = {} response_xml = http_get(client, "#{@xero_url}/Payments/#{payment_id}", request_params) parse_response(response_xml, {:request_params => request_params}, {:request_signature => 'GET/payments'}) end
[ "def", "get_payment", "(", "payment_id", ",", "options", "=", "{", "}", ")", "request_params", "=", "{", "}", "response_xml", "=", "http_get", "(", "client", ",", "\"#{@xero_url}/Payments/#{payment_id}\"", ",", "request_params", ")", "parse_response", "(", "response_xml", ",", "{", ":request_params", "=>", "request_params", "}", ",", "{", ":request_signature", "=>", "'GET/payments'", "}", ")", "end" ]
Gets a single Payment for a specific organsation in Xero
[ "Gets", "a", "single", "Payment", "for", "a", "specific", "organsation", "in", "Xero" ]
6f0afbc3ebb756b66c7eff6c37f77f1e33bd07c5
https://github.com/xero-gateway/xero_gateway/blob/6f0afbc3ebb756b66c7eff6c37f77f1e33bd07c5/lib/xero_gateway/gateway.rb#L608-L612
17,768
xero-gateway/xero_gateway
lib/xero_gateway/gateway.rb
XeroGateway.Gateway.get_payroll_calendars
def get_payroll_calendars(options = {}) request_params = {} response_xml = http_get(client, "#{@payroll_url}/PayrollCalendars", request_params) parse_response(response_xml, {:request_params => request_params}, {:request_signature => 'GET/payroll_calendars'}) end
ruby
def get_payroll_calendars(options = {}) request_params = {} response_xml = http_get(client, "#{@payroll_url}/PayrollCalendars", request_params) parse_response(response_xml, {:request_params => request_params}, {:request_signature => 'GET/payroll_calendars'}) end
[ "def", "get_payroll_calendars", "(", "options", "=", "{", "}", ")", "request_params", "=", "{", "}", "response_xml", "=", "http_get", "(", "client", ",", "\"#{@payroll_url}/PayrollCalendars\"", ",", "request_params", ")", "parse_response", "(", "response_xml", ",", "{", ":request_params", "=>", "request_params", "}", ",", "{", ":request_signature", "=>", "'GET/payroll_calendars'", "}", ")", "end" ]
Get the Payroll calendars for a specific organization in Xero
[ "Get", "the", "Payroll", "calendars", "for", "a", "specific", "organization", "in", "Xero" ]
6f0afbc3ebb756b66c7eff6c37f77f1e33bd07c5
https://github.com/xero-gateway/xero_gateway/blob/6f0afbc3ebb756b66c7eff6c37f77f1e33bd07c5/lib/xero_gateway/gateway.rb#L617-L621
17,769
xero-gateway/xero_gateway
lib/xero_gateway/gateway.rb
XeroGateway.Gateway.get_pay_runs
def get_pay_runs(options = {}) request_params = {} response_xml = http_get(client, "#{@payroll_url}/PayRuns", request_params) parse_response(response_xml, {:request_params => request_params}, {:request_signature => 'GET/pay_runs'}) end
ruby
def get_pay_runs(options = {}) request_params = {} response_xml = http_get(client, "#{@payroll_url}/PayRuns", request_params) parse_response(response_xml, {:request_params => request_params}, {:request_signature => 'GET/pay_runs'}) end
[ "def", "get_pay_runs", "(", "options", "=", "{", "}", ")", "request_params", "=", "{", "}", "response_xml", "=", "http_get", "(", "client", ",", "\"#{@payroll_url}/PayRuns\"", ",", "request_params", ")", "parse_response", "(", "response_xml", ",", "{", ":request_params", "=>", "request_params", "}", ",", "{", ":request_signature", "=>", "'GET/pay_runs'", "}", ")", "end" ]
Get the Pay Runs for a specific organization in Xero
[ "Get", "the", "Pay", "Runs", "for", "a", "specific", "organization", "in", "Xero" ]
6f0afbc3ebb756b66c7eff6c37f77f1e33bd07c5
https://github.com/xero-gateway/xero_gateway/blob/6f0afbc3ebb756b66c7eff6c37f77f1e33bd07c5/lib/xero_gateway/gateway.rb#L626-L630
17,770
xero-gateway/xero_gateway
lib/xero_gateway/gateway.rb
XeroGateway.Gateway.get_report
def get_report(id_or_name, options={}) request_params = options.inject({}) do |params, (key, val)| xero_key = key.to_s.camelize.gsub(/id/i, "ID").to_sym params[xero_key] = val params end response_xml = http_get(@client, "#{@xero_url}/reports/#{id_or_name}", request_params) parse_response(response_xml, {:request_params => request_params}, {:request_signature => 'GET/reports'}) end
ruby
def get_report(id_or_name, options={}) request_params = options.inject({}) do |params, (key, val)| xero_key = key.to_s.camelize.gsub(/id/i, "ID").to_sym params[xero_key] = val params end response_xml = http_get(@client, "#{@xero_url}/reports/#{id_or_name}", request_params) parse_response(response_xml, {:request_params => request_params}, {:request_signature => 'GET/reports'}) end
[ "def", "get_report", "(", "id_or_name", ",", "options", "=", "{", "}", ")", "request_params", "=", "options", ".", "inject", "(", "{", "}", ")", "do", "|", "params", ",", "(", "key", ",", "val", ")", "|", "xero_key", "=", "key", ".", "to_s", ".", "camelize", ".", "gsub", "(", "/", "/i", ",", "\"ID\"", ")", ".", "to_sym", "params", "[", "xero_key", "]", "=", "val", "params", "end", "response_xml", "=", "http_get", "(", "@client", ",", "\"#{@xero_url}/reports/#{id_or_name}\"", ",", "request_params", ")", "parse_response", "(", "response_xml", ",", "{", ":request_params", "=>", "request_params", "}", ",", "{", ":request_signature", "=>", "'GET/reports'", "}", ")", "end" ]
Retrieves reports from Xero Usage : get_report("BankStatement", bank_account_id: "AC993F75-035B-433C-82E0-7B7A2D40802C") get_report("297c2dc5-cc47-4afd-8ec8-74990b8761e9", bank_account_id: "AC993F75-035B-433C-82E0-7B7A2D40802C")
[ "Retrieves", "reports", "from", "Xero" ]
6f0afbc3ebb756b66c7eff6c37f77f1e33bd07c5
https://github.com/xero-gateway/xero_gateway/blob/6f0afbc3ebb756b66c7eff6c37f77f1e33bd07c5/lib/xero_gateway/gateway.rb#L636-L644
17,771
xero-gateway/xero_gateway
lib/xero_gateway/gateway.rb
XeroGateway.Gateway.save_contact
def save_contact(contact) request_xml = contact.to_xml response_xml = nil create_or_save = nil if contact.contact_id.nil? && contact.contact_number.nil? # Create new contact record. response_xml = http_put(@client, "#{@xero_url}/Contacts", request_xml, {}) create_or_save = :create else # Update existing contact record. response_xml = http_post(@client, "#{@xero_url}/Contacts", request_xml, {}) create_or_save = :save end response = parse_response(response_xml, {:request_xml => request_xml}, {:request_signature => "#{create_or_save == :create ? 'PUT' : 'POST'}/contact"}) contact.contact_id = response.contact.contact_id if response.contact && response.contact.contact_id response end
ruby
def save_contact(contact) request_xml = contact.to_xml response_xml = nil create_or_save = nil if contact.contact_id.nil? && contact.contact_number.nil? # Create new contact record. response_xml = http_put(@client, "#{@xero_url}/Contacts", request_xml, {}) create_or_save = :create else # Update existing contact record. response_xml = http_post(@client, "#{@xero_url}/Contacts", request_xml, {}) create_or_save = :save end response = parse_response(response_xml, {:request_xml => request_xml}, {:request_signature => "#{create_or_save == :create ? 'PUT' : 'POST'}/contact"}) contact.contact_id = response.contact.contact_id if response.contact && response.contact.contact_id response end
[ "def", "save_contact", "(", "contact", ")", "request_xml", "=", "contact", ".", "to_xml", "response_xml", "=", "nil", "create_or_save", "=", "nil", "if", "contact", ".", "contact_id", ".", "nil?", "&&", "contact", ".", "contact_number", ".", "nil?", "# Create new contact record.", "response_xml", "=", "http_put", "(", "@client", ",", "\"#{@xero_url}/Contacts\"", ",", "request_xml", ",", "{", "}", ")", "create_or_save", "=", ":create", "else", "# Update existing contact record.", "response_xml", "=", "http_post", "(", "@client", ",", "\"#{@xero_url}/Contacts\"", ",", "request_xml", ",", "{", "}", ")", "create_or_save", "=", ":save", "end", "response", "=", "parse_response", "(", "response_xml", ",", "{", ":request_xml", "=>", "request_xml", "}", ",", "{", ":request_signature", "=>", "\"#{create_or_save == :create ? 'PUT' : 'POST'}/contact\"", "}", ")", "contact", ".", "contact_id", "=", "response", ".", "contact", ".", "contact_id", "if", "response", ".", "contact", "&&", "response", ".", "contact", ".", "contact_id", "response", "end" ]
Create or update a contact record based on if it has a contact_id or contact_number.
[ "Create", "or", "update", "a", "contact", "record", "based", "on", "if", "it", "has", "a", "contact_id", "or", "contact_number", "." ]
6f0afbc3ebb756b66c7eff6c37f77f1e33bd07c5
https://github.com/xero-gateway/xero_gateway/blob/6f0afbc3ebb756b66c7eff6c37f77f1e33bd07c5/lib/xero_gateway/gateway.rb#L656-L674
17,772
xero-gateway/xero_gateway
lib/xero_gateway/gateway.rb
XeroGateway.Gateway.save_invoice
def save_invoice(invoice) request_xml = invoice.to_xml response_xml = nil create_or_save = nil if invoice.invoice_id.nil? # Create new invoice record. response_xml = http_put(@client, "#{@xero_url}/Invoices", request_xml, {}) create_or_save = :create else # Update existing invoice record. response_xml = http_post(@client, "#{@xero_url}/Invoices", request_xml, {}) create_or_save = :save end response = parse_response(response_xml, {:request_xml => request_xml}, {:request_signature => "#{create_or_save == :create ? 'PUT' : 'POST'}/invoice"}) # Xero returns invoices inside an <Invoices> tag, even though there's only ever # one for this request response.response_item = response.invoices.first if response.success? && response.invoice && response.invoice.invoice_id invoice.invoice_id = response.invoice.invoice_id end response end
ruby
def save_invoice(invoice) request_xml = invoice.to_xml response_xml = nil create_or_save = nil if invoice.invoice_id.nil? # Create new invoice record. response_xml = http_put(@client, "#{@xero_url}/Invoices", request_xml, {}) create_or_save = :create else # Update existing invoice record. response_xml = http_post(@client, "#{@xero_url}/Invoices", request_xml, {}) create_or_save = :save end response = parse_response(response_xml, {:request_xml => request_xml}, {:request_signature => "#{create_or_save == :create ? 'PUT' : 'POST'}/invoice"}) # Xero returns invoices inside an <Invoices> tag, even though there's only ever # one for this request response.response_item = response.invoices.first if response.success? && response.invoice && response.invoice.invoice_id invoice.invoice_id = response.invoice.invoice_id end response end
[ "def", "save_invoice", "(", "invoice", ")", "request_xml", "=", "invoice", ".", "to_xml", "response_xml", "=", "nil", "create_or_save", "=", "nil", "if", "invoice", ".", "invoice_id", ".", "nil?", "# Create new invoice record.", "response_xml", "=", "http_put", "(", "@client", ",", "\"#{@xero_url}/Invoices\"", ",", "request_xml", ",", "{", "}", ")", "create_or_save", "=", ":create", "else", "# Update existing invoice record.", "response_xml", "=", "http_post", "(", "@client", ",", "\"#{@xero_url}/Invoices\"", ",", "request_xml", ",", "{", "}", ")", "create_or_save", "=", ":save", "end", "response", "=", "parse_response", "(", "response_xml", ",", "{", ":request_xml", "=>", "request_xml", "}", ",", "{", ":request_signature", "=>", "\"#{create_or_save == :create ? 'PUT' : 'POST'}/invoice\"", "}", ")", "# Xero returns invoices inside an <Invoices> tag, even though there's only ever", "# one for this request", "response", ".", "response_item", "=", "response", ".", "invoices", ".", "first", "if", "response", ".", "success?", "&&", "response", ".", "invoice", "&&", "response", ".", "invoice", ".", "invoice_id", "invoice", ".", "invoice_id", "=", "response", ".", "invoice", ".", "invoice_id", "end", "response", "end" ]
Create or update an invoice record based on if it has an invoice_id.
[ "Create", "or", "update", "an", "invoice", "record", "based", "on", "if", "it", "has", "an", "invoice_id", "." ]
6f0afbc3ebb756b66c7eff6c37f77f1e33bd07c5
https://github.com/xero-gateway/xero_gateway/blob/6f0afbc3ebb756b66c7eff6c37f77f1e33bd07c5/lib/xero_gateway/gateway.rb#L677-L703
17,773
xero-gateway/xero_gateway
lib/xero_gateway/gateway.rb
XeroGateway.Gateway.save_bank_transaction
def save_bank_transaction(bank_transaction) request_xml = bank_transaction.to_xml response_xml = nil create_or_save = nil if bank_transaction.bank_transaction_id.nil? # Create new bank transaction record. response_xml = http_put(@client, "#{@xero_url}/BankTransactions", request_xml, {}) create_or_save = :create else # Update existing bank transaction record. response_xml = http_post(@client, "#{@xero_url}/BankTransactions", request_xml, {}) create_or_save = :save end response = parse_response(response_xml, {:request_xml => request_xml}, {:request_signature => "#{create_or_save == :create ? 'PUT' : 'POST'}/BankTransactions"}) # Xero returns bank transactions inside an <BankTransactions> tag, even though there's only ever # one for this request response.response_item = response.bank_transactions.first if response.success? && response.bank_transaction && response.bank_transaction.bank_transaction_id bank_transaction.bank_transaction_id = response.bank_transaction.bank_transaction_id end response end
ruby
def save_bank_transaction(bank_transaction) request_xml = bank_transaction.to_xml response_xml = nil create_or_save = nil if bank_transaction.bank_transaction_id.nil? # Create new bank transaction record. response_xml = http_put(@client, "#{@xero_url}/BankTransactions", request_xml, {}) create_or_save = :create else # Update existing bank transaction record. response_xml = http_post(@client, "#{@xero_url}/BankTransactions", request_xml, {}) create_or_save = :save end response = parse_response(response_xml, {:request_xml => request_xml}, {:request_signature => "#{create_or_save == :create ? 'PUT' : 'POST'}/BankTransactions"}) # Xero returns bank transactions inside an <BankTransactions> tag, even though there's only ever # one for this request response.response_item = response.bank_transactions.first if response.success? && response.bank_transaction && response.bank_transaction.bank_transaction_id bank_transaction.bank_transaction_id = response.bank_transaction.bank_transaction_id end response end
[ "def", "save_bank_transaction", "(", "bank_transaction", ")", "request_xml", "=", "bank_transaction", ".", "to_xml", "response_xml", "=", "nil", "create_or_save", "=", "nil", "if", "bank_transaction", ".", "bank_transaction_id", ".", "nil?", "# Create new bank transaction record.", "response_xml", "=", "http_put", "(", "@client", ",", "\"#{@xero_url}/BankTransactions\"", ",", "request_xml", ",", "{", "}", ")", "create_or_save", "=", ":create", "else", "# Update existing bank transaction record.", "response_xml", "=", "http_post", "(", "@client", ",", "\"#{@xero_url}/BankTransactions\"", ",", "request_xml", ",", "{", "}", ")", "create_or_save", "=", ":save", "end", "response", "=", "parse_response", "(", "response_xml", ",", "{", ":request_xml", "=>", "request_xml", "}", ",", "{", ":request_signature", "=>", "\"#{create_or_save == :create ? 'PUT' : 'POST'}/BankTransactions\"", "}", ")", "# Xero returns bank transactions inside an <BankTransactions> tag, even though there's only ever", "# one for this request", "response", ".", "response_item", "=", "response", ".", "bank_transactions", ".", "first", "if", "response", ".", "success?", "&&", "response", ".", "bank_transaction", "&&", "response", ".", "bank_transaction", ".", "bank_transaction_id", "bank_transaction", ".", "bank_transaction_id", "=", "response", ".", "bank_transaction", ".", "bank_transaction_id", "end", "response", "end" ]
Create or update a bank transaction record based on if it has an bank_transaction_id.
[ "Create", "or", "update", "a", "bank", "transaction", "record", "based", "on", "if", "it", "has", "an", "bank_transaction_id", "." ]
6f0afbc3ebb756b66c7eff6c37f77f1e33bd07c5
https://github.com/xero-gateway/xero_gateway/blob/6f0afbc3ebb756b66c7eff6c37f77f1e33bd07c5/lib/xero_gateway/gateway.rb#L706-L732
17,774
xero-gateway/xero_gateway
lib/xero_gateway/gateway.rb
XeroGateway.Gateway.save_manual_journal
def save_manual_journal(manual_journal) request_xml = manual_journal.to_xml response_xml = nil create_or_save = nil if manual_journal.manual_journal_id.nil? # Create new manual journal record. response_xml = http_put(@client, "#{@xero_url}/ManualJournals", request_xml, {}) create_or_save = :create else # Update existing manual journal record. response_xml = http_post(@client, "#{@xero_url}/ManualJournals", request_xml, {}) create_or_save = :save end response = parse_response(response_xml, {:request_xml => request_xml}, {:request_signature => "#{create_or_save == :create ? 'PUT' : 'POST'}/ManualJournals"}) # Xero returns manual journals inside an <ManualJournals> tag, even though there's only ever # one for this request response.response_item = response.manual_journals.first manual_journal.manual_journal_id = response.manual_journal.manual_journal_id if response.success? && response.manual_journal && response.manual_journal.manual_journal_id response end
ruby
def save_manual_journal(manual_journal) request_xml = manual_journal.to_xml response_xml = nil create_or_save = nil if manual_journal.manual_journal_id.nil? # Create new manual journal record. response_xml = http_put(@client, "#{@xero_url}/ManualJournals", request_xml, {}) create_or_save = :create else # Update existing manual journal record. response_xml = http_post(@client, "#{@xero_url}/ManualJournals", request_xml, {}) create_or_save = :save end response = parse_response(response_xml, {:request_xml => request_xml}, {:request_signature => "#{create_or_save == :create ? 'PUT' : 'POST'}/ManualJournals"}) # Xero returns manual journals inside an <ManualJournals> tag, even though there's only ever # one for this request response.response_item = response.manual_journals.first manual_journal.manual_journal_id = response.manual_journal.manual_journal_id if response.success? && response.manual_journal && response.manual_journal.manual_journal_id response end
[ "def", "save_manual_journal", "(", "manual_journal", ")", "request_xml", "=", "manual_journal", ".", "to_xml", "response_xml", "=", "nil", "create_or_save", "=", "nil", "if", "manual_journal", ".", "manual_journal_id", ".", "nil?", "# Create new manual journal record.", "response_xml", "=", "http_put", "(", "@client", ",", "\"#{@xero_url}/ManualJournals\"", ",", "request_xml", ",", "{", "}", ")", "create_or_save", "=", ":create", "else", "# Update existing manual journal record.", "response_xml", "=", "http_post", "(", "@client", ",", "\"#{@xero_url}/ManualJournals\"", ",", "request_xml", ",", "{", "}", ")", "create_or_save", "=", ":save", "end", "response", "=", "parse_response", "(", "response_xml", ",", "{", ":request_xml", "=>", "request_xml", "}", ",", "{", ":request_signature", "=>", "\"#{create_or_save == :create ? 'PUT' : 'POST'}/ManualJournals\"", "}", ")", "# Xero returns manual journals inside an <ManualJournals> tag, even though there's only ever", "# one for this request", "response", ".", "response_item", "=", "response", ".", "manual_journals", ".", "first", "manual_journal", ".", "manual_journal_id", "=", "response", ".", "manual_journal", ".", "manual_journal_id", "if", "response", ".", "success?", "&&", "response", ".", "manual_journal", "&&", "response", ".", "manual_journal", ".", "manual_journal_id", "response", "end" ]
Create or update a manual journal record based on if it has an manual_journal_id.
[ "Create", "or", "update", "a", "manual", "journal", "record", "based", "on", "if", "it", "has", "an", "manual_journal_id", "." ]
6f0afbc3ebb756b66c7eff6c37f77f1e33bd07c5
https://github.com/xero-gateway/xero_gateway/blob/6f0afbc3ebb756b66c7eff6c37f77f1e33bd07c5/lib/xero_gateway/gateway.rb#L735-L759
17,775
xero-gateway/xero_gateway
lib/xero_gateway/credit_note.rb
XeroGateway.CreditNote.build_contact
def build_contact(params = {}) self.contact = gateway ? gateway.build_contact(params) : Contact.new(params) end
ruby
def build_contact(params = {}) self.contact = gateway ? gateway.build_contact(params) : Contact.new(params) end
[ "def", "build_contact", "(", "params", "=", "{", "}", ")", "self", ".", "contact", "=", "gateway", "?", "gateway", ".", "build_contact", "(", "params", ")", ":", "Contact", ".", "new", "(", "params", ")", "end" ]
Helper method to create the associated contact object.
[ "Helper", "method", "to", "create", "the", "associated", "contact", "object", "." ]
6f0afbc3ebb756b66c7eff6c37f77f1e33bd07c5
https://github.com/xero-gateway/xero_gateway/blob/6f0afbc3ebb756b66c7eff6c37f77f1e33bd07c5/lib/xero_gateway/credit_note.rb#L99-L101
17,776
xero-gateway/xero_gateway
lib/xero_gateway/oauth.rb
XeroGateway.OAuth.renew_access_token
def renew_access_token(access_token = nil, access_secret = nil, session_handle = nil) access_token ||= @atoken access_secret ||= @asecret session_handle ||= @session_handle old_token = ::OAuth::RequestToken.new(consumer, access_token, access_secret) # Underlying oauth consumer accepts body params and headers for request via positional params - explicit nilling of # body parameters allows for correct position for headers access_token = old_token.get_access_token({ :oauth_session_handle => session_handle, :token => old_token }, nil, @base_headers) update_attributes_from_token(access_token) rescue ::OAuth::Unauthorized => e # If the original access token is for some reason invalid an OAuth::Unauthorized could be raised. # In this case raise a XeroGateway::OAuth::TokenInvalid which can be captured by the caller. In this # situation the end user will need to re-authorize the application via the request token authorization URL raise XeroGateway::OAuth::TokenInvalid.new(e.message) end
ruby
def renew_access_token(access_token = nil, access_secret = nil, session_handle = nil) access_token ||= @atoken access_secret ||= @asecret session_handle ||= @session_handle old_token = ::OAuth::RequestToken.new(consumer, access_token, access_secret) # Underlying oauth consumer accepts body params and headers for request via positional params - explicit nilling of # body parameters allows for correct position for headers access_token = old_token.get_access_token({ :oauth_session_handle => session_handle, :token => old_token }, nil, @base_headers) update_attributes_from_token(access_token) rescue ::OAuth::Unauthorized => e # If the original access token is for some reason invalid an OAuth::Unauthorized could be raised. # In this case raise a XeroGateway::OAuth::TokenInvalid which can be captured by the caller. In this # situation the end user will need to re-authorize the application via the request token authorization URL raise XeroGateway::OAuth::TokenInvalid.new(e.message) end
[ "def", "renew_access_token", "(", "access_token", "=", "nil", ",", "access_secret", "=", "nil", ",", "session_handle", "=", "nil", ")", "access_token", "||=", "@atoken", "access_secret", "||=", "@asecret", "session_handle", "||=", "@session_handle", "old_token", "=", "::", "OAuth", "::", "RequestToken", ".", "new", "(", "consumer", ",", "access_token", ",", "access_secret", ")", "# Underlying oauth consumer accepts body params and headers for request via positional params - explicit nilling of ", "# body parameters allows for correct position for headers", "access_token", "=", "old_token", ".", "get_access_token", "(", "{", ":oauth_session_handle", "=>", "session_handle", ",", ":token", "=>", "old_token", "}", ",", "nil", ",", "@base_headers", ")", "update_attributes_from_token", "(", "access_token", ")", "rescue", "::", "OAuth", "::", "Unauthorized", "=>", "e", "# If the original access token is for some reason invalid an OAuth::Unauthorized could be raised.", "# In this case raise a XeroGateway::OAuth::TokenInvalid which can be captured by the caller. In this", "# situation the end user will need to re-authorize the application via the request token authorization URL", "raise", "XeroGateway", "::", "OAuth", "::", "TokenInvalid", ".", "new", "(", "e", ".", "message", ")", "end" ]
Renewing access tokens only works for Partner applications
[ "Renewing", "access", "tokens", "only", "works", "for", "Partner", "applications" ]
6f0afbc3ebb756b66c7eff6c37f77f1e33bd07c5
https://github.com/xero-gateway/xero_gateway/blob/6f0afbc3ebb756b66c7eff6c37f77f1e33bd07c5/lib/xero_gateway/oauth.rb#L67-L87
17,777
xero-gateway/xero_gateway
lib/xero_gateway/oauth.rb
XeroGateway.OAuth.update_attributes_from_token
def update_attributes_from_token(access_token) @expires_at = Time.now + access_token.params[:oauth_expires_in].to_i @authorization_expires_at = Time.now + access_token.params[:oauth_authorization_expires_in].to_i @session_handle = access_token.params[:oauth_session_handle] @atoken, @asecret = access_token.token, access_token.secret @access_token = nil end
ruby
def update_attributes_from_token(access_token) @expires_at = Time.now + access_token.params[:oauth_expires_in].to_i @authorization_expires_at = Time.now + access_token.params[:oauth_authorization_expires_in].to_i @session_handle = access_token.params[:oauth_session_handle] @atoken, @asecret = access_token.token, access_token.secret @access_token = nil end
[ "def", "update_attributes_from_token", "(", "access_token", ")", "@expires_at", "=", "Time", ".", "now", "+", "access_token", ".", "params", "[", ":oauth_expires_in", "]", ".", "to_i", "@authorization_expires_at", "=", "Time", ".", "now", "+", "access_token", ".", "params", "[", ":oauth_authorization_expires_in", "]", ".", "to_i", "@session_handle", "=", "access_token", ".", "params", "[", ":oauth_session_handle", "]", "@atoken", ",", "@asecret", "=", "access_token", ".", "token", ",", "access_token", ".", "secret", "@access_token", "=", "nil", "end" ]
Update instance variables with those from the AccessToken.
[ "Update", "instance", "variables", "with", "those", "from", "the", "AccessToken", "." ]
6f0afbc3ebb756b66c7eff6c37f77f1e33bd07c5
https://github.com/xero-gateway/xero_gateway/blob/6f0afbc3ebb756b66c7eff6c37f77f1e33bd07c5/lib/xero_gateway/oauth.rb#L108-L114
17,778
xero-gateway/xero_gateway
lib/xero_gateway/bank_transaction.rb
XeroGateway.BankTransaction.valid?
def valid? @errors = [] if !bank_transaction_id.nil? && bank_transaction_id !~ GUID_REGEX @errors << ['bank_transaction_id', 'must be blank or a valid Xero GUID'] end if type && !TYPES[type] @errors << ['type', "must be one of #{TYPES.keys.join('/')}"] end if status && !STATUSES[status] @errors << ['status', "must be one of #{STATUSES.keys.join('/')}"] end unless date @errors << ['date', "can't be blank"] end # Make sure contact is valid. unless @contact && @contact.valid? @errors << ['contact', 'is invalid'] end # Make sure all line_items are valid. unless line_items.all? { | line_item | line_item.valid? } @errors << ['line_items', "at least one line item invalid"] end @errors.size == 0 end
ruby
def valid? @errors = [] if !bank_transaction_id.nil? && bank_transaction_id !~ GUID_REGEX @errors << ['bank_transaction_id', 'must be blank or a valid Xero GUID'] end if type && !TYPES[type] @errors << ['type', "must be one of #{TYPES.keys.join('/')}"] end if status && !STATUSES[status] @errors << ['status', "must be one of #{STATUSES.keys.join('/')}"] end unless date @errors << ['date', "can't be blank"] end # Make sure contact is valid. unless @contact && @contact.valid? @errors << ['contact', 'is invalid'] end # Make sure all line_items are valid. unless line_items.all? { | line_item | line_item.valid? } @errors << ['line_items', "at least one line item invalid"] end @errors.size == 0 end
[ "def", "valid?", "@errors", "=", "[", "]", "if", "!", "bank_transaction_id", ".", "nil?", "&&", "bank_transaction_id", "!~", "GUID_REGEX", "@errors", "<<", "[", "'bank_transaction_id'", ",", "'must be blank or a valid Xero GUID'", "]", "end", "if", "type", "&&", "!", "TYPES", "[", "type", "]", "@errors", "<<", "[", "'type'", ",", "\"must be one of #{TYPES.keys.join('/')}\"", "]", "end", "if", "status", "&&", "!", "STATUSES", "[", "status", "]", "@errors", "<<", "[", "'status'", ",", "\"must be one of #{STATUSES.keys.join('/')}\"", "]", "end", "unless", "date", "@errors", "<<", "[", "'date'", ",", "\"can't be blank\"", "]", "end", "# Make sure contact is valid.", "unless", "@contact", "&&", "@contact", ".", "valid?", "@errors", "<<", "[", "'contact'", ",", "'is invalid'", "]", "end", "# Make sure all line_items are valid.", "unless", "line_items", ".", "all?", "{", "|", "line_item", "|", "line_item", ".", "valid?", "}", "@errors", "<<", "[", "'line_items'", ",", "\"at least one line item invalid\"", "]", "end", "@errors", ".", "size", "==", "0", "end" ]
Validate the BankTransaction record according to what will be valid by the gateway. Usage: bank_transaction.valid? # Returns true/false Additionally sets bank_transaction.errors array to an array of field/error.
[ "Validate", "the", "BankTransaction", "record", "according", "to", "what", "will", "be", "valid", "by", "the", "gateway", "." ]
6f0afbc3ebb756b66c7eff6c37f77f1e33bd07c5
https://github.com/xero-gateway/xero_gateway/blob/6f0afbc3ebb756b66c7eff6c37f77f1e33bd07c5/lib/xero_gateway/bank_transaction.rb#L65-L95
17,779
xero-gateway/xero_gateway
lib/xero_gateway/manual_journal.rb
XeroGateway.ManualJournal.valid?
def valid? @errors = [] if !manual_journal_id.nil? && manual_journal_id !~ GUID_REGEX @errors << ['manual_journal_id', 'must be blank or a valid Xero GUID'] end if narration.blank? @errors << ['narration', "can't be blank"] end unless date @errors << ['date', "can't be blank"] end # Make sure all journal_items are valid. unless journal_lines.all? { | journal_line | journal_line.valid? } @errors << ['journal_lines', "at least one journal line invalid"] end # make sure there are at least 2 journal lines unless journal_lines.length > 1 @errors << ['journal_lines', "journal must contain at least two individual journal lines"] end if journal_lines.length > 100 @errors << ['journal_lines', "journal must contain less than one hundred journal lines"] end unless journal_lines.sum(&:line_amount).to_f == 0.0 @errors << ['journal_lines', "the total debits must be equal to total credits"] end @errors.size == 0 end
ruby
def valid? @errors = [] if !manual_journal_id.nil? && manual_journal_id !~ GUID_REGEX @errors << ['manual_journal_id', 'must be blank or a valid Xero GUID'] end if narration.blank? @errors << ['narration', "can't be blank"] end unless date @errors << ['date', "can't be blank"] end # Make sure all journal_items are valid. unless journal_lines.all? { | journal_line | journal_line.valid? } @errors << ['journal_lines', "at least one journal line invalid"] end # make sure there are at least 2 journal lines unless journal_lines.length > 1 @errors << ['journal_lines', "journal must contain at least two individual journal lines"] end if journal_lines.length > 100 @errors << ['journal_lines', "journal must contain less than one hundred journal lines"] end unless journal_lines.sum(&:line_amount).to_f == 0.0 @errors << ['journal_lines', "the total debits must be equal to total credits"] end @errors.size == 0 end
[ "def", "valid?", "@errors", "=", "[", "]", "if", "!", "manual_journal_id", ".", "nil?", "&&", "manual_journal_id", "!~", "GUID_REGEX", "@errors", "<<", "[", "'manual_journal_id'", ",", "'must be blank or a valid Xero GUID'", "]", "end", "if", "narration", ".", "blank?", "@errors", "<<", "[", "'narration'", ",", "\"can't be blank\"", "]", "end", "unless", "date", "@errors", "<<", "[", "'date'", ",", "\"can't be blank\"", "]", "end", "# Make sure all journal_items are valid.", "unless", "journal_lines", ".", "all?", "{", "|", "journal_line", "|", "journal_line", ".", "valid?", "}", "@errors", "<<", "[", "'journal_lines'", ",", "\"at least one journal line invalid\"", "]", "end", "# make sure there are at least 2 journal lines", "unless", "journal_lines", ".", "length", ">", "1", "@errors", "<<", "[", "'journal_lines'", ",", "\"journal must contain at least two individual journal lines\"", "]", "end", "if", "journal_lines", ".", "length", ">", "100", "@errors", "<<", "[", "'journal_lines'", ",", "\"journal must contain less than one hundred journal lines\"", "]", "end", "unless", "journal_lines", ".", "sum", "(", ":line_amount", ")", ".", "to_f", "==", "0.0", "@errors", "<<", "[", "'journal_lines'", ",", "\"the total debits must be equal to total credits\"", "]", "end", "@errors", ".", "size", "==", "0", "end" ]
Validate the ManualJournal record according to what will be valid by the gateway. Usage: manual_journal.valid? # Returns true/false Additionally sets manual_journal.errors array to an array of field/error.
[ "Validate", "the", "ManualJournal", "record", "according", "to", "what", "will", "be", "valid", "by", "the", "gateway", "." ]
6f0afbc3ebb756b66c7eff6c37f77f1e33bd07c5
https://github.com/xero-gateway/xero_gateway/blob/6f0afbc3ebb756b66c7eff6c37f77f1e33bd07c5/lib/xero_gateway/manual_journal.rb#L61-L95
17,780
xero-gateway/xero_gateway
lib/xero_gateway/tracking_category.rb
XeroGateway.TrackingCategory.to_xml_for_invoice_messages
def to_xml_for_invoice_messages(b = Builder::XmlMarkup.new) b.TrackingCategory { b.TrackingCategoryID self.tracking_category_id unless tracking_category_id.nil? b.Name self.name b.Option self.options.is_a?(Array) ? self.options.first : self.options.to_s } end
ruby
def to_xml_for_invoice_messages(b = Builder::XmlMarkup.new) b.TrackingCategory { b.TrackingCategoryID self.tracking_category_id unless tracking_category_id.nil? b.Name self.name b.Option self.options.is_a?(Array) ? self.options.first : self.options.to_s } end
[ "def", "to_xml_for_invoice_messages", "(", "b", "=", "Builder", "::", "XmlMarkup", ".", "new", ")", "b", ".", "TrackingCategory", "{", "b", ".", "TrackingCategoryID", "self", ".", "tracking_category_id", "unless", "tracking_category_id", ".", "nil?", "b", ".", "Name", "self", ".", "name", "b", ".", "Option", "self", ".", "options", ".", "is_a?", "(", "Array", ")", "?", "self", ".", "options", ".", "first", ":", "self", ".", "options", ".", "to_s", "}", "end" ]
When a tracking category is serialized as part of an invoice it may only have a single option, and the Options tag is omitted
[ "When", "a", "tracking", "category", "is", "serialized", "as", "part", "of", "an", "invoice", "it", "may", "only", "have", "a", "single", "option", "and", "the", "Options", "tag", "is", "omitted" ]
6f0afbc3ebb756b66c7eff6c37f77f1e33bd07c5
https://github.com/xero-gateway/xero_gateway/blob/6f0afbc3ebb756b66c7eff6c37f77f1e33bd07c5/lib/xero_gateway/tracking_category.rb#L80-L86
17,781
winston/google_visualr
lib/google_visualr/base_chart.rb
GoogleVisualr.BaseChart.to_js
def to_js(element_id) js = "" js << "\n<script type='text/javascript'>" js << load_js(element_id) js << draw_js(element_id) js << "\n</script>" js end
ruby
def to_js(element_id) js = "" js << "\n<script type='text/javascript'>" js << load_js(element_id) js << draw_js(element_id) js << "\n</script>" js end
[ "def", "to_js", "(", "element_id", ")", "js", "=", "\"\"", "js", "<<", "\"\\n<script type='text/javascript'>\"", "js", "<<", "load_js", "(", "element_id", ")", "js", "<<", "draw_js", "(", "element_id", ")", "js", "<<", "\"\\n</script>\"", "js", "end" ]
Generates JavaScript and renders the Google Chart in the final HTML output. Parameters: *div_id [Required] The ID of the DIV element that the Google Chart should be rendered in.
[ "Generates", "JavaScript", "and", "renders", "the", "Google", "Chart", "in", "the", "final", "HTML", "output", "." ]
17b97114a345baadd011e7b442b9a6c91a2b7ab5
https://github.com/winston/google_visualr/blob/17b97114a345baadd011e7b442b9a6c91a2b7ab5/lib/google_visualr/base_chart.rb#L63-L70
17,782
winston/google_visualr
lib/google_visualr/base_chart.rb
GoogleVisualr.BaseChart.draw_js
def draw_js(element_id) js = "" js << "\n function #{chart_function_name(element_id)}() {" js << "\n #{@data_table.to_js}" js << "\n var chart = new google.#{chart_class}.#{chart_name}(document.getElementById('#{element_id}'));" @listeners.each do |listener| js << "\n google.visualization.events.addListener(chart, '#{listener[:event]}', #{listener[:callback]});" end js << "\n chart.draw(data_table, #{js_parameters(@options)});" js << "\n };" js end
ruby
def draw_js(element_id) js = "" js << "\n function #{chart_function_name(element_id)}() {" js << "\n #{@data_table.to_js}" js << "\n var chart = new google.#{chart_class}.#{chart_name}(document.getElementById('#{element_id}'));" @listeners.each do |listener| js << "\n google.visualization.events.addListener(chart, '#{listener[:event]}', #{listener[:callback]});" end js << "\n chart.draw(data_table, #{js_parameters(@options)});" js << "\n };" js end
[ "def", "draw_js", "(", "element_id", ")", "js", "=", "\"\"", "js", "<<", "\"\\n function #{chart_function_name(element_id)}() {\"", "js", "<<", "\"\\n #{@data_table.to_js}\"", "js", "<<", "\"\\n var chart = new google.#{chart_class}.#{chart_name}(document.getElementById('#{element_id}'));\"", "@listeners", ".", "each", "do", "|", "listener", "|", "js", "<<", "\"\\n google.visualization.events.addListener(chart, '#{listener[:event]}', #{listener[:callback]});\"", "end", "js", "<<", "\"\\n chart.draw(data_table, #{js_parameters(@options)});\"", "js", "<<", "\"\\n };\"", "js", "end" ]
Generates JavaScript function for rendering the chart. Parameters: *div_id [Required] The ID of the DIV element that the Google Chart should be rendered in.
[ "Generates", "JavaScript", "function", "for", "rendering", "the", "chart", "." ]
17b97114a345baadd011e7b442b9a6c91a2b7ab5
https://github.com/winston/google_visualr/blob/17b97114a345baadd011e7b442b9a6c91a2b7ab5/lib/google_visualr/base_chart.rb#L86-L97
17,783
winston/google_visualr
lib/google_visualr/data_table.rb
GoogleVisualr.DataTable.new_columns
def new_columns(columns) columns.each do |column| new_column(column[:type], column[:label], column[:id], column[:role], column[:pattern]) end end
ruby
def new_columns(columns) columns.each do |column| new_column(column[:type], column[:label], column[:id], column[:role], column[:pattern]) end end
[ "def", "new_columns", "(", "columns", ")", "columns", ".", "each", "do", "|", "column", "|", "new_column", "(", "column", "[", ":type", "]", ",", "column", "[", ":label", "]", ",", "column", "[", ":id", "]", ",", "column", "[", ":role", "]", ",", "column", "[", ":pattern", "]", ")", "end", "end" ]
Adds multiple columns to the data_table. Parameters: * columns [Required] An array of column objects {:type, :label, :id, :role, :pattern}. Calls new_column for each column object.
[ "Adds", "multiple", "columns", "to", "the", "data_table", "." ]
17b97114a345baadd011e7b442b9a6c91a2b7ab5
https://github.com/winston/google_visualr/blob/17b97114a345baadd011e7b442b9a6c91a2b7ab5/lib/google_visualr/data_table.rb#L90-L94
17,784
winston/google_visualr
lib/google_visualr/data_table.rb
GoogleVisualr.DataTable.set_column
def set_column(column_index, column_values) if @rows.size < column_values.size 1.upto(column_values.size - @rows.size) { @rows << Array.new } end column_values.each_with_index do |column_value, row_index| set_cell(row_index, column_index, column_value) end end
ruby
def set_column(column_index, column_values) if @rows.size < column_values.size 1.upto(column_values.size - @rows.size) { @rows << Array.new } end column_values.each_with_index do |column_value, row_index| set_cell(row_index, column_index, column_value) end end
[ "def", "set_column", "(", "column_index", ",", "column_values", ")", "if", "@rows", ".", "size", "<", "column_values", ".", "size", "1", ".", "upto", "(", "column_values", ".", "size", "-", "@rows", ".", "size", ")", "{", "@rows", "<<", "Array", ".", "new", "}", "end", "column_values", ".", "each_with_index", "do", "|", "column_value", ",", "row_index", "|", "set_cell", "(", "row_index", ",", "column_index", ",", "column_value", ")", "end", "end" ]
Sets a column in data_table, specified by column_index with an array of column_values. column_index starts from 0. Parameters * column_index [Required] The column to assign column_values. column_index starts from 0. * column_values [Required] An array of cell values.
[ "Sets", "a", "column", "in", "data_table", "specified", "by", "column_index", "with", "an", "array", "of", "column_values", ".", "column_index", "starts", "from", "0", "." ]
17b97114a345baadd011e7b442b9a6c91a2b7ab5
https://github.com/winston/google_visualr/blob/17b97114a345baadd011e7b442b9a6c91a2b7ab5/lib/google_visualr/data_table.rb#L101-L109
17,785
winston/google_visualr
lib/google_visualr/data_table.rb
GoogleVisualr.DataTable.add_row
def add_row(row_values=[]) @rows << Array.new row_index = @rows.size-1 row_values.each_with_index do |row_value, column_index| set_cell(row_index, column_index, row_value) end end
ruby
def add_row(row_values=[]) @rows << Array.new row_index = @rows.size-1 row_values.each_with_index do |row_value, column_index| set_cell(row_index, column_index, row_value) end end
[ "def", "add_row", "(", "row_values", "=", "[", "]", ")", "@rows", "<<", "Array", ".", "new", "row_index", "=", "@rows", ".", "size", "-", "1", "row_values", ".", "each_with_index", "do", "|", "row_value", ",", "column_index", "|", "set_cell", "(", "row_index", ",", "column_index", ",", "row_value", ")", "end", "end" ]
Adds a new row to the data_table. Call method without any parameters to add an empty row, otherwise, call method with a row object. Parameters: * row [Optional] An array of cell values specifying the data for the new row. - You can specify a value for a cell (e.g. 'hi') or specify a formatted value using cell objects (e.g. {v:55, f:'Fifty-five'}) as described in the constructor section. - You can mix simple values and cell objects in the same method call. - To create an empty cell, use nil or empty string.
[ "Adds", "a", "new", "row", "to", "the", "data_table", ".", "Call", "method", "without", "any", "parameters", "to", "add", "an", "empty", "row", "otherwise", "call", "method", "with", "a", "row", "object", "." ]
17b97114a345baadd011e7b442b9a6c91a2b7ab5
https://github.com/winston/google_visualr/blob/17b97114a345baadd011e7b442b9a6c91a2b7ab5/lib/google_visualr/data_table.rb#L127-L134
17,786
winston/google_visualr
lib/google_visualr/data_table.rb
GoogleVisualr.DataTable.add_rows
def add_rows(array_or_num) if array_or_num.is_a?(Array) array_or_num.each do |row| add_row(row) end else array_or_num.times do add_row end end end
ruby
def add_rows(array_or_num) if array_or_num.is_a?(Array) array_or_num.each do |row| add_row(row) end else array_or_num.times do add_row end end end
[ "def", "add_rows", "(", "array_or_num", ")", "if", "array_or_num", ".", "is_a?", "(", "Array", ")", "array_or_num", ".", "each", "do", "|", "row", "|", "add_row", "(", "row", ")", "end", "else", "array_or_num", ".", "times", "do", "add_row", "end", "end", "end" ]
Adds multiple rows to the data_table. You can call this method with data to populate a set of new rows or create new empty rows. Parameters: * array_or_num [Required] Either an array or a number. - Array: An array of row objects used to populate a set of new rows. Each row is an object as described in add_row(). - Number: A number specifying the number of new empty rows to create.
[ "Adds", "multiple", "rows", "to", "the", "data_table", ".", "You", "can", "call", "this", "method", "with", "data", "to", "populate", "a", "set", "of", "new", "rows", "or", "create", "new", "empty", "rows", "." ]
17b97114a345baadd011e7b442b9a6c91a2b7ab5
https://github.com/winston/google_visualr/blob/17b97114a345baadd011e7b442b9a6c91a2b7ab5/lib/google_visualr/data_table.rb#L142-L152
17,787
winston/google_visualr
lib/google_visualr/data_table.rb
GoogleVisualr.DataTable.get_cell
def get_cell(row_index, column_index) if within_range?(row_index, column_index) @rows[row_index][column_index].v else raise RangeError, "row_index and column_index MUST be < @rows.size and @cols.size", caller end end
ruby
def get_cell(row_index, column_index) if within_range?(row_index, column_index) @rows[row_index][column_index].v else raise RangeError, "row_index and column_index MUST be < @rows.size and @cols.size", caller end end
[ "def", "get_cell", "(", "row_index", ",", "column_index", ")", "if", "within_range?", "(", "row_index", ",", "column_index", ")", "@rows", "[", "row_index", "]", "[", "column_index", "]", ".", "v", "else", "raise", "RangeError", ",", "\"row_index and column_index MUST be < @rows.size and @cols.size\"", ",", "caller", "end", "end" ]
Gets a cell value from the visualization, at row_index, column_index. row_index and column_index start from 0. Parameters: * row_index [Required] row_index starts from 0. * column_index [Required] column_index starts from 0.
[ "Gets", "a", "cell", "value", "from", "the", "visualization", "at", "row_index", "column_index", ".", "row_index", "and", "column_index", "start", "from", "0", "." ]
17b97114a345baadd011e7b442b9a6c91a2b7ab5
https://github.com/winston/google_visualr/blob/17b97114a345baadd011e7b442b9a6c91a2b7ab5/lib/google_visualr/data_table.rb#L185-L191
17,788
winston/google_visualr
lib/google_visualr/data_table.rb
GoogleVisualr.DataTable.to_js
def to_js js = "var data_table = new google.visualization.DataTable();" @cols.each do |column| js << "data_table.addColumn(" js << display(column) js << ");" end @rows.each do |row| js << "data_table.addRow(" js << "[#{row.map(&:to_js).join(", ")}]" unless row.empty? js << ");" end if @formatters @formatters.each do |formatter| js << formatter.to_js end end js end
ruby
def to_js js = "var data_table = new google.visualization.DataTable();" @cols.each do |column| js << "data_table.addColumn(" js << display(column) js << ");" end @rows.each do |row| js << "data_table.addRow(" js << "[#{row.map(&:to_js).join(", ")}]" unless row.empty? js << ");" end if @formatters @formatters.each do |formatter| js << formatter.to_js end end js end
[ "def", "to_js", "js", "=", "\"var data_table = new google.visualization.DataTable();\"", "@cols", ".", "each", "do", "|", "column", "|", "js", "<<", "\"data_table.addColumn(\"", "js", "<<", "display", "(", "column", ")", "js", "<<", "\");\"", "end", "@rows", ".", "each", "do", "|", "row", "|", "js", "<<", "\"data_table.addRow(\"", "js", "<<", "\"[#{row.map(&:to_js).join(\", \")}]\"", "unless", "row", ".", "empty?", "js", "<<", "\");\"", "end", "if", "@formatters", "@formatters", ".", "each", "do", "|", "formatter", "|", "js", "<<", "formatter", ".", "to_js", "end", "end", "js", "end" ]
Returns the JavaScript equivalent for this data_table instance.
[ "Returns", "the", "JavaScript", "equivalent", "for", "this", "data_table", "instance", "." ]
17b97114a345baadd011e7b442b9a6c91a2b7ab5
https://github.com/winston/google_visualr/blob/17b97114a345baadd011e7b442b9a6c91a2b7ab5/lib/google_visualr/data_table.rb#L203-L225
17,789
sparkleformation/sfn
lib/sfn/callback.rb
Sfn.Callback.run_action
def run_action(msg) ui.info("#{msg}... ", :nonewline) begin result = yield ui.puts ui.color("complete!", :green, :bold) result rescue => e ui.puts ui.color("error!", :red, :bold) ui.error "Reason - #{e}" raise end end
ruby
def run_action(msg) ui.info("#{msg}... ", :nonewline) begin result = yield ui.puts ui.color("complete!", :green, :bold) result rescue => e ui.puts ui.color("error!", :red, :bold) ui.error "Reason - #{e}" raise end end
[ "def", "run_action", "(", "msg", ")", "ui", ".", "info", "(", "\"#{msg}... \"", ",", ":nonewline", ")", "begin", "result", "=", "yield", "ui", ".", "puts", "ui", ".", "color", "(", "\"complete!\"", ",", ":green", ",", ":bold", ")", "result", "rescue", "=>", "e", "ui", ".", "puts", "ui", ".", "color", "(", "\"error!\"", ",", ":red", ",", ":bold", ")", "ui", ".", "error", "\"Reason - #{e}\"", "raise", "end", "end" ]
Create a new callback instance @param ui [Bogo::Ui] @param config [Smash] configuration hash @param arguments [Array<String>] arguments from the CLI @param api [Provider] API connection @return [self] Wrap action within status text @param msg [String] action text @yieldblock action to perform @return [Object] result of yield
[ "Create", "a", "new", "callback", "instance" ]
68dacff9b9a9cb3389d4b763566ca1e94659104b
https://github.com/sparkleformation/sfn/blob/68dacff9b9a9cb3389d4b763566ca1e94659104b/lib/sfn/callback.rb#L39-L50
17,790
sparkleformation/sfn
lib/sfn/provider.rb
Sfn.Provider.save_expanded_stack
def save_expanded_stack(stack_id, stack_attributes) current_stacks = MultiJson.load(cached_stacks) cache.locked_action(:stacks_lock) do logger.info "Saving expanded stack attributes in cache (#{stack_id})" current_stacks[stack_id] = stack_attributes.merge("Cached" => Time.now.to_i) cache[:stacks].value = MultiJson.dump(current_stacks) end true end
ruby
def save_expanded_stack(stack_id, stack_attributes) current_stacks = MultiJson.load(cached_stacks) cache.locked_action(:stacks_lock) do logger.info "Saving expanded stack attributes in cache (#{stack_id})" current_stacks[stack_id] = stack_attributes.merge("Cached" => Time.now.to_i) cache[:stacks].value = MultiJson.dump(current_stacks) end true end
[ "def", "save_expanded_stack", "(", "stack_id", ",", "stack_attributes", ")", "current_stacks", "=", "MultiJson", ".", "load", "(", "cached_stacks", ")", "cache", ".", "locked_action", "(", ":stacks_lock", ")", "do", "logger", ".", "info", "\"Saving expanded stack attributes in cache (#{stack_id})\"", "current_stacks", "[", "stack_id", "]", "=", "stack_attributes", ".", "merge", "(", "\"Cached\"", "=>", "Time", ".", "now", ".", "to_i", ")", "cache", "[", ":stacks", "]", ".", "value", "=", "MultiJson", ".", "dump", "(", "current_stacks", ")", "end", "true", "end" ]
Store stack attribute changes @param stack_id [String] @param stack_attributes [Hash] @return [TrueClass]
[ "Store", "stack", "attribute", "changes" ]
68dacff9b9a9cb3389d4b763566ca1e94659104b
https://github.com/sparkleformation/sfn/blob/68dacff9b9a9cb3389d4b763566ca1e94659104b/lib/sfn/provider.rb#L125-L133
17,791
sparkleformation/sfn
lib/sfn/provider.rb
Sfn.Provider.remove_stack
def remove_stack(stack_id) current_stacks = MultiJson.load(cached_stacks) logger.info "Attempting to remove stack from internal cache (#{stack_id})" cache.locked_action(:stacks_lock) do val = current_stacks.delete(stack_id) logger.info "Successfully removed stack from internal cache (#{stack_id})" cache[:stacks].value = MultiJson.dump(current_stacks) !!val end end
ruby
def remove_stack(stack_id) current_stacks = MultiJson.load(cached_stacks) logger.info "Attempting to remove stack from internal cache (#{stack_id})" cache.locked_action(:stacks_lock) do val = current_stacks.delete(stack_id) logger.info "Successfully removed stack from internal cache (#{stack_id})" cache[:stacks].value = MultiJson.dump(current_stacks) !!val end end
[ "def", "remove_stack", "(", "stack_id", ")", "current_stacks", "=", "MultiJson", ".", "load", "(", "cached_stacks", ")", "logger", ".", "info", "\"Attempting to remove stack from internal cache (#{stack_id})\"", "cache", ".", "locked_action", "(", ":stacks_lock", ")", "do", "val", "=", "current_stacks", ".", "delete", "(", "stack_id", ")", "logger", ".", "info", "\"Successfully removed stack from internal cache (#{stack_id})\"", "cache", "[", ":stacks", "]", ".", "value", "=", "MultiJson", ".", "dump", "(", "current_stacks", ")", "!", "!", "val", "end", "end" ]
Remove stack from the cache @param stack_id [String] @return [TrueClass, FalseClass]
[ "Remove", "stack", "from", "the", "cache" ]
68dacff9b9a9cb3389d4b763566ca1e94659104b
https://github.com/sparkleformation/sfn/blob/68dacff9b9a9cb3389d4b763566ca1e94659104b/lib/sfn/provider.rb#L139-L148
17,792
sparkleformation/sfn
lib/sfn/provider.rb
Sfn.Provider.expand_stack
def expand_stack(stack) logger.info "Stack expansion requested (#{stack.id})" if ((stack.in_progress? && Time.now.to_i - stack.attributes["Cached"].to_i > stack_expansion_interval) || !stack.attributes["Cached"]) begin expanded = false cache.locked_action(:stack_expansion_lock) do expanded = true stack.reload stack.data["Cached"] = Time.now.to_i end if expanded save_expanded_stack(stack.id, stack.to_json) end rescue => e logger.error "Stack expansion failed (#{stack.id}) - #{e.class}: #{e}" end else logger.info "Stack has been cached within expand interval. Expansion prevented. (#{stack.id})" end end
ruby
def expand_stack(stack) logger.info "Stack expansion requested (#{stack.id})" if ((stack.in_progress? && Time.now.to_i - stack.attributes["Cached"].to_i > stack_expansion_interval) || !stack.attributes["Cached"]) begin expanded = false cache.locked_action(:stack_expansion_lock) do expanded = true stack.reload stack.data["Cached"] = Time.now.to_i end if expanded save_expanded_stack(stack.id, stack.to_json) end rescue => e logger.error "Stack expansion failed (#{stack.id}) - #{e.class}: #{e}" end else logger.info "Stack has been cached within expand interval. Expansion prevented. (#{stack.id})" end end
[ "def", "expand_stack", "(", "stack", ")", "logger", ".", "info", "\"Stack expansion requested (#{stack.id})\"", "if", "(", "(", "stack", ".", "in_progress?", "&&", "Time", ".", "now", ".", "to_i", "-", "stack", ".", "attributes", "[", "\"Cached\"", "]", ".", "to_i", ">", "stack_expansion_interval", ")", "||", "!", "stack", ".", "attributes", "[", "\"Cached\"", "]", ")", "begin", "expanded", "=", "false", "cache", ".", "locked_action", "(", ":stack_expansion_lock", ")", "do", "expanded", "=", "true", "stack", ".", "reload", "stack", ".", "data", "[", "\"Cached\"", "]", "=", "Time", ".", "now", ".", "to_i", "end", "if", "expanded", "save_expanded_stack", "(", "stack", ".", "id", ",", "stack", ".", "to_json", ")", "end", "rescue", "=>", "e", "logger", ".", "error", "\"Stack expansion failed (#{stack.id}) - #{e.class}: #{e}\"", "end", "else", "logger", ".", "info", "\"Stack has been cached within expand interval. Expansion prevented. (#{stack.id})\"", "end", "end" ]
Expand all lazy loaded attributes within stack @param stack [Miasma::Models::Orchestration::Stack]
[ "Expand", "all", "lazy", "loaded", "attributes", "within", "stack" ]
68dacff9b9a9cb3389d4b763566ca1e94659104b
https://github.com/sparkleformation/sfn/blob/68dacff9b9a9cb3389d4b763566ca1e94659104b/lib/sfn/provider.rb#L153-L173
17,793
sparkleformation/sfn
lib/sfn/provider.rb
Sfn.Provider.fetch_stacks
def fetch_stacks(stack_id = nil) cache.locked_action(:stacks_lock) do logger.info "Lock aquired for stack update. Requesting stacks from upstream. (#{Thread.current})" if stack_id single_stack = connection.stacks.get(stack_id) stacks = single_stack ? {single_stack.id => single_stack} : {} else stacks = Hash[ connection.stacks.reload.all.map do |stack| [stack.id, stack.attributes] end ] end if cache[:stacks].value existing_stacks = MultiJson.load(cache[:stacks].value) # Force common types stacks = MultiJson.load(MultiJson.dump(stacks)) if stack_id stacks = existing_stacks.to_smash.deep_merge(stacks) else # Remove stacks that have been deleted stale_ids = existing_stacks.keys - stacks.keys stacks = existing_stacks.to_smash.deep_merge(stacks) stale_ids.each do |stale_id| stacks.delete(stale_id) end end end cache[:stacks].value = stacks.to_json logger.info "Stack list has been updated from upstream and cached locally" end @initial_fetch_complete = true end
ruby
def fetch_stacks(stack_id = nil) cache.locked_action(:stacks_lock) do logger.info "Lock aquired for stack update. Requesting stacks from upstream. (#{Thread.current})" if stack_id single_stack = connection.stacks.get(stack_id) stacks = single_stack ? {single_stack.id => single_stack} : {} else stacks = Hash[ connection.stacks.reload.all.map do |stack| [stack.id, stack.attributes] end ] end if cache[:stacks].value existing_stacks = MultiJson.load(cache[:stacks].value) # Force common types stacks = MultiJson.load(MultiJson.dump(stacks)) if stack_id stacks = existing_stacks.to_smash.deep_merge(stacks) else # Remove stacks that have been deleted stale_ids = existing_stacks.keys - stacks.keys stacks = existing_stacks.to_smash.deep_merge(stacks) stale_ids.each do |stale_id| stacks.delete(stale_id) end end end cache[:stacks].value = stacks.to_json logger.info "Stack list has been updated from upstream and cached locally" end @initial_fetch_complete = true end
[ "def", "fetch_stacks", "(", "stack_id", "=", "nil", ")", "cache", ".", "locked_action", "(", ":stacks_lock", ")", "do", "logger", ".", "info", "\"Lock aquired for stack update. Requesting stacks from upstream. (#{Thread.current})\"", "if", "stack_id", "single_stack", "=", "connection", ".", "stacks", ".", "get", "(", "stack_id", ")", "stacks", "=", "single_stack", "?", "{", "single_stack", ".", "id", "=>", "single_stack", "}", ":", "{", "}", "else", "stacks", "=", "Hash", "[", "connection", ".", "stacks", ".", "reload", ".", "all", ".", "map", "do", "|", "stack", "|", "[", "stack", ".", "id", ",", "stack", ".", "attributes", "]", "end", "]", "end", "if", "cache", "[", ":stacks", "]", ".", "value", "existing_stacks", "=", "MultiJson", ".", "load", "(", "cache", "[", ":stacks", "]", ".", "value", ")", "# Force common types", "stacks", "=", "MultiJson", ".", "load", "(", "MultiJson", ".", "dump", "(", "stacks", ")", ")", "if", "stack_id", "stacks", "=", "existing_stacks", ".", "to_smash", ".", "deep_merge", "(", "stacks", ")", "else", "# Remove stacks that have been deleted", "stale_ids", "=", "existing_stacks", ".", "keys", "-", "stacks", ".", "keys", "stacks", "=", "existing_stacks", ".", "to_smash", ".", "deep_merge", "(", "stacks", ")", "stale_ids", ".", "each", "do", "|", "stale_id", "|", "stacks", ".", "delete", "(", "stale_id", ")", "end", "end", "end", "cache", "[", ":stacks", "]", ".", "value", "=", "stacks", ".", "to_json", "logger", ".", "info", "\"Stack list has been updated from upstream and cached locally\"", "end", "@initial_fetch_complete", "=", "true", "end" ]
Request stack information and store in cache @return [TrueClass]
[ "Request", "stack", "information", "and", "store", "in", "cache" ]
68dacff9b9a9cb3389d4b763566ca1e94659104b
https://github.com/sparkleformation/sfn/blob/68dacff9b9a9cb3389d4b763566ca1e94659104b/lib/sfn/provider.rb#L178-L210
17,794
sparkleformation/sfn
lib/sfn/provider.rb
Sfn.Provider.update_stack_list!
def update_stack_list! if updater.nil? || !updater.alive? self.updater = Thread.new { loop do begin fetch_stacks sleep(stack_list_interval) rescue => e logger.error "Failure encountered on stack fetch: #{e.class} - #{e}" end end } true else false end end
ruby
def update_stack_list! if updater.nil? || !updater.alive? self.updater = Thread.new { loop do begin fetch_stacks sleep(stack_list_interval) rescue => e logger.error "Failure encountered on stack fetch: #{e.class} - #{e}" end end } true else false end end
[ "def", "update_stack_list!", "if", "updater", ".", "nil?", "||", "!", "updater", ".", "alive?", "self", ".", "updater", "=", "Thread", ".", "new", "{", "loop", "do", "begin", "fetch_stacks", "sleep", "(", "stack_list_interval", ")", "rescue", "=>", "e", "logger", ".", "error", "\"Failure encountered on stack fetch: #{e.class} - #{e}\"", "end", "end", "}", "true", "else", "false", "end", "end" ]
Start async stack list update. Creates thread that loops every `self.stack_list_interval` seconds and refreshes stack list in cache @return [TrueClass, FalseClass]
[ "Start", "async", "stack", "list", "update", ".", "Creates", "thread", "that", "loops", "every", "self", ".", "stack_list_interval", "seconds", "and", "refreshes", "stack", "list", "in", "cache" ]
68dacff9b9a9cb3389d4b763566ca1e94659104b
https://github.com/sparkleformation/sfn/blob/68dacff9b9a9cb3389d4b763566ca1e94659104b/lib/sfn/provider.rb#L216-L232
17,795
sparkleformation/sfn
lib/sfn/command.rb
Sfn.Command.load_api_provider_extensions!
def load_api_provider_extensions! if config.get(:credentials, :provider) base_ext = Bogo::Utility.camel(config.get(:credentials, :provider)).to_sym targ_ext = self.class.name.split("::").last if ApiProvider.constants.include?(base_ext) base_module = ApiProvider.const_get(base_ext) ui.debug "Loading core provider extensions via `#{base_module}`" extend base_module if base_module.constants.include?(targ_ext) targ_module = base_module.const_get(targ_ext) ui.debug "Loading targeted provider extensions via `#{targ_module}`" extend targ_module end true end end end
ruby
def load_api_provider_extensions! if config.get(:credentials, :provider) base_ext = Bogo::Utility.camel(config.get(:credentials, :provider)).to_sym targ_ext = self.class.name.split("::").last if ApiProvider.constants.include?(base_ext) base_module = ApiProvider.const_get(base_ext) ui.debug "Loading core provider extensions via `#{base_module}`" extend base_module if base_module.constants.include?(targ_ext) targ_module = base_module.const_get(targ_ext) ui.debug "Loading targeted provider extensions via `#{targ_module}`" extend targ_module end true end end end
[ "def", "load_api_provider_extensions!", "if", "config", ".", "get", "(", ":credentials", ",", ":provider", ")", "base_ext", "=", "Bogo", "::", "Utility", ".", "camel", "(", "config", ".", "get", "(", ":credentials", ",", ":provider", ")", ")", ".", "to_sym", "targ_ext", "=", "self", ".", "class", ".", "name", ".", "split", "(", "\"::\"", ")", ".", "last", "if", "ApiProvider", ".", "constants", ".", "include?", "(", "base_ext", ")", "base_module", "=", "ApiProvider", ".", "const_get", "(", "base_ext", ")", "ui", ".", "debug", "\"Loading core provider extensions via `#{base_module}`\"", "extend", "base_module", "if", "base_module", ".", "constants", ".", "include?", "(", "targ_ext", ")", "targ_module", "=", "base_module", ".", "const_get", "(", "targ_ext", ")", "ui", ".", "debug", "\"Loading targeted provider extensions via `#{targ_module}`\"", "extend", "targ_module", "end", "true", "end", "end", "end" ]
Load API provider specific overrides to customize behavior @return [TrueClass, FalseClass]
[ "Load", "API", "provider", "specific", "overrides", "to", "customize", "behavior" ]
68dacff9b9a9cb3389d4b763566ca1e94659104b
https://github.com/sparkleformation/sfn/blob/68dacff9b9a9cb3389d4b763566ca1e94659104b/lib/sfn/command.rb#L68-L84
17,796
sparkleformation/sfn
lib/sfn/command.rb
Sfn.Command.discover_config
def discover_config(opts) cwd = Dir.pwd.split(File::SEPARATOR) detected_path = "" until cwd.empty? || File.exists?(detected_path.to_s) detected_path = Dir.glob( (cwd + ["#{CONFIG_BASE_NAME}{#{VALID_CONFIG_EXTENSIONS.join(",")}}"]).join( File::SEPARATOR ) ).first cwd.pop end if opts.respond_to?(:fetch_option) opts.fetch_option("config").value = detected_path if detected_path else opts["config"] = detected_path if detected_path end opts end
ruby
def discover_config(opts) cwd = Dir.pwd.split(File::SEPARATOR) detected_path = "" until cwd.empty? || File.exists?(detected_path.to_s) detected_path = Dir.glob( (cwd + ["#{CONFIG_BASE_NAME}{#{VALID_CONFIG_EXTENSIONS.join(",")}}"]).join( File::SEPARATOR ) ).first cwd.pop end if opts.respond_to?(:fetch_option) opts.fetch_option("config").value = detected_path if detected_path else opts["config"] = detected_path if detected_path end opts end
[ "def", "discover_config", "(", "opts", ")", "cwd", "=", "Dir", ".", "pwd", ".", "split", "(", "File", "::", "SEPARATOR", ")", "detected_path", "=", "\"\"", "until", "cwd", ".", "empty?", "||", "File", ".", "exists?", "(", "detected_path", ".", "to_s", ")", "detected_path", "=", "Dir", ".", "glob", "(", "(", "cwd", "+", "[", "\"#{CONFIG_BASE_NAME}{#{VALID_CONFIG_EXTENSIONS.join(\",\")}}\"", "]", ")", ".", "join", "(", "File", "::", "SEPARATOR", ")", ")", ".", "first", "cwd", ".", "pop", "end", "if", "opts", ".", "respond_to?", "(", ":fetch_option", ")", "opts", ".", "fetch_option", "(", "\"config\"", ")", ".", "value", "=", "detected_path", "if", "detected_path", "else", "opts", "[", "\"config\"", "]", "=", "detected_path", "if", "detected_path", "end", "opts", "end" ]
Start with current working directory and traverse to root looking for a `.sfn` configuration file @param opts [Slop] @return [Slop]
[ "Start", "with", "current", "working", "directory", "and", "traverse", "to", "root", "looking", "for", "a", ".", "sfn", "configuration", "file" ]
68dacff9b9a9cb3389d4b763566ca1e94659104b
https://github.com/sparkleformation/sfn/blob/68dacff9b9a9cb3389d4b763566ca1e94659104b/lib/sfn/command.rb#L91-L108
17,797
sparkleformation/sfn
lib/sfn/cache.rb
Sfn.Cache.init
def init(name, kind, args = {}) get_storage(self.class.type, kind, name, args) true end
ruby
def init(name, kind, args = {}) get_storage(self.class.type, kind, name, args) true end
[ "def", "init", "(", "name", ",", "kind", ",", "args", "=", "{", "}", ")", "get_storage", "(", "self", ".", "class", ".", "type", ",", "kind", ",", "name", ",", "args", ")", "true", "end" ]
Create new instance @param key [String, Array] Initialize a new data type @param name [Symbol] name of data @param kind [Symbol] data type @param args [Hash] options for data type
[ "Create", "new", "instance" ]
68dacff9b9a9cb3389d4b763566ca1e94659104b
https://github.com/sparkleformation/sfn/blob/68dacff9b9a9cb3389d4b763566ca1e94659104b/lib/sfn/cache.rb#L93-L96
17,798
sparkleformation/sfn
lib/sfn/cache.rb
Sfn.Cache.get_storage
def get_storage(store_type, data_type, name, args = {}) full_name = "#{key}_#{name}" result = nil case store_type.to_sym when :redis result = get_redis_storage(data_type, full_name.to_s, args) when :local @_local_cache ||= {} unless @_local_cache[full_name.to_s] @_local_cache[full_name.to_s] = get_local_storage(data_type, full_name.to_s, args) end result = @_local_cache[full_name.to_s] else raise TypeError.new("Unsupported caching storage type encountered: #{store_type}") end unless full_name == "#{key}_registry_#{key}" registry[name.to_s] = data_type end result end
ruby
def get_storage(store_type, data_type, name, args = {}) full_name = "#{key}_#{name}" result = nil case store_type.to_sym when :redis result = get_redis_storage(data_type, full_name.to_s, args) when :local @_local_cache ||= {} unless @_local_cache[full_name.to_s] @_local_cache[full_name.to_s] = get_local_storage(data_type, full_name.to_s, args) end result = @_local_cache[full_name.to_s] else raise TypeError.new("Unsupported caching storage type encountered: #{store_type}") end unless full_name == "#{key}_registry_#{key}" registry[name.to_s] = data_type end result end
[ "def", "get_storage", "(", "store_type", ",", "data_type", ",", "name", ",", "args", "=", "{", "}", ")", "full_name", "=", "\"#{key}_#{name}\"", "result", "=", "nil", "case", "store_type", ".", "to_sym", "when", ":redis", "result", "=", "get_redis_storage", "(", "data_type", ",", "full_name", ".", "to_s", ",", "args", ")", "when", ":local", "@_local_cache", "||=", "{", "}", "unless", "@_local_cache", "[", "full_name", ".", "to_s", "]", "@_local_cache", "[", "full_name", ".", "to_s", "]", "=", "get_local_storage", "(", "data_type", ",", "full_name", ".", "to_s", ",", "args", ")", "end", "result", "=", "@_local_cache", "[", "full_name", ".", "to_s", "]", "else", "raise", "TypeError", ".", "new", "(", "\"Unsupported caching storage type encountered: #{store_type}\"", ")", "end", "unless", "full_name", "==", "\"#{key}_registry_#{key}\"", "registry", "[", "name", ".", "to_s", "]", "=", "data_type", "end", "result", "end" ]
Fetch item from storage @param store_type [Symbol] @param data_type [Symbol] @param name [Symbol] name of data @param args [Hash] options for underlying storage @return [Object]
[ "Fetch", "item", "from", "storage" ]
68dacff9b9a9cb3389d4b763566ca1e94659104b
https://github.com/sparkleformation/sfn/blob/68dacff9b9a9cb3389d4b763566ca1e94659104b/lib/sfn/cache.rb#L132-L151
17,799
sparkleformation/sfn
lib/sfn/cache.rb
Sfn.Cache.get_redis_storage
def get_redis_storage(data_type, full_name, args = {}) self.class.redis_ping! case data_type.to_sym when :array Redis::List.new(full_name, {:marshal => true}.merge(args)) when :hash Redis::HashKey.new(full_name) when :value Redis::Value.new(full_name, {:marshal => true}.merge(args)) when :lock Redis::Lock.new(full_name, {:expiration => 60, :timeout => 0.1}.merge(args)) when :stamped Stamped.new(full_name.sub("#{key}_", "").to_sym, get_redis_storage(:value, full_name), self) else raise TypeError.new("Unsupported caching data type encountered: #{data_type}") end end
ruby
def get_redis_storage(data_type, full_name, args = {}) self.class.redis_ping! case data_type.to_sym when :array Redis::List.new(full_name, {:marshal => true}.merge(args)) when :hash Redis::HashKey.new(full_name) when :value Redis::Value.new(full_name, {:marshal => true}.merge(args)) when :lock Redis::Lock.new(full_name, {:expiration => 60, :timeout => 0.1}.merge(args)) when :stamped Stamped.new(full_name.sub("#{key}_", "").to_sym, get_redis_storage(:value, full_name), self) else raise TypeError.new("Unsupported caching data type encountered: #{data_type}") end end
[ "def", "get_redis_storage", "(", "data_type", ",", "full_name", ",", "args", "=", "{", "}", ")", "self", ".", "class", ".", "redis_ping!", "case", "data_type", ".", "to_sym", "when", ":array", "Redis", "::", "List", ".", "new", "(", "full_name", ",", "{", ":marshal", "=>", "true", "}", ".", "merge", "(", "args", ")", ")", "when", ":hash", "Redis", "::", "HashKey", ".", "new", "(", "full_name", ")", "when", ":value", "Redis", "::", "Value", ".", "new", "(", "full_name", ",", "{", ":marshal", "=>", "true", "}", ".", "merge", "(", "args", ")", ")", "when", ":lock", "Redis", "::", "Lock", ".", "new", "(", "full_name", ",", "{", ":expiration", "=>", "60", ",", ":timeout", "=>", "0.1", "}", ".", "merge", "(", "args", ")", ")", "when", ":stamped", "Stamped", ".", "new", "(", "full_name", ".", "sub", "(", "\"#{key}_\"", ",", "\"\"", ")", ".", "to_sym", ",", "get_redis_storage", "(", ":value", ",", "full_name", ")", ",", "self", ")", "else", "raise", "TypeError", ".", "new", "(", "\"Unsupported caching data type encountered: #{data_type}\"", ")", "end", "end" ]
Fetch item from redis storage @param data_type [Symbol] @param full_name [Symbol] @param args [Hash] @return [Object]
[ "Fetch", "item", "from", "redis", "storage" ]
68dacff9b9a9cb3389d4b763566ca1e94659104b
https://github.com/sparkleformation/sfn/blob/68dacff9b9a9cb3389d4b763566ca1e94659104b/lib/sfn/cache.rb#L159-L175