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
sequence
docstring
stringlengths
8
16k
docstring_tokens
sequence
sha
stringlengths
40
40
url
stringlengths
94
266
partition
stringclasses
1 value
gocardless/coach
lib/coach/handler.rb
Coach.Handler.build_request_chain
def build_request_chain(sequence, context) sequence.reverse.reduce(nil) do |successor, item| item.build_middleware(context, successor) end end
ruby
def build_request_chain(sequence, context) sequence.reverse.reduce(nil) do |successor, item| item.build_middleware(context, successor) end end
[ "def", "build_request_chain", "(", "sequence", ",", "context", ")", "sequence", ".", "reverse", ".", "reduce", "(", "nil", ")", "do", "|", "successor", ",", "item", "|", "item", ".", "build_middleware", "(", "context", ",", "successor", ")", "end", "end" ]
Given a middleware sequence, filter out items not applicable to the current request, and set up a chain of instantiated middleware objects, ready to serve a request.
[ "Given", "a", "middleware", "sequence", "filter", "out", "items", "not", "applicable", "to", "the", "current", "request", "and", "set", "up", "a", "chain", "of", "instantiated", "middleware", "objects", "ready", "to", "serve", "a", "request", "." ]
a643771b63953bd9948d783505ae3ca5ac6a7f36
https://github.com/gocardless/coach/blob/a643771b63953bd9948d783505ae3ca5ac6a7f36/lib/coach/handler.rb#L65-L69
train
gocardless/coach
lib/coach/handler.rb
Coach.Handler.dedup_sequence
def dedup_sequence(sequence) sequence.uniq { |item| [item.class, item.middleware, item.config] } end
ruby
def dedup_sequence(sequence) sequence.uniq { |item| [item.class, item.middleware, item.config] } end
[ "def", "dedup_sequence", "(", "sequence", ")", "sequence", ".", "uniq", "{", "|", "item", "|", "[", "item", ".", "class", ",", "item", ".", "middleware", ",", "item", ".", "config", "]", "}", "end" ]
Remove middleware that have been included multiple times with the same config, leaving only the first instance
[ "Remove", "middleware", "that", "have", "been", "included", "multiple", "times", "with", "the", "same", "config", "leaving", "only", "the", "first", "instance" ]
a643771b63953bd9948d783505ae3ca5ac6a7f36
https://github.com/gocardless/coach/blob/a643771b63953bd9948d783505ae3ca5ac6a7f36/lib/coach/handler.rb#L79-L81
train
gocardless/coach
lib/coach/router.rb
Coach.Router.action_traits
def action_traits(list_of_actions) *list_of_actions, traits = list_of_actions if list_of_actions.last.is_a?(Hash) list_of_actions.reduce(traits || {}) do |memo, action| trait = ACTION_TRAITS.fetch(action) do raise Errors::RouterUnknownDefaultAction, action end memo.merge(action => trait) end end
ruby
def action_traits(list_of_actions) *list_of_actions, traits = list_of_actions if list_of_actions.last.is_a?(Hash) list_of_actions.reduce(traits || {}) do |memo, action| trait = ACTION_TRAITS.fetch(action) do raise Errors::RouterUnknownDefaultAction, action end memo.merge(action => trait) end end
[ "def", "action_traits", "(", "list_of_actions", ")", "*", "list_of_actions", ",", "traits", "=", "list_of_actions", "if", "list_of_actions", ".", "last", ".", "is_a?", "(", "Hash", ")", "list_of_actions", ".", "reduce", "(", "traits", "||", "{", "}", ")", "do", "|", "memo", ",", "action", "|", "trait", "=", "ACTION_TRAITS", ".", "fetch", "(", "action", ")", "do", "raise", "Errors", "::", "RouterUnknownDefaultAction", ",", "action", "end", "memo", ".", "merge", "(", "action", "=>", "trait", ")", "end", "end" ]
Receives an array of symbols that represent actions for which the default traits should be used, and then lastly an optional trait configuration. Example is... [ :index, :show, { refund: { url: ':id/refund', method: 'post' } } ] ...which will load the default route for `show` and `index`, while also configuring a refund route.
[ "Receives", "an", "array", "of", "symbols", "that", "represent", "actions", "for", "which", "the", "default", "traits", "should", "be", "used", "and", "then", "lastly", "an", "optional", "trait", "configuration", "." ]
a643771b63953bd9948d783505ae3ca5ac6a7f36
https://github.com/gocardless/coach/blob/a643771b63953bd9948d783505ae3ca5ac6a7f36/lib/coach/router.rb#L47-L57
train
gocardless/coach
lib/coach/middleware.rb
Coach.Middleware.provide
def provide(args) args.each do |name, value| unless self.class.provides?(name) raise NameError, "#{self.class} does not provide #{name}" end @_context[name] = value end end
ruby
def provide(args) args.each do |name, value| unless self.class.provides?(name) raise NameError, "#{self.class} does not provide #{name}" end @_context[name] = value end end
[ "def", "provide", "(", "args", ")", "args", ".", "each", "do", "|", "name", ",", "value", "|", "unless", "self", ".", "class", ".", "provides?", "(", "name", ")", "raise", "NameError", ",", "\"#{self.class} does not provide #{name}\"", "end", "@_context", "[", "name", "]", "=", "value", "end", "end" ]
Make values available to middleware further down the stack. Accepts a hash of name => value pairs. Names must have been declared by calling `provides` on the class.
[ "Make", "values", "available", "to", "middleware", "further", "down", "the", "stack", ".", "Accepts", "a", "hash", "of", "name", "=", ">", "value", "pairs", ".", "Names", "must", "have", "been", "declared", "by", "calling", "provides", "on", "the", "class", "." ]
a643771b63953bd9948d783505ae3ca5ac6a7f36
https://github.com/gocardless/coach/blob/a643771b63953bd9948d783505ae3ca5ac6a7f36/lib/coach/middleware.rb#L63-L71
train
gocardless/coach
lib/coach/middleware.rb
Coach.Middleware.instrument
def instrument proc do publish_start if ActiveSupport::Notifications.notifier.listening?("coach.middleware.finish") instrument_deprecated { call } else ActiveSupport::Notifications. instrument("finish_middleware.coach", middleware_event) { call } end end end
ruby
def instrument proc do publish_start if ActiveSupport::Notifications.notifier.listening?("coach.middleware.finish") instrument_deprecated { call } else ActiveSupport::Notifications. instrument("finish_middleware.coach", middleware_event) { call } end end end
[ "def", "instrument", "proc", "do", "publish_start", "if", "ActiveSupport", "::", "Notifications", ".", "notifier", ".", "listening?", "(", "\"coach.middleware.finish\"", ")", "instrument_deprecated", "{", "call", "}", "else", "ActiveSupport", "::", "Notifications", ".", "instrument", "(", "\"finish_middleware.coach\"", ",", "middleware_event", ")", "{", "call", "}", "end", "end", "end" ]
Use ActiveSupport to instrument the execution of the subsequent chain.
[ "Use", "ActiveSupport", "to", "instrument", "the", "execution", "of", "the", "subsequent", "chain", "." ]
a643771b63953bd9948d783505ae3ca5ac6a7f36
https://github.com/gocardless/coach/blob/a643771b63953bd9948d783505ae3ca5ac6a7f36/lib/coach/middleware.rb#L74-L85
train
gocardless/coach
lib/coach/middleware_validator.rb
Coach.MiddlewareValidator.validated_provides!
def validated_provides! if missing_requirements.any? raise Coach::Errors::MiddlewareDependencyNotMet.new( @middleware, @previous_middlewares, missing_requirements ) end @middleware.provided + provided_by_chain end
ruby
def validated_provides! if missing_requirements.any? raise Coach::Errors::MiddlewareDependencyNotMet.new( @middleware, @previous_middlewares, missing_requirements ) end @middleware.provided + provided_by_chain end
[ "def", "validated_provides!", "if", "missing_requirements", ".", "any?", "raise", "Coach", "::", "Errors", "::", "MiddlewareDependencyNotMet", ".", "new", "(", "@middleware", ",", "@previous_middlewares", ",", "missing_requirements", ")", "end", "@middleware", ".", "provided", "+", "provided_by_chain", "end" ]
Aggregates provided keys from the given middleware, and all the middleware it uses. Can raise at any level assuming a used middleware is missing a required dependency.
[ "Aggregates", "provided", "keys", "from", "the", "given", "middleware", "and", "all", "the", "middleware", "it", "uses", ".", "Can", "raise", "at", "any", "level", "assuming", "a", "used", "middleware", "is", "missing", "a", "required", "dependency", "." ]
a643771b63953bd9948d783505ae3ca5ac6a7f36
https://github.com/gocardless/coach/blob/a643771b63953bd9948d783505ae3ca5ac6a7f36/lib/coach/middleware_validator.rb#L13-L21
train
gocardless/coach
lib/coach/request_benchmark.rb
Coach.RequestBenchmark.stats
def stats { endpoint_name: @endpoint_name, started_at: @start, duration: format_ms(@duration), chain: sorted_chain.map do |event| { name: event[:name], duration: format_ms(event[:duration]) } end, } end
ruby
def stats { endpoint_name: @endpoint_name, started_at: @start, duration: format_ms(@duration), chain: sorted_chain.map do |event| { name: event[:name], duration: format_ms(event[:duration]) } end, } end
[ "def", "stats", "{", "endpoint_name", ":", "@endpoint_name", ",", "started_at", ":", "@start", ",", "duration", ":", "format_ms", "(", "@duration", ")", ",", "chain", ":", "sorted_chain", ".", "map", "do", "|", "event", "|", "{", "name", ":", "event", "[", ":name", "]", ",", "duration", ":", "format_ms", "(", "event", "[", ":duration", "]", ")", "}", "end", ",", "}", "end" ]
Serialize the results of the benchmarking
[ "Serialize", "the", "results", "of", "the", "benchmarking" ]
a643771b63953bd9948d783505ae3ca5ac6a7f36
https://github.com/gocardless/coach/blob/a643771b63953bd9948d783505ae3ca5ac6a7f36/lib/coach/request_benchmark.rb#L30-L39
train
gocardless/coach
lib/coach/notifications.rb
Coach.Notifications.broadcast
def broadcast(event, benchmark) serialized = RequestSerializer.new(event[:request]).serialize. merge(benchmark.stats). merge(event.slice(:response, :metadata)) if ActiveSupport::Notifications.notifier.listening?("coach.request") ActiveSupport::Deprecation.warn("The 'coach.request' event has been renamed " \ "to 'request.coach' and the old name will be removed in a future version.") ActiveSupport::Notifications.publish("coach.request", serialized) end ActiveSupport::Notifications.publish("request.coach", serialized) end
ruby
def broadcast(event, benchmark) serialized = RequestSerializer.new(event[:request]).serialize. merge(benchmark.stats). merge(event.slice(:response, :metadata)) if ActiveSupport::Notifications.notifier.listening?("coach.request") ActiveSupport::Deprecation.warn("The 'coach.request' event has been renamed " \ "to 'request.coach' and the old name will be removed in a future version.") ActiveSupport::Notifications.publish("coach.request", serialized) end ActiveSupport::Notifications.publish("request.coach", serialized) end
[ "def", "broadcast", "(", "event", ",", "benchmark", ")", "serialized", "=", "RequestSerializer", ".", "new", "(", "event", "[", ":request", "]", ")", ".", "serialize", ".", "merge", "(", "benchmark", ".", "stats", ")", ".", "merge", "(", "event", ".", "slice", "(", ":response", ",", ":metadata", ")", ")", "if", "ActiveSupport", "::", "Notifications", ".", "notifier", ".", "listening?", "(", "\"coach.request\"", ")", "ActiveSupport", "::", "Deprecation", ".", "warn", "(", "\"The 'coach.request' event has been renamed \"", "\"to 'request.coach' and the old name will be removed in a future version.\"", ")", "ActiveSupport", "::", "Notifications", ".", "publish", "(", "\"coach.request\"", ",", "serialized", ")", "end", "ActiveSupport", "::", "Notifications", ".", "publish", "(", "\"request.coach\"", ",", "serialized", ")", "end" ]
Receives a handler.finish event, with processed benchmark. Publishes to request.coach notification.
[ "Receives", "a", "handler", ".", "finish", "event", "with", "processed", "benchmark", ".", "Publishes", "to", "request", ".", "coach", "notification", "." ]
a643771b63953bd9948d783505ae3ca5ac6a7f36
https://github.com/gocardless/coach/blob/a643771b63953bd9948d783505ae3ca5ac6a7f36/lib/coach/notifications.rb#L88-L98
train
twitterdev/twitter-ruby-ads-sdk
lib/twitter-ads/campaign/line_item.rb
TwitterAds.LineItem.targeting_criteria
def targeting_criteria(id = nil, opts = {}) id ? TargetingCriteria.load(account, id, opts) : TargetingCriteria.all(account, @id, opts) end
ruby
def targeting_criteria(id = nil, opts = {}) id ? TargetingCriteria.load(account, id, opts) : TargetingCriteria.all(account, @id, opts) end
[ "def", "targeting_criteria", "(", "id", "=", "nil", ",", "opts", "=", "{", "}", ")", "id", "?", "TargetingCriteria", ".", "load", "(", "account", ",", "id", ",", "opts", ")", ":", "TargetingCriteria", ".", "all", "(", "account", ",", "@id", ",", "opts", ")", "end" ]
Returns a collection of targeting criteria available to the current line item. @param id [String] The TargetingCriteria ID value. @param opts [Hash] A Hash of extended options. @option opts [Boolean] :with_deleted Indicates if deleted items should be included. @option opts [String] :sort_by The object param to sort the API response by. @since 0.3.1 @return A Cursor or object instance.
[ "Returns", "a", "collection", "of", "targeting", "criteria", "available", "to", "the", "current", "line", "item", "." ]
93f35714890a81d533f45281e792403bb3a07112
https://github.com/twitterdev/twitter-ruby-ads-sdk/blob/93f35714890a81d533f45281e792403bb3a07112/lib/twitter-ads/campaign/line_item.rb#L97-L99
train
twitterdev/twitter-ruby-ads-sdk
lib/twitter-ads/cursor.rb
TwitterAds.Cursor.each
def each(offset = 0) return to_enum(:each, offset) unless block_given? @collection[offset..-1].each { |element| yield(element) } unless exhausted? offset = [@collection.size, offset].max fetch_next each(offset, &Proc.new) end self end
ruby
def each(offset = 0) return to_enum(:each, offset) unless block_given? @collection[offset..-1].each { |element| yield(element) } unless exhausted? offset = [@collection.size, offset].max fetch_next each(offset, &Proc.new) end self end
[ "def", "each", "(", "offset", "=", "0", ")", "return", "to_enum", "(", ":each", ",", "offset", ")", "unless", "block_given?", "@collection", "[", "offset", "..", "-", "1", "]", ".", "each", "{", "|", "element", "|", "yield", "(", "element", ")", "}", "unless", "exhausted?", "offset", "=", "[", "@collection", ".", "size", ",", "offset", "]", ".", "max", "fetch_next", "each", "(", "offset", ",", "Proc", ".", "new", ")", "end", "self", "end" ]
Method to iterate through all items until the Cursor is exhausted. @return [Cursor] The current Cursor instance. @since 0.1.0
[ "Method", "to", "iterate", "through", "all", "items", "until", "the", "Cursor", "is", "exhausted", "." ]
93f35714890a81d533f45281e792403bb3a07112
https://github.com/twitterdev/twitter-ruby-ads-sdk/blob/93f35714890a81d533f45281e792403bb3a07112/lib/twitter-ads/cursor.rb#L59-L68
train
twitterdev/twitter-ruby-ads-sdk
examples/metric_filtering.rb
TwitterAds.Metrics.filter
def filter(*line_items) result = {} params = { line_item_ids: line_items.join(','), with_deleted: true } @account.line_items(nil, params).each do |line_item| # filter by objective objective = line_item.objective.downcase.to_sym metrics = OBJECTIVES[objective].map { |family| METRIC_FAMILIES[family] }.flatten # filter by placements placements = line_item.placements.map { |p| p.downcase.to_sym } filter_placements(metrics, placements) # filter by product product = line_item.product_type.downcase.to_sym filter_product(metrics, product) # filter LTV metrics unless account has a MACT partner setup metrics.reject! { |m| m.include?('mobile_lifetime_value_') } unless @mact_enabled result[line_item.id] = metrics end result end
ruby
def filter(*line_items) result = {} params = { line_item_ids: line_items.join(','), with_deleted: true } @account.line_items(nil, params).each do |line_item| # filter by objective objective = line_item.objective.downcase.to_sym metrics = OBJECTIVES[objective].map { |family| METRIC_FAMILIES[family] }.flatten # filter by placements placements = line_item.placements.map { |p| p.downcase.to_sym } filter_placements(metrics, placements) # filter by product product = line_item.product_type.downcase.to_sym filter_product(metrics, product) # filter LTV metrics unless account has a MACT partner setup metrics.reject! { |m| m.include?('mobile_lifetime_value_') } unless @mact_enabled result[line_item.id] = metrics end result end
[ "def", "filter", "(", "*", "line_items", ")", "result", "=", "{", "}", "params", "=", "{", "line_item_ids", ":", "line_items", ".", "join", "(", "','", ")", ",", "with_deleted", ":", "true", "}", "@account", ".", "line_items", "(", "nil", ",", "params", ")", ".", "each", "do", "|", "line_item", "|", "# filter by objective", "objective", "=", "line_item", ".", "objective", ".", "downcase", ".", "to_sym", "metrics", "=", "OBJECTIVES", "[", "objective", "]", ".", "map", "{", "|", "family", "|", "METRIC_FAMILIES", "[", "family", "]", "}", ".", "flatten", "# filter by placements", "placements", "=", "line_item", ".", "placements", ".", "map", "{", "|", "p", "|", "p", ".", "downcase", ".", "to_sym", "}", "filter_placements", "(", "metrics", ",", "placements", ")", "# filter by product", "product", "=", "line_item", ".", "product_type", ".", "downcase", ".", "to_sym", "filter_product", "(", "metrics", ",", "product", ")", "# filter LTV metrics unless account has a MACT partner setup", "metrics", ".", "reject!", "{", "|", "m", "|", "m", ".", "include?", "(", "'mobile_lifetime_value_'", ")", "}", "unless", "@mact_enabled", "result", "[", "line_item", ".", "id", "]", "=", "metrics", "end", "result", "end" ]
Sets up the object with the correct account and client information. @example metric_filter = TwitterAds::Metric.new('xyz1') @param account_id [String] The ID for the account to be used. @param client [Client] Optional client instance to be used. Will default to ~/.twurlrc info. @param mact_enabled [Boolean] Indicates the account has a MACT partner setup (default: false). @return [self] The configured object instance. Determines relevant metrics from a list of line item IDs. @example metric_filter.filter(line_item_ids) @param line_items [String/Array] A list of one or more line item IDs. @return [Hash] A hash with relevant metrics for each line item.
[ "Sets", "up", "the", "object", "with", "the", "correct", "account", "and", "client", "information", "." ]
93f35714890a81d533f45281e792403bb3a07112
https://github.com/twitterdev/twitter-ruby-ads-sdk/blob/93f35714890a81d533f45281e792403bb3a07112/examples/metric_filtering.rb#L264-L286
train
twitterdev/twitter-ruby-ads-sdk
lib/twitter-ads/account.rb
TwitterAds.Account.features
def features validate_loaded resource = FEATURES % { id: @id } response = Request.new(client, :get, resource).perform response.body[:data] end
ruby
def features validate_loaded resource = FEATURES % { id: @id } response = Request.new(client, :get, resource).perform response.body[:data] end
[ "def", "features", "validate_loaded", "resource", "=", "FEATURES", "%", "{", "id", ":", "@id", "}", "response", "=", "Request", ".", "new", "(", "client", ",", ":get", ",", "resource", ")", ".", "perform", "response", ".", "body", "[", ":data", "]", "end" ]
Returns a collection of features available to the current account. @return [Array] The list of features enabled for the account. @since 0.1.0
[ "Returns", "a", "collection", "of", "features", "available", "to", "the", "current", "account", "." ]
93f35714890a81d533f45281e792403bb3a07112
https://github.com/twitterdev/twitter-ruby-ads-sdk/blob/93f35714890a81d533f45281e792403bb3a07112/lib/twitter-ads/account.rb#L90-L95
train
twitterdev/twitter-ruby-ads-sdk
lib/twitter-ads/account.rb
TwitterAds.Account.scoped_timeline
def scoped_timeline(ids, opts = {}) ids = ids.join(',') if ids.is_a?(Array) params = { user_ids: ids }.merge!(opts) resource = SCOPED_TIMELINE % { id: @id } request = Request.new(client, :get, resource, params: params) response = request.perform response.body[:data] end
ruby
def scoped_timeline(ids, opts = {}) ids = ids.join(',') if ids.is_a?(Array) params = { user_ids: ids }.merge!(opts) resource = SCOPED_TIMELINE % { id: @id } request = Request.new(client, :get, resource, params: params) response = request.perform response.body[:data] end
[ "def", "scoped_timeline", "(", "ids", ",", "opts", "=", "{", "}", ")", "ids", "=", "ids", ".", "join", "(", "','", ")", "if", "ids", ".", "is_a?", "(", "Array", ")", "params", "=", "{", "user_ids", ":", "ids", "}", ".", "merge!", "(", "opts", ")", "resource", "=", "SCOPED_TIMELINE", "%", "{", "id", ":", "@id", "}", "request", "=", "Request", ".", "new", "(", "client", ",", ":get", ",", "resource", ",", "params", ":", "params", ")", "response", "=", "request", ".", "perform", "response", ".", "body", "[", ":data", "]", "end" ]
Returns the most recent promotable Tweets created by one or more specified Twitter users. @param ids [Array] An Array of Twitter user IDs. @param opts [Hash] A Hash of extended options. @return [Array] An Array of Tweet objects. @since 0.2.3
[ "Returns", "the", "most", "recent", "promotable", "Tweets", "created", "by", "one", "or", "more", "specified", "Twitter", "users", "." ]
93f35714890a81d533f45281e792403bb3a07112
https://github.com/twitterdev/twitter-ruby-ads-sdk/blob/93f35714890a81d533f45281e792403bb3a07112/lib/twitter-ads/account.rb#L259-L266
train
twitterdev/twitter-ruby-ads-sdk
lib/twitter-ads/resources/persistence.rb
TwitterAds.Persistence.save
def save if @id resource = self.class::RESOURCE % { account_id: account.id, id: id } response = Request.new(account.client, :put, resource, params: to_params).perform else resource = self.class::RESOURCE_COLLECTION % { account_id: account.id } response = Request.new(account.client, :post, resource, params: to_params).perform end from_response(response.body[:data]) end
ruby
def save if @id resource = self.class::RESOURCE % { account_id: account.id, id: id } response = Request.new(account.client, :put, resource, params: to_params).perform else resource = self.class::RESOURCE_COLLECTION % { account_id: account.id } response = Request.new(account.client, :post, resource, params: to_params).perform end from_response(response.body[:data]) end
[ "def", "save", "if", "@id", "resource", "=", "self", ".", "class", "::", "RESOURCE", "%", "{", "account_id", ":", "account", ".", "id", ",", "id", ":", "id", "}", "response", "=", "Request", ".", "new", "(", "account", ".", "client", ",", ":put", ",", "resource", ",", "params", ":", "to_params", ")", ".", "perform", "else", "resource", "=", "self", ".", "class", "::", "RESOURCE_COLLECTION", "%", "{", "account_id", ":", "account", ".", "id", "}", "response", "=", "Request", ".", "new", "(", "account", ".", "client", ",", ":post", ",", "resource", ",", "params", ":", "to_params", ")", ".", "perform", "end", "from_response", "(", "response", ".", "body", "[", ":data", "]", ")", "end" ]
Saves or updates the current object instance depending on the presence of `object.id`. @example object.save @return [self] Returns the instance refreshed from the API. @since 0.1.0
[ "Saves", "or", "updates", "the", "current", "object", "instance", "depending", "on", "the", "presence", "of", "object", ".", "id", "." ]
93f35714890a81d533f45281e792403bb3a07112
https://github.com/twitterdev/twitter-ruby-ads-sdk/blob/93f35714890a81d533f45281e792403bb3a07112/lib/twitter-ads/resources/persistence.rb#L15-L24
train
twitterdev/twitter-ruby-ads-sdk
lib/twitter-ads/resources/persistence.rb
TwitterAds.Persistence.delete!
def delete! resource = self.class::RESOURCE % { account_id: account.id, id: id } response = Request.new(account.client, :delete, resource).perform from_response(response.body[:data]) end
ruby
def delete! resource = self.class::RESOURCE % { account_id: account.id, id: id } response = Request.new(account.client, :delete, resource).perform from_response(response.body[:data]) end
[ "def", "delete!", "resource", "=", "self", ".", "class", "::", "RESOURCE", "%", "{", "account_id", ":", "account", ".", "id", ",", "id", ":", "id", "}", "response", "=", "Request", ".", "new", "(", "account", ".", "client", ",", ":delete", ",", "resource", ")", ".", "perform", "from_response", "(", "response", ".", "body", "[", ":data", "]", ")", "end" ]
Deletes the current object instance depending on the presence of `object.id`. @example object.delete! Note: calls to this method are destructive and irreverisble for most API objects. @return [self] Returns the instance refreshed from the API. @since 0.1.0
[ "Deletes", "the", "current", "object", "instance", "depending", "on", "the", "presence", "of", "object", ".", "id", "." ]
93f35714890a81d533f45281e792403bb3a07112
https://github.com/twitterdev/twitter-ruby-ads-sdk/blob/93f35714890a81d533f45281e792403bb3a07112/lib/twitter-ads/resources/persistence.rb#L36-L40
train
twitterdev/twitter-ruby-ads-sdk
lib/twitter-ads/http/ton_upload.rb
TwitterAds.TONUpload.perform
def perform if @file_size < SINGLE_UPLOAD_MAX resource = "#{DEFAULT_RESOURCE}#{@bucket}" response = upload(resource, File.read(@file_path)) response.headers['location'][0] else response = init_chunked_upload bytes_per_chunk_size = response.headers['x-ton-min-chunk-size'][0].to_i location = response.headers['location'][0] bytes_read = 0 chunk_bytes = bytes_per_chunk_size * DEFAULT_CHUNK_SIZE File.open(@file_path) do |file| while bytes = file.read(chunk_bytes) bytes_start = bytes_read bytes_read += bytes.size upload_chunk(location, bytes, bytes_start, bytes_read) do |res| # Determines the chunk bytes based on response times response_time = res.headers['x-response-time'][0].to_f response_based_chunk_size = (DEFAULT_CHUNK_SIZE * (RESPONSE_TIME_MAX / response_time)).to_i next_chunk_size = [DEFAULT_CHUNK_SIZE, [1, response_based_chunk_size].max].min chunk_bytes = bytes_per_chunk_size * next_chunk_size end end end location.split('?')[0] end end
ruby
def perform if @file_size < SINGLE_UPLOAD_MAX resource = "#{DEFAULT_RESOURCE}#{@bucket}" response = upload(resource, File.read(@file_path)) response.headers['location'][0] else response = init_chunked_upload bytes_per_chunk_size = response.headers['x-ton-min-chunk-size'][0].to_i location = response.headers['location'][0] bytes_read = 0 chunk_bytes = bytes_per_chunk_size * DEFAULT_CHUNK_SIZE File.open(@file_path) do |file| while bytes = file.read(chunk_bytes) bytes_start = bytes_read bytes_read += bytes.size upload_chunk(location, bytes, bytes_start, bytes_read) do |res| # Determines the chunk bytes based on response times response_time = res.headers['x-response-time'][0].to_f response_based_chunk_size = (DEFAULT_CHUNK_SIZE * (RESPONSE_TIME_MAX / response_time)).to_i next_chunk_size = [DEFAULT_CHUNK_SIZE, [1, response_based_chunk_size].max].min chunk_bytes = bytes_per_chunk_size * next_chunk_size end end end location.split('?')[0] end end
[ "def", "perform", "if", "@file_size", "<", "SINGLE_UPLOAD_MAX", "resource", "=", "\"#{DEFAULT_RESOURCE}#{@bucket}\"", "response", "=", "upload", "(", "resource", ",", "File", ".", "read", "(", "@file_path", ")", ")", "response", ".", "headers", "[", "'location'", "]", "[", "0", "]", "else", "response", "=", "init_chunked_upload", "bytes_per_chunk_size", "=", "response", ".", "headers", "[", "'x-ton-min-chunk-size'", "]", "[", "0", "]", ".", "to_i", "location", "=", "response", ".", "headers", "[", "'location'", "]", "[", "0", "]", "bytes_read", "=", "0", "chunk_bytes", "=", "bytes_per_chunk_size", "*", "DEFAULT_CHUNK_SIZE", "File", ".", "open", "(", "@file_path", ")", "do", "|", "file", "|", "while", "bytes", "=", "file", ".", "read", "(", "chunk_bytes", ")", "bytes_start", "=", "bytes_read", "bytes_read", "+=", "bytes", ".", "size", "upload_chunk", "(", "location", ",", "bytes", ",", "bytes_start", ",", "bytes_read", ")", "do", "|", "res", "|", "# Determines the chunk bytes based on response times", "response_time", "=", "res", ".", "headers", "[", "'x-response-time'", "]", "[", "0", "]", ".", "to_f", "response_based_chunk_size", "=", "(", "DEFAULT_CHUNK_SIZE", "*", "(", "RESPONSE_TIME_MAX", "/", "response_time", ")", ")", ".", "to_i", "next_chunk_size", "=", "[", "DEFAULT_CHUNK_SIZE", ",", "[", "1", ",", "response_based_chunk_size", "]", ".", "max", "]", ".", "min", "chunk_bytes", "=", "bytes_per_chunk_size", "*", "next_chunk_size", "end", "end", "end", "location", ".", "split", "(", "'?'", ")", "[", "0", "]", "end", "end" ]
Creates a new TONUpload object instance. @example request = TONUpload.new(client, '/path/to/file') @param client [Client] The Client object instance. @param file_path [String] The path to the file to be uploaded. @since 0.3.0 @return [TONUpload] The TONUpload request instance. Executes the current TONUpload object. @example request = TONUpload.new(client, '/path/to/file') request.perform @since 0.3.0 @return [String] The upload location provided by the TON API.
[ "Creates", "a", "new", "TONUpload", "object", "instance", "." ]
93f35714890a81d533f45281e792403bb3a07112
https://github.com/twitterdev/twitter-ruby-ads-sdk/blob/93f35714890a81d533f45281e792403bb3a07112/lib/twitter-ads/http/ton_upload.rb#L60-L89
train
twitterdev/twitter-ruby-ads-sdk
lib/twitter-ads/http/ton_upload.rb
TwitterAds.TONUpload.upload
def upload(resource, bytes) headers = { 'x-ton-expires' => DEFAULT_EXPIRE, 'content-length' => @file_size, 'content-type' => content_type } TwitterAds::Request.new( @client, :post, resource, domain: DEFAULT_DOMAIN, headers: headers, body: bytes).perform end
ruby
def upload(resource, bytes) headers = { 'x-ton-expires' => DEFAULT_EXPIRE, 'content-length' => @file_size, 'content-type' => content_type } TwitterAds::Request.new( @client, :post, resource, domain: DEFAULT_DOMAIN, headers: headers, body: bytes).perform end
[ "def", "upload", "(", "resource", ",", "bytes", ")", "headers", "=", "{", "'x-ton-expires'", "=>", "DEFAULT_EXPIRE", ",", "'content-length'", "=>", "@file_size", ",", "'content-type'", "=>", "content_type", "}", "TwitterAds", "::", "Request", ".", "new", "(", "@client", ",", ":post", ",", "resource", ",", "domain", ":", "DEFAULT_DOMAIN", ",", "headers", ":", "headers", ",", "body", ":", "bytes", ")", ".", "perform", "end" ]
performs a single chunk upload
[ "performs", "a", "single", "chunk", "upload" ]
93f35714890a81d533f45281e792403bb3a07112
https://github.com/twitterdev/twitter-ruby-ads-sdk/blob/93f35714890a81d533f45281e792403bb3a07112/lib/twitter-ads/http/ton_upload.rb#L103-L111
train
twitterdev/twitter-ruby-ads-sdk
lib/twitter-ads/http/ton_upload.rb
TwitterAds.TONUpload.init_chunked_upload
def init_chunked_upload headers = { 'x-ton-content-type' => content_type, 'x-ton-content-length' => @file_size, 'x-ton-expires' => DEFAULT_EXPIRE, 'content-length' => 0, 'content-type' => content_type } resource = "#{DEFAULT_RESOURCE}#{@bucket}?resumable=true" TwitterAds::Request.new( @client, :post, resource, domain: DEFAULT_DOMAIN, headers: headers).perform end
ruby
def init_chunked_upload headers = { 'x-ton-content-type' => content_type, 'x-ton-content-length' => @file_size, 'x-ton-expires' => DEFAULT_EXPIRE, 'content-length' => 0, 'content-type' => content_type } resource = "#{DEFAULT_RESOURCE}#{@bucket}?resumable=true" TwitterAds::Request.new( @client, :post, resource, domain: DEFAULT_DOMAIN, headers: headers).perform end
[ "def", "init_chunked_upload", "headers", "=", "{", "'x-ton-content-type'", "=>", "content_type", ",", "'x-ton-content-length'", "=>", "@file_size", ",", "'x-ton-expires'", "=>", "DEFAULT_EXPIRE", ",", "'content-length'", "=>", "0", ",", "'content-type'", "=>", "content_type", "}", "resource", "=", "\"#{DEFAULT_RESOURCE}#{@bucket}?resumable=true\"", "TwitterAds", "::", "Request", ".", "new", "(", "@client", ",", ":post", ",", "resource", ",", "domain", ":", "DEFAULT_DOMAIN", ",", "headers", ":", "headers", ")", ".", "perform", "end" ]
initialization for a multi-chunk upload
[ "initialization", "for", "a", "multi", "-", "chunk", "upload" ]
93f35714890a81d533f45281e792403bb3a07112
https://github.com/twitterdev/twitter-ruby-ads-sdk/blob/93f35714890a81d533f45281e792403bb3a07112/lib/twitter-ads/http/ton_upload.rb#L114-L125
train
twitterdev/twitter-ruby-ads-sdk
lib/twitter-ads/http/ton_upload.rb
TwitterAds.TONUpload.upload_chunk
def upload_chunk(resource, bytes, bytes_start, bytes_read) headers = { 'content-type' => content_type, 'content-length' => bytes.size, 'content-range' => "bytes #{bytes_start}-#{bytes_read - 1}/#{@file_size}" } response = TwitterAds::Request.new( @client, :put, resource, domain: DEFAULT_DOMAIN, headers: headers, body: bytes).perform yield(response) response end
ruby
def upload_chunk(resource, bytes, bytes_start, bytes_read) headers = { 'content-type' => content_type, 'content-length' => bytes.size, 'content-range' => "bytes #{bytes_start}-#{bytes_read - 1}/#{@file_size}" } response = TwitterAds::Request.new( @client, :put, resource, domain: DEFAULT_DOMAIN, headers: headers, body: bytes).perform yield(response) response end
[ "def", "upload_chunk", "(", "resource", ",", "bytes", ",", "bytes_start", ",", "bytes_read", ")", "headers", "=", "{", "'content-type'", "=>", "content_type", ",", "'content-length'", "=>", "bytes", ".", "size", ",", "'content-range'", "=>", "\"bytes #{bytes_start}-#{bytes_read - 1}/#{@file_size}\"", "}", "response", "=", "TwitterAds", "::", "Request", ".", "new", "(", "@client", ",", ":put", ",", "resource", ",", "domain", ":", "DEFAULT_DOMAIN", ",", "headers", ":", "headers", ",", "body", ":", "bytes", ")", ".", "perform", "yield", "(", "response", ")", "response", "end" ]
uploads a single chunk of a multi-chunk upload
[ "uploads", "a", "single", "chunk", "of", "a", "multi", "-", "chunk", "upload" ]
93f35714890a81d533f45281e792403bb3a07112
https://github.com/twitterdev/twitter-ruby-ads-sdk/blob/93f35714890a81d533f45281e792403bb3a07112/lib/twitter-ads/http/ton_upload.rb#L128-L139
train
twitterdev/twitter-ruby-ads-sdk
lib/twitter-ads/audiences/tailored_audience.rb
TwitterAds.TailoredAudience.update
def update(file_path, list_type, operation = 'ADD') upload = TwitterAds::TONUpload.new(account.client, file_path) update_audience(self, upload.perform, list_type, operation) reload! end
ruby
def update(file_path, list_type, operation = 'ADD') upload = TwitterAds::TONUpload.new(account.client, file_path) update_audience(self, upload.perform, list_type, operation) reload! end
[ "def", "update", "(", "file_path", ",", "list_type", ",", "operation", "=", "'ADD'", ")", "upload", "=", "TwitterAds", "::", "TONUpload", ".", "new", "(", "account", ".", "client", ",", "file_path", ")", "update_audience", "(", "self", ",", "upload", ".", "perform", ",", "list_type", ",", "operation", ")", "reload!", "end" ]
Updates the current tailored audience instance. @example audience = account.tailored_audiences('xyz') audience.update('/path/to/file', 'EMAIL', 'REPLACE') @param file_path [String] The path to the file to be uploaded. @param list_type [String] The tailored audience list type. @param operation [String] The update operation type (Default: 'ADD'). @since 0.3.0 @return [TailoredAudience] [description]
[ "Updates", "the", "current", "tailored", "audience", "instance", "." ]
93f35714890a81d533f45281e792403bb3a07112
https://github.com/twitterdev/twitter-ruby-ads-sdk/blob/93f35714890a81d533f45281e792403bb3a07112/lib/twitter-ads/audiences/tailored_audience.rb#L146-L150
train
twitterdev/twitter-ruby-ads-sdk
lib/twitter-ads/audiences/tailored_audience.rb
TwitterAds.TailoredAudience.status
def status return nil unless id resource = RESOURCE_UPDATE % { account_id: account.id } request = Request.new(account.client, :get, resource, params: to_params) Cursor.new(nil, request).to_a.select { |change| change[:tailored_audience_id] == id } end
ruby
def status return nil unless id resource = RESOURCE_UPDATE % { account_id: account.id } request = Request.new(account.client, :get, resource, params: to_params) Cursor.new(nil, request).to_a.select { |change| change[:tailored_audience_id] == id } end
[ "def", "status", "return", "nil", "unless", "id", "resource", "=", "RESOURCE_UPDATE", "%", "{", "account_id", ":", "account", ".", "id", "}", "request", "=", "Request", ".", "new", "(", "account", ".", "client", ",", ":get", ",", "resource", ",", "params", ":", "to_params", ")", "Cursor", ".", "new", "(", "nil", ",", "request", ")", ".", "to_a", ".", "select", "{", "|", "change", "|", "change", "[", ":tailored_audience_id", "]", "==", "id", "}", "end" ]
Returns the status of all changes for the current tailored audience instance. @example audience.status @since 0.3.0 @return [Hash] Returns a hash object representing the tailored audience status.
[ "Returns", "the", "status", "of", "all", "changes", "for", "the", "current", "tailored", "audience", "instance", "." ]
93f35714890a81d533f45281e792403bb3a07112
https://github.com/twitterdev/twitter-ruby-ads-sdk/blob/93f35714890a81d533f45281e792403bb3a07112/lib/twitter-ads/audiences/tailored_audience.rb#L176-L181
train
twitterdev/twitter-ruby-ads-sdk
lib/twitter-ads/audiences/tailored_audience.rb
TwitterAds.TailoredAudience.users
def users(params) resource = RESOURCE_USERS % { account_id: account.id, id: id } headers = { 'Content-Type' => 'application/json' } response = TwitterAds::Request.new(account.client, :post, resource, headers: headers, body: params.to_json).perform success_count = response.body[:data][:success_count] total_count = response.body[:data][:total_count] [success_count, total_count] end
ruby
def users(params) resource = RESOURCE_USERS % { account_id: account.id, id: id } headers = { 'Content-Type' => 'application/json' } response = TwitterAds::Request.new(account.client, :post, resource, headers: headers, body: params.to_json).perform success_count = response.body[:data][:success_count] total_count = response.body[:data][:total_count] [success_count, total_count] end
[ "def", "users", "(", "params", ")", "resource", "=", "RESOURCE_USERS", "%", "{", "account_id", ":", "account", ".", "id", ",", "id", ":", "id", "}", "headers", "=", "{", "'Content-Type'", "=>", "'application/json'", "}", "response", "=", "TwitterAds", "::", "Request", ".", "new", "(", "account", ".", "client", ",", ":post", ",", "resource", ",", "headers", ":", "headers", ",", "body", ":", "params", ".", "to_json", ")", ".", "perform", "success_count", "=", "response", ".", "body", "[", ":data", "]", "[", ":success_count", "]", "total_count", "=", "response", ".", "body", "[", ":data", "]", "[", ":total_count", "]", "[", "success_count", ",", "total_count", "]", "end" ]
This is a private API and requires whitelisting from Twitter. This endpoint will allow partners to add, update and remove users from a given tailored_audience_id. The endpoint will also accept multiple user identifier types per user as well. @example tailored_audience.users( account, [ { "operation_type": "Update", "params": { "effective_at": "2018-05-15T00:00:00Z", "expires_at": "2019-01-01T07:00:00Z", "users": [ { "twitter_id": [ "4798b8bbdcf6f2a52e527f46a3d7a7c9aefb541afda03af79c74809ecc6376f3" ] } ] } } ] ) @since 4.0 @return success_count, total_count
[ "This", "is", "a", "private", "API", "and", "requires", "whitelisting", "from", "Twitter", "." ]
93f35714890a81d533f45281e792403bb3a07112
https://github.com/twitterdev/twitter-ruby-ads-sdk/blob/93f35714890a81d533f45281e792403bb3a07112/lib/twitter-ads/audiences/tailored_audience.rb#L249-L261
train
twitterdev/twitter-ruby-ads-sdk
lib/twitter-ads/client.rb
TwitterAds.Client.accounts
def accounts(id = nil, opts = {}) id ? Account.load(self, id) : Account.all(self, opts) end
ruby
def accounts(id = nil, opts = {}) id ? Account.load(self, id) : Account.all(self, opts) end
[ "def", "accounts", "(", "id", "=", "nil", ",", "opts", "=", "{", "}", ")", "id", "?", "Account", ".", "load", "(", "self", ",", "id", ")", ":", "Account", ".", "all", "(", "self", ",", "opts", ")", "end" ]
Returns a collection of advertiser Accounts available to the current access token. @example client.accounts client.accounts('3ofs6l') client.accounts('3ofs6l', with_deleted: true) @param id=nil [String] The account ID string. @param opts={} [Hash] Hash of optional values. @option opts [String] :with_deleted Indicates whether or not to included deleted objects. @since 0.1.0 @return [Account] The instance of the Account object.
[ "Returns", "a", "collection", "of", "advertiser", "Accounts", "available", "to", "the", "current", "access", "token", "." ]
93f35714890a81d533f45281e792403bb3a07112
https://github.com/twitterdev/twitter-ruby-ads-sdk/blob/93f35714890a81d533f45281e792403bb3a07112/lib/twitter-ads/client.rb#L81-L83
train
activerecord-hackery/meta_search
lib/meta_search/method.rb
MetaSearch.Method.evaluate
def evaluate(relation, param) if splat_param? relation.send(name, *format_param(param)) else relation.send(name, format_param(param)) end end
ruby
def evaluate(relation, param) if splat_param? relation.send(name, *format_param(param)) else relation.send(name, format_param(param)) end end
[ "def", "evaluate", "(", "relation", ",", "param", ")", "if", "splat_param?", "relation", ".", "send", "(", "name", ",", "format_param", "(", "param", ")", ")", "else", "relation", ".", "send", "(", "name", ",", "format_param", "(", "param", ")", ")", "end", "end" ]
Evaluate the method in the context of the supplied relation and parameter
[ "Evaluate", "the", "method", "in", "the", "context", "of", "the", "supplied", "relation", "and", "parameter" ]
c7f084412c483456830b8ec26514991e17da94c7
https://github.com/activerecord-hackery/meta_search/blob/c7f084412c483456830b8ec26514991e17da94c7/lib/meta_search/method.rb#L107-L113
train
brynary/webrat
lib/webrat/core/scope.rb
Webrat.Scope.fill_in
def fill_in(field_locator, options = {}) field = locate_field(field_locator, TextField, TextareaField, PasswordField) field.raise_error_if_disabled field.set(options[:with]) end
ruby
def fill_in(field_locator, options = {}) field = locate_field(field_locator, TextField, TextareaField, PasswordField) field.raise_error_if_disabled field.set(options[:with]) end
[ "def", "fill_in", "(", "field_locator", ",", "options", "=", "{", "}", ")", "field", "=", "locate_field", "(", "field_locator", ",", "TextField", ",", "TextareaField", ",", "PasswordField", ")", "field", ".", "raise_error_if_disabled", "field", ".", "set", "(", "options", "[", ":with", "]", ")", "end" ]
Verifies an input field or textarea exists on the current page, and stores a value for it which will be sent when the form is submitted. Examples: fill_in "Email", :with => "[email protected]" fill_in "user[email]", :with => "[email protected]" The field value is required, and must be specified in <tt>options[:with]</tt>. <tt>field</tt> can be either the value of a name attribute (i.e. <tt>user[email]</tt>) or the text inside a <tt><label></tt> element that points at the <tt><input></tt> field.
[ "Verifies", "an", "input", "field", "or", "textarea", "exists", "on", "the", "current", "page", "and", "stores", "a", "value", "for", "it", "which", "will", "be", "sent", "when", "the", "form", "is", "submitted", "." ]
1263639e24ce0f5e2eeeae614f10f900f498d92a
https://github.com/brynary/webrat/blob/1263639e24ce0f5e2eeeae614f10f900f498d92a/lib/webrat/core/scope.rb#L50-L54
train
brynary/webrat
lib/webrat/core/matchers/have_content.rb
Webrat.Matchers.assert_contain
def assert_contain(content) hc = HasContent.new(content) assert hc.matches?(current_dom), hc.failure_message end
ruby
def assert_contain(content) hc = HasContent.new(content) assert hc.matches?(current_dom), hc.failure_message end
[ "def", "assert_contain", "(", "content", ")", "hc", "=", "HasContent", ".", "new", "(", "content", ")", "assert", "hc", ".", "matches?", "(", "current_dom", ")", ",", "hc", ".", "failure_message", "end" ]
Asserts that the body of the response contain the supplied string or regexp
[ "Asserts", "that", "the", "body", "of", "the", "response", "contain", "the", "supplied", "string", "or", "regexp" ]
1263639e24ce0f5e2eeeae614f10f900f498d92a
https://github.com/brynary/webrat/blob/1263639e24ce0f5e2eeeae614f10f900f498d92a/lib/webrat/core/matchers/have_content.rb#L55-L58
train
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
train
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
train
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
train
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
train
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
train
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
train
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
train
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
train
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
train
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
train
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
train
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
train
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
train
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
train
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
train
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
train
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
train
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
train
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
train
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
train
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
train
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
train
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
train
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
train
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
train
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
train
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
train
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
train
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
train
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
train
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
train
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
train
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
train
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
train
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
train
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
train
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
train
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
train
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
train
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
train
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
train
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
train
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
train
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
train
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
train
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
train
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
train
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
train
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
train
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
train
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
train
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
train
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
train
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
train
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
train
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
train
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
train
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
train
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
train
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
train
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
train
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
train
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
train
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
train
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
train
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
train
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
train
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
train
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
train
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
train
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
train
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
train
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
train
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
train