repo
stringlengths
5
58
path
stringlengths
9
168
func_name
stringlengths
9
130
original_string
stringlengths
66
10.5k
language
stringclasses
1 value
code
stringlengths
66
10.5k
code_tokens
list
docstring
stringlengths
8
16k
docstring_tokens
list
sha
stringlengths
40
40
url
stringlengths
94
266
partition
stringclasses
1 value
couchrest/couchrest
lib/couchrest/attributes.rb
CouchRest.Attributes.as_couch_json
def as_couch_json _attributes.inject({}) {|h, (k,v)| h[k] = v.respond_to?(:as_couch_json) ? v.as_couch_json : v; h} end
ruby
def as_couch_json _attributes.inject({}) {|h, (k,v)| h[k] = v.respond_to?(:as_couch_json) ? v.as_couch_json : v; h} end
[ "def", "as_couch_json", "_attributes", ".", "inject", "(", "{", "}", ")", "{", "|", "h", ",", "(", "k", ",", "v", ")", "|", "h", "[", "k", "]", "=", "v", ".", "respond_to?", "(", ":as_couch_json", ")", "?", "v", ".", "as_couch_json", ":", "v", ";", "h", "}", "end" ]
Provide JSON data hash that can be stored in the database. Will go through each attribute value and request the `as_couch_json` method on each if available, or return the value as-is.
[ "Provide", "JSON", "data", "hash", "that", "can", "be", "stored", "in", "the", "database", ".", "Will", "go", "through", "each", "attribute", "value", "and", "request", "the", "as_couch_json", "method", "on", "each", "if", "available", "or", "return", "the", "value", "as", "-", "is", "." ]
cdd3ad30b9fa9aad5464cb4647c18c198b2c48d9
https://github.com/couchrest/couchrest/blob/cdd3ad30b9fa9aad5464cb4647c18c198b2c48d9/lib/couchrest/attributes.rb#L66-L68
train
couchrest/couchrest
lib/couchrest/server.rb
CouchRest.Server.database!
def database!(name) connection.head name # Check if the URL is valid database(name) rescue CouchRest::NotFound # Thrown if the HTTP HEAD fails create_db(name) end
ruby
def database!(name) connection.head name # Check if the URL is valid database(name) rescue CouchRest::NotFound # Thrown if the HTTP HEAD fails create_db(name) end
[ "def", "database!", "(", "name", ")", "connection", ".", "head", "name", "database", "(", "name", ")", "rescue", "CouchRest", "::", "NotFound", "create_db", "(", "name", ")", "end" ]
Creates the database if it doesn't exist
[ "Creates", "the", "database", "if", "it", "doesn", "t", "exist" ]
cdd3ad30b9fa9aad5464cb4647c18c198b2c48d9
https://github.com/couchrest/couchrest/blob/cdd3ad30b9fa9aad5464cb4647c18c198b2c48d9/lib/couchrest/server.rb#L46-L51
train
couchrest/couchrest
lib/couchrest/server.rb
CouchRest.Server.next_uuid
def next_uuid(count = @uuid_batch_count) if uuids.nil? || uuids.empty? @uuids = connection.get("_uuids?count=#{count}")["uuids"] end uuids.pop end
ruby
def next_uuid(count = @uuid_batch_count) if uuids.nil? || uuids.empty? @uuids = connection.get("_uuids?count=#{count}")["uuids"] end uuids.pop end
[ "def", "next_uuid", "(", "count", "=", "@uuid_batch_count", ")", "if", "uuids", ".", "nil?", "||", "uuids", ".", "empty?", "@uuids", "=", "connection", ".", "get", "(", "\"_uuids?count=#{count}\"", ")", "[", "\"uuids\"", "]", "end", "uuids", ".", "pop", "end" ]
Retrive an unused UUID from CouchDB. Server instances manage caching a list of unused UUIDs.
[ "Retrive", "an", "unused", "UUID", "from", "CouchDB", ".", "Server", "instances", "manage", "caching", "a", "list", "of", "unused", "UUIDs", "." ]
cdd3ad30b9fa9aad5464cb4647c18c198b2c48d9
https://github.com/couchrest/couchrest/blob/cdd3ad30b9fa9aad5464cb4647c18c198b2c48d9/lib/couchrest/server.rb#L70-L75
train
couchrest/couchrest
lib/couchrest/rest_api.rb
CouchRest.RestAPI.get
def get(url, options = {}) connection(url, options) do |uri, conn| conn.get(uri.request_uri, options) end end
ruby
def get(url, options = {}) connection(url, options) do |uri, conn| conn.get(uri.request_uri, options) end end
[ "def", "get", "(", "url", ",", "options", "=", "{", "}", ")", "connection", "(", "url", ",", "options", ")", "do", "|", "uri", ",", "conn", "|", "conn", ".", "get", "(", "uri", ".", "request_uri", ",", "options", ")", "end", "end" ]
Send a GET request.
[ "Send", "a", "GET", "request", "." ]
cdd3ad30b9fa9aad5464cb4647c18c198b2c48d9
https://github.com/couchrest/couchrest/blob/cdd3ad30b9fa9aad5464cb4647c18c198b2c48d9/lib/couchrest/rest_api.rb#L14-L18
train
couchrest/couchrest
lib/couchrest/rest_api.rb
CouchRest.RestAPI.put
def put(url, doc = nil, options = {}) connection(url, options) do |uri, conn| conn.put(uri.request_uri, doc, options) end end
ruby
def put(url, doc = nil, options = {}) connection(url, options) do |uri, conn| conn.put(uri.request_uri, doc, options) end end
[ "def", "put", "(", "url", ",", "doc", "=", "nil", ",", "options", "=", "{", "}", ")", "connection", "(", "url", ",", "options", ")", "do", "|", "uri", ",", "conn", "|", "conn", ".", "put", "(", "uri", ".", "request_uri", ",", "doc", ",", "options", ")", "end", "end" ]
Send a PUT request.
[ "Send", "a", "PUT", "request", "." ]
cdd3ad30b9fa9aad5464cb4647c18c198b2c48d9
https://github.com/couchrest/couchrest/blob/cdd3ad30b9fa9aad5464cb4647c18c198b2c48d9/lib/couchrest/rest_api.rb#L21-L25
train
couchrest/couchrest
lib/couchrest/rest_api.rb
CouchRest.RestAPI.delete
def delete(url, options = {}) connection(url, options) do |uri, conn| conn.delete(uri.request_uri, options) end end
ruby
def delete(url, options = {}) connection(url, options) do |uri, conn| conn.delete(uri.request_uri, options) end end
[ "def", "delete", "(", "url", ",", "options", "=", "{", "}", ")", "connection", "(", "url", ",", "options", ")", "do", "|", "uri", ",", "conn", "|", "conn", ".", "delete", "(", "uri", ".", "request_uri", ",", "options", ")", "end", "end" ]
Send a DELETE request.
[ "Send", "a", "DELETE", "request", "." ]
cdd3ad30b9fa9aad5464cb4647c18c198b2c48d9
https://github.com/couchrest/couchrest/blob/cdd3ad30b9fa9aad5464cb4647c18c198b2c48d9/lib/couchrest/rest_api.rb#L35-L39
train
couchrest/couchrest
lib/couchrest/database.rb
CouchRest.Database.replicate_from
def replicate_from(other_db, continuous = false, create_target = false, doc_ids = nil) replicate(other_db, continuous, :target => name, :create_target => create_target, :doc_ids => doc_ids) end
ruby
def replicate_from(other_db, continuous = false, create_target = false, doc_ids = nil) replicate(other_db, continuous, :target => name, :create_target => create_target, :doc_ids => doc_ids) end
[ "def", "replicate_from", "(", "other_db", ",", "continuous", "=", "false", ",", "create_target", "=", "false", ",", "doc_ids", "=", "nil", ")", "replicate", "(", "other_db", ",", "continuous", ",", ":target", "=>", "name", ",", ":create_target", "=>", "create_target", ",", ":doc_ids", "=>", "doc_ids", ")", "end" ]
Replicates via "pulling" from another database to this database. Makes no attempt to deal with conflicts.
[ "Replicates", "via", "pulling", "from", "another", "database", "to", "this", "database", ".", "Makes", "no", "attempt", "to", "deal", "with", "conflicts", "." ]
cdd3ad30b9fa9aad5464cb4647c18c198b2c48d9
https://github.com/couchrest/couchrest/blob/cdd3ad30b9fa9aad5464cb4647c18c198b2c48d9/lib/couchrest/database.rb#L75-L77
train
couchrest/couchrest
lib/couchrest/database.rb
CouchRest.Database.replicate_to
def replicate_to(other_db, continuous = false, create_target = false, doc_ids = nil) replicate(other_db, continuous, :source => name, :create_target => create_target, :doc_ids => doc_ids) end
ruby
def replicate_to(other_db, continuous = false, create_target = false, doc_ids = nil) replicate(other_db, continuous, :source => name, :create_target => create_target, :doc_ids => doc_ids) end
[ "def", "replicate_to", "(", "other_db", ",", "continuous", "=", "false", ",", "create_target", "=", "false", ",", "doc_ids", "=", "nil", ")", "replicate", "(", "other_db", ",", "continuous", ",", ":source", "=>", "name", ",", ":create_target", "=>", "create_target", ",", ":doc_ids", "=>", "doc_ids", ")", "end" ]
Replicates via "pushing" to another database. Makes no attempt to deal with conflicts.
[ "Replicates", "via", "pushing", "to", "another", "database", ".", "Makes", "no", "attempt", "to", "deal", "with", "conflicts", "." ]
cdd3ad30b9fa9aad5464cb4647c18c198b2c48d9
https://github.com/couchrest/couchrest/blob/cdd3ad30b9fa9aad5464cb4647c18c198b2c48d9/lib/couchrest/database.rb#L80-L82
train
couchrest/couchrest
lib/couchrest/database.rb
CouchRest.Database.get!
def get!(id, params = {}) slug = escape_docid(id) url = CouchRest.paramify_url("#{path}/#{slug}", params) result = connection.get(url) return result unless result.is_a?(Hash) doc = if /^_design/ =~ result["_id"] Design.new(result) else Document.new(result) end doc.database = self doc end
ruby
def get!(id, params = {}) slug = escape_docid(id) url = CouchRest.paramify_url("#{path}/#{slug}", params) result = connection.get(url) return result unless result.is_a?(Hash) doc = if /^_design/ =~ result["_id"] Design.new(result) else Document.new(result) end doc.database = self doc end
[ "def", "get!", "(", "id", ",", "params", "=", "{", "}", ")", "slug", "=", "escape_docid", "(", "id", ")", "url", "=", "CouchRest", ".", "paramify_url", "(", "\"#{path}/#{slug}\"", ",", "params", ")", "result", "=", "connection", ".", "get", "(", "url", ")", "return", "result", "unless", "result", ".", "is_a?", "(", "Hash", ")", "doc", "=", "if", "/", "/", "=~", "result", "[", "\"_id\"", "]", "Design", ".", "new", "(", "result", ")", "else", "Document", ".", "new", "(", "result", ")", "end", "doc", ".", "database", "=", "self", "doc", "end" ]
== Retrieving and saving single documents GET a document from CouchDB, by id. Returns a Document, Design, or raises an exception if the document does not exist.
[ "==", "Retrieving", "and", "saving", "single", "documents", "GET", "a", "document", "from", "CouchDB", "by", "id", ".", "Returns", "a", "Document", "Design", "or", "raises", "an", "exception", "if", "the", "document", "does", "not", "exist", "." ]
cdd3ad30b9fa9aad5464cb4647c18c198b2c48d9
https://github.com/couchrest/couchrest/blob/cdd3ad30b9fa9aad5464cb4647c18c198b2c48d9/lib/couchrest/database.rb#L95-L107
train
couchrest/couchrest
lib/couchrest/database.rb
CouchRest.Database.bulk_save
def bulk_save(docs = nil, opts = {}) opts = { :use_uuids => true, :all_or_nothing => false }.update(opts) if docs.nil? docs = @bulk_save_cache @bulk_save_cache = [] end if opts[:use_uuids] ids, noids = docs.partition{|d|d['_id']} uuid_count = [noids.length, @server.uuid_batch_count].max noids.each do |doc| nextid = server.next_uuid(uuid_count) rescue nil doc['_id'] = nextid if nextid end end request_body = {:docs => docs} if opts[:all_or_nothing] request_body[:all_or_nothing] = true end results = connection.post "#{path}/_bulk_docs", request_body docs_by_id = Hash[docs.map { |doc| [doc['_id'], doc] }] unless docs.nil? results.each { |r| docs_by_id[r['id']]['_rev'] = r['rev'] if r['ok'] } unless results.nil? results end
ruby
def bulk_save(docs = nil, opts = {}) opts = { :use_uuids => true, :all_or_nothing => false }.update(opts) if docs.nil? docs = @bulk_save_cache @bulk_save_cache = [] end if opts[:use_uuids] ids, noids = docs.partition{|d|d['_id']} uuid_count = [noids.length, @server.uuid_batch_count].max noids.each do |doc| nextid = server.next_uuid(uuid_count) rescue nil doc['_id'] = nextid if nextid end end request_body = {:docs => docs} if opts[:all_or_nothing] request_body[:all_or_nothing] = true end results = connection.post "#{path}/_bulk_docs", request_body docs_by_id = Hash[docs.map { |doc| [doc['_id'], doc] }] unless docs.nil? results.each { |r| docs_by_id[r['id']]['_rev'] = r['rev'] if r['ok'] } unless results.nil? results end
[ "def", "bulk_save", "(", "docs", "=", "nil", ",", "opts", "=", "{", "}", ")", "opts", "=", "{", ":use_uuids", "=>", "true", ",", ":all_or_nothing", "=>", "false", "}", ".", "update", "(", "opts", ")", "if", "docs", ".", "nil?", "docs", "=", "@bulk_save_cache", "@bulk_save_cache", "=", "[", "]", "end", "if", "opts", "[", ":use_uuids", "]", "ids", ",", "noids", "=", "docs", ".", "partition", "{", "|", "d", "|", "d", "[", "'_id'", "]", "}", "uuid_count", "=", "[", "noids", ".", "length", ",", "@server", ".", "uuid_batch_count", "]", ".", "max", "noids", ".", "each", "do", "|", "doc", "|", "nextid", "=", "server", ".", "next_uuid", "(", "uuid_count", ")", "rescue", "nil", "doc", "[", "'_id'", "]", "=", "nextid", "if", "nextid", "end", "end", "request_body", "=", "{", ":docs", "=>", "docs", "}", "if", "opts", "[", ":all_or_nothing", "]", "request_body", "[", ":all_or_nothing", "]", "=", "true", "end", "results", "=", "connection", ".", "post", "\"#{path}/_bulk_docs\"", ",", "request_body", "docs_by_id", "=", "Hash", "[", "docs", ".", "map", "{", "|", "doc", "|", "[", "doc", "[", "'_id'", "]", ",", "doc", "]", "}", "]", "unless", "docs", ".", "nil?", "results", ".", "each", "{", "|", "r", "|", "docs_by_id", "[", "r", "[", "'id'", "]", "]", "[", "'_rev'", "]", "=", "r", "[", "'rev'", "]", "if", "r", "[", "'ok'", "]", "}", "unless", "results", ".", "nil?", "results", "end" ]
POST an array of documents to CouchDB. If any of the documents are missing ids, supply one from the uuid cache. If called with no arguments, bulk saves the cache of documents to be bulk saved.
[ "POST", "an", "array", "of", "documents", "to", "CouchDB", ".", "If", "any", "of", "the", "documents", "are", "missing", "ids", "supply", "one", "from", "the", "uuid", "cache", "." ]
cdd3ad30b9fa9aad5464cb4647c18c198b2c48d9
https://github.com/couchrest/couchrest/blob/cdd3ad30b9fa9aad5464cb4647c18c198b2c48d9/lib/couchrest/database.rb#L187-L209
train
couchrest/couchrest
lib/couchrest/database.rb
CouchRest.Database.update_doc
def update_doc(doc_id, params = {}, update_limit = 10) resp = {'ok' => false} last_fail = nil until resp['ok'] or update_limit <= 0 doc = self.get(doc_id, params) yield doc begin resp = self.save_doc doc rescue CouchRest::RequestFailed => e if e.http_code == 409 # Update collision update_limit -= 1 last_fail = e else raise e end end end raise last_fail unless resp['ok'] doc end
ruby
def update_doc(doc_id, params = {}, update_limit = 10) resp = {'ok' => false} last_fail = nil until resp['ok'] or update_limit <= 0 doc = self.get(doc_id, params) yield doc begin resp = self.save_doc doc rescue CouchRest::RequestFailed => e if e.http_code == 409 # Update collision update_limit -= 1 last_fail = e else raise e end end end raise last_fail unless resp['ok'] doc end
[ "def", "update_doc", "(", "doc_id", ",", "params", "=", "{", "}", ",", "update_limit", "=", "10", ")", "resp", "=", "{", "'ok'", "=>", "false", "}", "last_fail", "=", "nil", "until", "resp", "[", "'ok'", "]", "or", "update_limit", "<=", "0", "doc", "=", "self", ".", "get", "(", "doc_id", ",", "params", ")", "yield", "doc", "begin", "resp", "=", "self", ".", "save_doc", "doc", "rescue", "CouchRest", "::", "RequestFailed", "=>", "e", "if", "e", ".", "http_code", "==", "409", "update_limit", "-=", "1", "last_fail", "=", "e", "else", "raise", "e", "end", "end", "end", "raise", "last_fail", "unless", "resp", "[", "'ok'", "]", "doc", "end" ]
Updates the given doc by yielding the current state of the doc and trying to update update_limit times. Returns the doc if successfully updated without hitting the limit. If the limit is reached, the last execption will be raised.
[ "Updates", "the", "given", "doc", "by", "yielding", "the", "current", "state", "of", "the", "doc", "and", "trying", "to", "update", "update_limit", "times", ".", "Returns", "the", "doc", "if", "successfully", "updated", "without", "hitting", "the", "limit", ".", "If", "the", "limit", "is", "reached", "the", "last", "execption", "will", "be", "raised", "." ]
cdd3ad30b9fa9aad5464cb4647c18c198b2c48d9
https://github.com/couchrest/couchrest/blob/cdd3ad30b9fa9aad5464cb4647c18c198b2c48d9/lib/couchrest/database.rb#L246-L267
train
couchrest/couchrest
lib/couchrest/database.rb
CouchRest.Database.put_attachment
def put_attachment(doc, name, file, options = {}) file = StringIO.new(file) if file.is_a?(String) connection.put path_for_attachment(doc, name), file, options end
ruby
def put_attachment(doc, name, file, options = {}) file = StringIO.new(file) if file.is_a?(String) connection.put path_for_attachment(doc, name), file, options end
[ "def", "put_attachment", "(", "doc", ",", "name", ",", "file", ",", "options", "=", "{", "}", ")", "file", "=", "StringIO", ".", "new", "(", "file", ")", "if", "file", ".", "is_a?", "(", "String", ")", "connection", ".", "put", "path_for_attachment", "(", "doc", ",", "name", ")", ",", "file", ",", "options", "end" ]
PUT an attachment directly to CouchDB, expects an IO object, or a string that will be converted to a StringIO in the 'file' parameter.
[ "PUT", "an", "attachment", "directly", "to", "CouchDB", "expects", "an", "IO", "object", "or", "a", "string", "that", "will", "be", "converted", "to", "a", "StringIO", "in", "the", "file", "parameter", "." ]
cdd3ad30b9fa9aad5464cb4647c18c198b2c48d9
https://github.com/couchrest/couchrest/blob/cdd3ad30b9fa9aad5464cb4647c18c198b2c48d9/lib/couchrest/database.rb#L341-L344
train
couchrest/couchrest
lib/couchrest/database.rb
CouchRest.Database.delete_attachment
def delete_attachment(doc, name, force=false) attach_path = path_for_attachment(doc, name) begin connection.delete(attach_path) rescue Exception => error if force # get over a 409 doc = get(doc['_id']) attach_path = path_for_attachment(doc, name) connection.delete(attach_path) else error end end end
ruby
def delete_attachment(doc, name, force=false) attach_path = path_for_attachment(doc, name) begin connection.delete(attach_path) rescue Exception => error if force # get over a 409 doc = get(doc['_id']) attach_path = path_for_attachment(doc, name) connection.delete(attach_path) else error end end end
[ "def", "delete_attachment", "(", "doc", ",", "name", ",", "force", "=", "false", ")", "attach_path", "=", "path_for_attachment", "(", "doc", ",", "name", ")", "begin", "connection", ".", "delete", "(", "attach_path", ")", "rescue", "Exception", "=>", "error", "if", "force", "doc", "=", "get", "(", "doc", "[", "'_id'", "]", ")", "attach_path", "=", "path_for_attachment", "(", "doc", ",", "name", ")", "connection", ".", "delete", "(", "attach_path", ")", "else", "error", "end", "end", "end" ]
DELETE an attachment directly from CouchDB
[ "DELETE", "an", "attachment", "directly", "from", "CouchDB" ]
cdd3ad30b9fa9aad5464cb4647c18c198b2c48d9
https://github.com/couchrest/couchrest/blob/cdd3ad30b9fa9aad5464cb4647c18c198b2c48d9/lib/couchrest/database.rb#L347-L361
train
couchrest/couchrest_model
lib/couchrest/model/property.rb
CouchRest::Model.Property.cast_value
def cast_value(parent, value) if !allow_blank && value.to_s.empty? nil else value = typecast_value(parent, self, value) associate_casted_value_to_parent(parent, value) end end
ruby
def cast_value(parent, value) if !allow_blank && value.to_s.empty? nil else value = typecast_value(parent, self, value) associate_casted_value_to_parent(parent, value) end end
[ "def", "cast_value", "(", "parent", ",", "value", ")", "if", "!", "allow_blank", "&&", "value", ".", "to_s", ".", "empty?", "nil", "else", "value", "=", "typecast_value", "(", "parent", ",", "self", ",", "value", ")", "associate_casted_value_to_parent", "(", "parent", ",", "value", ")", "end", "end" ]
Cast an individual value
[ "Cast", "an", "individual", "value" ]
d30a61f52a8dc4a639105c2235353a41f11aeb53
https://github.com/couchrest/couchrest_model/blob/d30a61f52a8dc4a639105c2235353a41f11aeb53/lib/couchrest/model/property.rb#L48-L55
train
couchrest/couchrest_model
lib/couchrest/model/property.rb
CouchRest::Model.Property.build
def build(*args) raise StandardError, "Cannot build property without a class" if @type.nil? if @init_method.is_a?(Proc) @init_method.call(*args) else @type.send(@init_method, *args) end end
ruby
def build(*args) raise StandardError, "Cannot build property without a class" if @type.nil? if @init_method.is_a?(Proc) @init_method.call(*args) else @type.send(@init_method, *args) end end
[ "def", "build", "(", "*", "args", ")", "raise", "StandardError", ",", "\"Cannot build property without a class\"", "if", "@type", ".", "nil?", "if", "@init_method", ".", "is_a?", "(", "Proc", ")", "@init_method", ".", "call", "(", "*", "args", ")", "else", "@type", ".", "send", "(", "@init_method", ",", "*", "args", ")", "end", "end" ]
Initialize a new instance of a property's type ready to be used. If a proc is defined for the init method, it will be used instead of a normal call to the class.
[ "Initialize", "a", "new", "instance", "of", "a", "property", "s", "type", "ready", "to", "be", "used", ".", "If", "a", "proc", "is", "defined", "for", "the", "init", "method", "it", "will", "be", "used", "instead", "of", "a", "normal", "call", "to", "the", "class", "." ]
d30a61f52a8dc4a639105c2235353a41f11aeb53
https://github.com/couchrest/couchrest_model/blob/d30a61f52a8dc4a639105c2235353a41f11aeb53/lib/couchrest/model/property.rb#L70-L78
train
tedconf/front_end_builds
lib/front_end_builds/ext/routes.rb
ActionDispatch::Routing.Mapper.front_end
def front_end(name, path = name, options = {}) defaults = { app_name: name }.merge(options) # Create a new build for this app. post( "#{path}" => "front_end_builds/builds#create", defaults: { app_name: name } ) # Get a build for this app. constraints FrontEndBuilds::HtmlRoutingConstraint.new do get( "/#{path}/(*path)" => "front_end_builds/bests#show", defaults: defaults ) # Need a better way to do this front_end_route = Rails.application.routes.routes.routes.find do |route| route.defaults == defaults.merge( controller: "front_end_builds/bests", action: "show" ) end FrontEndBuilds::App.register_url(name, front_end_route.format({})) end end
ruby
def front_end(name, path = name, options = {}) defaults = { app_name: name }.merge(options) # Create a new build for this app. post( "#{path}" => "front_end_builds/builds#create", defaults: { app_name: name } ) # Get a build for this app. constraints FrontEndBuilds::HtmlRoutingConstraint.new do get( "/#{path}/(*path)" => "front_end_builds/bests#show", defaults: defaults ) # Need a better way to do this front_end_route = Rails.application.routes.routes.routes.find do |route| route.defaults == defaults.merge( controller: "front_end_builds/bests", action: "show" ) end FrontEndBuilds::App.register_url(name, front_end_route.format({})) end end
[ "def", "front_end", "(", "name", ",", "path", "=", "name", ",", "options", "=", "{", "}", ")", "defaults", "=", "{", "app_name", ":", "name", "}", ".", "merge", "(", "options", ")", "post", "(", "\"#{path}\"", "=>", "\"front_end_builds/builds#create\"", ",", "defaults", ":", "{", "app_name", ":", "name", "}", ")", "constraints", "FrontEndBuilds", "::", "HtmlRoutingConstraint", ".", "new", "do", "get", "(", "\"/#{path}/(*path)\"", "=>", "\"front_end_builds/bests#show\"", ",", "defaults", ":", "defaults", ")", "front_end_route", "=", "Rails", ".", "application", ".", "routes", ".", "routes", ".", "routes", ".", "find", "do", "|", "route", "|", "route", ".", "defaults", "==", "defaults", ".", "merge", "(", "controller", ":", "\"front_end_builds/bests\"", ",", "action", ":", "\"show\"", ")", "end", "FrontEndBuilds", "::", "App", ".", "register_url", "(", "name", ",", "front_end_route", ".", "format", "(", "{", "}", ")", ")", "end", "end" ]
Create a front end in your rails router.
[ "Create", "a", "front", "end", "in", "your", "rails", "router", "." ]
98c4ec80b3641fc7c7248e5955ee6b0c3f6c19b6
https://github.com/tedconf/front_end_builds/blob/98c4ec80b3641fc7c7248e5955ee6b0c3f6c19b6/lib/front_end_builds/ext/routes.rb#L7-L38
train
simi/mongoid_paranoia
lib/mongoid/paranoia.rb
Mongoid.Paranoia.restore
def restore(opts = {}) run_callbacks(:restore) do _paranoia_update("$unset" => { paranoid_field => true }) attributes.delete("deleted_at") @destroyed = false restore_relations if opts[:recursive] true end end
ruby
def restore(opts = {}) run_callbacks(:restore) do _paranoia_update("$unset" => { paranoid_field => true }) attributes.delete("deleted_at") @destroyed = false restore_relations if opts[:recursive] true end end
[ "def", "restore", "(", "opts", "=", "{", "}", ")", "run_callbacks", "(", ":restore", ")", "do", "_paranoia_update", "(", "\"$unset\"", "=>", "{", "paranoid_field", "=>", "true", "}", ")", "attributes", ".", "delete", "(", "\"deleted_at\"", ")", "@destroyed", "=", "false", "restore_relations", "if", "opts", "[", ":recursive", "]", "true", "end", "end" ]
Restores a previously soft-deleted document. Handles this by removing the deleted_at flag. @example Restore the document from deleted state. document.restore For resoring associated documents use :recursive => true @example Restore the associated documents from deleted state. document.restore(:recursive => true) TODO: @return [ Time ] The time the document had been deleted. @since 1.0.0
[ "Restores", "a", "previously", "soft", "-", "deleted", "document", ".", "Handles", "this", "by", "removing", "the", "deleted_at", "flag", "." ]
8b92c3b41d70f138b40057c28bece54de89d2186
https://github.com/simi/mongoid_paranoia/blob/8b92c3b41d70f138b40057c28bece54de89d2186/lib/mongoid/paranoia.rb#L147-L155
train
pboling/sanitize_email
lib/sanitize_email/overridden_addresses.rb
SanitizeEmail.OverriddenAddresses.good_listize
def good_listize(real_addresses) good_listed = clean_addresses(real_addresses, :good_list) good_listed = clean_addresses(good_listed, :bad_list) unless good_listed.empty? good_listed end
ruby
def good_listize(real_addresses) good_listed = clean_addresses(real_addresses, :good_list) good_listed = clean_addresses(good_listed, :bad_list) unless good_listed.empty? good_listed end
[ "def", "good_listize", "(", "real_addresses", ")", "good_listed", "=", "clean_addresses", "(", "real_addresses", ",", ":good_list", ")", "good_listed", "=", "clean_addresses", "(", "good_listed", ",", ":bad_list", ")", "unless", "good_listed", ".", "empty?", "good_listed", "end" ]
Replace non-white-listed addresses with these sanitized addresses. Allow good listed email addresses, and then remove the bad listed addresses
[ "Replace", "non", "-", "white", "-", "listed", "addresses", "with", "these", "sanitized", "addresses", ".", "Allow", "good", "listed", "email", "addresses", "and", "then", "remove", "the", "bad", "listed", "addresses" ]
d369fe68aaba042645151da2944e1ff28f30beef
https://github.com/pboling/sanitize_email/blob/d369fe68aaba042645151da2944e1ff28f30beef/lib/sanitize_email/overridden_addresses.rb#L38-L42
train
domitry/nyaplot
lib/nyaplot/color.rb
Nyaplot.Color.to_html
def to_html html = '<table><tr>' @source.each{|color| html.concat("<th>" + color + "</th>")} html.concat("</tr><tr>") @source.each{|color| html.concat("<td style=\"background-color:" + color + ";\">&nbsp;</td>")} html += '</tr></table>' return html end
ruby
def to_html html = '<table><tr>' @source.each{|color| html.concat("<th>" + color + "</th>")} html.concat("</tr><tr>") @source.each{|color| html.concat("<td style=\"background-color:" + color + ";\">&nbsp;</td>")} html += '</tr></table>' return html end
[ "def", "to_html", "html", "=", "'<table><tr>'", "@source", ".", "each", "{", "|", "color", "|", "html", ".", "concat", "(", "\"<th>\"", "+", "color", "+", "\"</th>\"", ")", "}", "html", ".", "concat", "(", "\"</tr><tr>\"", ")", "@source", ".", "each", "{", "|", "color", "|", "html", ".", "concat", "(", "\"<td style=\\\"background-color:\"", "+", "color", "+", "\";\\\">&nbsp;</td>\"", ")", "}", "html", "+=", "'</tr></table>'", "return", "html", "end" ]
display colorset on IRuby notebook as a html table @return [String] generated html
[ "display", "colorset", "on", "IRuby", "notebook", "as", "a", "html", "table" ]
2341ebe730c38abee5d330ef30423cb74a2e2f94
https://github.com/domitry/nyaplot/blob/2341ebe730c38abee5d330ef30423cb74a2e2f94/lib/nyaplot/color.rb#L70-L77
train
domitry/nyaplot
lib/nyaplot/exportable.rb
Nyaplot.Exportable.generate_html
def generate_html(temp_path) path = File.expand_path(temp_path, __FILE__) url = Nyaplot.get_url id = SecureRandom.uuid model = to_json template = File.read(path) ERB.new(template).result(binding) end
ruby
def generate_html(temp_path) path = File.expand_path(temp_path, __FILE__) url = Nyaplot.get_url id = SecureRandom.uuid model = to_json template = File.read(path) ERB.new(template).result(binding) end
[ "def", "generate_html", "(", "temp_path", ")", "path", "=", "File", ".", "expand_path", "(", "temp_path", ",", "__FILE__", ")", "url", "=", "Nyaplot", ".", "get_url", "id", "=", "SecureRandom", ".", "uuid", "model", "=", "to_json", "template", "=", "File", ".", "read", "(", "path", ")", "ERB", ".", "new", "(", "template", ")", ".", "result", "(", "binding", ")", "end" ]
generate static html file @return [String] generated html
[ "generate", "static", "html", "file" ]
2341ebe730c38abee5d330ef30423cb74a2e2f94
https://github.com/domitry/nyaplot/blob/2341ebe730c38abee5d330ef30423cb74a2e2f94/lib/nyaplot/exportable.rb#L14-L21
train
domitry/nyaplot
lib/nyaplot/exportable.rb
Nyaplot.Exportable.export_html
def export_html(path="./plot.html", to_png=false) path = File.expand_path(path, Dir::pwd) body = generate_html("../templates/iruby.erb") temp_path = File.expand_path("../templates/static_html.erb", __FILE__) template = File.read(temp_path) num = File.write(path, ERB.new(template).result(binding)) "Plot was saved to " + path end
ruby
def export_html(path="./plot.html", to_png=false) path = File.expand_path(path, Dir::pwd) body = generate_html("../templates/iruby.erb") temp_path = File.expand_path("../templates/static_html.erb", __FILE__) template = File.read(temp_path) num = File.write(path, ERB.new(template).result(binding)) "Plot was saved to " + path end
[ "def", "export_html", "(", "path", "=", "\"./plot.html\"", ",", "to_png", "=", "false", ")", "path", "=", "File", ".", "expand_path", "(", "path", ",", "Dir", "::", "pwd", ")", "body", "=", "generate_html", "(", "\"../templates/iruby.erb\"", ")", "temp_path", "=", "File", ".", "expand_path", "(", "\"../templates/static_html.erb\"", ",", "__FILE__", ")", "template", "=", "File", ".", "read", "(", "temp_path", ")", "num", "=", "File", ".", "write", "(", "path", ",", "ERB", ".", "new", "(", "template", ")", ".", "result", "(", "binding", ")", ")", "\"Plot was saved to \"", "+", "path", "end" ]
export static html file
[ "export", "static", "html", "file" ]
2341ebe730c38abee5d330ef30423cb74a2e2f94
https://github.com/domitry/nyaplot/blob/2341ebe730c38abee5d330ef30423cb74a2e2f94/lib/nyaplot/exportable.rb#L24-L31
train
domitry/nyaplot
lib/nyaplot3d/plot3d.rb
Nyaplot.Plot3D.add
def add(type, *data) df = DataFrame.new({x: data[0], y: data[1], z: data[2]}) return add_with_df(df, type, :x, :y, :z) end
ruby
def add(type, *data) df = DataFrame.new({x: data[0], y: data[1], z: data[2]}) return add_with_df(df, type, :x, :y, :z) end
[ "def", "add", "(", "type", ",", "*", "data", ")", "df", "=", "DataFrame", ".", "new", "(", "{", "x", ":", "data", "[", "0", "]", ",", "y", ":", "data", "[", "1", "]", ",", "z", ":", "data", "[", "2", "]", "}", ")", "return", "add_with_df", "(", "df", ",", "type", ",", ":x", ",", ":y", ",", ":z", ")", "end" ]
Add diagram with Array @param [Symbol] type the type of diagram to add @param [Array<Array>] *data array from which diagram is created @example plot.add(:surface, [0,1,2], [0,1,2], [0,1,2])
[ "Add", "diagram", "with", "Array" ]
2341ebe730c38abee5d330ef30423cb74a2e2f94
https://github.com/domitry/nyaplot/blob/2341ebe730c38abee5d330ef30423cb74a2e2f94/lib/nyaplot3d/plot3d.rb#L25-L28
train
domitry/nyaplot
lib/nyaplot3d/plot3d.rb
Nyaplot.Plot3D.add_with_df
def add_with_df(df, type, *labels) diagram = Diagram3D.new(df, type, labels) diagrams = get_property(:diagrams) diagrams.push(diagram) return diagram end
ruby
def add_with_df(df, type, *labels) diagram = Diagram3D.new(df, type, labels) diagrams = get_property(:diagrams) diagrams.push(diagram) return diagram end
[ "def", "add_with_df", "(", "df", ",", "type", ",", "*", "labels", ")", "diagram", "=", "Diagram3D", ".", "new", "(", "df", ",", "type", ",", "labels", ")", "diagrams", "=", "get_property", "(", ":diagrams", ")", "diagrams", ".", "push", "(", "diagram", ")", "return", "diagram", "end" ]
Add diagram with DataFrame @param [DataFrame] DataFrame from which diagram is created @param [Symbol] type the type of diagram to add @param [Array<Symbol>] *labels column labels for x, y or some other dimension @example df = Nyaplot::DataFrame.new({x: [0,1,2], y: [0,1,2], z: [0,1,2]}) plot.add(df, :surface, :x, :y, :z)
[ "Add", "diagram", "with", "DataFrame" ]
2341ebe730c38abee5d330ef30423cb74a2e2f94
https://github.com/domitry/nyaplot/blob/2341ebe730c38abee5d330ef30423cb74a2e2f94/lib/nyaplot3d/plot3d.rb#L37-L42
train
domitry/nyaplot
lib/nyaplot3d/plot3d.rb
Nyaplot.Plot3D.export_html
def export_html(path=nil) require 'securerandom' path = "./plot-" + SecureRandom.uuid().to_s + ".html" if path.nil? Frame.new.tap {|f| f.add(self) }.export_html(path) end
ruby
def export_html(path=nil) require 'securerandom' path = "./plot-" + SecureRandom.uuid().to_s + ".html" if path.nil? Frame.new.tap {|f| f.add(self) }.export_html(path) end
[ "def", "export_html", "(", "path", "=", "nil", ")", "require", "'securerandom'", "path", "=", "\"./plot-\"", "+", "SecureRandom", ".", "uuid", "(", ")", ".", "to_s", "+", "\".html\"", "if", "path", ".", "nil?", "Frame", ".", "new", ".", "tap", "{", "|", "f", "|", "f", ".", "add", "(", "self", ")", "}", ".", "export_html", "(", "path", ")", "end" ]
export html file
[ "export", "html", "file" ]
2341ebe730c38abee5d330ef30423cb74a2e2f94
https://github.com/domitry/nyaplot/blob/2341ebe730c38abee5d330ef30423cb74a2e2f94/lib/nyaplot3d/plot3d.rb#L55-L59
train
applicationsonline/librarian
lib/librarian/spec_change_set.rb
Librarian.SpecChangeSet.analyze
def analyze @analyze ||= begin debug { "Analyzing spec and lock:" } if same? debug { " Same!" } return lock.manifests end debug { " Removed:" } ; removed_dependency_names.each { |name| debug { " #{name}" } } debug { " ExplicitRemoved:" } ; explicit_removed_dependency_names.each { |name| debug { " #{name}" } } debug { " Added:" } ; added_dependency_names.each { |name| debug { " #{name}" } } debug { " NonMatchingAdded:" } ; nonmatching_added_dependency_names.each { |name| debug { " #{name}" } } debug { " Changed:" } ; changed_dependency_names.each { |name| debug { " #{name}" } } debug { " DeepKeep:" } ; deep_keep_manifest_names.each { |name| debug { " #{name}" } } debug { " ShallowStrip:" } ; shallow_strip_manifest_names.each { |name| debug { " #{name}" } } manifests = ManifestSet.new(lock_manifests) manifests.deep_keep!(deep_keep_manifest_names) manifests.shallow_strip!(shallow_strip_manifest_names) manifests.to_a end end
ruby
def analyze @analyze ||= begin debug { "Analyzing spec and lock:" } if same? debug { " Same!" } return lock.manifests end debug { " Removed:" } ; removed_dependency_names.each { |name| debug { " #{name}" } } debug { " ExplicitRemoved:" } ; explicit_removed_dependency_names.each { |name| debug { " #{name}" } } debug { " Added:" } ; added_dependency_names.each { |name| debug { " #{name}" } } debug { " NonMatchingAdded:" } ; nonmatching_added_dependency_names.each { |name| debug { " #{name}" } } debug { " Changed:" } ; changed_dependency_names.each { |name| debug { " #{name}" } } debug { " DeepKeep:" } ; deep_keep_manifest_names.each { |name| debug { " #{name}" } } debug { " ShallowStrip:" } ; shallow_strip_manifest_names.each { |name| debug { " #{name}" } } manifests = ManifestSet.new(lock_manifests) manifests.deep_keep!(deep_keep_manifest_names) manifests.shallow_strip!(shallow_strip_manifest_names) manifests.to_a end end
[ "def", "analyze", "@analyze", "||=", "begin", "debug", "{", "\"Analyzing spec and lock:\"", "}", "if", "same?", "debug", "{", "\" Same!\"", "}", "return", "lock", ".", "manifests", "end", "debug", "{", "\" Removed:\"", "}", ";", "removed_dependency_names", ".", "each", "{", "|", "name", "|", "debug", "{", "\" #{name}\"", "}", "}", "debug", "{", "\" ExplicitRemoved:\"", "}", ";", "explicit_removed_dependency_names", ".", "each", "{", "|", "name", "|", "debug", "{", "\" #{name}\"", "}", "}", "debug", "{", "\" Added:\"", "}", ";", "added_dependency_names", ".", "each", "{", "|", "name", "|", "debug", "{", "\" #{name}\"", "}", "}", "debug", "{", "\" NonMatchingAdded:\"", "}", ";", "nonmatching_added_dependency_names", ".", "each", "{", "|", "name", "|", "debug", "{", "\" #{name}\"", "}", "}", "debug", "{", "\" Changed:\"", "}", ";", "changed_dependency_names", ".", "each", "{", "|", "name", "|", "debug", "{", "\" #{name}\"", "}", "}", "debug", "{", "\" DeepKeep:\"", "}", ";", "deep_keep_manifest_names", ".", "each", "{", "|", "name", "|", "debug", "{", "\" #{name}\"", "}", "}", "debug", "{", "\" ShallowStrip:\"", "}", ";", "shallow_strip_manifest_names", ".", "each", "{", "|", "name", "|", "debug", "{", "\" #{name}\"", "}", "}", "manifests", "=", "ManifestSet", ".", "new", "(", "lock_manifests", ")", "manifests", ".", "deep_keep!", "(", "deep_keep_manifest_names", ")", "manifests", ".", "shallow_strip!", "(", "shallow_strip_manifest_names", ")", "manifests", ".", "to_a", "end", "end" ]
Returns an array of those manifests from the previous spec which should be kept, based on inspecting the new spec against the locked resolution from the previous spec.
[ "Returns", "an", "array", "of", "those", "manifests", "from", "the", "previous", "spec", "which", "should", "be", "kept", "based", "on", "inspecting", "the", "new", "spec", "against", "the", "locked", "resolution", "from", "the", "previous", "spec", "." ]
b968cd91a3955657bf6ea728b922f2cb74843264
https://github.com/applicationsonline/librarian/blob/b968cd91a3955657bf6ea728b922f2cb74843264/lib/librarian/spec_change_set.rb#L142-L164
train
applicationsonline/librarian
lib/librarian/manifest_set.rb
Librarian.ManifestSet.dependencies_of
def dependencies_of(names) names = Array === names ? names.dup : names.to_a assert_strings!(names) deps = Set.new until names.empty? name = names.shift next if deps.include?(name) deps << name names.concat index[name].dependencies.map(&:name) end deps.to_a end
ruby
def dependencies_of(names) names = Array === names ? names.dup : names.to_a assert_strings!(names) deps = Set.new until names.empty? name = names.shift next if deps.include?(name) deps << name names.concat index[name].dependencies.map(&:name) end deps.to_a end
[ "def", "dependencies_of", "(", "names", ")", "names", "=", "Array", "===", "names", "?", "names", ".", "dup", ":", "names", ".", "to_a", "assert_strings!", "(", "names", ")", "deps", "=", "Set", ".", "new", "until", "names", ".", "empty?", "name", "=", "names", ".", "shift", "next", "if", "deps", ".", "include?", "(", "name", ")", "deps", "<<", "name", "names", ".", "concat", "index", "[", "name", "]", ".", "dependencies", ".", "map", "(", "&", ":name", ")", "end", "deps", ".", "to_a", "end" ]
Straightforward breadth-first graph traversal algorithm.
[ "Straightforward", "breadth", "-", "first", "graph", "traversal", "algorithm", "." ]
b968cd91a3955657bf6ea728b922f2cb74843264
https://github.com/applicationsonline/librarian/blob/b968cd91a3955657bf6ea728b922f2cb74843264/lib/librarian/manifest_set.rb#L130-L143
train
apiqcms/kms
app/services/kms/page_fetcher.rb
Kms.PageFetcher.fetch_templatable_page!
def fetch_templatable_page! parent_page_path = File.dirname(@path) parent_page_path = Kms::Page::INDEX_FULLPATH if parent_page_path == "." parent_page = Kms::Page.published.find_by_fullpath!(parent_page_path) templatable_pages = parent_page.children.where(templatable: true) templatable_pages.detect do |templatable_page| templatable_page.fetch_item(File.basename(@path)) end end
ruby
def fetch_templatable_page! parent_page_path = File.dirname(@path) parent_page_path = Kms::Page::INDEX_FULLPATH if parent_page_path == "." parent_page = Kms::Page.published.find_by_fullpath!(parent_page_path) templatable_pages = parent_page.children.where(templatable: true) templatable_pages.detect do |templatable_page| templatable_page.fetch_item(File.basename(@path)) end end
[ "def", "fetch_templatable_page!", "parent_page_path", "=", "File", ".", "dirname", "(", "@path", ")", "parent_page_path", "=", "Kms", "::", "Page", "::", "INDEX_FULLPATH", "if", "parent_page_path", "==", "\".\"", "parent_page", "=", "Kms", "::", "Page", ".", "published", ".", "find_by_fullpath!", "(", "parent_page_path", ")", "templatable_pages", "=", "parent_page", ".", "children", ".", "where", "(", "templatable", ":", "true", ")", "templatable_pages", ".", "detect", "do", "|", "templatable_page", "|", "templatable_page", ".", "fetch_item", "(", "File", ".", "basename", "(", "@path", ")", ")", "end", "end" ]
finds templatable page that works for path
[ "finds", "templatable", "page", "that", "works", "for", "path" ]
a5590ca71c37dee9b45f6e1edf83cf95056932f5
https://github.com/apiqcms/kms/blob/a5590ca71c37dee9b45f6e1edf83cf95056932f5/app/services/kms/page_fetcher.rb#L15-L23
train
apiqcms/kms
app/models/concerns/kms/permalinkable.rb
Kms.Permalinkable.permalink
def permalink templatable_page = Kms::Page.where(templatable_type: self.class.name).first if templatable_page Pathname.new(templatable_page.parent.fullpath).join(slug.to_s).to_s end end
ruby
def permalink templatable_page = Kms::Page.where(templatable_type: self.class.name).first if templatable_page Pathname.new(templatable_page.parent.fullpath).join(slug.to_s).to_s end end
[ "def", "permalink", "templatable_page", "=", "Kms", "::", "Page", ".", "where", "(", "templatable_type", ":", "self", ".", "class", ".", "name", ")", ".", "first", "if", "templatable_page", "Pathname", ".", "new", "(", "templatable_page", ".", "parent", ".", "fullpath", ")", ".", "join", "(", "slug", ".", "to_s", ")", ".", "to_s", "end", "end" ]
Entity should respond to "slug"
[ "Entity", "should", "respond", "to", "slug" ]
a5590ca71c37dee9b45f6e1edf83cf95056932f5
https://github.com/apiqcms/kms/blob/a5590ca71c37dee9b45f6e1edf83cf95056932f5/app/models/concerns/kms/permalinkable.rb#L6-L11
train
rudionrails/yell
lib/yell/level.rb
Yell.Level.set
def set( *severities ) @severities = Yell::Severities.map { true } severity = severities.length > 1 ? severities : severities.first case severity when Array then at(*severity) when Range then gte(severity.first).lte(severity.last) when String then interpret(severity) when Integer, Symbol then gte(severity) when Yell::Level then @severities = severity.severities end end
ruby
def set( *severities ) @severities = Yell::Severities.map { true } severity = severities.length > 1 ? severities : severities.first case severity when Array then at(*severity) when Range then gte(severity.first).lte(severity.last) when String then interpret(severity) when Integer, Symbol then gte(severity) when Yell::Level then @severities = severity.severities end end
[ "def", "set", "(", "*", "severities", ")", "@severities", "=", "Yell", "::", "Severities", ".", "map", "{", "true", "}", "severity", "=", "severities", ".", "length", ">", "1", "?", "severities", ":", "severities", ".", "first", "case", "severity", "when", "Array", "then", "at", "(", "*", "severity", ")", "when", "Range", "then", "gte", "(", "severity", ".", "first", ")", ".", "lte", "(", "severity", ".", "last", ")", "when", "String", "then", "interpret", "(", "severity", ")", "when", "Integer", ",", "Symbol", "then", "gte", "(", "severity", ")", "when", "Yell", "::", "Level", "then", "@severities", "=", "severity", ".", "severities", "end", "end" ]
Create a new level instance. @example Enable all severities Yell::Level.new @example Pass the minimum possible severity Yell::Level.new :warn @example Pass an array to exactly set the level at the given severities Yell::Level.new [:info, :error] @example Pass a range to set the level within the severities Yell::Level.new (:info..:error) @param [Integer,String,Symbol,Array,Range,nil] severity The severity for the level. Set the severity to the given format
[ "Create", "a", "new", "level", "instance", "." ]
4fffff3a4f583ad75b37538d916d0939e498e5a6
https://github.com/rudionrails/yell/blob/4fffff3a4f583ad75b37538d916d0939e498e5a6/lib/yell/level.rb#L48-L59
train
plataformatec/show_for
lib/show_for/helper.rb
ShowFor.Helper.show_for
def show_for(object, html_options={}, &block) html_options = html_options.dup tag = html_options.delete(:show_for_tag) || ShowFor.show_for_tag html_options[:id] ||= dom_id(object) html_options[:class] = show_for_html_class(object, html_options) builder = html_options.delete(:builder) || ShowFor::Builder content = capture(builder.new(object, self), &block) content_tag(tag, content, html_options) end
ruby
def show_for(object, html_options={}, &block) html_options = html_options.dup tag = html_options.delete(:show_for_tag) || ShowFor.show_for_tag html_options[:id] ||= dom_id(object) html_options[:class] = show_for_html_class(object, html_options) builder = html_options.delete(:builder) || ShowFor::Builder content = capture(builder.new(object, self), &block) content_tag(tag, content, html_options) end
[ "def", "show_for", "(", "object", ",", "html_options", "=", "{", "}", ",", "&", "block", ")", "html_options", "=", "html_options", ".", "dup", "tag", "=", "html_options", ".", "delete", "(", ":show_for_tag", ")", "||", "ShowFor", ".", "show_for_tag", "html_options", "[", ":id", "]", "||=", "dom_id", "(", "object", ")", "html_options", "[", ":class", "]", "=", "show_for_html_class", "(", "object", ",", "html_options", ")", "builder", "=", "html_options", ".", "delete", "(", ":builder", ")", "||", "ShowFor", "::", "Builder", "content", "=", "capture", "(", "builder", ".", "new", "(", "object", ",", "self", ")", ",", "&", "block", ")", "content_tag", "(", "tag", ",", "content", ",", "html_options", ")", "end" ]
Creates a div around the object and yields a builder. Example: show_for @user do |f| f.attribute :name f.attribute :email end
[ "Creates", "a", "div", "around", "the", "object", "and", "yields", "a", "builder", "." ]
28166bfd03dc7b9ad54ec2f9939b5b24c8aff76f
https://github.com/plataformatec/show_for/blob/28166bfd03dc7b9ad54ec2f9939b5b24c8aff76f/lib/show_for/helper.rb#L12-L24
train
aeseducation/scorm-cloud
lib/scorm_cloud/connection.rb
ScormCloud.Base.execute_call_xml
def execute_call_xml(url) doc = REXML::Document.new(execute_call_plain(url)) raise create_error(doc) unless doc.elements["rsp"].attributes["stat"] == "ok" doc end
ruby
def execute_call_xml(url) doc = REXML::Document.new(execute_call_plain(url)) raise create_error(doc) unless doc.elements["rsp"].attributes["stat"] == "ok" doc end
[ "def", "execute_call_xml", "(", "url", ")", "doc", "=", "REXML", "::", "Document", ".", "new", "(", "execute_call_plain", "(", "url", ")", ")", "raise", "create_error", "(", "doc", ")", "unless", "doc", ".", "elements", "[", "\"rsp\"", "]", ".", "attributes", "[", "\"stat\"", "]", "==", "\"ok\"", "doc", "end" ]
Get plain response body and parse the XML doc
[ "Get", "plain", "response", "body", "and", "parse", "the", "XML", "doc" ]
0b822e0a2c2adc9a3308df7d23375fb64b0aff60
https://github.com/aeseducation/scorm-cloud/blob/0b822e0a2c2adc9a3308df7d23375fb64b0aff60/lib/scorm_cloud/connection.rb#L20-L24
train
aeseducation/scorm-cloud
lib/scorm_cloud/connection.rb
ScormCloud.Base.execute_call_plain
def execute_call_plain(url) res = Net::HTTP.get_response(URI.parse(url)) case res when Net::HTTPRedirection # Return the new URL res['location'] when Net::HTTPSuccess res.body else raise "HTTP Error connecting to scorm cloud: #{res.inspect}" end end
ruby
def execute_call_plain(url) res = Net::HTTP.get_response(URI.parse(url)) case res when Net::HTTPRedirection # Return the new URL res['location'] when Net::HTTPSuccess res.body else raise "HTTP Error connecting to scorm cloud: #{res.inspect}" end end
[ "def", "execute_call_plain", "(", "url", ")", "res", "=", "Net", "::", "HTTP", ".", "get_response", "(", "URI", ".", "parse", "(", "url", ")", ")", "case", "res", "when", "Net", "::", "HTTPRedirection", "res", "[", "'location'", "]", "when", "Net", "::", "HTTPSuccess", "res", ".", "body", "else", "raise", "\"HTTP Error connecting to scorm cloud: #{res.inspect}\"", "end", "end" ]
Execute the call - returns response body or redirect url
[ "Execute", "the", "call", "-", "returns", "response", "body", "or", "redirect", "url" ]
0b822e0a2c2adc9a3308df7d23375fb64b0aff60
https://github.com/aeseducation/scorm-cloud/blob/0b822e0a2c2adc9a3308df7d23375fb64b0aff60/lib/scorm_cloud/connection.rb#L27-L38
train
aeseducation/scorm-cloud
lib/scorm_cloud/connection.rb
ScormCloud.Base.prepare_url
def prepare_url(method, params = {}) timestamp = Time.now.utc.strftime('%Y%m%d%H%M%S') params[:method] = method params[:appid] = @appid params[:ts] = timestamp html_params = params.map { |k,v| "#{k.to_s}=#{v}" }.join("&") raw = @secret + params.keys. sort{ |a,b| a.to_s.downcase <=> b.to_s.downcase }. map{ |k| "#{k.to_s}#{params[k]}" }. join sig = Digest::MD5.hexdigest(raw) "http://cloud.scorm.com/api?#{html_params}&sig=#{sig}" end
ruby
def prepare_url(method, params = {}) timestamp = Time.now.utc.strftime('%Y%m%d%H%M%S') params[:method] = method params[:appid] = @appid params[:ts] = timestamp html_params = params.map { |k,v| "#{k.to_s}=#{v}" }.join("&") raw = @secret + params.keys. sort{ |a,b| a.to_s.downcase <=> b.to_s.downcase }. map{ |k| "#{k.to_s}#{params[k]}" }. join sig = Digest::MD5.hexdigest(raw) "http://cloud.scorm.com/api?#{html_params}&sig=#{sig}" end
[ "def", "prepare_url", "(", "method", ",", "params", "=", "{", "}", ")", "timestamp", "=", "Time", ".", "now", ".", "utc", ".", "strftime", "(", "'%Y%m%d%H%M%S'", ")", "params", "[", ":method", "]", "=", "method", "params", "[", ":appid", "]", "=", "@appid", "params", "[", ":ts", "]", "=", "timestamp", "html_params", "=", "params", ".", "map", "{", "|", "k", ",", "v", "|", "\"#{k.to_s}=#{v}\"", "}", ".", "join", "(", "\"&\"", ")", "raw", "=", "@secret", "+", "params", ".", "keys", ".", "sort", "{", "|", "a", ",", "b", "|", "a", ".", "to_s", ".", "downcase", "<=>", "b", ".", "to_s", ".", "downcase", "}", ".", "map", "{", "|", "k", "|", "\"#{k.to_s}#{params[k]}\"", "}", ".", "join", "sig", "=", "Digest", "::", "MD5", ".", "hexdigest", "(", "raw", ")", "\"http://cloud.scorm.com/api?#{html_params}&sig=#{sig}\"", "end" ]
Get the URL for the call
[ "Get", "the", "URL", "for", "the", "call" ]
0b822e0a2c2adc9a3308df7d23375fb64b0aff60
https://github.com/aeseducation/scorm-cloud/blob/0b822e0a2c2adc9a3308df7d23375fb64b0aff60/lib/scorm_cloud/connection.rb#L41-L55
train
aeseducation/scorm-cloud
lib/scorm_cloud/base.rb
ScormCloud.Base.create_error
def create_error(doc, url) err = doc.elements["rsp"].elements["err"] code = err.attributes["code"] msg = err.attributes["msg"] "Error In Scorm Cloud: Error=#{code} Message=#{msg} URL=#{url}" end
ruby
def create_error(doc, url) err = doc.elements["rsp"].elements["err"] code = err.attributes["code"] msg = err.attributes["msg"] "Error In Scorm Cloud: Error=#{code} Message=#{msg} URL=#{url}" end
[ "def", "create_error", "(", "doc", ",", "url", ")", "err", "=", "doc", ".", "elements", "[", "\"rsp\"", "]", ".", "elements", "[", "\"err\"", "]", "code", "=", "err", ".", "attributes", "[", "\"code\"", "]", "msg", "=", "err", ".", "attributes", "[", "\"msg\"", "]", "\"Error In Scorm Cloud: Error=#{code} Message=#{msg} URL=#{url}\"", "end" ]
Create an exception with code & message
[ "Create", "an", "exception", "with", "code", "&", "message" ]
0b822e0a2c2adc9a3308df7d23375fb64b0aff60
https://github.com/aeseducation/scorm-cloud/blob/0b822e0a2c2adc9a3308df7d23375fb64b0aff60/lib/scorm_cloud/base.rb#L87-L92
train
Dan-Q/twee2
lib/twee2/story_format.rb
Twee2.StoryFormat.compile
def compile @source.gsub('{{STORY_NAME}}', Twee2::build_config.story_name).gsub('{{STORY_DATA}}', Twee2::build_config.story_file.xmldata).gsub('{{STORY_FORMAT}}', @name) end
ruby
def compile @source.gsub('{{STORY_NAME}}', Twee2::build_config.story_name).gsub('{{STORY_DATA}}', Twee2::build_config.story_file.xmldata).gsub('{{STORY_FORMAT}}', @name) end
[ "def", "compile", "@source", ".", "gsub", "(", "'{{STORY_NAME}}'", ",", "Twee2", "::", "build_config", ".", "story_name", ")", ".", "gsub", "(", "'{{STORY_DATA}}'", ",", "Twee2", "::", "build_config", ".", "story_file", ".", "xmldata", ")", ".", "gsub", "(", "'{{STORY_FORMAT}}'", ",", "@name", ")", "end" ]
Loads the StoryFormat with the specified name Given a story file, injects it into the StoryFormat and returns the HTML results
[ "Loads", "the", "StoryFormat", "with", "the", "specified", "name", "Given", "a", "story", "file", "injects", "it", "into", "the", "StoryFormat", "and", "returns", "the", "HTML", "results" ]
d7659d84b5415d594dcc868628d74c3c9b48f496
https://github.com/Dan-Q/twee2/blob/d7659d84b5415d594dcc868628d74c3c9b48f496/lib/twee2/story_format.rb#L18-L20
train
Dan-Q/twee2
lib/twee2/story_file.rb
Twee2.StoryFile.run_preprocessors
def run_preprocessors @passages.each_key do |k| # HAML if @passages[k][:tags].include? 'haml' @passages[k][:content] = Haml::Engine.new(@passages[k][:content], HAML_OPTIONS).render @passages[k][:tags].delete 'haml' end # Coffeescript if @passages[k][:tags].include? 'coffee' @passages[k][:content] = CoffeeScript.compile(@passages[k][:content], COFFEESCRIPT_OPTIONS) @passages[k][:tags].delete 'coffee' end # SASS / SCSS if @passages[k][:tags].include? 'sass' @passages[k][:content] = Sass::Engine.new(@passages[k][:content], :syntax => :sass).render end if @passages[k][:tags].include? 'scss' @passages[k][:content] = Sass::Engine.new(@passages[k][:content], :syntax => :scss).render end end end
ruby
def run_preprocessors @passages.each_key do |k| # HAML if @passages[k][:tags].include? 'haml' @passages[k][:content] = Haml::Engine.new(@passages[k][:content], HAML_OPTIONS).render @passages[k][:tags].delete 'haml' end # Coffeescript if @passages[k][:tags].include? 'coffee' @passages[k][:content] = CoffeeScript.compile(@passages[k][:content], COFFEESCRIPT_OPTIONS) @passages[k][:tags].delete 'coffee' end # SASS / SCSS if @passages[k][:tags].include? 'sass' @passages[k][:content] = Sass::Engine.new(@passages[k][:content], :syntax => :sass).render end if @passages[k][:tags].include? 'scss' @passages[k][:content] = Sass::Engine.new(@passages[k][:content], :syntax => :scss).render end end end
[ "def", "run_preprocessors", "@passages", ".", "each_key", "do", "|", "k", "|", "if", "@passages", "[", "k", "]", "[", ":tags", "]", ".", "include?", "'haml'", "@passages", "[", "k", "]", "[", ":content", "]", "=", "Haml", "::", "Engine", ".", "new", "(", "@passages", "[", "k", "]", "[", ":content", "]", ",", "HAML_OPTIONS", ")", ".", "render", "@passages", "[", "k", "]", "[", ":tags", "]", ".", "delete", "'haml'", "end", "if", "@passages", "[", "k", "]", "[", ":tags", "]", ".", "include?", "'coffee'", "@passages", "[", "k", "]", "[", ":content", "]", "=", "CoffeeScript", ".", "compile", "(", "@passages", "[", "k", "]", "[", ":content", "]", ",", "COFFEESCRIPT_OPTIONS", ")", "@passages", "[", "k", "]", "[", ":tags", "]", ".", "delete", "'coffee'", "end", "if", "@passages", "[", "k", "]", "[", ":tags", "]", ".", "include?", "'sass'", "@passages", "[", "k", "]", "[", ":content", "]", "=", "Sass", "::", "Engine", ".", "new", "(", "@passages", "[", "k", "]", "[", ":content", "]", ",", ":syntax", "=>", ":sass", ")", ".", "render", "end", "if", "@passages", "[", "k", "]", "[", ":tags", "]", ".", "include?", "'scss'", "@passages", "[", "k", "]", "[", ":content", "]", "=", "Sass", "::", "Engine", ".", "new", "(", "@passages", "[", "k", "]", "[", ":content", "]", ",", ":syntax", "=>", ":scss", ")", ".", "render", "end", "end", "end" ]
Runs HAML, Coffeescript etc. preprocessors across each applicable passage
[ "Runs", "HAML", "Coffeescript", "etc", ".", "preprocessors", "across", "each", "applicable", "passage" ]
d7659d84b5415d594dcc868628d74c3c9b48f496
https://github.com/Dan-Q/twee2/blob/d7659d84b5415d594dcc868628d74c3c9b48f496/lib/twee2/story_file.rb#L121-L141
train
Katello/hammer-cli-katello
lib/hammer_cli_katello/id_name_options_validator.rb
HammerCLIKatello.IdNameOptionsValidator.validate_id_or_name
def validate_id_or_name(record_name = nil) child_options = IdNameOptionsValidator.build_child_options(record_name) validate_options do any(*child_options).required end end
ruby
def validate_id_or_name(record_name = nil) child_options = IdNameOptionsValidator.build_child_options(record_name) validate_options do any(*child_options).required end end
[ "def", "validate_id_or_name", "(", "record_name", "=", "nil", ")", "child_options", "=", "IdNameOptionsValidator", ".", "build_child_options", "(", "record_name", ")", "validate_options", "do", "any", "(", "*", "child_options", ")", ".", "required", "end", "end" ]
This method simply checks that either id or name is supplied Some examples: # checks for a --id or --name option validate_id_or_name # checks for --content-view-id or --content-view-name validate_id_or_name :content_view
[ "This", "method", "simply", "checks", "that", "either", "id", "or", "name", "is", "supplied" ]
3dfc3237631d2241cbd0bb43049fdc3ce5555b16
https://github.com/Katello/hammer-cli-katello/blob/3dfc3237631d2241cbd0bb43049fdc3ce5555b16/lib/hammer_cli_katello/id_name_options_validator.rb#L39-L45
train
maccman/bowline
lib/bowline/watcher.rb
Bowline.Watcher.call
def call(event, *args) return unless @listeners[event] @listeners[event].each do |callback| callback.call(*args) end end
ruby
def call(event, *args) return unless @listeners[event] @listeners[event].each do |callback| callback.call(*args) end end
[ "def", "call", "(", "event", ",", "*", "args", ")", "return", "unless", "@listeners", "[", "event", "]", "@listeners", "[", "event", "]", ".", "each", "do", "|", "callback", "|", "callback", ".", "call", "(", "*", "args", ")", "end", "end" ]
Call an event's callbacks with provided arguments.
[ "Call", "an", "event", "s", "callbacks", "with", "provided", "arguments", "." ]
33acc83f68fdd2b46e1f217c3b7948047811f492
https://github.com/maccman/bowline/blob/33acc83f68fdd2b46e1f217c3b7948047811f492/lib/bowline/watcher.rb#L102-L107
train
maccman/bowline
lib/bowline/watcher.rb
Bowline.Watcher.remove
def remove(event, value=nil) return unless @listeners[event] if value @listeners[event].delete(value) if @listeners[event].empty? @listeners.delete(event) end else @listeners.delete(event) end end
ruby
def remove(event, value=nil) return unless @listeners[event] if value @listeners[event].delete(value) if @listeners[event].empty? @listeners.delete(event) end else @listeners.delete(event) end end
[ "def", "remove", "(", "event", ",", "value", "=", "nil", ")", "return", "unless", "@listeners", "[", "event", "]", "if", "value", "@listeners", "[", "event", "]", ".", "delete", "(", "value", ")", "if", "@listeners", "[", "event", "]", ".", "empty?", "@listeners", ".", "delete", "(", "event", ")", "end", "else", "@listeners", ".", "delete", "(", "event", ")", "end", "end" ]
Remove an specific callback on an event, or all an event's callbacks.
[ "Remove", "an", "specific", "callback", "on", "an", "event", "or", "all", "an", "event", "s", "callbacks", "." ]
33acc83f68fdd2b46e1f217c3b7948047811f492
https://github.com/maccman/bowline/blob/33acc83f68fdd2b46e1f217c3b7948047811f492/lib/bowline/watcher.rb#L111-L121
train
maccman/bowline
lib/bowline/initializer.rb
Bowline.Initializer.set_autoload_paths
def set_autoload_paths # Rails 3 master support if ActiveSupport::Dependencies.respond_to?(:autoload_paths) ActiveSupport::Dependencies.autoload_paths = configuration.autoload_paths.uniq ActiveSupport::Dependencies.autoload_once_paths = configuration.autoload_once_paths.uniq else ActiveSupport::Dependencies.load_paths = configuration.autoload_paths.uniq ActiveSupport::Dependencies.load_once_paths = configuration.autoload_once_paths.uniq end end
ruby
def set_autoload_paths # Rails 3 master support if ActiveSupport::Dependencies.respond_to?(:autoload_paths) ActiveSupport::Dependencies.autoload_paths = configuration.autoload_paths.uniq ActiveSupport::Dependencies.autoload_once_paths = configuration.autoload_once_paths.uniq else ActiveSupport::Dependencies.load_paths = configuration.autoload_paths.uniq ActiveSupport::Dependencies.load_once_paths = configuration.autoload_once_paths.uniq end end
[ "def", "set_autoload_paths", "if", "ActiveSupport", "::", "Dependencies", ".", "respond_to?", "(", ":autoload_paths", ")", "ActiveSupport", "::", "Dependencies", ".", "autoload_paths", "=", "configuration", ".", "autoload_paths", ".", "uniq", "ActiveSupport", "::", "Dependencies", ".", "autoload_once_paths", "=", "configuration", ".", "autoload_once_paths", ".", "uniq", "else", "ActiveSupport", "::", "Dependencies", ".", "load_paths", "=", "configuration", ".", "autoload_paths", ".", "uniq", "ActiveSupport", "::", "Dependencies", ".", "load_once_paths", "=", "configuration", ".", "autoload_once_paths", ".", "uniq", "end", "end" ]
Set the paths from which Bowline will automatically load source files, and the load_once paths.
[ "Set", "the", "paths", "from", "which", "Bowline", "will", "automatically", "load", "source", "files", "and", "the", "load_once", "paths", "." ]
33acc83f68fdd2b46e1f217c3b7948047811f492
https://github.com/maccman/bowline/blob/33acc83f68fdd2b46e1f217c3b7948047811f492/lib/bowline/initializer.rb#L112-L121
train
maccman/bowline
lib/bowline/initializer.rb
Bowline.Configuration.set_root_path!
def set_root_path! raise 'APP_ROOT is not set' unless defined?(::APP_ROOT) raise 'APP_ROOT is not a directory' unless File.directory?(::APP_ROOT) @root_path = # Pathname is incompatible with Windows, but Windows doesn't have # real symlinks so File.expand_path is safe. if RUBY_PLATFORM =~ /(:?mswin|mingw)/ File.expand_path(::APP_ROOT) # Otherwise use Pathname#realpath which respects symlinks. else Pathname.new(::APP_ROOT).realpath.to_s end Object.const_set(:RELATIVE_APP_ROOT, ::APP_ROOT.dup) unless defined?(::RELATIVE_APP_ROOT) ::APP_ROOT.replace @root_path end
ruby
def set_root_path! raise 'APP_ROOT is not set' unless defined?(::APP_ROOT) raise 'APP_ROOT is not a directory' unless File.directory?(::APP_ROOT) @root_path = # Pathname is incompatible with Windows, but Windows doesn't have # real symlinks so File.expand_path is safe. if RUBY_PLATFORM =~ /(:?mswin|mingw)/ File.expand_path(::APP_ROOT) # Otherwise use Pathname#realpath which respects symlinks. else Pathname.new(::APP_ROOT).realpath.to_s end Object.const_set(:RELATIVE_APP_ROOT, ::APP_ROOT.dup) unless defined?(::RELATIVE_APP_ROOT) ::APP_ROOT.replace @root_path end
[ "def", "set_root_path!", "raise", "'APP_ROOT is not set'", "unless", "defined?", "(", "::", "APP_ROOT", ")", "raise", "'APP_ROOT is not a directory'", "unless", "File", ".", "directory?", "(", "::", "APP_ROOT", ")", "@root_path", "=", "if", "RUBY_PLATFORM", "=~", "/", "/", "File", ".", "expand_path", "(", "::", "APP_ROOT", ")", "else", "Pathname", ".", "new", "(", "::", "APP_ROOT", ")", ".", "realpath", ".", "to_s", "end", "Object", ".", "const_set", "(", ":RELATIVE_APP_ROOT", ",", "::", "APP_ROOT", ".", "dup", ")", "unless", "defined?", "(", "::", "RELATIVE_APP_ROOT", ")", "::", "APP_ROOT", ".", "replace", "@root_path", "end" ]
Create a new Configuration instance, initialized with the default values. Set the root_path to APP_ROOT and canonicalize it.
[ "Create", "a", "new", "Configuration", "instance", "initialized", "with", "the", "default", "values", ".", "Set", "the", "root_path", "to", "APP_ROOT", "and", "canonicalize", "it", "." ]
33acc83f68fdd2b46e1f217c3b7948047811f492
https://github.com/maccman/bowline/blob/33acc83f68fdd2b46e1f217c3b7948047811f492/lib/bowline/initializer.rb#L521-L538
train
CocoaPods/cocoapods-stats
lib/cocoapods_stats/target_mapper.rb
CocoaPodsStats.TargetMapper.pods_from_project
def pods_from_project(context, master_pods) context.umbrella_targets.flat_map do |target| root_specs = target.specs.map(&:root).uniq # As it's hard to look up the source of a pod, we # can check if the pod exists in the master specs repo though pods = root_specs. select { |spec| master_pods.include?(spec.name) }. map { |spec| { :name => spec.name, :version => spec.version.to_s } } # This will be an empty array for `integrate_targets: false` Podfiles user_targets(target).map do |user_target| # Send in a digested'd UUID anyway, a second layer # of misdirection can't hurt { :uuid => Digest::SHA256.hexdigest(user_target.uuid), :type => user_target.product_type, :pods => pods, :platform => user_target.platform_name, } end end end
ruby
def pods_from_project(context, master_pods) context.umbrella_targets.flat_map do |target| root_specs = target.specs.map(&:root).uniq # As it's hard to look up the source of a pod, we # can check if the pod exists in the master specs repo though pods = root_specs. select { |spec| master_pods.include?(spec.name) }. map { |spec| { :name => spec.name, :version => spec.version.to_s } } # This will be an empty array for `integrate_targets: false` Podfiles user_targets(target).map do |user_target| # Send in a digested'd UUID anyway, a second layer # of misdirection can't hurt { :uuid => Digest::SHA256.hexdigest(user_target.uuid), :type => user_target.product_type, :pods => pods, :platform => user_target.platform_name, } end end end
[ "def", "pods_from_project", "(", "context", ",", "master_pods", ")", "context", ".", "umbrella_targets", ".", "flat_map", "do", "|", "target", "|", "root_specs", "=", "target", ".", "specs", ".", "map", "(", "&", ":root", ")", ".", "uniq", "pods", "=", "root_specs", ".", "select", "{", "|", "spec", "|", "master_pods", ".", "include?", "(", "spec", ".", "name", ")", "}", ".", "map", "{", "|", "spec", "|", "{", ":name", "=>", "spec", ".", "name", ",", ":version", "=>", "spec", ".", "version", ".", "to_s", "}", "}", "user_targets", "(", "target", ")", ".", "map", "do", "|", "user_target", "|", "{", ":uuid", "=>", "Digest", "::", "SHA256", ".", "hexdigest", "(", "user_target", ".", "uuid", ")", ",", ":type", "=>", "user_target", ".", "product_type", ",", ":pods", "=>", "pods", ",", ":platform", "=>", "user_target", ".", "platform_name", ",", "}", "end", "end", "end" ]
Loop though all targets in the pod generate a collection of hashes
[ "Loop", "though", "all", "targets", "in", "the", "pod", "generate", "a", "collection", "of", "hashes" ]
ad869b620a46c6ba5048b54d5772e1956d2d9d83
https://github.com/CocoaPods/cocoapods-stats/blob/ad869b620a46c6ba5048b54d5772e1956d2d9d83/lib/cocoapods_stats/target_mapper.rb#L8-L31
train
matthodan/jekyll-asset-pipeline
lib/jekyll_asset_pipeline/pipeline.rb
JekyllAssetPipeline.Pipeline.collect
def collect @assets = YAML.safe_load(@manifest).map! do |path| full_path = File.join(@source, path) File.open(File.join(@source, path)) do |file| ::JekyllAssetPipeline::Asset.new(file.read, File.basename(path), File.dirname(full_path)) end end rescue StandardError => e puts 'Asset Pipeline: Failed to load assets from provided ' \ "manifest: #{e.message}" raise e end
ruby
def collect @assets = YAML.safe_load(@manifest).map! do |path| full_path = File.join(@source, path) File.open(File.join(@source, path)) do |file| ::JekyllAssetPipeline::Asset.new(file.read, File.basename(path), File.dirname(full_path)) end end rescue StandardError => e puts 'Asset Pipeline: Failed to load assets from provided ' \ "manifest: #{e.message}" raise e end
[ "def", "collect", "@assets", "=", "YAML", ".", "safe_load", "(", "@manifest", ")", ".", "map!", "do", "|", "path", "|", "full_path", "=", "File", ".", "join", "(", "@source", ",", "path", ")", "File", ".", "open", "(", "File", ".", "join", "(", "@source", ",", "path", ")", ")", "do", "|", "file", "|", "::", "JekyllAssetPipeline", "::", "Asset", ".", "new", "(", "file", ".", "read", ",", "File", ".", "basename", "(", "path", ")", ",", "File", ".", "dirname", "(", "full_path", ")", ")", "end", "end", "rescue", "StandardError", "=>", "e", "puts", "'Asset Pipeline: Failed to load assets from provided '", "\"manifest: #{e.message}\"", "raise", "e", "end" ]
Collect assets based on manifest
[ "Collect", "assets", "based", "on", "manifest" ]
fa0be3aa2beae83ab0e46663c433d48750717a46
https://github.com/matthodan/jekyll-asset-pipeline/blob/fa0be3aa2beae83ab0e46663c433d48750717a46/lib/jekyll_asset_pipeline/pipeline.rb#L114-L126
train
matthodan/jekyll-asset-pipeline
lib/jekyll_asset_pipeline/pipeline.rb
JekyllAssetPipeline.Pipeline.convert_asset
def convert_asset(klass, asset) # Convert asset content converter = klass.new(asset) # Replace asset content and filename asset.content = converter.converted asset.filename = File.basename(asset.filename, '.*') # Add back the output extension if no extension left if File.extname(asset.filename) == '' asset.filename = "#{asset.filename}#{@type}" end rescue StandardError => e puts "Asset Pipeline: Failed to convert '#{asset.filename}' " \ "with '#{klass}': #{e.message}" raise e end
ruby
def convert_asset(klass, asset) # Convert asset content converter = klass.new(asset) # Replace asset content and filename asset.content = converter.converted asset.filename = File.basename(asset.filename, '.*') # Add back the output extension if no extension left if File.extname(asset.filename) == '' asset.filename = "#{asset.filename}#{@type}" end rescue StandardError => e puts "Asset Pipeline: Failed to convert '#{asset.filename}' " \ "with '#{klass}': #{e.message}" raise e end
[ "def", "convert_asset", "(", "klass", ",", "asset", ")", "converter", "=", "klass", ".", "new", "(", "asset", ")", "asset", ".", "content", "=", "converter", ".", "converted", "asset", ".", "filename", "=", "File", ".", "basename", "(", "asset", ".", "filename", ",", "'.*'", ")", "if", "File", ".", "extname", "(", "asset", ".", "filename", ")", "==", "''", "asset", ".", "filename", "=", "\"#{asset.filename}#{@type}\"", "end", "rescue", "StandardError", "=>", "e", "puts", "\"Asset Pipeline: Failed to convert '#{asset.filename}' \"", "\"with '#{klass}': #{e.message}\"", "raise", "e", "end" ]
Convert an asset with a given converter class
[ "Convert", "an", "asset", "with", "a", "given", "converter", "class" ]
fa0be3aa2beae83ab0e46663c433d48750717a46
https://github.com/matthodan/jekyll-asset-pipeline/blob/fa0be3aa2beae83ab0e46663c433d48750717a46/lib/jekyll_asset_pipeline/pipeline.rb#L148-L164
train
matthodan/jekyll-asset-pipeline
lib/jekyll_asset_pipeline/pipeline.rb
JekyllAssetPipeline.Pipeline.compress
def compress @assets.each do |asset| # Find a compressor to use klass = ::JekyllAssetPipeline::Compressor.subclasses.select do |c| c.filetype == @type end.last break unless klass begin asset.content = klass.new(asset.content).compressed rescue StandardError => e puts "Asset Pipeline: Failed to compress '#{asset.filename}' " \ "with '#{klass}': #{e.message}" raise e end end end
ruby
def compress @assets.each do |asset| # Find a compressor to use klass = ::JekyllAssetPipeline::Compressor.subclasses.select do |c| c.filetype == @type end.last break unless klass begin asset.content = klass.new(asset.content).compressed rescue StandardError => e puts "Asset Pipeline: Failed to compress '#{asset.filename}' " \ "with '#{klass}': #{e.message}" raise e end end end
[ "def", "compress", "@assets", ".", "each", "do", "|", "asset", "|", "klass", "=", "::", "JekyllAssetPipeline", "::", "Compressor", ".", "subclasses", ".", "select", "do", "|", "c", "|", "c", ".", "filetype", "==", "@type", "end", ".", "last", "break", "unless", "klass", "begin", "asset", ".", "content", "=", "klass", ".", "new", "(", "asset", ".", "content", ")", ".", "compressed", "rescue", "StandardError", "=>", "e", "puts", "\"Asset Pipeline: Failed to compress '#{asset.filename}' \"", "\"with '#{klass}': #{e.message}\"", "raise", "e", "end", "end", "end" ]
Compress assets if compressor is defined
[ "Compress", "assets", "if", "compressor", "is", "defined" ]
fa0be3aa2beae83ab0e46663c433d48750717a46
https://github.com/matthodan/jekyll-asset-pipeline/blob/fa0be3aa2beae83ab0e46663c433d48750717a46/lib/jekyll_asset_pipeline/pipeline.rb#L177-L194
train
matthodan/jekyll-asset-pipeline
lib/jekyll_asset_pipeline/pipeline.rb
JekyllAssetPipeline.Pipeline.gzip
def gzip @assets.map! do |asset| gzip_content = Zlib::Deflate.deflate(asset.content) [ asset, ::JekyllAssetPipeline::Asset .new(gzip_content, "#{asset.filename}.gz", asset.dirname) ] end.flatten! end
ruby
def gzip @assets.map! do |asset| gzip_content = Zlib::Deflate.deflate(asset.content) [ asset, ::JekyllAssetPipeline::Asset .new(gzip_content, "#{asset.filename}.gz", asset.dirname) ] end.flatten! end
[ "def", "gzip", "@assets", ".", "map!", "do", "|", "asset", "|", "gzip_content", "=", "Zlib", "::", "Deflate", ".", "deflate", "(", "asset", ".", "content", ")", "[", "asset", ",", "::", "JekyllAssetPipeline", "::", "Asset", ".", "new", "(", "gzip_content", ",", "\"#{asset.filename}.gz\"", ",", "asset", ".", "dirname", ")", "]", "end", ".", "flatten!", "end" ]
Create Gzip versions of assets
[ "Create", "Gzip", "versions", "of", "assets" ]
fa0be3aa2beae83ab0e46663c433d48750717a46
https://github.com/matthodan/jekyll-asset-pipeline/blob/fa0be3aa2beae83ab0e46663c433d48750717a46/lib/jekyll_asset_pipeline/pipeline.rb#L197-L206
train
matthodan/jekyll-asset-pipeline
lib/jekyll_asset_pipeline/pipeline.rb
JekyllAssetPipeline.Pipeline.save
def save output_path = @options['output_path'] staging_path = @options['staging_path'] @assets.each do |asset| directory = File.join(@source, staging_path, output_path) write_asset_file(directory, asset) # Store output path of saved file asset.output_path = output_path end end
ruby
def save output_path = @options['output_path'] staging_path = @options['staging_path'] @assets.each do |asset| directory = File.join(@source, staging_path, output_path) write_asset_file(directory, asset) # Store output path of saved file asset.output_path = output_path end end
[ "def", "save", "output_path", "=", "@options", "[", "'output_path'", "]", "staging_path", "=", "@options", "[", "'staging_path'", "]", "@assets", ".", "each", "do", "|", "asset", "|", "directory", "=", "File", ".", "join", "(", "@source", ",", "staging_path", ",", "output_path", ")", "write_asset_file", "(", "directory", ",", "asset", ")", "asset", ".", "output_path", "=", "output_path", "end", "end" ]
Save assets to file
[ "Save", "assets", "to", "file" ]
fa0be3aa2beae83ab0e46663c433d48750717a46
https://github.com/matthodan/jekyll-asset-pipeline/blob/fa0be3aa2beae83ab0e46663c433d48750717a46/lib/jekyll_asset_pipeline/pipeline.rb#L209-L220
train
starling/starling
lib/starling/queue_collection.rb
StarlingServer.QueueCollection.put
def put(key, data) queue = queues(key) return nil unless queue @stats[:current_bytes] += data.size @stats[:total_items] += 1 queue.push(data) return true end
ruby
def put(key, data) queue = queues(key) return nil unless queue @stats[:current_bytes] += data.size @stats[:total_items] += 1 queue.push(data) return true end
[ "def", "put", "(", "key", ",", "data", ")", "queue", "=", "queues", "(", "key", ")", "return", "nil", "unless", "queue", "@stats", "[", ":current_bytes", "]", "+=", "data", ".", "size", "@stats", "[", ":total_items", "]", "+=", "1", "queue", ".", "push", "(", "data", ")", "return", "true", "end" ]
Create a new QueueCollection at +path+ Puts +data+ onto the queue named +key+
[ "Create", "a", "new", "QueueCollection", "at", "+", "path", "+" ]
058512e66dec325f6c469e279d5c57a9ce015a89
https://github.com/starling/starling/blob/058512e66dec325f6c469e279d5c57a9ce015a89/lib/starling/queue_collection.rb#L35-L45
train
starling/starling
lib/starling/queue_collection.rb
StarlingServer.QueueCollection.take
def take(key) queue = queues(key) if queue.nil? || queue.length == 0 @stats[:get_misses] += 1 return nil else @stats[:get_hits] += 1 end result = queue.pop @stats[:current_bytes] -= result.size result end
ruby
def take(key) queue = queues(key) if queue.nil? || queue.length == 0 @stats[:get_misses] += 1 return nil else @stats[:get_hits] += 1 end result = queue.pop @stats[:current_bytes] -= result.size result end
[ "def", "take", "(", "key", ")", "queue", "=", "queues", "(", "key", ")", "if", "queue", ".", "nil?", "||", "queue", ".", "length", "==", "0", "@stats", "[", ":get_misses", "]", "+=", "1", "return", "nil", "else", "@stats", "[", ":get_hits", "]", "+=", "1", "end", "result", "=", "queue", ".", "pop", "@stats", "[", ":current_bytes", "]", "-=", "result", ".", "size", "result", "end" ]
Retrieves data from the queue named +key+
[ "Retrieves", "data", "from", "the", "queue", "named", "+", "key", "+" ]
058512e66dec325f6c469e279d5c57a9ce015a89
https://github.com/starling/starling/blob/058512e66dec325f6c469e279d5c57a9ce015a89/lib/starling/queue_collection.rb#L50-L61
train
starling/starling
lib/starling/queue_collection.rb
StarlingServer.QueueCollection.queues
def queues(key=nil) return nil if @shutdown_mutex.locked? return @queues if key.nil? # First try to return the queue named 'key' if it's available. return @queues[key] if @queues[key] # If the queue wasn't available, create or get the mutex that will # wrap creation of the Queue. @queue_init_mutexes[key] ||= Mutex.new # Otherwise, check to see if another process is already loading # the queue named 'key'. if @queue_init_mutexes[key].locked? # return an empty/false result if we're waiting for the queue # to be loaded and we're not the first process to request the queue return nil else begin @queue_init_mutexes[key].lock # we've locked the mutex, but only go ahead if the queue hasn't # been loaded. There's a race condition otherwise, and we could # end up loading the queue multiple times. if @queues[key].nil? @queues[key] = PersistentQueue.new(@path, key) @stats[:current_bytes] += @queues[key].initial_bytes end rescue Object => exc puts "ZOMG There was an exception reading back the queue. That totally sucks." puts "The exception was: #{exc}. Backtrace: #{exc.backtrace.join("\n")}" ensure @queue_init_mutexes[key].unlock end end return @queues[key] end
ruby
def queues(key=nil) return nil if @shutdown_mutex.locked? return @queues if key.nil? # First try to return the queue named 'key' if it's available. return @queues[key] if @queues[key] # If the queue wasn't available, create or get the mutex that will # wrap creation of the Queue. @queue_init_mutexes[key] ||= Mutex.new # Otherwise, check to see if another process is already loading # the queue named 'key'. if @queue_init_mutexes[key].locked? # return an empty/false result if we're waiting for the queue # to be loaded and we're not the first process to request the queue return nil else begin @queue_init_mutexes[key].lock # we've locked the mutex, but only go ahead if the queue hasn't # been loaded. There's a race condition otherwise, and we could # end up loading the queue multiple times. if @queues[key].nil? @queues[key] = PersistentQueue.new(@path, key) @stats[:current_bytes] += @queues[key].initial_bytes end rescue Object => exc puts "ZOMG There was an exception reading back the queue. That totally sucks." puts "The exception was: #{exc}. Backtrace: #{exc.backtrace.join("\n")}" ensure @queue_init_mutexes[key].unlock end end return @queues[key] end
[ "def", "queues", "(", "key", "=", "nil", ")", "return", "nil", "if", "@shutdown_mutex", ".", "locked?", "return", "@queues", "if", "key", ".", "nil?", "return", "@queues", "[", "key", "]", "if", "@queues", "[", "key", "]", "@queue_init_mutexes", "[", "key", "]", "||=", "Mutex", ".", "new", "if", "@queue_init_mutexes", "[", "key", "]", ".", "locked?", "return", "nil", "else", "begin", "@queue_init_mutexes", "[", "key", "]", ".", "lock", "if", "@queues", "[", "key", "]", ".", "nil?", "@queues", "[", "key", "]", "=", "PersistentQueue", ".", "new", "(", "@path", ",", "key", ")", "@stats", "[", ":current_bytes", "]", "+=", "@queues", "[", "key", "]", ".", "initial_bytes", "end", "rescue", "Object", "=>", "exc", "puts", "\"ZOMG There was an exception reading back the queue. That totally sucks.\"", "puts", "\"The exception was: #{exc}. Backtrace: #{exc.backtrace.join(\"\\n\")}\"", "ensure", "@queue_init_mutexes", "[", "key", "]", ".", "unlock", "end", "end", "return", "@queues", "[", "key", "]", "end" ]
Returns all active queues.
[ "Returns", "all", "active", "queues", "." ]
058512e66dec325f6c469e279d5c57a9ce015a89
https://github.com/starling/starling/blob/058512e66dec325f6c469e279d5c57a9ce015a89/lib/starling/queue_collection.rb#L72-L109
train
starling/starling
lib/starling/persistent_queue.rb
StarlingServer.PersistentQueue.pop
def pop(log_trx = true) raise NoTransactionLog if log_trx && !@trx begin rv = super(!log_trx) rescue ThreadError puts "WARNING: The queue was empty when trying to pop(). Technically this shouldn't ever happen. Probably a bug in the transactional underpinnings. Or maybe shutdown didn't happen cleanly at some point. Ignoring." rv = [now_usec, ''] end transaction "\001" if log_trx @current_age = (now_usec - rv[0]) / 1000 rv[1] end
ruby
def pop(log_trx = true) raise NoTransactionLog if log_trx && !@trx begin rv = super(!log_trx) rescue ThreadError puts "WARNING: The queue was empty when trying to pop(). Technically this shouldn't ever happen. Probably a bug in the transactional underpinnings. Or maybe shutdown didn't happen cleanly at some point. Ignoring." rv = [now_usec, ''] end transaction "\001" if log_trx @current_age = (now_usec - rv[0]) / 1000 rv[1] end
[ "def", "pop", "(", "log_trx", "=", "true", ")", "raise", "NoTransactionLog", "if", "log_trx", "&&", "!", "@trx", "begin", "rv", "=", "super", "(", "!", "log_trx", ")", "rescue", "ThreadError", "puts", "\"WARNING: The queue was empty when trying to pop(). Technically this shouldn't ever happen. Probably a bug in the transactional underpinnings. Or maybe shutdown didn't happen cleanly at some point. Ignoring.\"", "rv", "=", "[", "now_usec", ",", "''", "]", "end", "transaction", "\"\\001\"", "if", "log_trx", "@current_age", "=", "(", "now_usec", "-", "rv", "[", "0", "]", ")", "/", "1000", "rv", "[", "1", "]", "end" ]
Retrieves data from the queue.
[ "Retrieves", "data", "from", "the", "queue", "." ]
058512e66dec325f6c469e279d5c57a9ce015a89
https://github.com/starling/starling/blob/058512e66dec325f6c469e279d5c57a9ce015a89/lib/starling/persistent_queue.rb#L59-L71
train
starling/starling
lib/starling/server.rb
StarlingServer.Base.run
def run @stats[:start_time] = Time.now if @opts[:syslog_channel] begin require 'syslog_logger' @@logger = SyslogLogger.new(@opts[:syslog_channel]) rescue LoadError # SyslogLogger isn't available, so we're just going to use Logger end end @@logger ||= case @opts[:logger] when IO, String; Logger.new(@opts[:logger]) when Logger; @opts[:logger] else; Logger.new(STDERR) end begin @opts[:queue] = QueueCollection.new(@opts[:path]) rescue InaccessibleQueuePath => e puts "Error: #{e.message}" exit 1 end @@logger.level = @opts[:log_level] || Logger::ERROR @@logger.info "Starling STARTUP on #{@opts[:host]}:#{@opts[:port]}" EventMachine.epoll EventMachine.set_descriptor_table_size(4096) EventMachine.run do EventMachine.start_server(@opts[:host], @opts[:port], Handler, @opts) end # code here will get executed on shutdown: @opts[:queue].close end
ruby
def run @stats[:start_time] = Time.now if @opts[:syslog_channel] begin require 'syslog_logger' @@logger = SyslogLogger.new(@opts[:syslog_channel]) rescue LoadError # SyslogLogger isn't available, so we're just going to use Logger end end @@logger ||= case @opts[:logger] when IO, String; Logger.new(@opts[:logger]) when Logger; @opts[:logger] else; Logger.new(STDERR) end begin @opts[:queue] = QueueCollection.new(@opts[:path]) rescue InaccessibleQueuePath => e puts "Error: #{e.message}" exit 1 end @@logger.level = @opts[:log_level] || Logger::ERROR @@logger.info "Starling STARTUP on #{@opts[:host]}:#{@opts[:port]}" EventMachine.epoll EventMachine.set_descriptor_table_size(4096) EventMachine.run do EventMachine.start_server(@opts[:host], @opts[:port], Handler, @opts) end # code here will get executed on shutdown: @opts[:queue].close end
[ "def", "run", "@stats", "[", ":start_time", "]", "=", "Time", ".", "now", "if", "@opts", "[", ":syslog_channel", "]", "begin", "require", "'syslog_logger'", "@@logger", "=", "SyslogLogger", ".", "new", "(", "@opts", "[", ":syslog_channel", "]", ")", "rescue", "LoadError", "end", "end", "@@logger", "||=", "case", "@opts", "[", ":logger", "]", "when", "IO", ",", "String", ";", "Logger", ".", "new", "(", "@opts", "[", ":logger", "]", ")", "when", "Logger", ";", "@opts", "[", ":logger", "]", "else", ";", "Logger", ".", "new", "(", "STDERR", ")", "end", "begin", "@opts", "[", ":queue", "]", "=", "QueueCollection", ".", "new", "(", "@opts", "[", ":path", "]", ")", "rescue", "InaccessibleQueuePath", "=>", "e", "puts", "\"Error: #{e.message}\"", "exit", "1", "end", "@@logger", ".", "level", "=", "@opts", "[", ":log_level", "]", "||", "Logger", "::", "ERROR", "@@logger", ".", "info", "\"Starling STARTUP on #{@opts[:host]}:#{@opts[:port]}\"", "EventMachine", ".", "epoll", "EventMachine", ".", "set_descriptor_table_size", "(", "4096", ")", "EventMachine", ".", "run", "do", "EventMachine", ".", "start_server", "(", "@opts", "[", ":host", "]", ",", "@opts", "[", ":port", "]", ",", "Handler", ",", "@opts", ")", "end", "@opts", "[", ":queue", "]", ".", "close", "end" ]
Initialize a new Starling server, but do not accept connections or process requests. +opts+ is as for +start+ Start listening and processing requests.
[ "Initialize", "a", "new", "Starling", "server", "but", "do", "not", "accept", "connections", "or", "process", "requests", "." ]
058512e66dec325f6c469e279d5c57a9ce015a89
https://github.com/starling/starling/blob/058512e66dec325f6c469e279d5c57a9ce015a89/lib/starling/server.rb#L67-L103
train
starling/starling
lib/starling/handler.rb
StarlingServer.Handler.post_init
def post_init @stash = [] @data = "" @data_buf = "" @server = @opts[:server] @logger = StarlingServer::Base.logger @expiry_stats = Hash.new(0) @expected_length = nil @server.stats[:total_connections] += 1 set_comm_inactivity_timeout @opts[:timeout] @queue_collection = @opts[:queue] @session_id = @@next_session_id @@next_session_id += 1 peer = Socket.unpack_sockaddr_in(get_peername) #@logger.debug "(#{@session_id}) New session from #{peer[1]}:#{peer[0]}" end
ruby
def post_init @stash = [] @data = "" @data_buf = "" @server = @opts[:server] @logger = StarlingServer::Base.logger @expiry_stats = Hash.new(0) @expected_length = nil @server.stats[:total_connections] += 1 set_comm_inactivity_timeout @opts[:timeout] @queue_collection = @opts[:queue] @session_id = @@next_session_id @@next_session_id += 1 peer = Socket.unpack_sockaddr_in(get_peername) #@logger.debug "(#{@session_id}) New session from #{peer[1]}:#{peer[0]}" end
[ "def", "post_init", "@stash", "=", "[", "]", "@data", "=", "\"\"", "@data_buf", "=", "\"\"", "@server", "=", "@opts", "[", ":server", "]", "@logger", "=", "StarlingServer", "::", "Base", ".", "logger", "@expiry_stats", "=", "Hash", ".", "new", "(", "0", ")", "@expected_length", "=", "nil", "@server", ".", "stats", "[", ":total_connections", "]", "+=", "1", "set_comm_inactivity_timeout", "@opts", "[", ":timeout", "]", "@queue_collection", "=", "@opts", "[", ":queue", "]", "@session_id", "=", "@@next_session_id", "@@next_session_id", "+=", "1", "peer", "=", "Socket", ".", "unpack_sockaddr_in", "(", "get_peername", ")", "end" ]
Creates a new handler for the MemCache protocol that communicates with a given client. Process incoming commands from the attached client.
[ "Creates", "a", "new", "handler", "for", "the", "MemCache", "protocol", "that", "communicates", "with", "a", "given", "client", "." ]
058512e66dec325f6c469e279d5c57a9ce015a89
https://github.com/starling/starling/blob/058512e66dec325f6c469e279d5c57a9ce015a89/lib/starling/handler.rb#L78-L95
train
adamcooke/attach
lib/attach/attachment.rb
Attach.Attachment.child
def child(role) @cached_children ||= {} @cached_children[role.to_sym] ||= self.children.where(:role => role).first || :nil @cached_children[role.to_sym] == :nil ? nil : @cached_children[role.to_sym] end
ruby
def child(role) @cached_children ||= {} @cached_children[role.to_sym] ||= self.children.where(:role => role).first || :nil @cached_children[role.to_sym] == :nil ? nil : @cached_children[role.to_sym] end
[ "def", "child", "(", "role", ")", "@cached_children", "||=", "{", "}", "@cached_children", "[", "role", ".", "to_sym", "]", "||=", "self", ".", "children", ".", "where", "(", ":role", "=>", "role", ")", ".", "first", "||", ":nil", "@cached_children", "[", "role", ".", "to_sym", "]", "==", ":nil", "?", "nil", ":", "@cached_children", "[", "role", ".", "to_sym", "]", "end" ]
Return a child process
[ "Return", "a", "child", "process" ]
09aa63f38fa28b215d0a4274851203af56534f07
https://github.com/adamcooke/attach/blob/09aa63f38fa28b215d0a4274851203af56534f07/lib/attach/attachment.rb#L89-L93
train
adamcooke/attach
lib/attach/attachment.rb
Attach.Attachment.add_child
def add_child(role, &block) attachment = self.children.build attachment.role = role attachment.owner = self.owner attachment.file_name = self.file_name attachment.file_type = self.file_type attachment.disposition = self.disposition attachment.cache_type = self.cache_type attachment.cache_max_age = self.cache_max_age attachment.type = self.type block.call(attachment) attachment.save! end
ruby
def add_child(role, &block) attachment = self.children.build attachment.role = role attachment.owner = self.owner attachment.file_name = self.file_name attachment.file_type = self.file_type attachment.disposition = self.disposition attachment.cache_type = self.cache_type attachment.cache_max_age = self.cache_max_age attachment.type = self.type block.call(attachment) attachment.save! end
[ "def", "add_child", "(", "role", ",", "&", "block", ")", "attachment", "=", "self", ".", "children", ".", "build", "attachment", ".", "role", "=", "role", "attachment", ".", "owner", "=", "self", ".", "owner", "attachment", ".", "file_name", "=", "self", ".", "file_name", "attachment", ".", "file_type", "=", "self", ".", "file_type", "attachment", ".", "disposition", "=", "self", ".", "disposition", "attachment", ".", "cache_type", "=", "self", ".", "cache_type", "attachment", ".", "cache_max_age", "=", "self", ".", "cache_max_age", "attachment", ".", "type", "=", "self", ".", "type", "block", ".", "call", "(", "attachment", ")", "attachment", ".", "save!", "end" ]
Add a child attachment
[ "Add", "a", "child", "attachment" ]
09aa63f38fa28b215d0a4274851203af56534f07
https://github.com/adamcooke/attach/blob/09aa63f38fa28b215d0a4274851203af56534f07/lib/attach/attachment.rb#L101-L113
train
ManageIQ/linux_admin
lib/linux_admin/network_interface.rb
LinuxAdmin.NetworkInterface.netmask6
def netmask6(scope = :global) if [:global, :link].include?(scope) @network_conf["mask6_#{scope}".to_sym] ||= IPAddr.new('ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff').mask(prefix6(scope)).to_s if prefix6(scope) else raise ArgumentError, "Unrecognized address scope #{scope}" end end
ruby
def netmask6(scope = :global) if [:global, :link].include?(scope) @network_conf["mask6_#{scope}".to_sym] ||= IPAddr.new('ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff').mask(prefix6(scope)).to_s if prefix6(scope) else raise ArgumentError, "Unrecognized address scope #{scope}" end end
[ "def", "netmask6", "(", "scope", "=", ":global", ")", "if", "[", ":global", ",", ":link", "]", ".", "include?", "(", "scope", ")", "@network_conf", "[", "\"mask6_#{scope}\"", ".", "to_sym", "]", "||=", "IPAddr", ".", "new", "(", "'ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff'", ")", ".", "mask", "(", "prefix6", "(", "scope", ")", ")", ".", "to_s", "if", "prefix6", "(", "scope", ")", "else", "raise", "ArgumentError", ",", "\"Unrecognized address scope #{scope}\"", "end", "end" ]
Retrieve the IPv6 sub-net mask assigned to the interface @return [String] IPv6 netmask @raise [ArgumentError] if the given scope is not `:global` or `:link`
[ "Retrieve", "the", "IPv6", "sub", "-", "net", "mask", "assigned", "to", "the", "interface" ]
6c91b6ea7ccfcbcae617d24618c6df0543dfee28
https://github.com/ManageIQ/linux_admin/blob/6c91b6ea7ccfcbcae617d24618c6df0543dfee28/lib/linux_admin/network_interface.rb#L100-L106
train
ManageIQ/linux_admin
lib/linux_admin/network_interface/network_interface_rh.rb
LinuxAdmin.NetworkInterfaceRH.apply_static
def apply_static(ip, mask, gw, dns, search = nil) self.address = ip self.netmask = mask self.gateway = gw self.dns = dns self.search_order = search if search save end
ruby
def apply_static(ip, mask, gw, dns, search = nil) self.address = ip self.netmask = mask self.gateway = gw self.dns = dns self.search_order = search if search save end
[ "def", "apply_static", "(", "ip", ",", "mask", ",", "gw", ",", "dns", ",", "search", "=", "nil", ")", "self", ".", "address", "=", "ip", "self", ".", "netmask", "=", "mask", "self", ".", "gateway", "=", "gw", "self", ".", "dns", "=", "dns", "self", ".", "search_order", "=", "search", "if", "search", "save", "end" ]
Applies the given static network configuration to the interface @param ip [String] IPv4 address @param mask [String] subnet mask @param gw [String] gateway address @param dns [Array<String>] list of dns servers @param search [Array<String>] list of search domains @return [Boolean] true on success, false otherwise @raise ArgumentError if an IP is not formatted properly
[ "Applies", "the", "given", "static", "network", "configuration", "to", "the", "interface" ]
6c91b6ea7ccfcbcae617d24618c6df0543dfee28
https://github.com/ManageIQ/linux_admin/blob/6c91b6ea7ccfcbcae617d24618c6df0543dfee28/lib/linux_admin/network_interface/network_interface_rh.rb#L132-L139
train
ManageIQ/linux_admin
lib/linux_admin/network_interface/network_interface_rh.rb
LinuxAdmin.NetworkInterfaceRH.apply_static6
def apply_static6(ip, prefix, gw, dns, search = nil) self.address6 = "#{ip}/#{prefix}" self.gateway6 = gw self.dns = dns self.search_order = search if search save end
ruby
def apply_static6(ip, prefix, gw, dns, search = nil) self.address6 = "#{ip}/#{prefix}" self.gateway6 = gw self.dns = dns self.search_order = search if search save end
[ "def", "apply_static6", "(", "ip", ",", "prefix", ",", "gw", ",", "dns", ",", "search", "=", "nil", ")", "self", ".", "address6", "=", "\"#{ip}/#{prefix}\"", "self", ".", "gateway6", "=", "gw", "self", ".", "dns", "=", "dns", "self", ".", "search_order", "=", "search", "if", "search", "save", "end" ]
Applies the given static IPv6 network configuration to the interface @param ip [String] IPv6 address @param prefix [Number] prefix length for IPv6 address @param gw [String] gateway address @param dns [Array<String>] list of dns servers @param search [Array<String>] list of search domains @return [Boolean] true on success, false otherwise @raise ArgumentError if an IP is not formatted properly or interface does not start
[ "Applies", "the", "given", "static", "IPv6", "network", "configuration", "to", "the", "interface" ]
6c91b6ea7ccfcbcae617d24618c6df0543dfee28
https://github.com/ManageIQ/linux_admin/blob/6c91b6ea7ccfcbcae617d24618c6df0543dfee28/lib/linux_admin/network_interface/network_interface_rh.rb#L150-L156
train
locomotivecms/custom_fields
lib/custom_fields/source.rb
CustomFields.Source.klass_with_custom_fields
def klass_with_custom_fields(name) # Rails.logger.debug "[CustomFields] klass_with_custom_fields #{self.send(name).metadata.klass} / #{self.send(name).metadata[:old_klass]}" if defined?(Rails) # DEBUG recipe = self.custom_fields_recipe_for(name) _metadata = self.send(name).relation_metadata target = _metadata[:original_klass] || _metadata.klass # avoid to use an already enhanced klass target.klass_with_custom_fields(recipe) end
ruby
def klass_with_custom_fields(name) # Rails.logger.debug "[CustomFields] klass_with_custom_fields #{self.send(name).metadata.klass} / #{self.send(name).metadata[:old_klass]}" if defined?(Rails) # DEBUG recipe = self.custom_fields_recipe_for(name) _metadata = self.send(name).relation_metadata target = _metadata[:original_klass] || _metadata.klass # avoid to use an already enhanced klass target.klass_with_custom_fields(recipe) end
[ "def", "klass_with_custom_fields", "(", "name", ")", "recipe", "=", "self", ".", "custom_fields_recipe_for", "(", "name", ")", "_metadata", "=", "self", ".", "send", "(", "name", ")", ".", "relation_metadata", "target", "=", "_metadata", "[", ":original_klass", "]", "||", "_metadata", ".", "klass", "target", ".", "klass_with_custom_fields", "(", "recipe", ")", "end" ]
Returns the class enhanced by the custom fields. Be careful, call this method only if the source class has been saved with success. @param [ String, Symbol ] name The name of the relation. @return [ Class ] The modified class.
[ "Returns", "the", "class", "enhanced", "by", "the", "custom", "fields", ".", "Be", "careful", "call", "this", "method", "only", "if", "the", "source", "class", "has", "been", "saved", "with", "success", "." ]
251b1b93472506f5eb255d60d92f65bcfc354095
https://github.com/locomotivecms/custom_fields/blob/251b1b93472506f5eb255d60d92f65bcfc354095/lib/custom_fields/source.rb#L36-L42
train
locomotivecms/custom_fields
lib/custom_fields/source.rb
CustomFields.Source.collect_custom_fields_diff
def collect_custom_fields_diff(name, fields) # puts "==> collect_custom_fields_diff for #{name}, #{fields.size}" # DEBUG memo = self.initialize_custom_fields_diff(name) fields.map do |field| field.collect_diff(memo) end # collect fields with a modified localized field fields.each do |field| if field.localized_changed? && field.persisted? self._custom_field_localize_diff[name] << { field: field.name, localized: field.localized? } end end end
ruby
def collect_custom_fields_diff(name, fields) # puts "==> collect_custom_fields_diff for #{name}, #{fields.size}" # DEBUG memo = self.initialize_custom_fields_diff(name) fields.map do |field| field.collect_diff(memo) end # collect fields with a modified localized field fields.each do |field| if field.localized_changed? && field.persisted? self._custom_field_localize_diff[name] << { field: field.name, localized: field.localized? } end end end
[ "def", "collect_custom_fields_diff", "(", "name", ",", "fields", ")", "memo", "=", "self", ".", "initialize_custom_fields_diff", "(", "name", ")", "fields", ".", "map", "do", "|", "field", "|", "field", ".", "collect_diff", "(", "memo", ")", "end", "fields", ".", "each", "do", "|", "field", "|", "if", "field", ".", "localized_changed?", "&&", "field", ".", "persisted?", "self", ".", "_custom_field_localize_diff", "[", "name", "]", "<<", "{", "field", ":", "field", ".", "name", ",", "localized", ":", "field", ".", "localized?", "}", "end", "end", "end" ]
Collects all the modifications of the custom fields @param [ String, Symbol ] name The name of the relation. @return [ Array ] An array of hashes storing the modifications
[ "Collects", "all", "the", "modifications", "of", "the", "custom", "fields" ]
251b1b93472506f5eb255d60d92f65bcfc354095
https://github.com/locomotivecms/custom_fields/blob/251b1b93472506f5eb255d60d92f65bcfc354095/lib/custom_fields/source.rb#L145-L160
train
locomotivecms/custom_fields
lib/custom_fields/source.rb
CustomFields.Source.apply_custom_fields_diff
def apply_custom_fields_diff(name) # puts "==> apply_custom_fields_recipes for #{name}, #{self._custom_fields_diff[name].inspect}" # DEBUG operations = self._custom_fields_diff[name] operations['$set'].merge!({ 'custom_fields_recipe.version' => self.custom_fields_version(name) }) collection, selector = self.send(name).collection, self.send(name).criteria.selector # http://docs.mongodb.org/manual/reference/method/db.collection.update/#update-parameter # The <update> document must contain only update operator expressions. %w(set unset rename).each do |operation_name| _fields = operations.delete("$#{operation_name}") next if _fields.empty? _operation = { "$#{operation_name}" => _fields } collection.find(selector).update_many _operation end end
ruby
def apply_custom_fields_diff(name) # puts "==> apply_custom_fields_recipes for #{name}, #{self._custom_fields_diff[name].inspect}" # DEBUG operations = self._custom_fields_diff[name] operations['$set'].merge!({ 'custom_fields_recipe.version' => self.custom_fields_version(name) }) collection, selector = self.send(name).collection, self.send(name).criteria.selector # http://docs.mongodb.org/manual/reference/method/db.collection.update/#update-parameter # The <update> document must contain only update operator expressions. %w(set unset rename).each do |operation_name| _fields = operations.delete("$#{operation_name}") next if _fields.empty? _operation = { "$#{operation_name}" => _fields } collection.find(selector).update_many _operation end end
[ "def", "apply_custom_fields_diff", "(", "name", ")", "operations", "=", "self", ".", "_custom_fields_diff", "[", "name", "]", "operations", "[", "'$set'", "]", ".", "merge!", "(", "{", "'custom_fields_recipe.version'", "=>", "self", ".", "custom_fields_version", "(", "name", ")", "}", ")", "collection", ",", "selector", "=", "self", ".", "send", "(", "name", ")", ".", "collection", ",", "self", ".", "send", "(", "name", ")", ".", "criteria", ".", "selector", "%w(", "set", "unset", "rename", ")", ".", "each", "do", "|", "operation_name", "|", "_fields", "=", "operations", ".", "delete", "(", "\"$#{operation_name}\"", ")", "next", "if", "_fields", ".", "empty?", "_operation", "=", "{", "\"$#{operation_name}\"", "=>", "_fields", "}", "collection", ".", "find", "(", "selector", ")", ".", "update_many", "_operation", "end", "end" ]
Apply the modifications collected from the custom fields by updating all the documents of the relation. The update uses the power of mongodb to make it fully optimized. @param [ String, Symbol ] name The name of the relation.
[ "Apply", "the", "modifications", "collected", "from", "the", "custom", "fields", "by", "updating", "all", "the", "documents", "of", "the", "relation", ".", "The", "update", "uses", "the", "power", "of", "mongodb", "to", "make", "it", "fully", "optimized", "." ]
251b1b93472506f5eb255d60d92f65bcfc354095
https://github.com/locomotivecms/custom_fields/blob/251b1b93472506f5eb255d60d92f65bcfc354095/lib/custom_fields/source.rb#L168-L185
train
locomotivecms/custom_fields
lib/custom_fields/source.rb
CustomFields.Source.apply_custom_fields_localize_diff
def apply_custom_fields_localize_diff(name) return if self._custom_field_localize_diff[name].empty? self.send(name).all.each do |record| updates = {} # puts "[apply_custom_fields_localize_diff] processing: record #{record._id} / #{self._custom_field_localize_diff[name].inspect}" # DEBUG self._custom_field_localize_diff[name].each do |changes| if changes[:localized] value = record.read_attribute(changes[:field].to_sym) updates[changes[:field]] = { Mongoid::Fields::I18n.locale.to_s => value } else # the other way around value = record.read_attribute(changes[:field].to_sym) next if value.nil? updates[changes[:field]] = value[Mongoid::Fields::I18n.locale.to_s] end end next if updates.empty? collection = self.send(name).collection collection.find(record.atomic_selector).update_one({ '$set' => updates }) end end
ruby
def apply_custom_fields_localize_diff(name) return if self._custom_field_localize_diff[name].empty? self.send(name).all.each do |record| updates = {} # puts "[apply_custom_fields_localize_diff] processing: record #{record._id} / #{self._custom_field_localize_diff[name].inspect}" # DEBUG self._custom_field_localize_diff[name].each do |changes| if changes[:localized] value = record.read_attribute(changes[:field].to_sym) updates[changes[:field]] = { Mongoid::Fields::I18n.locale.to_s => value } else # the other way around value = record.read_attribute(changes[:field].to_sym) next if value.nil? updates[changes[:field]] = value[Mongoid::Fields::I18n.locale.to_s] end end next if updates.empty? collection = self.send(name).collection collection.find(record.atomic_selector).update_one({ '$set' => updates }) end end
[ "def", "apply_custom_fields_localize_diff", "(", "name", ")", "return", "if", "self", ".", "_custom_field_localize_diff", "[", "name", "]", ".", "empty?", "self", ".", "send", "(", "name", ")", ".", "all", ".", "each", "do", "|", "record", "|", "updates", "=", "{", "}", "self", ".", "_custom_field_localize_diff", "[", "name", "]", ".", "each", "do", "|", "changes", "|", "if", "changes", "[", ":localized", "]", "value", "=", "record", ".", "read_attribute", "(", "changes", "[", ":field", "]", ".", "to_sym", ")", "updates", "[", "changes", "[", ":field", "]", "]", "=", "{", "Mongoid", "::", "Fields", "::", "I18n", ".", "locale", ".", "to_s", "=>", "value", "}", "else", "value", "=", "record", ".", "read_attribute", "(", "changes", "[", ":field", "]", ".", "to_sym", ")", "next", "if", "value", ".", "nil?", "updates", "[", "changes", "[", ":field", "]", "]", "=", "value", "[", "Mongoid", "::", "Fields", "::", "I18n", ".", "locale", ".", "to_s", "]", "end", "end", "next", "if", "updates", ".", "empty?", "collection", "=", "self", ".", "send", "(", "name", ")", ".", "collection", "collection", ".", "find", "(", "record", ".", "atomic_selector", ")", ".", "update_one", "(", "{", "'$set'", "=>", "updates", "}", ")", "end", "end" ]
If the localized attribute has been changed in at least one of the custom fields, we have to upgrade all the records enhanced by custom_fields in order to make the values consistent with the mongoid localize option. Ex: post.attributes[:name] = 'Hello world' => post.attributes[:name] = { en: 'Hello world' } @param [ String, Symbol ] name The name of the relation.
[ "If", "the", "localized", "attribute", "has", "been", "changed", "in", "at", "least", "one", "of", "the", "custom", "fields", "we", "have", "to", "upgrade", "all", "the", "records", "enhanced", "by", "custom_fields", "in", "order", "to", "make", "the", "values", "consistent", "with", "the", "mongoid", "localize", "option", "." ]
251b1b93472506f5eb255d60d92f65bcfc354095
https://github.com/locomotivecms/custom_fields/blob/251b1b93472506f5eb255d60d92f65bcfc354095/lib/custom_fields/source.rb#L195-L219
train
locomotivecms/custom_fields
lib/custom_fields/target_helpers.rb
CustomFields.TargetHelpers.custom_fields_methods
def custom_fields_methods(&filter) self.custom_fields_recipe['rules'].map do |rule| method = self.custom_fields_getters_for rule['name'], rule['type'] if block_given? filter.call(rule) ? method : nil else method end end.compact.flatten end
ruby
def custom_fields_methods(&filter) self.custom_fields_recipe['rules'].map do |rule| method = self.custom_fields_getters_for rule['name'], rule['type'] if block_given? filter.call(rule) ? method : nil else method end end.compact.flatten end
[ "def", "custom_fields_methods", "(", "&", "filter", ")", "self", ".", "custom_fields_recipe", "[", "'rules'", "]", ".", "map", "do", "|", "rule", "|", "method", "=", "self", ".", "custom_fields_getters_for", "rule", "[", "'name'", "]", ",", "rule", "[", "'type'", "]", "if", "block_given?", "filter", ".", "call", "(", "rule", ")", "?", "method", ":", "nil", "else", "method", "end", "end", ".", "compact", ".", "flatten", "end" ]
Return the list of the getters dynamically based on the custom_fields recipe in order to get the formatted values of the custom fields. If a block is passed, then the list will be filtered accordingly with the following logic. If the block is evaluated as true, then the method will be kept in the list, otherwise it will be removed. @example # keep all the methods except for the field named 'foo' project.custom_fields_methods do |rule| rule['name] != 'foo' end @return [ List ] a list of method names (string)
[ "Return", "the", "list", "of", "the", "getters", "dynamically", "based", "on", "the", "custom_fields", "recipe", "in", "order", "to", "get", "the", "formatted", "values", "of", "the", "custom", "fields", ".", "If", "a", "block", "is", "passed", "then", "the", "list", "will", "be", "filtered", "accordingly", "with", "the", "following", "logic", ".", "If", "the", "block", "is", "evaluated", "as", "true", "then", "the", "method", "will", "be", "kept", "in", "the", "list", "otherwise", "it", "will", "be", "removed", "." ]
251b1b93472506f5eb255d60d92f65bcfc354095
https://github.com/locomotivecms/custom_fields/blob/251b1b93472506f5eb255d60d92f65bcfc354095/lib/custom_fields/target_helpers.rb#L20-L29
train
locomotivecms/custom_fields
lib/custom_fields/target_helpers.rb
CustomFields.TargetHelpers.custom_fields_safe_setters
def custom_fields_safe_setters self.custom_fields_recipe['rules'].map do |rule| case rule['type'].to_sym when :date, :date_time, :money then "formatted_#{rule['name']}" when :file then [rule['name'], "remove_#{rule['name']}", "remote_#{rule['name']}_url"] when :select, :belongs_to then ["#{rule['name']}_id", "position_in_#{rule['name']}"] when :has_many, :many_to_many then nil else rule['name'] end end.compact.flatten end
ruby
def custom_fields_safe_setters self.custom_fields_recipe['rules'].map do |rule| case rule['type'].to_sym when :date, :date_time, :money then "formatted_#{rule['name']}" when :file then [rule['name'], "remove_#{rule['name']}", "remote_#{rule['name']}_url"] when :select, :belongs_to then ["#{rule['name']}_id", "position_in_#{rule['name']}"] when :has_many, :many_to_many then nil else rule['name'] end end.compact.flatten end
[ "def", "custom_fields_safe_setters", "self", ".", "custom_fields_recipe", "[", "'rules'", "]", ".", "map", "do", "|", "rule", "|", "case", "rule", "[", "'type'", "]", ".", "to_sym", "when", ":date", ",", ":date_time", ",", ":money", "then", "\"formatted_#{rule['name']}\"", "when", ":file", "then", "[", "rule", "[", "'name'", "]", ",", "\"remove_#{rule['name']}\"", ",", "\"remote_#{rule['name']}_url\"", "]", "when", ":select", ",", ":belongs_to", "then", "[", "\"#{rule['name']}_id\"", ",", "\"position_in_#{rule['name']}\"", "]", "when", ":has_many", ",", ":many_to_many", "then", "nil", "else", "rule", "[", "'name'", "]", "end", "end", ".", "compact", ".", "flatten", "end" ]
List all the setters that are used by the custom_fields in order to get updated thru a html form for instance. @return [ List ] a list of method names (string)
[ "List", "all", "the", "setters", "that", "are", "used", "by", "the", "custom_fields", "in", "order", "to", "get", "updated", "thru", "a", "html", "form", "for", "instance", "." ]
251b1b93472506f5eb255d60d92f65bcfc354095
https://github.com/locomotivecms/custom_fields/blob/251b1b93472506f5eb255d60d92f65bcfc354095/lib/custom_fields/target_helpers.rb#L36-L47
train
locomotivecms/custom_fields
lib/custom_fields/target_helpers.rb
CustomFields.TargetHelpers.custom_fields_basic_attributes
def custom_fields_basic_attributes {}.tap do |hash| self.non_relationship_custom_fields.each do |rule| name, type = rule['name'], rule['type'].to_sym # method of the custom getter method_name = "#{type}_attribute_get" hash.merge!(self.class.send(method_name, self, name)) end end end
ruby
def custom_fields_basic_attributes {}.tap do |hash| self.non_relationship_custom_fields.each do |rule| name, type = rule['name'], rule['type'].to_sym # method of the custom getter method_name = "#{type}_attribute_get" hash.merge!(self.class.send(method_name, self, name)) end end end
[ "def", "custom_fields_basic_attributes", "{", "}", ".", "tap", "do", "|", "hash", "|", "self", ".", "non_relationship_custom_fields", ".", "each", "do", "|", "rule", "|", "name", ",", "type", "=", "rule", "[", "'name'", "]", ",", "rule", "[", "'type'", "]", ".", "to_sym", "method_name", "=", "\"#{type}_attribute_get\"", "hash", ".", "merge!", "(", "self", ".", "class", ".", "send", "(", "method_name", ",", "self", ",", "name", ")", ")", "end", "end", "end" ]
Build a hash for all the non-relationship fields meaning string, text, date, boolean, select, file types. This hash stores their name and their value. @return [ Hash ] Field name / formatted value
[ "Build", "a", "hash", "for", "all", "the", "non", "-", "relationship", "fields", "meaning", "string", "text", "date", "boolean", "select", "file", "types", ".", "This", "hash", "stores", "their", "name", "and", "their", "value", "." ]
251b1b93472506f5eb255d60d92f65bcfc354095
https://github.com/locomotivecms/custom_fields/blob/251b1b93472506f5eb255d60d92f65bcfc354095/lib/custom_fields/target_helpers.rb#L55-L66
train
locomotivecms/custom_fields
lib/custom_fields/target_helpers.rb
CustomFields.TargetHelpers.is_a_custom_field_many_relationship?
def is_a_custom_field_many_relationship?(name) rule = self.custom_fields_recipe['rules'].detect do |rule| rule['name'] == name && _custom_field_many_relationship?(rule['type']) end end
ruby
def is_a_custom_field_many_relationship?(name) rule = self.custom_fields_recipe['rules'].detect do |rule| rule['name'] == name && _custom_field_many_relationship?(rule['type']) end end
[ "def", "is_a_custom_field_many_relationship?", "(", "name", ")", "rule", "=", "self", ".", "custom_fields_recipe", "[", "'rules'", "]", ".", "detect", "do", "|", "rule", "|", "rule", "[", "'name'", "]", "==", "name", "&&", "_custom_field_many_relationship?", "(", "rule", "[", "'type'", "]", ")", "end", "end" ]
Check if the rule defined by the name is a "many" relationship kind. A "many" relationship includes "has_many" and "many_to_many" @param [ String ] name The name of the rule @return [ Boolean ] True if the rule is a "many" relationship kind.
[ "Check", "if", "the", "rule", "defined", "by", "the", "name", "is", "a", "many", "relationship", "kind", ".", "A", "many", "relationship", "includes", "has_many", "and", "many_to_many" ]
251b1b93472506f5eb255d60d92f65bcfc354095
https://github.com/locomotivecms/custom_fields/blob/251b1b93472506f5eb255d60d92f65bcfc354095/lib/custom_fields/target_helpers.rb#L91-L95
train
Instrumental/instrumental_agent-ruby
lib/instrumental/agent.rb
Instrumental.Agent.gauge
def gauge(metric, value, time = Time.now, count = 1) if valid?(metric, value, time, count) && send_command("gauge", metric, value, time.to_i, count.to_i) value else nil end rescue Exception => e report_exception(e) nil end
ruby
def gauge(metric, value, time = Time.now, count = 1) if valid?(metric, value, time, count) && send_command("gauge", metric, value, time.to_i, count.to_i) value else nil end rescue Exception => e report_exception(e) nil end
[ "def", "gauge", "(", "metric", ",", "value", ",", "time", "=", "Time", ".", "now", ",", "count", "=", "1", ")", "if", "valid?", "(", "metric", ",", "value", ",", "time", ",", "count", ")", "&&", "send_command", "(", "\"gauge\"", ",", "metric", ",", "value", ",", "time", ".", "to_i", ",", "count", ".", "to_i", ")", "value", "else", "nil", "end", "rescue", "Exception", "=>", "e", "report_exception", "(", "e", ")", "nil", "end" ]
Sets up a connection to the collector. Instrumental::Agent.new(API_KEY) Instrumental::Agent.new(API_KEY, :collector => 'hostname:port') Store a gauge for a metric, optionally at a specific time. agent.gauge('load', 1.23)
[ "Sets", "up", "a", "connection", "to", "the", "collector", "." ]
24c518299217b24fccfa6b01e7a659519554c7a1
https://github.com/Instrumental/instrumental_agent-ruby/blob/24c518299217b24fccfa6b01e7a659519554c7a1/lib/instrumental/agent.rb#L94-L104
train
Instrumental/instrumental_agent-ruby
lib/instrumental/agent.rb
Instrumental.Agent.time
def time(metric, multiplier = 1) start = Time.now begin result = yield ensure finish = Time.now duration = finish - start gauge(metric, duration * multiplier, start) end result end
ruby
def time(metric, multiplier = 1) start = Time.now begin result = yield ensure finish = Time.now duration = finish - start gauge(metric, duration * multiplier, start) end result end
[ "def", "time", "(", "metric", ",", "multiplier", "=", "1", ")", "start", "=", "Time", ".", "now", "begin", "result", "=", "yield", "ensure", "finish", "=", "Time", ".", "now", "duration", "=", "finish", "-", "start", "gauge", "(", "metric", ",", "duration", "*", "multiplier", ",", "start", ")", "end", "result", "end" ]
Store the duration of a block in a metric. multiplier can be used to scale the duration to desired unit or change the duration in some meaningful way. agent.time('response_time') do # potentially slow stuff end agent.time('response_time_in_ms', 1000) do # potentially slow stuff end ids = [1, 2, 3] agent.time('find_time_per_post', 1 / ids.size.to_f) do Post.find(ids) end
[ "Store", "the", "duration", "of", "a", "block", "in", "a", "metric", ".", "multiplier", "can", "be", "used", "to", "scale", "the", "duration", "to", "desired", "unit", "or", "change", "the", "duration", "in", "some", "meaningful", "way", "." ]
24c518299217b24fccfa6b01e7a659519554c7a1
https://github.com/Instrumental/instrumental_agent-ruby/blob/24c518299217b24fccfa6b01e7a659519554c7a1/lib/instrumental/agent.rb#L122-L132
train
Instrumental/instrumental_agent-ruby
lib/instrumental/agent.rb
Instrumental.Agent.cleanup
def cleanup if running? logger.info "Cleaning up agent, queue size: #{@queue.size}, thread running: #{@thread.alive?}" @allow_reconnect = false if @queue.size > 0 queue_message('exit') begin with_timeout(EXIT_FLUSH_TIMEOUT) { @thread.join } rescue Timeout::Error if @queue.size > 0 logger.error "Timed out working agent thread on exit, dropping #{@queue.size} metrics" else logger.error "Timed out Instrumental Agent, exiting" end end end end end
ruby
def cleanup if running? logger.info "Cleaning up agent, queue size: #{@queue.size}, thread running: #{@thread.alive?}" @allow_reconnect = false if @queue.size > 0 queue_message('exit') begin with_timeout(EXIT_FLUSH_TIMEOUT) { @thread.join } rescue Timeout::Error if @queue.size > 0 logger.error "Timed out working agent thread on exit, dropping #{@queue.size} metrics" else logger.error "Timed out Instrumental Agent, exiting" end end end end end
[ "def", "cleanup", "if", "running?", "logger", ".", "info", "\"Cleaning up agent, queue size: #{@queue.size}, thread running: #{@thread.alive?}\"", "@allow_reconnect", "=", "false", "if", "@queue", ".", "size", ">", "0", "queue_message", "(", "'exit'", ")", "begin", "with_timeout", "(", "EXIT_FLUSH_TIMEOUT", ")", "{", "@thread", ".", "join", "}", "rescue", "Timeout", "::", "Error", "if", "@queue", ".", "size", ">", "0", "logger", ".", "error", "\"Timed out working agent thread on exit, dropping #{@queue.size} metrics\"", "else", "logger", ".", "error", "\"Timed out Instrumental Agent, exiting\"", "end", "end", "end", "end", "end" ]
Called when a process is exiting to give it some extra time to push events to the service. An at_exit handler is automatically registered for this method, but can be called manually in cases where at_exit is bypassed like Resque workers.
[ "Called", "when", "a", "process", "is", "exiting", "to", "give", "it", "some", "extra", "time", "to", "push", "events", "to", "the", "service", ".", "An", "at_exit", "handler", "is", "automatically", "registered", "for", "this", "method", "but", "can", "be", "called", "manually", "in", "cases", "where", "at_exit", "is", "bypassed", "like", "Resque", "workers", "." ]
24c518299217b24fccfa6b01e7a659519554c7a1
https://github.com/Instrumental/instrumental_agent-ruby/blob/24c518299217b24fccfa6b01e7a659519554c7a1/lib/instrumental/agent.rb#L222-L239
train
cryptape/ruby-bitcoin-secp256k1
lib/secp256k1/ecdsa.rb
Secp256k1.ECDSA.ecdsa_signature_normalize
def ecdsa_signature_normalize(raw_sig, check_only: false) sigout = check_only ? nil : C::ECDSASignature.new.pointer res = C.secp256k1_ecdsa_signature_normalize(@ctx, sigout, raw_sig) [res == 1, sigout] end
ruby
def ecdsa_signature_normalize(raw_sig, check_only: false) sigout = check_only ? nil : C::ECDSASignature.new.pointer res = C.secp256k1_ecdsa_signature_normalize(@ctx, sigout, raw_sig) [res == 1, sigout] end
[ "def", "ecdsa_signature_normalize", "(", "raw_sig", ",", "check_only", ":", "false", ")", "sigout", "=", "check_only", "?", "nil", ":", "C", "::", "ECDSASignature", ".", "new", ".", "pointer", "res", "=", "C", ".", "secp256k1_ecdsa_signature_normalize", "(", "@ctx", ",", "sigout", ",", "raw_sig", ")", "[", "res", "==", "1", ",", "sigout", "]", "end" ]
Check and optionally convert a signature to a normalized lower-S form. If check_only is `true` then the normalized signature is not returned. This function always return a tuple containing a boolean (`true` if not previously normalized or `false` if signature was already normalized), and the normalized signature. When check_only is `true`, the normalized signature returned is always `nil`.
[ "Check", "and", "optionally", "convert", "a", "signature", "to", "a", "normalized", "lower", "-", "S", "form", ".", "If", "check_only", "is", "true", "then", "the", "normalized", "signature", "is", "not", "returned", "." ]
ae975c29648246aa0662cc9d7c6f2fc7a83a0bed
https://github.com/cryptape/ruby-bitcoin-secp256k1/blob/ae975c29648246aa0662cc9d7c6f2fc7a83a0bed/lib/secp256k1/ecdsa.rb#L56-L60
train
cryptape/ruby-bitcoin-secp256k1
lib/secp256k1/key.rb
Secp256k1.PublicKey.combine
def combine(pubkeys) raise ArgumentError, 'must give at least 1 pubkey' if pubkeys.empty? outpub = FFI::Pubkey.new.pointer #pubkeys.each {|item| } res = C.secp256k1_ec_pubkey_combine(@ctx, outpub, pubkeys, pubkeys.size) raise AssertError, 'failed to combine public keys' unless res == 1 @public_key = outpub outpub end
ruby
def combine(pubkeys) raise ArgumentError, 'must give at least 1 pubkey' if pubkeys.empty? outpub = FFI::Pubkey.new.pointer #pubkeys.each {|item| } res = C.secp256k1_ec_pubkey_combine(@ctx, outpub, pubkeys, pubkeys.size) raise AssertError, 'failed to combine public keys' unless res == 1 @public_key = outpub outpub end
[ "def", "combine", "(", "pubkeys", ")", "raise", "ArgumentError", ",", "'must give at least 1 pubkey'", "if", "pubkeys", ".", "empty?", "outpub", "=", "FFI", "::", "Pubkey", ".", "new", ".", "pointer", "res", "=", "C", ".", "secp256k1_ec_pubkey_combine", "(", "@ctx", ",", "outpub", ",", "pubkeys", ",", "pubkeys", ".", "size", ")", "raise", "AssertError", ",", "'failed to combine public keys'", "unless", "res", "==", "1", "@public_key", "=", "outpub", "outpub", "end" ]
Add a number of public keys together.
[ "Add", "a", "number", "of", "public", "keys", "together", "." ]
ae975c29648246aa0662cc9d7c6f2fc7a83a0bed
https://github.com/cryptape/ruby-bitcoin-secp256k1/blob/ae975c29648246aa0662cc9d7c6f2fc7a83a0bed/lib/secp256k1/key.rb#L72-L83
train
hipchat/hipchat-rb
lib/hipchat/room.rb
HipChat.Room.get_room
def get_room response = self.class.get(@api.get_room_config[:url], :query => {:auth_token => @token }.merge(@api.get_room_config[:query_params]), :headers => @api.headers ) ErrorHandler.response_code_to_exception_for :room, room_id, response response.parsed_response end
ruby
def get_room response = self.class.get(@api.get_room_config[:url], :query => {:auth_token => @token }.merge(@api.get_room_config[:query_params]), :headers => @api.headers ) ErrorHandler.response_code_to_exception_for :room, room_id, response response.parsed_response end
[ "def", "get_room", "response", "=", "self", ".", "class", ".", "get", "(", "@api", ".", "get_room_config", "[", ":url", "]", ",", ":query", "=>", "{", ":auth_token", "=>", "@token", "}", ".", "merge", "(", "@api", ".", "get_room_config", "[", ":query_params", "]", ")", ",", ":headers", "=>", "@api", ".", "headers", ")", "ErrorHandler", ".", "response_code_to_exception_for", ":room", ",", "room_id", ",", "response", "response", ".", "parsed_response", "end" ]
Retrieve data for this room
[ "Retrieve", "data", "for", "this", "room" ]
523578ecb7fe68cde347225c210dfd3bc1a64c48
https://github.com/hipchat/hipchat-rb/blob/523578ecb7fe68cde347225c210dfd3bc1a64c48/lib/hipchat/room.rb#L20-L28
train
hipchat/hipchat-rb
lib/hipchat/room.rb
HipChat.Room.update_room
def update_room(options = {}) merged_options = { :privacy => 'public', :is_archived => false, :is_guest_accessible => false }.merge symbolize(options) response = self.class.send(@api.topic_config[:method], @api.update_room_config[:url], :query => { :auth_token => @token }, :body => { :name => merged_options[:name], :topic => merged_options[:topic], :privacy => merged_options[:privacy], :is_archived => @api.bool_val(merged_options[:is_archived]), :is_guest_accessible => @api.bool_val(merged_options[:is_guest_accessible]), :owner => merged_options[:owner] }.to_json, :headers => @api.headers) ErrorHandler.response_code_to_exception_for :room, room_id, response true end
ruby
def update_room(options = {}) merged_options = { :privacy => 'public', :is_archived => false, :is_guest_accessible => false }.merge symbolize(options) response = self.class.send(@api.topic_config[:method], @api.update_room_config[:url], :query => { :auth_token => @token }, :body => { :name => merged_options[:name], :topic => merged_options[:topic], :privacy => merged_options[:privacy], :is_archived => @api.bool_val(merged_options[:is_archived]), :is_guest_accessible => @api.bool_val(merged_options[:is_guest_accessible]), :owner => merged_options[:owner] }.to_json, :headers => @api.headers) ErrorHandler.response_code_to_exception_for :room, room_id, response true end
[ "def", "update_room", "(", "options", "=", "{", "}", ")", "merged_options", "=", "{", ":privacy", "=>", "'public'", ",", ":is_archived", "=>", "false", ",", ":is_guest_accessible", "=>", "false", "}", ".", "merge", "symbolize", "(", "options", ")", "response", "=", "self", ".", "class", ".", "send", "(", "@api", ".", "topic_config", "[", ":method", "]", ",", "@api", ".", "update_room_config", "[", ":url", "]", ",", ":query", "=>", "{", ":auth_token", "=>", "@token", "}", ",", ":body", "=>", "{", ":name", "=>", "merged_options", "[", ":name", "]", ",", ":topic", "=>", "merged_options", "[", ":topic", "]", ",", ":privacy", "=>", "merged_options", "[", ":privacy", "]", ",", ":is_archived", "=>", "@api", ".", "bool_val", "(", "merged_options", "[", ":is_archived", "]", ")", ",", ":is_guest_accessible", "=>", "@api", ".", "bool_val", "(", "merged_options", "[", ":is_guest_accessible", "]", ")", ",", ":owner", "=>", "merged_options", "[", ":owner", "]", "}", ".", "to_json", ",", ":headers", "=>", "@api", ".", "headers", ")", "ErrorHandler", ".", "response_code_to_exception_for", ":room", ",", "room_id", ",", "response", "true", "end" ]
Update a room
[ "Update", "a", "room" ]
523578ecb7fe68cde347225c210dfd3bc1a64c48
https://github.com/hipchat/hipchat-rb/blob/523578ecb7fe68cde347225c210dfd3bc1a64c48/lib/hipchat/room.rb#L31-L52
train
hipchat/hipchat-rb
lib/hipchat/room.rb
HipChat.Room.delete_room
def delete_room response = self.class.send(@api.delete_room_config[:method], @api.delete_room_config[:url], :query => {:auth_token => @token }.merge(@api.get_room_config[:query_params]), :headers => @api.headers) ErrorHandler.response_code_to_exception_for :room, room_id, response true end
ruby
def delete_room response = self.class.send(@api.delete_room_config[:method], @api.delete_room_config[:url], :query => {:auth_token => @token }.merge(@api.get_room_config[:query_params]), :headers => @api.headers) ErrorHandler.response_code_to_exception_for :room, room_id, response true end
[ "def", "delete_room", "response", "=", "self", ".", "class", ".", "send", "(", "@api", ".", "delete_room_config", "[", ":method", "]", ",", "@api", ".", "delete_room_config", "[", ":url", "]", ",", ":query", "=>", "{", ":auth_token", "=>", "@token", "}", ".", "merge", "(", "@api", ".", "get_room_config", "[", ":query_params", "]", ")", ",", ":headers", "=>", "@api", ".", "headers", ")", "ErrorHandler", ".", "response_code_to_exception_for", ":room", ",", "room_id", ",", "response", "true", "end" ]
Delete a room
[ "Delete", "a", "room" ]
523578ecb7fe68cde347225c210dfd3bc1a64c48
https://github.com/hipchat/hipchat-rb/blob/523578ecb7fe68cde347225c210dfd3bc1a64c48/lib/hipchat/room.rb#L55-L61
train
hipchat/hipchat-rb
lib/hipchat/room.rb
HipChat.Room.invite
def invite(user, reason='') response = self.class.post(@api.invite_config[:url]+"/#{user}", :query => { :auth_token => @token }, :body => { :reason => reason }.to_json, :headers => @api.headers) ErrorHandler.response_code_to_exception_for :room, room_id, response true end
ruby
def invite(user, reason='') response = self.class.post(@api.invite_config[:url]+"/#{user}", :query => { :auth_token => @token }, :body => { :reason => reason }.to_json, :headers => @api.headers) ErrorHandler.response_code_to_exception_for :room, room_id, response true end
[ "def", "invite", "(", "user", ",", "reason", "=", "''", ")", "response", "=", "self", ".", "class", ".", "post", "(", "@api", ".", "invite_config", "[", ":url", "]", "+", "\"/#{user}\"", ",", ":query", "=>", "{", ":auth_token", "=>", "@token", "}", ",", ":body", "=>", "{", ":reason", "=>", "reason", "}", ".", "to_json", ",", ":headers", "=>", "@api", ".", "headers", ")", "ErrorHandler", ".", "response_code_to_exception_for", ":room", ",", "room_id", ",", "response", "true", "end" ]
Invite user to this room
[ "Invite", "user", "to", "this", "room" ]
523578ecb7fe68cde347225c210dfd3bc1a64c48
https://github.com/hipchat/hipchat-rb/blob/523578ecb7fe68cde347225c210dfd3bc1a64c48/lib/hipchat/room.rb#L64-L74
train
hipchat/hipchat-rb
lib/hipchat/room.rb
HipChat.Room.add_member
def add_member(user, room_roles=['room_member']) response = self.class.put(@api.member_config[:url]+"/#{user}", :query => { :auth_token => @token }, :body => { :room_roles => room_roles }.to_json, :headers => @api.headers) ErrorHandler.response_code_to_exception_for :room, room_id, response true end
ruby
def add_member(user, room_roles=['room_member']) response = self.class.put(@api.member_config[:url]+"/#{user}", :query => { :auth_token => @token }, :body => { :room_roles => room_roles }.to_json, :headers => @api.headers) ErrorHandler.response_code_to_exception_for :room, room_id, response true end
[ "def", "add_member", "(", "user", ",", "room_roles", "=", "[", "'room_member'", "]", ")", "response", "=", "self", ".", "class", ".", "put", "(", "@api", ".", "member_config", "[", ":url", "]", "+", "\"/#{user}\"", ",", ":query", "=>", "{", ":auth_token", "=>", "@token", "}", ",", ":body", "=>", "{", ":room_roles", "=>", "room_roles", "}", ".", "to_json", ",", ":headers", "=>", "@api", ".", "headers", ")", "ErrorHandler", ".", "response_code_to_exception_for", ":room", ",", "room_id", ",", "response", "true", "end" ]
Add member to this room
[ "Add", "member", "to", "this", "room" ]
523578ecb7fe68cde347225c210dfd3bc1a64c48
https://github.com/hipchat/hipchat-rb/blob/523578ecb7fe68cde347225c210dfd3bc1a64c48/lib/hipchat/room.rb#L77-L87
train
hipchat/hipchat-rb
lib/hipchat/room.rb
HipChat.Room.members
def members(options = {}) response = self.class.get(@api.member_config[:url], :query => { :auth_token => @token }.merge(options), :headers => @api.headers) ErrorHandler.response_code_to_exception_for :room, room_id, response wrap_users(response) end
ruby
def members(options = {}) response = self.class.get(@api.member_config[:url], :query => { :auth_token => @token }.merge(options), :headers => @api.headers) ErrorHandler.response_code_to_exception_for :room, room_id, response wrap_users(response) end
[ "def", "members", "(", "options", "=", "{", "}", ")", "response", "=", "self", ".", "class", ".", "get", "(", "@api", ".", "member_config", "[", ":url", "]", ",", ":query", "=>", "{", ":auth_token", "=>", "@token", "}", ".", "merge", "(", "options", ")", ",", ":headers", "=>", "@api", ".", "headers", ")", "ErrorHandler", ".", "response_code_to_exception_for", ":room", ",", "room_id", ",", "response", "wrap_users", "(", "response", ")", "end" ]
Get a list of members in this room This is all people who have been added a to a private room
[ "Get", "a", "list", "of", "members", "in", "this", "room", "This", "is", "all", "people", "who", "have", "been", "added", "a", "to", "a", "private", "room" ]
523578ecb7fe68cde347225c210dfd3bc1a64c48
https://github.com/hipchat/hipchat-rb/blob/523578ecb7fe68cde347225c210dfd3bc1a64c48/lib/hipchat/room.rb#L91-L98
train
hipchat/hipchat-rb
lib/hipchat/room.rb
HipChat.Room.participants
def participants(options = {}) response = self.class.get(@api.participant_config[:url], :query => { :auth_token => @token }.merge(options), :headers => @api.headers) ErrorHandler.response_code_to_exception_for :room, room_id, response wrap_users(response) end
ruby
def participants(options = {}) response = self.class.get(@api.participant_config[:url], :query => { :auth_token => @token }.merge(options), :headers => @api.headers) ErrorHandler.response_code_to_exception_for :room, room_id, response wrap_users(response) end
[ "def", "participants", "(", "options", "=", "{", "}", ")", "response", "=", "self", ".", "class", ".", "get", "(", "@api", ".", "participant_config", "[", ":url", "]", ",", ":query", "=>", "{", ":auth_token", "=>", "@token", "}", ".", "merge", "(", "options", ")", ",", ":headers", "=>", "@api", ".", "headers", ")", "ErrorHandler", ".", "response_code_to_exception_for", ":room", ",", "room_id", ",", "response", "wrap_users", "(", "response", ")", "end" ]
Get a list of participants in this room This is all people currently in the room
[ "Get", "a", "list", "of", "participants", "in", "this", "room", "This", "is", "all", "people", "currently", "in", "the", "room" ]
523578ecb7fe68cde347225c210dfd3bc1a64c48
https://github.com/hipchat/hipchat-rb/blob/523578ecb7fe68cde347225c210dfd3bc1a64c48/lib/hipchat/room.rb#L102-L109
train
hipchat/hipchat-rb
lib/hipchat/room.rb
HipChat.Room.send_message
def send_message(message) response = self.class.post(@api.send_message_config[:url], :query => { :auth_token => @token }, :body => { :room_id => room_id, :message => message, }.send(@api.send_config[:body_format]), :headers => @api.headers ) ErrorHandler.response_code_to_exception_for :room, room_id, response true end
ruby
def send_message(message) response = self.class.post(@api.send_message_config[:url], :query => { :auth_token => @token }, :body => { :room_id => room_id, :message => message, }.send(@api.send_config[:body_format]), :headers => @api.headers ) ErrorHandler.response_code_to_exception_for :room, room_id, response true end
[ "def", "send_message", "(", "message", ")", "response", "=", "self", ".", "class", ".", "post", "(", "@api", ".", "send_message_config", "[", ":url", "]", ",", ":query", "=>", "{", ":auth_token", "=>", "@token", "}", ",", ":body", "=>", "{", ":room_id", "=>", "room_id", ",", ":message", "=>", "message", ",", "}", ".", "send", "(", "@api", ".", "send_config", "[", ":body_format", "]", ")", ",", ":headers", "=>", "@api", ".", "headers", ")", "ErrorHandler", ".", "response_code_to_exception_for", ":room", ",", "room_id", ",", "response", "true", "end" ]
Send a message to this room. Usage: # Default send 'some message'
[ "Send", "a", "message", "to", "this", "room", "." ]
523578ecb7fe68cde347225c210dfd3bc1a64c48
https://github.com/hipchat/hipchat-rb/blob/523578ecb7fe68cde347225c210dfd3bc1a64c48/lib/hipchat/room.rb#L118-L130
train
hipchat/hipchat-rb
lib/hipchat/room.rb
HipChat.Room.send
def send(from, message, options_or_notify = {}) if from.length > 20 raise UsernameTooLong, "Username #{from} is `#{from.length} characters long. Limit is 20'" end if options_or_notify == true or options_or_notify == false warn 'DEPRECATED: Specify notify flag as an option (e.g., :notify => true)' options = { :notify => options_or_notify } else options = options_or_notify end merged_options = { :color => 'yellow', :notify => false, :message_format => 'html' }.merge options body = { :room_id => room_id, :from => from, :message => message, :message_format => merged_options[:message_format], :color => merged_options[:color], :card => merged_options[:card], :notify => @api.bool_val(merged_options[:notify]) }.delete_if { |_k, v| v.nil? } response = self.class.post(@api.send_config[:url], :query => { :auth_token => @token }, :body => body.send(@api.send_config[:body_format]), :headers => @api.headers ) ErrorHandler.response_code_to_exception_for :room, room_id, response true end
ruby
def send(from, message, options_or_notify = {}) if from.length > 20 raise UsernameTooLong, "Username #{from} is `#{from.length} characters long. Limit is 20'" end if options_or_notify == true or options_or_notify == false warn 'DEPRECATED: Specify notify flag as an option (e.g., :notify => true)' options = { :notify => options_or_notify } else options = options_or_notify end merged_options = { :color => 'yellow', :notify => false, :message_format => 'html' }.merge options body = { :room_id => room_id, :from => from, :message => message, :message_format => merged_options[:message_format], :color => merged_options[:color], :card => merged_options[:card], :notify => @api.bool_val(merged_options[:notify]) }.delete_if { |_k, v| v.nil? } response = self.class.post(@api.send_config[:url], :query => { :auth_token => @token }, :body => body.send(@api.send_config[:body_format]), :headers => @api.headers ) ErrorHandler.response_code_to_exception_for :room, room_id, response true end
[ "def", "send", "(", "from", ",", "message", ",", "options_or_notify", "=", "{", "}", ")", "if", "from", ".", "length", ">", "20", "raise", "UsernameTooLong", ",", "\"Username #{from} is `#{from.length} characters long. Limit is 20'\"", "end", "if", "options_or_notify", "==", "true", "or", "options_or_notify", "==", "false", "warn", "'DEPRECATED: Specify notify flag as an option (e.g., :notify => true)'", "options", "=", "{", ":notify", "=>", "options_or_notify", "}", "else", "options", "=", "options_or_notify", "end", "merged_options", "=", "{", ":color", "=>", "'yellow'", ",", ":notify", "=>", "false", ",", ":message_format", "=>", "'html'", "}", ".", "merge", "options", "body", "=", "{", ":room_id", "=>", "room_id", ",", ":from", "=>", "from", ",", ":message", "=>", "message", ",", ":message_format", "=>", "merged_options", "[", ":message_format", "]", ",", ":color", "=>", "merged_options", "[", ":color", "]", ",", ":card", "=>", "merged_options", "[", ":card", "]", ",", ":notify", "=>", "@api", ".", "bool_val", "(", "merged_options", "[", ":notify", "]", ")", "}", ".", "delete_if", "{", "|", "_k", ",", "v", "|", "v", ".", "nil?", "}", "response", "=", "self", ".", "class", ".", "post", "(", "@api", ".", "send_config", "[", ":url", "]", ",", ":query", "=>", "{", ":auth_token", "=>", "@token", "}", ",", ":body", "=>", "body", ".", "send", "(", "@api", ".", "send_config", "[", ":body_format", "]", ")", ",", ":headers", "=>", "@api", ".", "headers", ")", "ErrorHandler", ".", "response_code_to_exception_for", ":room", ",", "room_id", ",", "response", "true", "end" ]
Send a notification message to this room. Usage: # Default send 'nickname', 'some message' # Notify users and color the message red send 'nickname', 'some message', :notify => true, :color => 'red' # Notify users (deprecated) send 'nickname', 'some message', true Options: +color+:: "yellow", "red", "green", "purple", or "random" (default "yellow") +notify+:: true or false (default false)
[ "Send", "a", "notification", "message", "to", "this", "room", "." ]
523578ecb7fe68cde347225c210dfd3bc1a64c48
https://github.com/hipchat/hipchat-rb/blob/523578ecb7fe68cde347225c210dfd3bc1a64c48/lib/hipchat/room.rb#L152-L183
train
hipchat/hipchat-rb
lib/hipchat/room.rb
HipChat.Room.send_file
def send_file(from, message, file) if from.length > 20 raise UsernameTooLong, "Username #{from} is `#{from.length} characters long. Limit is 20'" end response = self.class.post(@api.send_file_config[:url], :query => { :auth_token => @token }, :body => file_body( { :room_id => room_id, :from => from, :message => message, }.send(@api.send_config[:body_format]), file ), :headers => file_body_headers(@api.headers) ) ErrorHandler.response_code_to_exception_for :room, room_id, response true end
ruby
def send_file(from, message, file) if from.length > 20 raise UsernameTooLong, "Username #{from} is `#{from.length} characters long. Limit is 20'" end response = self.class.post(@api.send_file_config[:url], :query => { :auth_token => @token }, :body => file_body( { :room_id => room_id, :from => from, :message => message, }.send(@api.send_config[:body_format]), file ), :headers => file_body_headers(@api.headers) ) ErrorHandler.response_code_to_exception_for :room, room_id, response true end
[ "def", "send_file", "(", "from", ",", "message", ",", "file", ")", "if", "from", ".", "length", ">", "20", "raise", "UsernameTooLong", ",", "\"Username #{from} is `#{from.length} characters long. Limit is 20'\"", "end", "response", "=", "self", ".", "class", ".", "post", "(", "@api", ".", "send_file_config", "[", ":url", "]", ",", ":query", "=>", "{", ":auth_token", "=>", "@token", "}", ",", ":body", "=>", "file_body", "(", "{", ":room_id", "=>", "room_id", ",", ":from", "=>", "from", ",", ":message", "=>", "message", ",", "}", ".", "send", "(", "@api", ".", "send_config", "[", ":body_format", "]", ")", ",", "file", ")", ",", ":headers", "=>", "file_body_headers", "(", "@api", ".", "headers", ")", ")", "ErrorHandler", ".", "response_code_to_exception_for", ":room", ",", "room_id", ",", "response", "true", "end" ]
Send a file to this room. Usage: # Default send_file 'nickname', 'some message', File.open("/path/to/file")
[ "Send", "a", "file", "to", "this", "room", "." ]
523578ecb7fe68cde347225c210dfd3bc1a64c48
https://github.com/hipchat/hipchat-rb/blob/523578ecb7fe68cde347225c210dfd3bc1a64c48/lib/hipchat/room.rb#L221-L240
train
hipchat/hipchat-rb
lib/hipchat/room.rb
HipChat.Room.topic
def topic(new_topic, options = {}) merged_options = { :from => 'API' }.merge options response = self.class.send(@api.topic_config[:method], @api.topic_config[:url], :query => { :auth_token => @token }, :body => { :room_id => room_id, :from => merged_options[:from], :topic => new_topic }.send(@api.topic_config[:body_format]), :headers => @api.headers ) ErrorHandler.response_code_to_exception_for :room, room_id, response true end
ruby
def topic(new_topic, options = {}) merged_options = { :from => 'API' }.merge options response = self.class.send(@api.topic_config[:method], @api.topic_config[:url], :query => { :auth_token => @token }, :body => { :room_id => room_id, :from => merged_options[:from], :topic => new_topic }.send(@api.topic_config[:body_format]), :headers => @api.headers ) ErrorHandler.response_code_to_exception_for :room, room_id, response true end
[ "def", "topic", "(", "new_topic", ",", "options", "=", "{", "}", ")", "merged_options", "=", "{", ":from", "=>", "'API'", "}", ".", "merge", "options", "response", "=", "self", ".", "class", ".", "send", "(", "@api", ".", "topic_config", "[", ":method", "]", ",", "@api", ".", "topic_config", "[", ":url", "]", ",", ":query", "=>", "{", ":auth_token", "=>", "@token", "}", ",", ":body", "=>", "{", ":room_id", "=>", "room_id", ",", ":from", "=>", "merged_options", "[", ":from", "]", ",", ":topic", "=>", "new_topic", "}", ".", "send", "(", "@api", ".", "topic_config", "[", ":body_format", "]", ")", ",", ":headers", "=>", "@api", ".", "headers", ")", "ErrorHandler", ".", "response_code_to_exception_for", ":room", ",", "room_id", ",", "response", "true", "end" ]
Change this room's topic Usage: # Default topic 'my awesome topic' Options: +from+:: the name of the person changing the topic (default "API")
[ "Change", "this", "room", "s", "topic" ]
523578ecb7fe68cde347225c210dfd3bc1a64c48
https://github.com/hipchat/hipchat-rb/blob/523578ecb7fe68cde347225c210dfd3bc1a64c48/lib/hipchat/room.rb#L253-L269
train
hipchat/hipchat-rb
lib/hipchat/room.rb
HipChat.Room.history
def history(options = {}) merged_options = { :date => 'recent', :timezone => 'UTC', :format => 'JSON', :'max-results' => 100, :'start-index' => 0, :'end-date' => nil }.merge options response = self.class.get(@api.history_config[:url], :query => { :room_id => room_id, :date => merged_options[:date], :timezone => merged_options[:timezone], :format => merged_options[:format], :'max-results' => merged_options[:'max-results'], :'start-index' => merged_options[:'start-index'], :'end-date' => merged_options[:'end-date'], :auth_token => @token }.reject!{|k,v| v.nil?}, :headers => @api.headers ) ErrorHandler.response_code_to_exception_for :room, room_id, response response.body end
ruby
def history(options = {}) merged_options = { :date => 'recent', :timezone => 'UTC', :format => 'JSON', :'max-results' => 100, :'start-index' => 0, :'end-date' => nil }.merge options response = self.class.get(@api.history_config[:url], :query => { :room_id => room_id, :date => merged_options[:date], :timezone => merged_options[:timezone], :format => merged_options[:format], :'max-results' => merged_options[:'max-results'], :'start-index' => merged_options[:'start-index'], :'end-date' => merged_options[:'end-date'], :auth_token => @token }.reject!{|k,v| v.nil?}, :headers => @api.headers ) ErrorHandler.response_code_to_exception_for :room, room_id, response response.body end
[ "def", "history", "(", "options", "=", "{", "}", ")", "merged_options", "=", "{", ":date", "=>", "'recent'", ",", ":timezone", "=>", "'UTC'", ",", ":format", "=>", "'JSON'", ",", ":'", "'", "=>", "100", ",", ":'", "'", "=>", "0", ",", ":'", "'", "=>", "nil", "}", ".", "merge", "options", "response", "=", "self", ".", "class", ".", "get", "(", "@api", ".", "history_config", "[", ":url", "]", ",", ":query", "=>", "{", ":room_id", "=>", "room_id", ",", ":date", "=>", "merged_options", "[", ":date", "]", ",", ":timezone", "=>", "merged_options", "[", ":timezone", "]", ",", ":format", "=>", "merged_options", "[", ":format", "]", ",", ":'", "'", "=>", "merged_options", "[", ":'", "'", "]", ",", ":'", "'", "=>", "merged_options", "[", ":'", "'", "]", ",", ":'", "'", "=>", "merged_options", "[", ":'", "'", "]", ",", ":auth_token", "=>", "@token", "}", ".", "reject!", "{", "|", "k", ",", "v", "|", "v", ".", "nil?", "}", ",", ":headers", "=>", "@api", ".", "headers", ")", "ErrorHandler", ".", "response_code_to_exception_for", ":room", ",", "room_id", ",", "response", "response", ".", "body", "end" ]
Pull this room's history Usage # Default Options +date+:: Whether to return a specific day (YYYY-MM-DD format) or recent (default "recent") +timezone+:: Your timezone. Supported timezones are at: https://www.hipchat.com/docs/api/timezones (default "UTC") +format+:: Format to retrieve the history in. Valid options are JSON and XML (default "JSON")
[ "Pull", "this", "room", "s", "history" ]
523578ecb7fe68cde347225c210dfd3bc1a64c48
https://github.com/hipchat/hipchat-rb/blob/523578ecb7fe68cde347225c210dfd3bc1a64c48/lib/hipchat/room.rb#L286-L313
train
hipchat/hipchat-rb
lib/hipchat/room.rb
HipChat.Room.statistics
def statistics(options = {}) response = self.class.get(@api.statistics_config[:url], :query => { :room_id => room_id, :date => options[:date], :timezone => options[:timezone], :format => options[:format], :auth_token => @token, }.reject!{|k,v| v.nil?}, :headers => @api.headers ) ErrorHandler.response_code_to_exception_for :room, room_id, response response.body end
ruby
def statistics(options = {}) response = self.class.get(@api.statistics_config[:url], :query => { :room_id => room_id, :date => options[:date], :timezone => options[:timezone], :format => options[:format], :auth_token => @token, }.reject!{|k,v| v.nil?}, :headers => @api.headers ) ErrorHandler.response_code_to_exception_for :room, room_id, response response.body end
[ "def", "statistics", "(", "options", "=", "{", "}", ")", "response", "=", "self", ".", "class", ".", "get", "(", "@api", ".", "statistics_config", "[", ":url", "]", ",", ":query", "=>", "{", ":room_id", "=>", "room_id", ",", ":date", "=>", "options", "[", ":date", "]", ",", ":timezone", "=>", "options", "[", ":timezone", "]", ",", ":format", "=>", "options", "[", ":format", "]", ",", ":auth_token", "=>", "@token", ",", "}", ".", "reject!", "{", "|", "k", ",", "v", "|", "v", ".", "nil?", "}", ",", ":headers", "=>", "@api", ".", "headers", ")", "ErrorHandler", ".", "response_code_to_exception_for", ":room", ",", "room_id", ",", "response", "response", ".", "body", "end" ]
Pull this room's statistics
[ "Pull", "this", "room", "s", "statistics" ]
523578ecb7fe68cde347225c210dfd3bc1a64c48
https://github.com/hipchat/hipchat-rb/blob/523578ecb7fe68cde347225c210dfd3bc1a64c48/lib/hipchat/room.rb#L316-L331
train
hipchat/hipchat-rb
lib/hipchat/room.rb
HipChat.Room.create_webhook
def create_webhook(url, event, options = {}) raise InvalidEvent.new("Invalid event: #{event}") unless %w(room_message room_notification room_exit room_enter room_topic_change room_archived room_deleted room_unarchived).include? event begin u = URI::parse(url) raise InvalidUrl.new("Invalid Scheme: #{url}") unless %w(http https).include? u.scheme rescue URI::InvalidURIError raise InvalidUrl.new("Invalid URL: #{url}") end merged_options = { :pattern => '', :name => '' }.merge options response = self.class.post(@api.webhook_config[:url], :query => { :auth_token => @token }, :body => {:url => url, :pattern => merged_options[:pattern], :event => event, :name => merged_options[:name]}.send(@api.send_config[:body_format]), :headers => @api.headers ) ErrorHandler.response_code_to_exception_for :room, room_id, response response.body end
ruby
def create_webhook(url, event, options = {}) raise InvalidEvent.new("Invalid event: #{event}") unless %w(room_message room_notification room_exit room_enter room_topic_change room_archived room_deleted room_unarchived).include? event begin u = URI::parse(url) raise InvalidUrl.new("Invalid Scheme: #{url}") unless %w(http https).include? u.scheme rescue URI::InvalidURIError raise InvalidUrl.new("Invalid URL: #{url}") end merged_options = { :pattern => '', :name => '' }.merge options response = self.class.post(@api.webhook_config[:url], :query => { :auth_token => @token }, :body => {:url => url, :pattern => merged_options[:pattern], :event => event, :name => merged_options[:name]}.send(@api.send_config[:body_format]), :headers => @api.headers ) ErrorHandler.response_code_to_exception_for :room, room_id, response response.body end
[ "def", "create_webhook", "(", "url", ",", "event", ",", "options", "=", "{", "}", ")", "raise", "InvalidEvent", ".", "new", "(", "\"Invalid event: #{event}\"", ")", "unless", "%w(", "room_message", "room_notification", "room_exit", "room_enter", "room_topic_change", "room_archived", "room_deleted", "room_unarchived", ")", ".", "include?", "event", "begin", "u", "=", "URI", "::", "parse", "(", "url", ")", "raise", "InvalidUrl", ".", "new", "(", "\"Invalid Scheme: #{url}\"", ")", "unless", "%w(", "http", "https", ")", ".", "include?", "u", ".", "scheme", "rescue", "URI", "::", "InvalidURIError", "raise", "InvalidUrl", ".", "new", "(", "\"Invalid URL: #{url}\"", ")", "end", "merged_options", "=", "{", ":pattern", "=>", "''", ",", ":name", "=>", "''", "}", ".", "merge", "options", "response", "=", "self", ".", "class", ".", "post", "(", "@api", ".", "webhook_config", "[", ":url", "]", ",", ":query", "=>", "{", ":auth_token", "=>", "@token", "}", ",", ":body", "=>", "{", ":url", "=>", "url", ",", ":pattern", "=>", "merged_options", "[", ":pattern", "]", ",", ":event", "=>", "event", ",", ":name", "=>", "merged_options", "[", ":name", "]", "}", ".", "send", "(", "@api", ".", "send_config", "[", ":body_format", "]", ")", ",", ":headers", "=>", "@api", ".", "headers", ")", "ErrorHandler", ".", "response_code_to_exception_for", ":room", ",", "room_id", ",", "response", "response", ".", "body", "end" ]
Create a webhook for this room Usage: # Default create_webhook 'http://example.org/path/to/my/webhook', 'room_event' Options: +pattern+:: The regular expression pattern to match against messages. Only applicable for message events. (default "") +name+:: The label for this webhook (default "")
[ "Create", "a", "webhook", "for", "this", "room" ]
523578ecb7fe68cde347225c210dfd3bc1a64c48
https://github.com/hipchat/hipchat-rb/blob/523578ecb7fe68cde347225c210dfd3bc1a64c48/lib/hipchat/room.rb#L346-L371
train
hipchat/hipchat-rb
lib/hipchat/room.rb
HipChat.Room.delete_webhook
def delete_webhook(webhook_id) response = self.class.delete("#{@api.webhook_config[:url]}/#{URI::escape(webhook_id)}", :query => { :auth_token => @token }, :headers => @api.headers ) ErrorHandler.response_code_to_exception_for :webhook, webhook_id, response true end
ruby
def delete_webhook(webhook_id) response = self.class.delete("#{@api.webhook_config[:url]}/#{URI::escape(webhook_id)}", :query => { :auth_token => @token }, :headers => @api.headers ) ErrorHandler.response_code_to_exception_for :webhook, webhook_id, response true end
[ "def", "delete_webhook", "(", "webhook_id", ")", "response", "=", "self", ".", "class", ".", "delete", "(", "\"#{@api.webhook_config[:url]}/#{URI::escape(webhook_id)}\"", ",", ":query", "=>", "{", ":auth_token", "=>", "@token", "}", ",", ":headers", "=>", "@api", ".", "headers", ")", "ErrorHandler", ".", "response_code_to_exception_for", ":webhook", ",", "webhook_id", ",", "response", "true", "end" ]
Delete a webhook for this room Usage: # Default delete_webhook 'webhook_id'
[ "Delete", "a", "webhook", "for", "this", "room" ]
523578ecb7fe68cde347225c210dfd3bc1a64c48
https://github.com/hipchat/hipchat-rb/blob/523578ecb7fe68cde347225c210dfd3bc1a64c48/lib/hipchat/room.rb#L379-L389
train
hipchat/hipchat-rb
lib/hipchat/room.rb
HipChat.Room.get_all_webhooks
def get_all_webhooks(options = {}) merged_options = {:'start-index' => 0, :'max-results' => 100}.merge(options) response = self.class.get(@api.webhook_config[:url], :query => { :auth_token => @token, :'start-index' => merged_options[:'start-index'], :'max-results' => merged_options[:'max-results'] }, :headers => @api.headers ) ErrorHandler.response_code_to_exception_for :room, room_id, response response.body end
ruby
def get_all_webhooks(options = {}) merged_options = {:'start-index' => 0, :'max-results' => 100}.merge(options) response = self.class.get(@api.webhook_config[:url], :query => { :auth_token => @token, :'start-index' => merged_options[:'start-index'], :'max-results' => merged_options[:'max-results'] }, :headers => @api.headers ) ErrorHandler.response_code_to_exception_for :room, room_id, response response.body end
[ "def", "get_all_webhooks", "(", "options", "=", "{", "}", ")", "merged_options", "=", "{", ":'", "'", "=>", "0", ",", ":'", "'", "=>", "100", "}", ".", "merge", "(", "options", ")", "response", "=", "self", ".", "class", ".", "get", "(", "@api", ".", "webhook_config", "[", ":url", "]", ",", ":query", "=>", "{", ":auth_token", "=>", "@token", ",", ":'", "'", "=>", "merged_options", "[", ":'", "'", "]", ",", ":'", "'", "=>", "merged_options", "[", ":'", "'", "]", "}", ",", ":headers", "=>", "@api", ".", "headers", ")", "ErrorHandler", ".", "response_code_to_exception_for", ":room", ",", "room_id", ",", "response", "response", ".", "body", "end" ]
Gets all webhooks for this room Usage: # Default get_all_webhooks Options: +start-index+:: The regular expression pattern to match against messages. Only applicable for message events. (default "") +max-results+:: The label for this webhook (default "")
[ "Gets", "all", "webhooks", "for", "this", "room" ]
523578ecb7fe68cde347225c210dfd3bc1a64c48
https://github.com/hipchat/hipchat-rb/blob/523578ecb7fe68cde347225c210dfd3bc1a64c48/lib/hipchat/room.rb#L404-L418
train
hipchat/hipchat-rb
lib/hipchat/room.rb
HipChat.Room.get_webhook
def get_webhook(webhook_id) response = self.class.get("#{@api.webhook_config[:url]}/#{URI::escape(webhook_id)}", :query => { :auth_token => @token }, :headers => @api.headers ) ErrorHandler.response_code_to_exception_for :webhook, webhook_id, response response.body end
ruby
def get_webhook(webhook_id) response = self.class.get("#{@api.webhook_config[:url]}/#{URI::escape(webhook_id)}", :query => { :auth_token => @token }, :headers => @api.headers ) ErrorHandler.response_code_to_exception_for :webhook, webhook_id, response response.body end
[ "def", "get_webhook", "(", "webhook_id", ")", "response", "=", "self", ".", "class", ".", "get", "(", "\"#{@api.webhook_config[:url]}/#{URI::escape(webhook_id)}\"", ",", ":query", "=>", "{", ":auth_token", "=>", "@token", "}", ",", ":headers", "=>", "@api", ".", "headers", ")", "ErrorHandler", ".", "response_code_to_exception_for", ":webhook", ",", "webhook_id", ",", "response", "response", ".", "body", "end" ]
Get a webhook for this room Usage: # Default get_webhook 'webhook_id'
[ "Get", "a", "webhook", "for", "this", "room" ]
523578ecb7fe68cde347225c210dfd3bc1a64c48
https://github.com/hipchat/hipchat-rb/blob/523578ecb7fe68cde347225c210dfd3bc1a64c48/lib/hipchat/room.rb#L426-L436
train
seatgeek/soulmate
lib/soulmate/loader.rb
Soulmate.Loader.add
def add(item, opts = {}) opts = { :skip_duplicate_check => false }.merge(opts) raise ArgumentError, "Items must specify both an id and a term" unless item["id"] && item["term"] # kill any old items with this id remove("id" => item["id"]) unless opts[:skip_duplicate_check] Soulmate.redis.pipelined do # store the raw data in a separate key to reduce memory usage Soulmate.redis.hset(database, item["id"], MultiJson.encode(item)) phrase = ([item["term"]] + (item["aliases"] || [])).join(' ') prefixes_for_phrase(phrase).each do |p| Soulmate.redis.sadd(base, p) # remember this prefix in a master set Soulmate.redis.zadd("#{base}:#{p}", item["score"], item["id"]) # store the id of this term in the index end end end
ruby
def add(item, opts = {}) opts = { :skip_duplicate_check => false }.merge(opts) raise ArgumentError, "Items must specify both an id and a term" unless item["id"] && item["term"] # kill any old items with this id remove("id" => item["id"]) unless opts[:skip_duplicate_check] Soulmate.redis.pipelined do # store the raw data in a separate key to reduce memory usage Soulmate.redis.hset(database, item["id"], MultiJson.encode(item)) phrase = ([item["term"]] + (item["aliases"] || [])).join(' ') prefixes_for_phrase(phrase).each do |p| Soulmate.redis.sadd(base, p) # remember this prefix in a master set Soulmate.redis.zadd("#{base}:#{p}", item["score"], item["id"]) # store the id of this term in the index end end end
[ "def", "add", "(", "item", ",", "opts", "=", "{", "}", ")", "opts", "=", "{", ":skip_duplicate_check", "=>", "false", "}", ".", "merge", "(", "opts", ")", "raise", "ArgumentError", ",", "\"Items must specify both an id and a term\"", "unless", "item", "[", "\"id\"", "]", "&&", "item", "[", "\"term\"", "]", "remove", "(", "\"id\"", "=>", "item", "[", "\"id\"", "]", ")", "unless", "opts", "[", ":skip_duplicate_check", "]", "Soulmate", ".", "redis", ".", "pipelined", "do", "Soulmate", ".", "redis", ".", "hset", "(", "database", ",", "item", "[", "\"id\"", "]", ",", "MultiJson", ".", "encode", "(", "item", ")", ")", "phrase", "=", "(", "[", "item", "[", "\"term\"", "]", "]", "+", "(", "item", "[", "\"aliases\"", "]", "||", "[", "]", ")", ")", ".", "join", "(", "' '", ")", "prefixes_for_phrase", "(", "phrase", ")", ".", "each", "do", "|", "p", "|", "Soulmate", ".", "redis", ".", "sadd", "(", "base", ",", "p", ")", "Soulmate", ".", "redis", ".", "zadd", "(", "\"#{base}:#{p}\"", ",", "item", "[", "\"score\"", "]", ",", "item", "[", "\"id\"", "]", ")", "end", "end", "end" ]
"id", "term", "score", "aliases", "data"
[ "id", "term", "score", "aliases", "data" ]
0f5a62122e07ac672fcb7e8854f586b61539057b
https://github.com/seatgeek/soulmate/blob/0f5a62122e07ac672fcb7e8854f586b61539057b/lib/soulmate/loader.rb#L29-L45
train
seatgeek/soulmate
lib/soulmate/loader.rb
Soulmate.Loader.remove
def remove(item) prev_item = Soulmate.redis.hget(database, item["id"]) if prev_item prev_item = MultiJson.decode(prev_item) # undo the operations done in add Soulmate.redis.pipelined do Soulmate.redis.hdel(database, prev_item["id"]) phrase = ([prev_item["term"]] + (prev_item["aliases"] || [])).join(' ') prefixes_for_phrase(phrase).each do |p| Soulmate.redis.srem(base, p) Soulmate.redis.zrem("#{base}:#{p}", prev_item["id"]) end end end end
ruby
def remove(item) prev_item = Soulmate.redis.hget(database, item["id"]) if prev_item prev_item = MultiJson.decode(prev_item) # undo the operations done in add Soulmate.redis.pipelined do Soulmate.redis.hdel(database, prev_item["id"]) phrase = ([prev_item["term"]] + (prev_item["aliases"] || [])).join(' ') prefixes_for_phrase(phrase).each do |p| Soulmate.redis.srem(base, p) Soulmate.redis.zrem("#{base}:#{p}", prev_item["id"]) end end end end
[ "def", "remove", "(", "item", ")", "prev_item", "=", "Soulmate", ".", "redis", ".", "hget", "(", "database", ",", "item", "[", "\"id\"", "]", ")", "if", "prev_item", "prev_item", "=", "MultiJson", ".", "decode", "(", "prev_item", ")", "Soulmate", ".", "redis", ".", "pipelined", "do", "Soulmate", ".", "redis", ".", "hdel", "(", "database", ",", "prev_item", "[", "\"id\"", "]", ")", "phrase", "=", "(", "[", "prev_item", "[", "\"term\"", "]", "]", "+", "(", "prev_item", "[", "\"aliases\"", "]", "||", "[", "]", ")", ")", ".", "join", "(", "' '", ")", "prefixes_for_phrase", "(", "phrase", ")", ".", "each", "do", "|", "p", "|", "Soulmate", ".", "redis", ".", "srem", "(", "base", ",", "p", ")", "Soulmate", ".", "redis", ".", "zrem", "(", "\"#{base}:#{p}\"", ",", "prev_item", "[", "\"id\"", "]", ")", "end", "end", "end", "end" ]
remove only cares about an item's id, but for consistency takes an object
[ "remove", "only", "cares", "about", "an", "item", "s", "id", "but", "for", "consistency", "takes", "an", "object" ]
0f5a62122e07ac672fcb7e8854f586b61539057b
https://github.com/seatgeek/soulmate/blob/0f5a62122e07ac672fcb7e8854f586b61539057b/lib/soulmate/loader.rb#L48-L62
train
hipchat/hipchat-rb
lib/hipchat/user.rb
HipChat.User.send
def send(message, options = {}) message_format = options[:message_format] ? options[:message_format] : 'text' notify = options[:notify] ? options[:notify] : false response = self.class.post(@api.send_config[:url], :query => { :auth_token => @token }, :body => { :message => message, :message_format => message_format, :notify => notify }.send(@api.send_config[:body_format]), :headers => @api.headers ) ErrorHandler.response_code_to_exception_for :user, user_id, response true end
ruby
def send(message, options = {}) message_format = options[:message_format] ? options[:message_format] : 'text' notify = options[:notify] ? options[:notify] : false response = self.class.post(@api.send_config[:url], :query => { :auth_token => @token }, :body => { :message => message, :message_format => message_format, :notify => notify }.send(@api.send_config[:body_format]), :headers => @api.headers ) ErrorHandler.response_code_to_exception_for :user, user_id, response true end
[ "def", "send", "(", "message", ",", "options", "=", "{", "}", ")", "message_format", "=", "options", "[", ":message_format", "]", "?", "options", "[", ":message_format", "]", ":", "'text'", "notify", "=", "options", "[", ":notify", "]", "?", "options", "[", ":notify", "]", ":", "false", "response", "=", "self", ".", "class", ".", "post", "(", "@api", ".", "send_config", "[", ":url", "]", ",", ":query", "=>", "{", ":auth_token", "=>", "@token", "}", ",", ":body", "=>", "{", ":message", "=>", "message", ",", ":message_format", "=>", "message_format", ",", ":notify", "=>", "notify", "}", ".", "send", "(", "@api", ".", "send_config", "[", ":body_format", "]", ")", ",", ":headers", "=>", "@api", ".", "headers", ")", "ErrorHandler", ".", "response_code_to_exception_for", ":user", ",", "user_id", ",", "response", "true", "end" ]
Send a private message to user.
[ "Send", "a", "private", "message", "to", "user", "." ]
523578ecb7fe68cde347225c210dfd3bc1a64c48
https://github.com/hipchat/hipchat-rb/blob/523578ecb7fe68cde347225c210dfd3bc1a64c48/lib/hipchat/user.rb#L22-L37
train
hipchat/hipchat-rb
lib/hipchat/user.rb
HipChat.User.send_file
def send_file(message, file) response = self.class.post(@api.send_file_config[:url], :query => { :auth_token => @token }, :body => file_body({ :message => message }.send(@api.send_config[:body_format]), file), :headers => file_body_headers(@api.headers) ) ErrorHandler.response_code_to_exception_for :user, user_id, response true end
ruby
def send_file(message, file) response = self.class.post(@api.send_file_config[:url], :query => { :auth_token => @token }, :body => file_body({ :message => message }.send(@api.send_config[:body_format]), file), :headers => file_body_headers(@api.headers) ) ErrorHandler.response_code_to_exception_for :user, user_id, response true end
[ "def", "send_file", "(", "message", ",", "file", ")", "response", "=", "self", ".", "class", ".", "post", "(", "@api", ".", "send_file_config", "[", ":url", "]", ",", ":query", "=>", "{", ":auth_token", "=>", "@token", "}", ",", ":body", "=>", "file_body", "(", "{", ":message", "=>", "message", "}", ".", "send", "(", "@api", ".", "send_config", "[", ":body_format", "]", ")", ",", "file", ")", ",", ":headers", "=>", "file_body_headers", "(", "@api", ".", "headers", ")", ")", "ErrorHandler", ".", "response_code_to_exception_for", ":user", ",", "user_id", ",", "response", "true", "end" ]
Send a private file to user.
[ "Send", "a", "private", "file", "to", "user", "." ]
523578ecb7fe68cde347225c210dfd3bc1a64c48
https://github.com/hipchat/hipchat-rb/blob/523578ecb7fe68cde347225c210dfd3bc1a64c48/lib/hipchat/user.rb#L42-L51
train
hipchat/hipchat-rb
lib/hipchat/user.rb
HipChat.User.view
def view response = self.class.get(@api.view_config[:url], :query => { :auth_token => @token }.merge(@api.view_config[:query_params]), :headers => @api.headers ) ErrorHandler.response_code_to_exception_for :user, user_id, response User.new(@token, response.merge(:api_version => @api.version, :server_url => server_url)) end
ruby
def view response = self.class.get(@api.view_config[:url], :query => { :auth_token => @token }.merge(@api.view_config[:query_params]), :headers => @api.headers ) ErrorHandler.response_code_to_exception_for :user, user_id, response User.new(@token, response.merge(:api_version => @api.version, :server_url => server_url)) end
[ "def", "view", "response", "=", "self", ".", "class", ".", "get", "(", "@api", ".", "view_config", "[", ":url", "]", ",", ":query", "=>", "{", ":auth_token", "=>", "@token", "}", ".", "merge", "(", "@api", ".", "view_config", "[", ":query_params", "]", ")", ",", ":headers", "=>", "@api", ".", "headers", ")", "ErrorHandler", ".", "response_code_to_exception_for", ":user", ",", "user_id", ",", "response", "User", ".", "new", "(", "@token", ",", "response", ".", "merge", "(", ":api_version", "=>", "@api", ".", "version", ",", ":server_url", "=>", "server_url", ")", ")", "end" ]
Get a user's details.
[ "Get", "a", "user", "s", "details", "." ]
523578ecb7fe68cde347225c210dfd3bc1a64c48
https://github.com/hipchat/hipchat-rb/blob/523578ecb7fe68cde347225c210dfd3bc1a64c48/lib/hipchat/user.rb#L56-L64
train
hipchat/hipchat-rb
lib/hipchat/user.rb
HipChat.User.rooms
def rooms response = self.class.get(@api.user_joined_rooms_config[:url], :query => { :auth_token => @token }.merge(@api.user_joined_rooms_config[:query_params]), :headers => @api.headers ) ErrorHandler.response_code_to_exception_for :user, user_id, response User.new(@token, response.merge(:api_version => @api.version)) end
ruby
def rooms response = self.class.get(@api.user_joined_rooms_config[:url], :query => { :auth_token => @token }.merge(@api.user_joined_rooms_config[:query_params]), :headers => @api.headers ) ErrorHandler.response_code_to_exception_for :user, user_id, response User.new(@token, response.merge(:api_version => @api.version)) end
[ "def", "rooms", "response", "=", "self", ".", "class", ".", "get", "(", "@api", ".", "user_joined_rooms_config", "[", ":url", "]", ",", ":query", "=>", "{", ":auth_token", "=>", "@token", "}", ".", "merge", "(", "@api", ".", "user_joined_rooms_config", "[", ":query_params", "]", ")", ",", ":headers", "=>", "@api", ".", "headers", ")", "ErrorHandler", ".", "response_code_to_exception_for", ":user", ",", "user_id", ",", "response", "User", ".", "new", "(", "@token", ",", "response", ".", "merge", "(", ":api_version", "=>", "@api", ".", "version", ")", ")", "end" ]
Getting all rooms details in which user is present
[ "Getting", "all", "rooms", "details", "in", "which", "user", "is", "present" ]
523578ecb7fe68cde347225c210dfd3bc1a64c48
https://github.com/hipchat/hipchat-rb/blob/523578ecb7fe68cde347225c210dfd3bc1a64c48/lib/hipchat/user.rb#L157-L164
train
hipchat/hipchat-rb
lib/hipchat/file_helper.rb
HipChat.FileHelper.file_body
def file_body(message, file) file_name = File.basename(file.path) mime_type = MimeMagic.by_path(file_name) file_content = Base64.encode64(file.read) body = ["--#{BOUNDARY}"] body << 'Content-Type: application/json; charset=UTF-8' body << 'Content-Disposition: attachment; name="metadata"' body << '' body << message body << "--#{BOUNDARY}" body << "Content-Type: #{mime_type}; charset=UTF-8" body << 'Content-Transfer-Encoding: base64' body << %{Content-Disposition: attachment; name="file"; filename="#{file_name}"} body << '' body << file_content body << "--#{BOUNDARY}--" body.join("\n") end
ruby
def file_body(message, file) file_name = File.basename(file.path) mime_type = MimeMagic.by_path(file_name) file_content = Base64.encode64(file.read) body = ["--#{BOUNDARY}"] body << 'Content-Type: application/json; charset=UTF-8' body << 'Content-Disposition: attachment; name="metadata"' body << '' body << message body << "--#{BOUNDARY}" body << "Content-Type: #{mime_type}; charset=UTF-8" body << 'Content-Transfer-Encoding: base64' body << %{Content-Disposition: attachment; name="file"; filename="#{file_name}"} body << '' body << file_content body << "--#{BOUNDARY}--" body.join("\n") end
[ "def", "file_body", "(", "message", ",", "file", ")", "file_name", "=", "File", ".", "basename", "(", "file", ".", "path", ")", "mime_type", "=", "MimeMagic", ".", "by_path", "(", "file_name", ")", "file_content", "=", "Base64", ".", "encode64", "(", "file", ".", "read", ")", "body", "=", "[", "\"--#{BOUNDARY}\"", "]", "body", "<<", "'Content-Type: application/json; charset=UTF-8'", "body", "<<", "'Content-Disposition: attachment; name=\"metadata\"'", "body", "<<", "''", "body", "<<", "message", "body", "<<", "\"--#{BOUNDARY}\"", "body", "<<", "\"Content-Type: #{mime_type}; charset=UTF-8\"", "body", "<<", "'Content-Transfer-Encoding: base64'", "body", "<<", "%{Content-Disposition: attachment; name=\"file\"; filename=\"#{file_name}\"}", "body", "<<", "''", "body", "<<", "file_content", "body", "<<", "\"--#{BOUNDARY}--\"", "body", ".", "join", "(", "\"\\n\"", ")", "end" ]
Builds a multipart file body for the api. message - a message to attach file - a File instance
[ "Builds", "a", "multipart", "file", "body", "for", "the", "api", "." ]
523578ecb7fe68cde347225c210dfd3bc1a64c48
https://github.com/hipchat/hipchat-rb/blob/523578ecb7fe68cde347225c210dfd3bc1a64c48/lib/hipchat/file_helper.rb#L14-L32
train
hipchat/hipchat-rb
lib/hipchat/client.rb
HipChat.Client.scopes
def scopes(room: nil) path = "#{@api.scopes_config[:url]}/#{URI::escape(@token)}" response = self.class.get(path, :query => { :auth_token => @token }, :headers => @api.headers ) ErrorHandler.response_code_to_exception_for :room, 'scopes', response return response['scopes'] unless response['client']['room'] if room && response['client']['room']['id'] == room.room_id return response['scopes'] end end
ruby
def scopes(room: nil) path = "#{@api.scopes_config[:url]}/#{URI::escape(@token)}" response = self.class.get(path, :query => { :auth_token => @token }, :headers => @api.headers ) ErrorHandler.response_code_to_exception_for :room, 'scopes', response return response['scopes'] unless response['client']['room'] if room && response['client']['room']['id'] == room.room_id return response['scopes'] end end
[ "def", "scopes", "(", "room", ":", "nil", ")", "path", "=", "\"#{@api.scopes_config[:url]}/#{URI::escape(@token)}\"", "response", "=", "self", ".", "class", ".", "get", "(", "path", ",", ":query", "=>", "{", ":auth_token", "=>", "@token", "}", ",", ":headers", "=>", "@api", ".", "headers", ")", "ErrorHandler", ".", "response_code_to_exception_for", ":room", ",", "'scopes'", ",", "response", "return", "response", "[", "'scopes'", "]", "unless", "response", "[", "'client'", "]", "[", "'room'", "]", "if", "room", "&&", "response", "[", "'client'", "]", "[", "'room'", "]", "[", "'id'", "]", "==", "room", ".", "room_id", "return", "response", "[", "'scopes'", "]", "end", "end" ]
Returns the scopes for the Auth token Calls the endpoint: https://api.hipchat.com/v2/oauth/token/#{token} The response is a JSON object containing a client key. The client object contains a list of allowed scopes. There are two possible response types, for a global API token, the room object will be nil. For a room API token, the room object will be populated: Optional room parameter can be passed in. The method will return the following: - if it's a global API token and room param is nil: scopes - if it's a global API token and room param is not nil: scopes - if it's a room API token and room param is nil: nil - if it's a room API token and room param is not nil - if room param's room_id matches token room_id: scopes - if room param's room_id doesn't match token room_id: nil Raises errors if response is unrecognizable
[ "Returns", "the", "scopes", "for", "the", "Auth", "token" ]
523578ecb7fe68cde347225c210dfd3bc1a64c48
https://github.com/hipchat/hipchat-rb/blob/523578ecb7fe68cde347225c210dfd3bc1a64c48/lib/hipchat/client.rb#L52-L63
train
instana/ruby-sensor
lib/instana/tracing/span.rb
Instana.Span.add_stack
def add_stack(limit: nil, stack: Kernel.caller) frame_count = 0 @data[:stack] = [] stack.each do |i| # If the stack has the full instana gem version in it's path # then don't include that frame. Also don't exclude the Rack module. if !i.match(/instana\/instrumentation\/rack.rb/).nil? || (i.match(::Instana::VERSION_FULL).nil? && i.match('lib/instana/').nil?) break if limit && frame_count >= limit x = i.split(':') @data[:stack] << { :c => x[0], :n => x[1], :m => x[2] } frame_count = frame_count + 1 if limit end end end
ruby
def add_stack(limit: nil, stack: Kernel.caller) frame_count = 0 @data[:stack] = [] stack.each do |i| # If the stack has the full instana gem version in it's path # then don't include that frame. Also don't exclude the Rack module. if !i.match(/instana\/instrumentation\/rack.rb/).nil? || (i.match(::Instana::VERSION_FULL).nil? && i.match('lib/instana/').nil?) break if limit && frame_count >= limit x = i.split(':') @data[:stack] << { :c => x[0], :n => x[1], :m => x[2] } frame_count = frame_count + 1 if limit end end end
[ "def", "add_stack", "(", "limit", ":", "nil", ",", "stack", ":", "Kernel", ".", "caller", ")", "frame_count", "=", "0", "@data", "[", ":stack", "]", "=", "[", "]", "stack", ".", "each", "do", "|", "i", "|", "if", "!", "i", ".", "match", "(", "/", "\\/", "\\/", "/", ")", ".", "nil?", "||", "(", "i", ".", "match", "(", "::", "Instana", "::", "VERSION_FULL", ")", ".", "nil?", "&&", "i", ".", "match", "(", "'lib/instana/'", ")", ".", "nil?", ")", "break", "if", "limit", "&&", "frame_count", ">=", "limit", "x", "=", "i", ".", "split", "(", "':'", ")", "@data", "[", ":stack", "]", "<<", "{", ":c", "=>", "x", "[", "0", "]", ",", ":n", "=>", "x", "[", "1", "]", ",", ":m", "=>", "x", "[", "2", "]", "}", "frame_count", "=", "frame_count", "+", "1", "if", "limit", "end", "end", "end" ]
Adds a backtrace to this span @param limit [Integer] Limit the backtrace to the top <limit> frames
[ "Adds", "a", "backtrace", "to", "this", "span" ]
9d1b3e46b22c4f77919f67ff6ee5831dad5d5b99
https://github.com/instana/ruby-sensor/blob/9d1b3e46b22c4f77919f67ff6ee5831dad5d5b99/lib/instana/tracing/span.rb#L55-L77
train
instana/ruby-sensor
lib/instana/tracing/span.rb
Instana.Span.add_error
def add_error(e) @data[:error] = true if @data.key?(:ec) @data[:ec] = @data[:ec] + 1 else @data[:ec] = 1 end # If a valid exception has been passed in, log the information about it # In case of just logging an error for things such as HTTP client 5xx # responses, an exception/backtrace may not exist. if e if e.backtrace.is_a?(Array) add_stack(stack: e.backtrace) end if HTTP_SPANS.include?(@data[:n]) set_tags(:http => { :error => "#{e.class}: #{e.message}" }) else log(:error, Time.now, { :message => e.message, :parameters => e.class.to_s }) end e.instance_variable_set(:@instana_logged, true) end self end
ruby
def add_error(e) @data[:error] = true if @data.key?(:ec) @data[:ec] = @data[:ec] + 1 else @data[:ec] = 1 end # If a valid exception has been passed in, log the information about it # In case of just logging an error for things such as HTTP client 5xx # responses, an exception/backtrace may not exist. if e if e.backtrace.is_a?(Array) add_stack(stack: e.backtrace) end if HTTP_SPANS.include?(@data[:n]) set_tags(:http => { :error => "#{e.class}: #{e.message}" }) else log(:error, Time.now, { :message => e.message, :parameters => e.class.to_s }) end e.instance_variable_set(:@instana_logged, true) end self end
[ "def", "add_error", "(", "e", ")", "@data", "[", ":error", "]", "=", "true", "if", "@data", ".", "key?", "(", ":ec", ")", "@data", "[", ":ec", "]", "=", "@data", "[", ":ec", "]", "+", "1", "else", "@data", "[", ":ec", "]", "=", "1", "end", "if", "e", "if", "e", ".", "backtrace", ".", "is_a?", "(", "Array", ")", "add_stack", "(", "stack", ":", "e", ".", "backtrace", ")", "end", "if", "HTTP_SPANS", ".", "include?", "(", "@data", "[", ":n", "]", ")", "set_tags", "(", ":http", "=>", "{", ":error", "=>", "\"#{e.class}: #{e.message}\"", "}", ")", "else", "log", "(", ":error", ",", "Time", ".", "now", ",", "{", ":message", "=>", "e", ".", "message", ",", ":parameters", "=>", "e", ".", "class", ".", "to_s", "}", ")", "end", "e", ".", "instance_variable_set", "(", ":@instana_logged", ",", "true", ")", "end", "self", "end" ]
Log an error into the span @param e [Exception] The exception to be logged
[ "Log", "an", "error", "into", "the", "span" ]
9d1b3e46b22c4f77919f67ff6ee5831dad5d5b99
https://github.com/instana/ruby-sensor/blob/9d1b3e46b22c4f77919f67ff6ee5831dad5d5b99/lib/instana/tracing/span.rb#L83-L108
train
instana/ruby-sensor
lib/instana/tracing/span.rb
Instana.Span.set_tags
def set_tags(tags) return unless tags.is_a?(Hash) tags.each do |k,v| set_tag(k, v) end self end
ruby
def set_tags(tags) return unless tags.is_a?(Hash) tags.each do |k,v| set_tag(k, v) end self end
[ "def", "set_tags", "(", "tags", ")", "return", "unless", "tags", ".", "is_a?", "(", "Hash", ")", "tags", ".", "each", "do", "|", "k", ",", "v", "|", "set_tag", "(", "k", ",", "v", ")", "end", "self", "end" ]
Helper method to add multiple tags to this span @params tags [Hash] @return [Span]
[ "Helper", "method", "to", "add", "multiple", "tags", "to", "this", "span" ]
9d1b3e46b22c4f77919f67ff6ee5831dad5d5b99
https://github.com/instana/ruby-sensor/blob/9d1b3e46b22c4f77919f67ff6ee5831dad5d5b99/lib/instana/tracing/span.rb#L304-L310
train
instana/ruby-sensor
lib/instana/tracing/span.rb
Instana.Span.tags
def tags(key = nil) if custom? tags = @data[:data][:sdk][:custom][:tags] else tags = @data[:data][key] end key ? tags[key] : tags end
ruby
def tags(key = nil) if custom? tags = @data[:data][:sdk][:custom][:tags] else tags = @data[:data][key] end key ? tags[key] : tags end
[ "def", "tags", "(", "key", "=", "nil", ")", "if", "custom?", "tags", "=", "@data", "[", ":data", "]", "[", ":sdk", "]", "[", ":custom", "]", "[", ":tags", "]", "else", "tags", "=", "@data", "[", ":data", "]", "[", "key", "]", "end", "key", "?", "tags", "[", "key", "]", ":", "tags", "end" ]
Retrieve the hash of tags for this span
[ "Retrieve", "the", "hash", "of", "tags", "for", "this", "span" ]
9d1b3e46b22c4f77919f67ff6ee5831dad5d5b99
https://github.com/instana/ruby-sensor/blob/9d1b3e46b22c4f77919f67ff6ee5831dad5d5b99/lib/instana/tracing/span.rb#L342-L349
train