id
int32 0
24.9k
| repo
stringlengths 5
58
| path
stringlengths 9
168
| func_name
stringlengths 9
130
| original_string
stringlengths 66
10.5k
| language
stringclasses 1
value | code
stringlengths 66
10.5k
| code_tokens
list | docstring
stringlengths 8
16k
| docstring_tokens
list | sha
stringlengths 40
40
| url
stringlengths 94
266
|
|---|---|---|---|---|---|---|---|---|---|---|---|
9,300
|
sugaryourcoffee/syclink
|
lib/syclink/formatter.rb
|
SycLink.Formatter.print_horizontal_line
|
def print_horizontal_line(line, separator, widths)
puts widths.map { |width| line * width }.join(separator)
end
|
ruby
|
def print_horizontal_line(line, separator, widths)
puts widths.map { |width| line * width }.join(separator)
end
|
[
"def",
"print_horizontal_line",
"(",
"line",
",",
"separator",
",",
"widths",
")",
"puts",
"widths",
".",
"map",
"{",
"|",
"width",
"|",
"line",
"*",
"width",
"}",
".",
"join",
"(",
"separator",
")",
"end"
] |
Prints a horizontal line below the header
|
[
"Prints",
"a",
"horizontal",
"line",
"below",
"the",
"header"
] |
941ee2045c946daa1e0db394eb643aa82c1254cc
|
https://github.com/sugaryourcoffee/syclink/blob/941ee2045c946daa1e0db394eb643aa82c1254cc/lib/syclink/formatter.rb#L100-L102
|
9,301
|
sugaryourcoffee/syclink
|
lib/syclink/formatter.rb
|
SycLink.Formatter.print_table
|
def print_table(columns, formatter)
columns.transpose.each { |row| puts sprintf(formatter, *row) }
end
|
ruby
|
def print_table(columns, formatter)
columns.transpose.each { |row| puts sprintf(formatter, *row) }
end
|
[
"def",
"print_table",
"(",
"columns",
",",
"formatter",
")",
"columns",
".",
"transpose",
".",
"each",
"{",
"|",
"row",
"|",
"puts",
"sprintf",
"(",
"formatter",
",",
"row",
")",
"}",
"end"
] |
Prints columns in a table format
|
[
"Prints",
"columns",
"in",
"a",
"table",
"format"
] |
941ee2045c946daa1e0db394eb643aa82c1254cc
|
https://github.com/sugaryourcoffee/syclink/blob/941ee2045c946daa1e0db394eb643aa82c1254cc/lib/syclink/formatter.rb#L105-L107
|
9,302
|
lyrasis/collectionspace-client
|
lib/collectionspace/client/helpers.rb
|
CollectionSpace.Helpers.all
|
def all(path, options = {}, &block)
all = []
list_type, list_item = get_list_types(path)
result = request('GET', path, options)
raise RequestError.new result.status if result.status_code != 200 or result.parsed[list_type].nil?
total = result.parsed[list_type]['totalItems'].to_i
items = result.parsed[list_type]['itemsInPage'].to_i
return all if total == 0
pages = (total / config.page_size) + 1
(0 .. pages - 1).each do |i|
options[:query][:pgNum] = i
result = request('GET', path, options)
raise RequestError.new result.status if result.status_code != 200
list_items = result.parsed[list_type][list_item]
list_items = [ list_items ] if items == 1
list_items.each { |item| yield item if block_given? }
all.concat list_items
end
all
end
|
ruby
|
def all(path, options = {}, &block)
all = []
list_type, list_item = get_list_types(path)
result = request('GET', path, options)
raise RequestError.new result.status if result.status_code != 200 or result.parsed[list_type].nil?
total = result.parsed[list_type]['totalItems'].to_i
items = result.parsed[list_type]['itemsInPage'].to_i
return all if total == 0
pages = (total / config.page_size) + 1
(0 .. pages - 1).each do |i|
options[:query][:pgNum] = i
result = request('GET', path, options)
raise RequestError.new result.status if result.status_code != 200
list_items = result.parsed[list_type][list_item]
list_items = [ list_items ] if items == 1
list_items.each { |item| yield item if block_given? }
all.concat list_items
end
all
end
|
[
"def",
"all",
"(",
"path",
",",
"options",
"=",
"{",
"}",
",",
"&",
"block",
")",
"all",
"=",
"[",
"]",
"list_type",
",",
"list_item",
"=",
"get_list_types",
"(",
"path",
")",
"result",
"=",
"request",
"(",
"'GET'",
",",
"path",
",",
"options",
")",
"raise",
"RequestError",
".",
"new",
"result",
".",
"status",
"if",
"result",
".",
"status_code",
"!=",
"200",
"or",
"result",
".",
"parsed",
"[",
"list_type",
"]",
".",
"nil?",
"total",
"=",
"result",
".",
"parsed",
"[",
"list_type",
"]",
"[",
"'totalItems'",
"]",
".",
"to_i",
"items",
"=",
"result",
".",
"parsed",
"[",
"list_type",
"]",
"[",
"'itemsInPage'",
"]",
".",
"to_i",
"return",
"all",
"if",
"total",
"==",
"0",
"pages",
"=",
"(",
"total",
"/",
"config",
".",
"page_size",
")",
"+",
"1",
"(",
"0",
"..",
"pages",
"-",
"1",
")",
".",
"each",
"do",
"|",
"i",
"|",
"options",
"[",
":query",
"]",
"[",
":pgNum",
"]",
"=",
"i",
"result",
"=",
"request",
"(",
"'GET'",
",",
"path",
",",
"options",
")",
"raise",
"RequestError",
".",
"new",
"result",
".",
"status",
"if",
"result",
".",
"status_code",
"!=",
"200",
"list_items",
"=",
"result",
".",
"parsed",
"[",
"list_type",
"]",
"[",
"list_item",
"]",
"list_items",
"=",
"[",
"list_items",
"]",
"if",
"items",
"==",
"1",
"list_items",
".",
"each",
"{",
"|",
"item",
"|",
"yield",
"item",
"if",
"block_given?",
"}",
"all",
".",
"concat",
"list_items",
"end",
"all",
"end"
] |
get ALL records at path by paging through record set
can pass block to act on each page of results
|
[
"get",
"ALL",
"records",
"at",
"path",
"by",
"paging",
"through",
"record",
"set",
"can",
"pass",
"block",
"to",
"act",
"on",
"each",
"page",
"of",
"results"
] |
6db26dffb792bda2e8a5b46863a63dc1d56932a3
|
https://github.com/lyrasis/collectionspace-client/blob/6db26dffb792bda2e8a5b46863a63dc1d56932a3/lib/collectionspace/client/helpers.rb#L23-L45
|
9,303
|
lyrasis/collectionspace-client
|
lib/collectionspace/client/helpers.rb
|
CollectionSpace.Helpers.post_blob_url
|
def post_blob_url(url)
raise ArgumentError.new("Invalid blob URL #{url}") unless URI.parse(url).scheme =~ /^https?/
request 'POST', "blobs", {
query: { "blobUri" => url },
}
end
|
ruby
|
def post_blob_url(url)
raise ArgumentError.new("Invalid blob URL #{url}") unless URI.parse(url).scheme =~ /^https?/
request 'POST', "blobs", {
query: { "blobUri" => url },
}
end
|
[
"def",
"post_blob_url",
"(",
"url",
")",
"raise",
"ArgumentError",
".",
"new",
"(",
"\"Invalid blob URL #{url}\"",
")",
"unless",
"URI",
".",
"parse",
"(",
"url",
")",
".",
"scheme",
"=~",
"/",
"/",
"request",
"'POST'",
",",
"\"blobs\"",
",",
"{",
"query",
":",
"{",
"\"blobUri\"",
"=>",
"url",
"}",
",",
"}",
"end"
] |
create blob record by external url
|
[
"create",
"blob",
"record",
"by",
"external",
"url"
] |
6db26dffb792bda2e8a5b46863a63dc1d56932a3
|
https://github.com/lyrasis/collectionspace-client/blob/6db26dffb792bda2e8a5b46863a63dc1d56932a3/lib/collectionspace/client/helpers.rb#L56-L61
|
9,304
|
lyrasis/collectionspace-client
|
lib/collectionspace/client/helpers.rb
|
CollectionSpace.Helpers.to_object
|
def to_object(record, attribute_map, stringify_keys = false)
attributes = {}
attribute_map.each do |map|
map = map.inject({}) { |memo,(k,v)| memo[k.to_s] = v; memo} if stringify_keys
if map["with"]
as = deep_find(record, map["key"], map["nested_key"])
values = []
if as.is_a? Array
values = as.map { |a| strip_refname( deep_find(a, map["with"]) ) }
elsif as.is_a? Hash and as[ map["with"] ]
values = as[ map["with"] ].is_a?(Array) ? as[ map["with"] ].map { |a| strip_refname(a) } : [ strip_refname(as[ map["with"] ]) ]
end
attributes[map["field"]] = values
else
attributes[map["field"]] = deep_find(record, map["key"], map["nested_key"])
end
end
attributes
end
|
ruby
|
def to_object(record, attribute_map, stringify_keys = false)
attributes = {}
attribute_map.each do |map|
map = map.inject({}) { |memo,(k,v)| memo[k.to_s] = v; memo} if stringify_keys
if map["with"]
as = deep_find(record, map["key"], map["nested_key"])
values = []
if as.is_a? Array
values = as.map { |a| strip_refname( deep_find(a, map["with"]) ) }
elsif as.is_a? Hash and as[ map["with"] ]
values = as[ map["with"] ].is_a?(Array) ? as[ map["with"] ].map { |a| strip_refname(a) } : [ strip_refname(as[ map["with"] ]) ]
end
attributes[map["field"]] = values
else
attributes[map["field"]] = deep_find(record, map["key"], map["nested_key"])
end
end
attributes
end
|
[
"def",
"to_object",
"(",
"record",
",",
"attribute_map",
",",
"stringify_keys",
"=",
"false",
")",
"attributes",
"=",
"{",
"}",
"attribute_map",
".",
"each",
"do",
"|",
"map",
"|",
"map",
"=",
"map",
".",
"inject",
"(",
"{",
"}",
")",
"{",
"|",
"memo",
",",
"(",
"k",
",",
"v",
")",
"|",
"memo",
"[",
"k",
".",
"to_s",
"]",
"=",
"v",
";",
"memo",
"}",
"if",
"stringify_keys",
"if",
"map",
"[",
"\"with\"",
"]",
"as",
"=",
"deep_find",
"(",
"record",
",",
"map",
"[",
"\"key\"",
"]",
",",
"map",
"[",
"\"nested_key\"",
"]",
")",
"values",
"=",
"[",
"]",
"if",
"as",
".",
"is_a?",
"Array",
"values",
"=",
"as",
".",
"map",
"{",
"|",
"a",
"|",
"strip_refname",
"(",
"deep_find",
"(",
"a",
",",
"map",
"[",
"\"with\"",
"]",
")",
")",
"}",
"elsif",
"as",
".",
"is_a?",
"Hash",
"and",
"as",
"[",
"map",
"[",
"\"with\"",
"]",
"]",
"values",
"=",
"as",
"[",
"map",
"[",
"\"with\"",
"]",
"]",
".",
"is_a?",
"(",
"Array",
")",
"?",
"as",
"[",
"map",
"[",
"\"with\"",
"]",
"]",
".",
"map",
"{",
"|",
"a",
"|",
"strip_refname",
"(",
"a",
")",
"}",
":",
"[",
"strip_refname",
"(",
"as",
"[",
"map",
"[",
"\"with\"",
"]",
"]",
")",
"]",
"end",
"attributes",
"[",
"map",
"[",
"\"field\"",
"]",
"]",
"=",
"values",
"else",
"attributes",
"[",
"map",
"[",
"\"field\"",
"]",
"]",
"=",
"deep_find",
"(",
"record",
",",
"map",
"[",
"\"key\"",
"]",
",",
"map",
"[",
"\"nested_key\"",
"]",
")",
"end",
"end",
"attributes",
"end"
] |
parsed record and map to get restructured object
|
[
"parsed",
"record",
"and",
"map",
"to",
"get",
"restructured",
"object"
] |
6db26dffb792bda2e8a5b46863a63dc1d56932a3
|
https://github.com/lyrasis/collectionspace-client/blob/6db26dffb792bda2e8a5b46863a63dc1d56932a3/lib/collectionspace/client/helpers.rb#L86-L104
|
9,305
|
tbuehlmann/ponder
|
lib/ponder/channel.rb
|
Ponder.Channel.topic
|
def topic
if @topic
@topic
else
connected do
fiber = Fiber.current
callbacks = {}
[331, 332, 403, 442].each do |numeric|
callbacks[numeric] = @thaum.on(numeric) do |event_data|
topic = event_data[:params].match(':(.*)').captures.first
fiber.resume topic
end
end
raw "TOPIC #{@name}"
@topic = Fiber.yield
callbacks.each do |type, callback|
@thaum.callbacks[type].delete(callback)
end
@topic
end
end
end
|
ruby
|
def topic
if @topic
@topic
else
connected do
fiber = Fiber.current
callbacks = {}
[331, 332, 403, 442].each do |numeric|
callbacks[numeric] = @thaum.on(numeric) do |event_data|
topic = event_data[:params].match(':(.*)').captures.first
fiber.resume topic
end
end
raw "TOPIC #{@name}"
@topic = Fiber.yield
callbacks.each do |type, callback|
@thaum.callbacks[type].delete(callback)
end
@topic
end
end
end
|
[
"def",
"topic",
"if",
"@topic",
"@topic",
"else",
"connected",
"do",
"fiber",
"=",
"Fiber",
".",
"current",
"callbacks",
"=",
"{",
"}",
"[",
"331",
",",
"332",
",",
"403",
",",
"442",
"]",
".",
"each",
"do",
"|",
"numeric",
"|",
"callbacks",
"[",
"numeric",
"]",
"=",
"@thaum",
".",
"on",
"(",
"numeric",
")",
"do",
"|",
"event_data",
"|",
"topic",
"=",
"event_data",
"[",
":params",
"]",
".",
"match",
"(",
"':(.*)'",
")",
".",
"captures",
".",
"first",
"fiber",
".",
"resume",
"topic",
"end",
"end",
"raw",
"\"TOPIC #{@name}\"",
"@topic",
"=",
"Fiber",
".",
"yield",
"callbacks",
".",
"each",
"do",
"|",
"type",
",",
"callback",
"|",
"@thaum",
".",
"callbacks",
"[",
"type",
"]",
".",
"delete",
"(",
"callback",
")",
"end",
"@topic",
"end",
"end",
"end"
] |
Experimental, no tests so far.
|
[
"Experimental",
"no",
"tests",
"so",
"far",
"."
] |
930912e1b78b41afa1359121aca46197e9edff9c
|
https://github.com/tbuehlmann/ponder/blob/930912e1b78b41afa1359121aca46197e9edff9c/lib/ponder/channel.rb#L21-L44
|
9,306
|
j-a-m-l/scrapula
|
lib/scrapula/page.rb
|
Scrapula.Page.search!
|
def search! query, operations = [], &block
result = @agent_page.search query
# FIXME on every object
result = operations.reduce(result) do |tmp, op|
tmp.__send__ op
end if result
yield result if block_given?
result
end
|
ruby
|
def search! query, operations = [], &block
result = @agent_page.search query
# FIXME on every object
result = operations.reduce(result) do |tmp, op|
tmp.__send__ op
end if result
yield result if block_given?
result
end
|
[
"def",
"search!",
"query",
",",
"operations",
"=",
"[",
"]",
",",
"&",
"block",
"result",
"=",
"@agent_page",
".",
"search",
"query",
"# FIXME on every object",
"result",
"=",
"operations",
".",
"reduce",
"(",
"result",
")",
"do",
"|",
"tmp",
",",
"op",
"|",
"tmp",
".",
"__send__",
"op",
"end",
"if",
"result",
"yield",
"result",
"if",
"block_given?",
"result",
"end"
] |
at returns the first one only, but search returns all
|
[
"at",
"returns",
"the",
"first",
"one",
"only",
"but",
"search",
"returns",
"all"
] |
d5df8e1f05f0bd24e2f346ac2f2c3fc3b385b211
|
https://github.com/j-a-m-l/scrapula/blob/d5df8e1f05f0bd24e2f346ac2f2c3fc3b385b211/lib/scrapula/page.rb#L24-L35
|
9,307
|
ouvrages/guard-haml-coffee
|
lib/guard/haml-coffee.rb
|
Guard.HamlCoffee.get_output
|
def get_output(file)
file_dir = File.dirname(file)
file_name = File.basename(file).split('.')[0..-2].join('.')
file_name = "#{file_name}.js" if file_name.match("\.js").nil?
file_dir = file_dir.gsub(Regexp.new("#{@options[:input]}(\/){0,1}"), '') if @options[:input]
file_dir = File.join(@options[:output], file_dir) if @options[:output]
if file_dir == ''
file_name
else
File.join(file_dir, file_name)
end
end
|
ruby
|
def get_output(file)
file_dir = File.dirname(file)
file_name = File.basename(file).split('.')[0..-2].join('.')
file_name = "#{file_name}.js" if file_name.match("\.js").nil?
file_dir = file_dir.gsub(Regexp.new("#{@options[:input]}(\/){0,1}"), '') if @options[:input]
file_dir = File.join(@options[:output], file_dir) if @options[:output]
if file_dir == ''
file_name
else
File.join(file_dir, file_name)
end
end
|
[
"def",
"get_output",
"(",
"file",
")",
"file_dir",
"=",
"File",
".",
"dirname",
"(",
"file",
")",
"file_name",
"=",
"File",
".",
"basename",
"(",
"file",
")",
".",
"split",
"(",
"'.'",
")",
"[",
"0",
"..",
"-",
"2",
"]",
".",
"join",
"(",
"'.'",
")",
"file_name",
"=",
"\"#{file_name}.js\"",
"if",
"file_name",
".",
"match",
"(",
"\"\\.js\"",
")",
".",
"nil?",
"file_dir",
"=",
"file_dir",
".",
"gsub",
"(",
"Regexp",
".",
"new",
"(",
"\"#{@options[:input]}(\\/){0,1}\"",
")",
",",
"''",
")",
"if",
"@options",
"[",
":input",
"]",
"file_dir",
"=",
"File",
".",
"join",
"(",
"@options",
"[",
":output",
"]",
",",
"file_dir",
")",
"if",
"@options",
"[",
":output",
"]",
"if",
"file_dir",
"==",
"''",
"file_name",
"else",
"File",
".",
"join",
"(",
"file_dir",
",",
"file_name",
")",
"end",
"end"
] |
Get the file path to output the html based on the file being
built. The output path is relative to where guard is being run.
@param file [String] path to file being built
@return [String] path to file where output should be written
|
[
"Get",
"the",
"file",
"path",
"to",
"output",
"the",
"html",
"based",
"on",
"the",
"file",
"being",
"built",
".",
"The",
"output",
"path",
"is",
"relative",
"to",
"where",
"guard",
"is",
"being",
"run",
"."
] |
cfa5021cf8512c4f333c345f33f4c0199a5207ae
|
https://github.com/ouvrages/guard-haml-coffee/blob/cfa5021cf8512c4f333c345f33f4c0199a5207ae/lib/guard/haml-coffee.rb#L41-L55
|
9,308
|
npepinpe/redstruct
|
lib/redstruct/sorted_set.rb
|
Redstruct.SortedSet.slice
|
def slice(**options)
defaults = {
lower: nil,
upper: nil,
exclusive: false,
lex: @lex
}
self.class::Slice.new(self, **defaults.merge(options))
end
|
ruby
|
def slice(**options)
defaults = {
lower: nil,
upper: nil,
exclusive: false,
lex: @lex
}
self.class::Slice.new(self, **defaults.merge(options))
end
|
[
"def",
"slice",
"(",
"**",
"options",
")",
"defaults",
"=",
"{",
"lower",
":",
"nil",
",",
"upper",
":",
"nil",
",",
"exclusive",
":",
"false",
",",
"lex",
":",
"@lex",
"}",
"self",
".",
"class",
"::",
"Slice",
".",
"new",
"(",
"self",
",",
"**",
"defaults",
".",
"merge",
"(",
"options",
")",
")",
"end"
] |
Returns a slice or partial selection of the set.
@see Redstruct::SortedSet::Slice#initialize
@return [Redstruct::SortedSet::Slice] a newly created slice for this set
|
[
"Returns",
"a",
"slice",
"or",
"partial",
"selection",
"of",
"the",
"set",
"."
] |
c97b45e7227f8ed9029f0effff352fc4d82dc3cb
|
https://github.com/npepinpe/redstruct/blob/c97b45e7227f8ed9029f0effff352fc4d82dc3cb/lib/redstruct/sorted_set.rb#L72-L81
|
9,309
|
npepinpe/redstruct
|
lib/redstruct/sorted_set.rb
|
Redstruct.SortedSet.to_enum
|
def to_enum(match: '*', count: 10, with_scores: false)
enumerator = self.connection.zscan_each(@key, match: match, count: count)
return enumerator if with_scores
return Enumerator.new do |yielder|
loop do
item, = enumerator.next
yielder << item
end
end
end
|
ruby
|
def to_enum(match: '*', count: 10, with_scores: false)
enumerator = self.connection.zscan_each(@key, match: match, count: count)
return enumerator if with_scores
return Enumerator.new do |yielder|
loop do
item, = enumerator.next
yielder << item
end
end
end
|
[
"def",
"to_enum",
"(",
"match",
":",
"'*'",
",",
"count",
":",
"10",
",",
"with_scores",
":",
"false",
")",
"enumerator",
"=",
"self",
".",
"connection",
".",
"zscan_each",
"(",
"@key",
",",
"match",
":",
"match",
",",
"count",
":",
"count",
")",
"return",
"enumerator",
"if",
"with_scores",
"return",
"Enumerator",
".",
"new",
"do",
"|",
"yielder",
"|",
"loop",
"do",
"item",
",",
"=",
"enumerator",
".",
"next",
"yielder",
"<<",
"item",
"end",
"end",
"end"
] |
Use redis-rb zscan_each method to iterate over particular keys
@return [Enumerator] base enumerator to iterate of the namespaced keys
|
[
"Use",
"redis",
"-",
"rb",
"zscan_each",
"method",
"to",
"iterate",
"over",
"particular",
"keys"
] |
c97b45e7227f8ed9029f0effff352fc4d82dc3cb
|
https://github.com/npepinpe/redstruct/blob/c97b45e7227f8ed9029f0effff352fc4d82dc3cb/lib/redstruct/sorted_set.rb#L142-L151
|
9,310
|
teodor-pripoae/scalaroid
|
lib/scalaroid/replicated_dht.rb
|
Scalaroid.ReplicatedDHT.delete
|
def delete(key, timeout = 2000)
result_raw = @conn.call(:delete, [key, timeout])
result = @conn.class.process_result_delete(result_raw)
@lastDeleteResult = result[:results]
if result[:success] == true
return result[:ok]
elsif result[:success] == :timeout
raise TimeoutError.new(result_raw)
else
raise UnknownError.new(result_raw)
end
end
|
ruby
|
def delete(key, timeout = 2000)
result_raw = @conn.call(:delete, [key, timeout])
result = @conn.class.process_result_delete(result_raw)
@lastDeleteResult = result[:results]
if result[:success] == true
return result[:ok]
elsif result[:success] == :timeout
raise TimeoutError.new(result_raw)
else
raise UnknownError.new(result_raw)
end
end
|
[
"def",
"delete",
"(",
"key",
",",
"timeout",
"=",
"2000",
")",
"result_raw",
"=",
"@conn",
".",
"call",
"(",
":delete",
",",
"[",
"key",
",",
"timeout",
"]",
")",
"result",
"=",
"@conn",
".",
"class",
".",
"process_result_delete",
"(",
"result_raw",
")",
"@lastDeleteResult",
"=",
"result",
"[",
":results",
"]",
"if",
"result",
"[",
":success",
"]",
"==",
"true",
"return",
"result",
"[",
":ok",
"]",
"elsif",
"result",
"[",
":success",
"]",
"==",
":timeout",
"raise",
"TimeoutError",
".",
"new",
"(",
"result_raw",
")",
"else",
"raise",
"UnknownError",
".",
"new",
"(",
"result_raw",
")",
"end",
"end"
] |
Create a new object using the given connection.
Tries to delete the value at the given key.
WARNING: This function can lead to inconsistent data (e.g. deleted items
can re-appear). Also when re-creating an item the version before the
delete can re-appear.
returns the number of successfully deleted items
use get_last_delete_result() to get more details
|
[
"Create",
"a",
"new",
"object",
"using",
"the",
"given",
"connection",
".",
"Tries",
"to",
"delete",
"the",
"value",
"at",
"the",
"given",
"key",
"."
] |
4e9e90e71ce3008da79a72eae40fe2f187580be2
|
https://github.com/teodor-pripoae/scalaroid/blob/4e9e90e71ce3008da79a72eae40fe2f187580be2/lib/scalaroid/replicated_dht.rb#L17-L28
|
9,311
|
vast/rokko
|
lib/rokko.rb
|
Rokko.Rokko.prettify
|
def prettify(blocks)
docs_blocks, code_blocks = blocks
# Combine all docs blocks into a single big markdown document with section
# dividers and run through the Markdown processor. Then split it back out
# into separate sections
rendered_html = self.class.renderer.render(docs_blocks.join("\n\n##### DIVIDER\n\n"))
rendered_html = ' ' if rendered_html == '' # ''.split() won't return anything useful
docs_html = rendered_html.split(/\n*<h5>DIVIDER<\/h5>\n*/m)
docs_html.zip(code_blocks)
end
|
ruby
|
def prettify(blocks)
docs_blocks, code_blocks = blocks
# Combine all docs blocks into a single big markdown document with section
# dividers and run through the Markdown processor. Then split it back out
# into separate sections
rendered_html = self.class.renderer.render(docs_blocks.join("\n\n##### DIVIDER\n\n"))
rendered_html = ' ' if rendered_html == '' # ''.split() won't return anything useful
docs_html = rendered_html.split(/\n*<h5>DIVIDER<\/h5>\n*/m)
docs_html.zip(code_blocks)
end
|
[
"def",
"prettify",
"(",
"blocks",
")",
"docs_blocks",
",",
"code_blocks",
"=",
"blocks",
"# Combine all docs blocks into a single big markdown document with section",
"# dividers and run through the Markdown processor. Then split it back out",
"# into separate sections",
"rendered_html",
"=",
"self",
".",
"class",
".",
"renderer",
".",
"render",
"(",
"docs_blocks",
".",
"join",
"(",
"\"\\n\\n##### DIVIDER\\n\\n\"",
")",
")",
"rendered_html",
"=",
"' '",
"if",
"rendered_html",
"==",
"''",
"# ''.split() won't return anything useful",
"docs_html",
"=",
"rendered_html",
".",
"split",
"(",
"/",
"\\n",
"\\/",
"\\n",
"/m",
")",
"docs_html",
".",
"zip",
"(",
"code_blocks",
")",
"end"
] |
Take the result of `split` and apply Markdown formatting to comments
|
[
"Take",
"the",
"result",
"of",
"split",
"and",
"apply",
"Markdown",
"formatting",
"to",
"comments"
] |
37f451db3d0bd92151809fcaba5a88bb597bbcc0
|
https://github.com/vast/rokko/blob/37f451db3d0bd92151809fcaba5a88bb597bbcc0/lib/rokko.rb#L150-L161
|
9,312
|
daily-scrum/domain_neutral
|
lib/domain_neutral/symbolized_class.rb
|
DomainNeutral.SymbolizedClass.method_missing
|
def method_missing(method, *args)
if method.to_s =~ /^(\w+)\?$/
v = self.class.find_by_symbol($1)
raise NameError unless v
other = v.to_sym
self.class.class_eval { define_method(method) { self.to_sym == other }}
return self.to_sym == other
end
super
end
|
ruby
|
def method_missing(method, *args)
if method.to_s =~ /^(\w+)\?$/
v = self.class.find_by_symbol($1)
raise NameError unless v
other = v.to_sym
self.class.class_eval { define_method(method) { self.to_sym == other }}
return self.to_sym == other
end
super
end
|
[
"def",
"method_missing",
"(",
"method",
",",
"*",
"args",
")",
"if",
"method",
".",
"to_s",
"=~",
"/",
"\\w",
"\\?",
"/",
"v",
"=",
"self",
".",
"class",
".",
"find_by_symbol",
"(",
"$1",
")",
"raise",
"NameError",
"unless",
"v",
"other",
"=",
"v",
".",
"to_sym",
"self",
".",
"class",
".",
"class_eval",
"{",
"define_method",
"(",
"method",
")",
"{",
"self",
".",
"to_sym",
"==",
"other",
"}",
"}",
"return",
"self",
".",
"to_sym",
"==",
"other",
"end",
"super",
"end"
] |
Allow to test for a specific role or similar like Role.accountant?
|
[
"Allow",
"to",
"test",
"for",
"a",
"specific",
"role",
"or",
"similar",
"like",
"Role",
".",
"accountant?"
] |
9176915226c00ef3eff782c216922ee4ab4f06c5
|
https://github.com/daily-scrum/domain_neutral/blob/9176915226c00ef3eff782c216922ee4ab4f06c5/lib/domain_neutral/symbolized_class.rb#L154-L163
|
9,313
|
daily-scrum/domain_neutral
|
lib/domain_neutral/symbolized_class.rb
|
DomainNeutral.SymbolizedClass.flush_cache
|
def flush_cache
Rails.cache.delete([self.class.name, symbol_was.to_s])
Rails.cache.delete([self.class.name, id])
end
|
ruby
|
def flush_cache
Rails.cache.delete([self.class.name, symbol_was.to_s])
Rails.cache.delete([self.class.name, id])
end
|
[
"def",
"flush_cache",
"Rails",
".",
"cache",
".",
"delete",
"(",
"[",
"self",
".",
"class",
".",
"name",
",",
"symbol_was",
".",
"to_s",
"]",
")",
"Rails",
".",
"cache",
".",
"delete",
"(",
"[",
"self",
".",
"class",
".",
"name",
",",
"id",
"]",
")",
"end"
] |
Flushes cache if record is saved
|
[
"Flushes",
"cache",
"if",
"record",
"is",
"saved"
] |
9176915226c00ef3eff782c216922ee4ab4f06c5
|
https://github.com/daily-scrum/domain_neutral/blob/9176915226c00ef3eff782c216922ee4ab4f06c5/lib/domain_neutral/symbolized_class.rb#L173-L176
|
9,314
|
koffeinfrei/technologist
|
lib/technologist/git_repository.rb
|
Technologist.GitRepository.find_blob
|
def find_blob(blob_name, current_tree = root_tree, &block)
blob = current_tree[blob_name]
if blob
blob = repository.lookup(blob[:oid])
if !block_given? || yield(blob)
return blob
end
end
# recurse
current_tree.each_tree do |sub_tree|
blob = find_blob(blob_name, repository.lookup(sub_tree[:oid]), &block)
break blob if blob
end
end
|
ruby
|
def find_blob(blob_name, current_tree = root_tree, &block)
blob = current_tree[blob_name]
if blob
blob = repository.lookup(blob[:oid])
if !block_given? || yield(blob)
return blob
end
end
# recurse
current_tree.each_tree do |sub_tree|
blob = find_blob(blob_name, repository.lookup(sub_tree[:oid]), &block)
break blob if blob
end
end
|
[
"def",
"find_blob",
"(",
"blob_name",
",",
"current_tree",
"=",
"root_tree",
",",
"&",
"block",
")",
"blob",
"=",
"current_tree",
"[",
"blob_name",
"]",
"if",
"blob",
"blob",
"=",
"repository",
".",
"lookup",
"(",
"blob",
"[",
":oid",
"]",
")",
"if",
"!",
"block_given?",
"||",
"yield",
"(",
"blob",
")",
"return",
"blob",
"end",
"end",
"# recurse",
"current_tree",
".",
"each_tree",
"do",
"|",
"sub_tree",
"|",
"blob",
"=",
"find_blob",
"(",
"blob_name",
",",
"repository",
".",
"lookup",
"(",
"sub_tree",
"[",
":oid",
"]",
")",
",",
"block",
")",
"break",
"blob",
"if",
"blob",
"end",
"end"
] |
Recursively searches for the blob identified by `blob_name`
in all subdirectories in the repository. A blob is usually either
a file or a directory.
@param blob_name [String] the blob name
@param current_tree [Rugged::Tree] the git directory tree in which to look for the blob.
Defaults to the root tree (see `#root_tree`).
@yield [Rugged::Blob] Yields the found blob to an optional block.
If the block returns `true` it means that the file is found and
recursion is stopped. If the return value is `false`, the resursion continues.
@return [Rugged::Blob] The blob blob or nil if it cannot be found.
|
[
"Recursively",
"searches",
"for",
"the",
"blob",
"identified",
"by",
"blob_name",
"in",
"all",
"subdirectories",
"in",
"the",
"repository",
".",
"A",
"blob",
"is",
"usually",
"either",
"a",
"file",
"or",
"a",
"directory",
"."
] |
0fd1d5c07c6d73ac5a184b26ad6db40981388573
|
https://github.com/koffeinfrei/technologist/blob/0fd1d5c07c6d73ac5a184b26ad6db40981388573/lib/technologist/git_repository.rb#L28-L43
|
9,315
|
neiljohari/scram
|
app/models/scram/target.rb
|
Scram.Target.conditions_hash_validations
|
def conditions_hash_validations
conditions.each do |comparator, mappings|
errors.add(:conditions, "can't use undefined comparators") unless Scram::DSL::Definitions::COMPARATORS.keys.include? comparator.to_sym
errors.add(:conditions, "comparators must have values of type Hash") unless mappings.is_a? Hash
end
end
|
ruby
|
def conditions_hash_validations
conditions.each do |comparator, mappings|
errors.add(:conditions, "can't use undefined comparators") unless Scram::DSL::Definitions::COMPARATORS.keys.include? comparator.to_sym
errors.add(:conditions, "comparators must have values of type Hash") unless mappings.is_a? Hash
end
end
|
[
"def",
"conditions_hash_validations",
"conditions",
".",
"each",
"do",
"|",
"comparator",
",",
"mappings",
"|",
"errors",
".",
"add",
"(",
":conditions",
",",
"\"can't use undefined comparators\"",
")",
"unless",
"Scram",
"::",
"DSL",
"::",
"Definitions",
"::",
"COMPARATORS",
".",
"keys",
".",
"include?",
"comparator",
".",
"to_sym",
"errors",
".",
"add",
"(",
":conditions",
",",
"\"comparators must have values of type Hash\"",
")",
"unless",
"mappings",
".",
"is_a?",
"Hash",
"end",
"end"
] |
Validates that the conditions Hash follows an expected format
|
[
"Validates",
"that",
"the",
"conditions",
"Hash",
"follows",
"an",
"expected",
"format"
] |
df3e48e9e9cab4b363b1370df5991319d21c256d
|
https://github.com/neiljohari/scram/blob/df3e48e9e9cab4b363b1370df5991319d21c256d/app/models/scram/target.rb#L75-L80
|
9,316
|
postmodern/data_paths
|
lib/data_paths/methods.rb
|
DataPaths.Methods.register_data_path
|
def register_data_path(path)
path = File.expand_path(path)
DataPaths.register(path)
data_paths << path unless data_paths.include?(path)
return path
end
|
ruby
|
def register_data_path(path)
path = File.expand_path(path)
DataPaths.register(path)
data_paths << path unless data_paths.include?(path)
return path
end
|
[
"def",
"register_data_path",
"(",
"path",
")",
"path",
"=",
"File",
".",
"expand_path",
"(",
"path",
")",
"DataPaths",
".",
"register",
"(",
"path",
")",
"data_paths",
"<<",
"path",
"unless",
"data_paths",
".",
"include?",
"(",
"path",
")",
"return",
"path",
"end"
] |
Registers a path as a data directory.
@param [String] path
The path to add to {DataPaths.paths}.
@return [String]
The fully qualified form of the specified path.
@example
register_data_dir File.join(File.dirname(__FILE__),'..','..','..','data')
@raise [RuntimeError]
The specified path is not a directory.
@since 0.3.0
|
[
"Registers",
"a",
"path",
"as",
"a",
"data",
"directory",
"."
] |
17938884593b458b90b591a353686945884749d6
|
https://github.com/postmodern/data_paths/blob/17938884593b458b90b591a353686945884749d6/lib/data_paths/methods.rb#L30-L37
|
9,317
|
postmodern/data_paths
|
lib/data_paths/methods.rb
|
DataPaths.Methods.unregister_data_path
|
def unregister_data_path(path)
path = File.expand_path(path)
self.data_paths.delete(path)
return DataPaths.unregister!(path)
end
|
ruby
|
def unregister_data_path(path)
path = File.expand_path(path)
self.data_paths.delete(path)
return DataPaths.unregister!(path)
end
|
[
"def",
"unregister_data_path",
"(",
"path",
")",
"path",
"=",
"File",
".",
"expand_path",
"(",
"path",
")",
"self",
".",
"data_paths",
".",
"delete",
"(",
"path",
")",
"return",
"DataPaths",
".",
"unregister!",
"(",
"path",
")",
"end"
] |
Unregisters any matching data directories.
@param [String] path
The path to unregister.
@return [String]
The unregistered data path.
@since 0.3.0
|
[
"Unregisters",
"any",
"matching",
"data",
"directories",
"."
] |
17938884593b458b90b591a353686945884749d6
|
https://github.com/postmodern/data_paths/blob/17938884593b458b90b591a353686945884749d6/lib/data_paths/methods.rb#L60-L65
|
9,318
|
postmodern/data_paths
|
lib/data_paths/methods.rb
|
DataPaths.Methods.unregister_data_paths
|
def unregister_data_paths
data_paths.each { |path| DataPaths.unregister!(path) }
data_paths.clear
return true
end
|
ruby
|
def unregister_data_paths
data_paths.each { |path| DataPaths.unregister!(path) }
data_paths.clear
return true
end
|
[
"def",
"unregister_data_paths",
"data_paths",
".",
"each",
"{",
"|",
"path",
"|",
"DataPaths",
".",
"unregister!",
"(",
"path",
")",
"}",
"data_paths",
".",
"clear",
"return",
"true",
"end"
] |
Unregisters all previously registered data directories.
@return [true]
Specifies all data paths were successfully unregistered.
@since 0.3.0
|
[
"Unregisters",
"all",
"previously",
"registered",
"data",
"directories",
"."
] |
17938884593b458b90b591a353686945884749d6
|
https://github.com/postmodern/data_paths/blob/17938884593b458b90b591a353686945884749d6/lib/data_paths/methods.rb#L85-L89
|
9,319
|
ktonon/code_node
|
spec/fixtures/activerecord/src/active_record/identity_map.rb
|
ActiveRecord.IdentityMap.reinit_with
|
def reinit_with(coder)
@attributes_cache = {}
dirty = @changed_attributes.keys
attributes = self.class.initialize_attributes(coder['attributes'].except(*dirty))
@attributes.update(attributes)
@changed_attributes.update(coder['attributes'].slice(*dirty))
@changed_attributes.delete_if{|k,v| v.eql? @attributes[k]}
run_callbacks :find
self
end
|
ruby
|
def reinit_with(coder)
@attributes_cache = {}
dirty = @changed_attributes.keys
attributes = self.class.initialize_attributes(coder['attributes'].except(*dirty))
@attributes.update(attributes)
@changed_attributes.update(coder['attributes'].slice(*dirty))
@changed_attributes.delete_if{|k,v| v.eql? @attributes[k]}
run_callbacks :find
self
end
|
[
"def",
"reinit_with",
"(",
"coder",
")",
"@attributes_cache",
"=",
"{",
"}",
"dirty",
"=",
"@changed_attributes",
".",
"keys",
"attributes",
"=",
"self",
".",
"class",
".",
"initialize_attributes",
"(",
"coder",
"[",
"'attributes'",
"]",
".",
"except",
"(",
"dirty",
")",
")",
"@attributes",
".",
"update",
"(",
"attributes",
")",
"@changed_attributes",
".",
"update",
"(",
"coder",
"[",
"'attributes'",
"]",
".",
"slice",
"(",
"dirty",
")",
")",
"@changed_attributes",
".",
"delete_if",
"{",
"|",
"k",
",",
"v",
"|",
"v",
".",
"eql?",
"@attributes",
"[",
"k",
"]",
"}",
"run_callbacks",
":find",
"self",
"end"
] |
Reinitialize an Identity Map model object from +coder+.
+coder+ must contain the attributes necessary for initializing an empty
model object.
|
[
"Reinitialize",
"an",
"Identity",
"Map",
"model",
"object",
"from",
"+",
"coder",
"+",
".",
"+",
"coder",
"+",
"must",
"contain",
"the",
"attributes",
"necessary",
"for",
"initializing",
"an",
"empty",
"model",
"object",
"."
] |
48d5d1a7442d9cade602be4fb782a1b56c7677f5
|
https://github.com/ktonon/code_node/blob/48d5d1a7442d9cade602be4fb782a1b56c7677f5/spec/fixtures/activerecord/src/active_record/identity_map.rb#L118-L129
|
9,320
|
m-nasser/discourse_mountable_sso
|
app/controllers/discourse_mountable_sso/discourse_sso_controller.rb
|
DiscourseMountableSso.DiscourseSsoController.sso
|
def sso
require "discourse_mountable_sso/single_sign_on"
sso = DiscourseMountableSso::SingleSignOn.parse(
((session[:discourse_mountable_sso] || {}).delete(:query_string).presence || request.query_string),
@config.secret
)
discourse_data = send @config.discourse_data_method
discourse_data.each_pair {|k,v| sso.send("#{ k }=", v) }
sso.sso_secret = @config.secret
yield sso if block_given?
redirect_to sso.to_url("#{@config.discourse_url}/session/sso_login")
end
|
ruby
|
def sso
require "discourse_mountable_sso/single_sign_on"
sso = DiscourseMountableSso::SingleSignOn.parse(
((session[:discourse_mountable_sso] || {}).delete(:query_string).presence || request.query_string),
@config.secret
)
discourse_data = send @config.discourse_data_method
discourse_data.each_pair {|k,v| sso.send("#{ k }=", v) }
sso.sso_secret = @config.secret
yield sso if block_given?
redirect_to sso.to_url("#{@config.discourse_url}/session/sso_login")
end
|
[
"def",
"sso",
"require",
"\"discourse_mountable_sso/single_sign_on\"",
"sso",
"=",
"DiscourseMountableSso",
"::",
"SingleSignOn",
".",
"parse",
"(",
"(",
"(",
"session",
"[",
":discourse_mountable_sso",
"]",
"||",
"{",
"}",
")",
".",
"delete",
"(",
":query_string",
")",
".",
"presence",
"||",
"request",
".",
"query_string",
")",
",",
"@config",
".",
"secret",
")",
"discourse_data",
"=",
"send",
"@config",
".",
"discourse_data_method",
"discourse_data",
".",
"each_pair",
"{",
"|",
"k",
",",
"v",
"|",
"sso",
".",
"send",
"(",
"\"#{ k }=\"",
",",
"v",
")",
"}",
"sso",
".",
"sso_secret",
"=",
"@config",
".",
"secret",
"yield",
"sso",
"if",
"block_given?",
"redirect_to",
"sso",
".",
"to_url",
"(",
"\"#{@config.discourse_url}/session/sso_login\"",
")",
"end"
] |
ensures user must login
|
[
"ensures",
"user",
"must",
"login"
] |
0adb568ea0ec4c06a4dc65abb95a9badce460bf1
|
https://github.com/m-nasser/discourse_mountable_sso/blob/0adb568ea0ec4c06a4dc65abb95a9badce460bf1/app/controllers/discourse_mountable_sso/discourse_sso_controller.rb#L6-L20
|
9,321
|
jtadeulopes/meme
|
lib/meme/info.rb
|
Meme.Info.followers
|
def followers(count=10)
count = 0 if count.is_a?(Symbol) && count == :all
query = "SELECT * FROM meme.followers(#{count}) WHERE owner_guid='#{self.guid}'"
parse = Request.parse(query)
if parse
results = parse['query']['results']
results.nil? ? nil : results['meme'].map {|m| Info.new(m)}
else
parse.error!
end
end
|
ruby
|
def followers(count=10)
count = 0 if count.is_a?(Symbol) && count == :all
query = "SELECT * FROM meme.followers(#{count}) WHERE owner_guid='#{self.guid}'"
parse = Request.parse(query)
if parse
results = parse['query']['results']
results.nil? ? nil : results['meme'].map {|m| Info.new(m)}
else
parse.error!
end
end
|
[
"def",
"followers",
"(",
"count",
"=",
"10",
")",
"count",
"=",
"0",
"if",
"count",
".",
"is_a?",
"(",
"Symbol",
")",
"&&",
"count",
"==",
":all",
"query",
"=",
"\"SELECT * FROM meme.followers(#{count}) WHERE owner_guid='#{self.guid}'\"",
"parse",
"=",
"Request",
".",
"parse",
"(",
"query",
")",
"if",
"parse",
"results",
"=",
"parse",
"[",
"'query'",
"]",
"[",
"'results'",
"]",
"results",
".",
"nil?",
"?",
"nil",
":",
"results",
"[",
"'meme'",
"]",
".",
"map",
"{",
"|",
"m",
"|",
"Info",
".",
"new",
"(",
"m",
")",
"}",
"else",
"parse",
".",
"error!",
"end",
"end"
] |
Return user followers
Example:
# Search user
user = Meme::Info.find('jtadeulopes')
# Default
followers = user.followers
followers.count
=> 10
# Specify a count
followers = user.followers(100)
followers.count
=> 100
# All followers
followers = user.followers(:all)
followers.count
follower = followers.first
follower.name
=> "zigotto"
follower.url
=> "http://meme.yahoo.com/zigotto/"
|
[
"Return",
"user",
"followers"
] |
dc3888c4af3c30d49053ec53f328187cb9255e88
|
https://github.com/jtadeulopes/meme/blob/dc3888c4af3c30d49053ec53f328187cb9255e88/lib/meme/info.rb#L81-L91
|
9,322
|
jtadeulopes/meme
|
lib/meme/info.rb
|
Meme.Info.posts
|
def posts(quantity=0)
query = "SELECT * FROM meme.posts(#{quantity}) WHERE owner_guid='#{self.guid}';"
parse = Request.parse(query)
if parse
results = parse['query']['results']
results.nil? ? nil : results['post'].map {|m| Post.new(m)}
else
parse.error!
end
end
|
ruby
|
def posts(quantity=0)
query = "SELECT * FROM meme.posts(#{quantity}) WHERE owner_guid='#{self.guid}';"
parse = Request.parse(query)
if parse
results = parse['query']['results']
results.nil? ? nil : results['post'].map {|m| Post.new(m)}
else
parse.error!
end
end
|
[
"def",
"posts",
"(",
"quantity",
"=",
"0",
")",
"query",
"=",
"\"SELECT * FROM meme.posts(#{quantity}) WHERE owner_guid='#{self.guid}';\"",
"parse",
"=",
"Request",
".",
"parse",
"(",
"query",
")",
"if",
"parse",
"results",
"=",
"parse",
"[",
"'query'",
"]",
"[",
"'results'",
"]",
"results",
".",
"nil?",
"?",
"nil",
":",
"results",
"[",
"'post'",
"]",
".",
"map",
"{",
"|",
"m",
"|",
"Post",
".",
"new",
"(",
"m",
")",
"}",
"else",
"parse",
".",
"error!",
"end",
"end"
] |
Retrieves all posts of an user
|
[
"Retrieves",
"all",
"posts",
"of",
"an",
"user"
] |
dc3888c4af3c30d49053ec53f328187cb9255e88
|
https://github.com/jtadeulopes/meme/blob/dc3888c4af3c30d49053ec53f328187cb9255e88/lib/meme/info.rb#L128-L137
|
9,323
|
sugaryourcoffee/syclink
|
lib/syclink/designer.rb
|
SycLink.Designer.add_links_from_file
|
def add_links_from_file(file)
File.foreach(file) do |line|
next if line.chomp.empty?
url, name, description, tag = line.chomp.split(';')
website.add_link(Link.new(url, { name: name,
description: description,
tag: tag }))
end
end
|
ruby
|
def add_links_from_file(file)
File.foreach(file) do |line|
next if line.chomp.empty?
url, name, description, tag = line.chomp.split(';')
website.add_link(Link.new(url, { name: name,
description: description,
tag: tag }))
end
end
|
[
"def",
"add_links_from_file",
"(",
"file",
")",
"File",
".",
"foreach",
"(",
"file",
")",
"do",
"|",
"line",
"|",
"next",
"if",
"line",
".",
"chomp",
".",
"empty?",
"url",
",",
"name",
",",
"description",
",",
"tag",
"=",
"line",
".",
"chomp",
".",
"split",
"(",
"';'",
")",
"website",
".",
"add_link",
"(",
"Link",
".",
"new",
"(",
"url",
",",
"{",
"name",
":",
"name",
",",
"description",
":",
"description",
",",
"tag",
":",
"tag",
"}",
")",
")",
"end",
"end"
] |
Reads arguments from a CSV file and creates links accordingly. The links
are added to the websie
|
[
"Reads",
"arguments",
"from",
"a",
"CSV",
"file",
"and",
"creates",
"links",
"accordingly",
".",
"The",
"links",
"are",
"added",
"to",
"the",
"websie"
] |
941ee2045c946daa1e0db394eb643aa82c1254cc
|
https://github.com/sugaryourcoffee/syclink/blob/941ee2045c946daa1e0db394eb643aa82c1254cc/lib/syclink/designer.rb#L33-L41
|
9,324
|
sugaryourcoffee/syclink
|
lib/syclink/designer.rb
|
SycLink.Designer.export
|
def export(format)
message = "to_#{format.downcase}"
if website.respond_to? message
website.send(message)
else
raise "cannot export to #{format}"
end
end
|
ruby
|
def export(format)
message = "to_#{format.downcase}"
if website.respond_to? message
website.send(message)
else
raise "cannot export to #{format}"
end
end
|
[
"def",
"export",
"(",
"format",
")",
"message",
"=",
"\"to_#{format.downcase}\"",
"if",
"website",
".",
"respond_to?",
"message",
"website",
".",
"send",
"(",
"message",
")",
"else",
"raise",
"\"cannot export to #{format}\"",
"end",
"end"
] |
Export links to specified format
|
[
"Export",
"links",
"to",
"specified",
"format"
] |
941ee2045c946daa1e0db394eb643aa82c1254cc
|
https://github.com/sugaryourcoffee/syclink/blob/941ee2045c946daa1e0db394eb643aa82c1254cc/lib/syclink/designer.rb#L51-L58
|
9,325
|
sugaryourcoffee/syclink
|
lib/syclink/designer.rb
|
SycLink.Designer.update_links_from_file
|
def update_links_from_file(file)
File.foreach(file) do |line|
next if line.chomp.empty?
url, name, description, tag = line.chomp.split(';')
website.find_links(url).first.update({ name: name,
description: description,
tag: tag })
end
end
|
ruby
|
def update_links_from_file(file)
File.foreach(file) do |line|
next if line.chomp.empty?
url, name, description, tag = line.chomp.split(';')
website.find_links(url).first.update({ name: name,
description: description,
tag: tag })
end
end
|
[
"def",
"update_links_from_file",
"(",
"file",
")",
"File",
".",
"foreach",
"(",
"file",
")",
"do",
"|",
"line",
"|",
"next",
"if",
"line",
".",
"chomp",
".",
"empty?",
"url",
",",
"name",
",",
"description",
",",
"tag",
"=",
"line",
".",
"chomp",
".",
"split",
"(",
"';'",
")",
"website",
".",
"find_links",
"(",
"url",
")",
".",
"first",
".",
"update",
"(",
"{",
"name",
":",
"name",
",",
"description",
":",
"description",
",",
"tag",
":",
"tag",
"}",
")",
"end",
"end"
] |
Updates links read from a file
|
[
"Updates",
"links",
"read",
"from",
"a",
"file"
] |
941ee2045c946daa1e0db394eb643aa82c1254cc
|
https://github.com/sugaryourcoffee/syclink/blob/941ee2045c946daa1e0db394eb643aa82c1254cc/lib/syclink/designer.rb#L97-L105
|
9,326
|
sugaryourcoffee/syclink
|
lib/syclink/designer.rb
|
SycLink.Designer.remove_links
|
def remove_links(urls)
urls.map { |url| list_links({ url: url }) }.flatten.compact.each do |link|
website.remove_link(link)
end
end
|
ruby
|
def remove_links(urls)
urls.map { |url| list_links({ url: url }) }.flatten.compact.each do |link|
website.remove_link(link)
end
end
|
[
"def",
"remove_links",
"(",
"urls",
")",
"urls",
".",
"map",
"{",
"|",
"url",
"|",
"list_links",
"(",
"{",
"url",
":",
"url",
"}",
")",
"}",
".",
"flatten",
".",
"compact",
".",
"each",
"do",
"|",
"link",
"|",
"website",
".",
"remove_link",
"(",
"link",
")",
"end",
"end"
] |
Deletes one or more links from the website. Returns the deleted links.
Expects the links provided in an array
|
[
"Deletes",
"one",
"or",
"more",
"links",
"from",
"the",
"website",
".",
"Returns",
"the",
"deleted",
"links",
".",
"Expects",
"the",
"links",
"provided",
"in",
"an",
"array"
] |
941ee2045c946daa1e0db394eb643aa82c1254cc
|
https://github.com/sugaryourcoffee/syclink/blob/941ee2045c946daa1e0db394eb643aa82c1254cc/lib/syclink/designer.rb#L114-L118
|
9,327
|
sugaryourcoffee/syclink
|
lib/syclink/designer.rb
|
SycLink.Designer.remove_links_from_file
|
def remove_links_from_file(file)
urls = File.foreach(file).map { |url| url.chomp unless url.empty? }
remove_links(urls)
end
|
ruby
|
def remove_links_from_file(file)
urls = File.foreach(file).map { |url| url.chomp unless url.empty? }
remove_links(urls)
end
|
[
"def",
"remove_links_from_file",
"(",
"file",
")",
"urls",
"=",
"File",
".",
"foreach",
"(",
"file",
")",
".",
"map",
"{",
"|",
"url",
"|",
"url",
".",
"chomp",
"unless",
"url",
".",
"empty?",
"}",
"remove_links",
"(",
"urls",
")",
"end"
] |
Deletes links based on URLs that are provided in a file. Each URL has to
be in one line
|
[
"Deletes",
"links",
"based",
"on",
"URLs",
"that",
"are",
"provided",
"in",
"a",
"file",
".",
"Each",
"URL",
"has",
"to",
"be",
"in",
"one",
"line"
] |
941ee2045c946daa1e0db394eb643aa82c1254cc
|
https://github.com/sugaryourcoffee/syclink/blob/941ee2045c946daa1e0db394eb643aa82c1254cc/lib/syclink/designer.rb#L122-L125
|
9,328
|
sugaryourcoffee/syclink
|
lib/syclink/designer.rb
|
SycLink.Designer.save_website
|
def save_website(directory)
File.open(yaml_file(directory, website.title), 'w') do |f|
YAML.dump(website, f)
end
end
|
ruby
|
def save_website(directory)
File.open(yaml_file(directory, website.title), 'w') do |f|
YAML.dump(website, f)
end
end
|
[
"def",
"save_website",
"(",
"directory",
")",
"File",
".",
"open",
"(",
"yaml_file",
"(",
"directory",
",",
"website",
".",
"title",
")",
",",
"'w'",
")",
"do",
"|",
"f",
"|",
"YAML",
".",
"dump",
"(",
"website",
",",
"f",
")",
"end",
"end"
] |
Saves the website to the specified directory with the downcased name of
the website and the extension 'website'. The website is save as YAML
|
[
"Saves",
"the",
"website",
"to",
"the",
"specified",
"directory",
"with",
"the",
"downcased",
"name",
"of",
"the",
"website",
"and",
"the",
"extension",
"website",
".",
"The",
"website",
"is",
"save",
"as",
"YAML"
] |
941ee2045c946daa1e0db394eb643aa82c1254cc
|
https://github.com/sugaryourcoffee/syclink/blob/941ee2045c946daa1e0db394eb643aa82c1254cc/lib/syclink/designer.rb#L129-L133
|
9,329
|
sugaryourcoffee/syclink
|
lib/syclink/designer.rb
|
SycLink.Designer.delete_website
|
def delete_website(directory)
if File.exists? yaml_file(directory, website.title)
FileUtils.rm(yaml_file(directory, website.title))
end
end
|
ruby
|
def delete_website(directory)
if File.exists? yaml_file(directory, website.title)
FileUtils.rm(yaml_file(directory, website.title))
end
end
|
[
"def",
"delete_website",
"(",
"directory",
")",
"if",
"File",
".",
"exists?",
"yaml_file",
"(",
"directory",
",",
"website",
".",
"title",
")",
"FileUtils",
".",
"rm",
"(",
"yaml_file",
"(",
"directory",
",",
"website",
".",
"title",
")",
")",
"end",
"end"
] |
Deletes the website if it already exists
|
[
"Deletes",
"the",
"website",
"if",
"it",
"already",
"exists"
] |
941ee2045c946daa1e0db394eb643aa82c1254cc
|
https://github.com/sugaryourcoffee/syclink/blob/941ee2045c946daa1e0db394eb643aa82c1254cc/lib/syclink/designer.rb#L142-L146
|
9,330
|
cbrumelle/blueprintr
|
lib/blueprint-css/lib/blueprint/css_parser.rb
|
Blueprint.CSSParser.parse
|
def parse(data = nil)
data ||= @raw_data
# wrapper array holding hashes of css tags/rules
css_out = []
# clear initial spaces
data.strip_side_space!.strip_space!
# split on end of assignments
data.split('}').each_with_index do |assignments, index|
# split again to separate tags from rules
tags, styles = assignments.split('{').map{|a| a.strip_side_space!}
unless styles.blank?
# clean up tags and apply namespaces as needed
tags.strip_selector_space!
tags.gsub!(/\./, ".#{namespace}") unless namespace.blank?
# split on semicolon to iterate through each rule
rules = []
styles.split(';').each do |key_val_pair|
unless key_val_pair.nil?
# split by property/val and append to rules array with correct declaration
property, value = key_val_pair.split(':', 2).map{|kv| kv.strip_side_space!}
break unless property && value
rules << "#{property}:#{value};"
end
end
# now keeps track of index as hashes don't keep track of position (which will be fixed in Ruby 1.9)
css_out << {:tags => tags, :rules => rules.join, :idx => index} unless tags.blank? || rules.to_s.blank?
end
end
css_out
end
|
ruby
|
def parse(data = nil)
data ||= @raw_data
# wrapper array holding hashes of css tags/rules
css_out = []
# clear initial spaces
data.strip_side_space!.strip_space!
# split on end of assignments
data.split('}').each_with_index do |assignments, index|
# split again to separate tags from rules
tags, styles = assignments.split('{').map{|a| a.strip_side_space!}
unless styles.blank?
# clean up tags and apply namespaces as needed
tags.strip_selector_space!
tags.gsub!(/\./, ".#{namespace}") unless namespace.blank?
# split on semicolon to iterate through each rule
rules = []
styles.split(';').each do |key_val_pair|
unless key_val_pair.nil?
# split by property/val and append to rules array with correct declaration
property, value = key_val_pair.split(':', 2).map{|kv| kv.strip_side_space!}
break unless property && value
rules << "#{property}:#{value};"
end
end
# now keeps track of index as hashes don't keep track of position (which will be fixed in Ruby 1.9)
css_out << {:tags => tags, :rules => rules.join, :idx => index} unless tags.blank? || rules.to_s.blank?
end
end
css_out
end
|
[
"def",
"parse",
"(",
"data",
"=",
"nil",
")",
"data",
"||=",
"@raw_data",
"# wrapper array holding hashes of css tags/rules",
"css_out",
"=",
"[",
"]",
"# clear initial spaces",
"data",
".",
"strip_side_space!",
".",
"strip_space!",
"# split on end of assignments",
"data",
".",
"split",
"(",
"'}'",
")",
".",
"each_with_index",
"do",
"|",
"assignments",
",",
"index",
"|",
"# split again to separate tags from rules",
"tags",
",",
"styles",
"=",
"assignments",
".",
"split",
"(",
"'{'",
")",
".",
"map",
"{",
"|",
"a",
"|",
"a",
".",
"strip_side_space!",
"}",
"unless",
"styles",
".",
"blank?",
"# clean up tags and apply namespaces as needed",
"tags",
".",
"strip_selector_space!",
"tags",
".",
"gsub!",
"(",
"/",
"\\.",
"/",
",",
"\".#{namespace}\"",
")",
"unless",
"namespace",
".",
"blank?",
"# split on semicolon to iterate through each rule",
"rules",
"=",
"[",
"]",
"styles",
".",
"split",
"(",
"';'",
")",
".",
"each",
"do",
"|",
"key_val_pair",
"|",
"unless",
"key_val_pair",
".",
"nil?",
"# split by property/val and append to rules array with correct declaration",
"property",
",",
"value",
"=",
"key_val_pair",
".",
"split",
"(",
"':'",
",",
"2",
")",
".",
"map",
"{",
"|",
"kv",
"|",
"kv",
".",
"strip_side_space!",
"}",
"break",
"unless",
"property",
"&&",
"value",
"rules",
"<<",
"\"#{property}:#{value};\"",
"end",
"end",
"# now keeps track of index as hashes don't keep track of position (which will be fixed in Ruby 1.9)",
"css_out",
"<<",
"{",
":tags",
"=>",
"tags",
",",
":rules",
"=>",
"rules",
".",
"join",
",",
":idx",
"=>",
"index",
"}",
"unless",
"tags",
".",
"blank?",
"||",
"rules",
".",
"to_s",
".",
"blank?",
"end",
"end",
"css_out",
"end"
] |
returns a hash of all CSS data passed
==== Options
* <tt>data</tt> -- CSS string; defaults to string passed into the constructor
|
[
"returns",
"a",
"hash",
"of",
"all",
"CSS",
"data",
"passed"
] |
b414436f614a8d97d77b47b588ddcf3f5e61b6bd
|
https://github.com/cbrumelle/blueprintr/blob/b414436f614a8d97d77b47b588ddcf3f5e61b6bd/lib/blueprint-css/lib/blueprint/css_parser.rb#L26-L58
|
9,331
|
aleak/bender
|
lib/bender/cli.rb
|
Bender.CLI.load_enviroment
|
def load_enviroment(file = nil)
file ||= "."
if File.directory?(file) && File.exists?(File.expand_path("#{file}/config/environment.rb"))
require 'rails'
require File.expand_path("#{file}/config/environment.rb")
if defined?(::Rails) && ::Rails.respond_to?(:application)
# Rails 3
::Rails.application.eager_load!
elsif defined?(::Rails::Initializer)
# Rails 2.3
$rails_rake_task = false
::Rails::Initializer.run :load_application_classes
end
elsif File.file?(file)
require File.expand_path(file)
end
end
|
ruby
|
def load_enviroment(file = nil)
file ||= "."
if File.directory?(file) && File.exists?(File.expand_path("#{file}/config/environment.rb"))
require 'rails'
require File.expand_path("#{file}/config/environment.rb")
if defined?(::Rails) && ::Rails.respond_to?(:application)
# Rails 3
::Rails.application.eager_load!
elsif defined?(::Rails::Initializer)
# Rails 2.3
$rails_rake_task = false
::Rails::Initializer.run :load_application_classes
end
elsif File.file?(file)
require File.expand_path(file)
end
end
|
[
"def",
"load_enviroment",
"(",
"file",
"=",
"nil",
")",
"file",
"||=",
"\".\"",
"if",
"File",
".",
"directory?",
"(",
"file",
")",
"&&",
"File",
".",
"exists?",
"(",
"File",
".",
"expand_path",
"(",
"\"#{file}/config/environment.rb\"",
")",
")",
"require",
"'rails'",
"require",
"File",
".",
"expand_path",
"(",
"\"#{file}/config/environment.rb\"",
")",
"if",
"defined?",
"(",
"::",
"Rails",
")",
"&&",
"::",
"Rails",
".",
"respond_to?",
"(",
":application",
")",
"# Rails 3",
"::",
"Rails",
".",
"application",
".",
"eager_load!",
"elsif",
"defined?",
"(",
"::",
"Rails",
"::",
"Initializer",
")",
"# Rails 2.3",
"$rails_rake_task",
"=",
"false",
"::",
"Rails",
"::",
"Initializer",
".",
"run",
":load_application_classes",
"end",
"elsif",
"File",
".",
"file?",
"(",
"file",
")",
"require",
"File",
".",
"expand_path",
"(",
"file",
")",
"end",
"end"
] |
Loads the environment from the given configuration file.
@api private
|
[
"Loads",
"the",
"environment",
"from",
"the",
"given",
"configuration",
"file",
"."
] |
5892e6ffce84fc531d8cbf452b2676b4d012ab09
|
https://github.com/aleak/bender/blob/5892e6ffce84fc531d8cbf452b2676b4d012ab09/lib/bender/cli.rb#L56-L73
|
9,332
|
michaeledgar/amp-front
|
lib/amp-front/third_party/maruku/structures_iterators.rb
|
MaRuKu.MDElement.each_element
|
def each_element(e_node_type=nil, &block)
@children.each do |c|
if c.kind_of? MDElement
if (not e_node_type) || (e_node_type == c.node_type)
block.call c
end
c.each_element(e_node_type, &block)
end
end
end
|
ruby
|
def each_element(e_node_type=nil, &block)
@children.each do |c|
if c.kind_of? MDElement
if (not e_node_type) || (e_node_type == c.node_type)
block.call c
end
c.each_element(e_node_type, &block)
end
end
end
|
[
"def",
"each_element",
"(",
"e_node_type",
"=",
"nil",
",",
"&",
"block",
")",
"@children",
".",
"each",
"do",
"|",
"c",
"|",
"if",
"c",
".",
"kind_of?",
"MDElement",
"if",
"(",
"not",
"e_node_type",
")",
"||",
"(",
"e_node_type",
"==",
"c",
".",
"node_type",
")",
"block",
".",
"call",
"c",
"end",
"c",
".",
"each_element",
"(",
"e_node_type",
",",
"block",
")",
"end",
"end",
"end"
] |
Yields to each element of specified node_type
All elements if e_node_type is nil.
|
[
"Yields",
"to",
"each",
"element",
"of",
"specified",
"node_type",
"All",
"elements",
"if",
"e_node_type",
"is",
"nil",
"."
] |
d939b7ed9a7b0e5a3d26e536b95149f88b64e3a9
|
https://github.com/michaeledgar/amp-front/blob/d939b7ed9a7b0e5a3d26e536b95149f88b64e3a9/lib/amp-front/third_party/maruku/structures_iterators.rb#L28-L37
|
9,333
|
michaeledgar/amp-front
|
lib/amp-front/third_party/maruku/structures_iterators.rb
|
MaRuKu.MDElement.replace_each_string
|
def replace_each_string(&block)
for c in @children
if c.kind_of? MDElement
c.replace_each_string(&block)
end
end
processed = []
until @children.empty?
c = @children.shift
if c.kind_of? String
result = block.call(c)
[*result].each do |e| processed << e end
else
processed << c
end
end
@children = processed
end
|
ruby
|
def replace_each_string(&block)
for c in @children
if c.kind_of? MDElement
c.replace_each_string(&block)
end
end
processed = []
until @children.empty?
c = @children.shift
if c.kind_of? String
result = block.call(c)
[*result].each do |e| processed << e end
else
processed << c
end
end
@children = processed
end
|
[
"def",
"replace_each_string",
"(",
"&",
"block",
")",
"for",
"c",
"in",
"@children",
"if",
"c",
".",
"kind_of?",
"MDElement",
"c",
".",
"replace_each_string",
"(",
"block",
")",
"end",
"end",
"processed",
"=",
"[",
"]",
"until",
"@children",
".",
"empty?",
"c",
"=",
"@children",
".",
"shift",
"if",
"c",
".",
"kind_of?",
"String",
"result",
"=",
"block",
".",
"call",
"(",
"c",
")",
"[",
"result",
"]",
".",
"each",
"do",
"|",
"e",
"|",
"processed",
"<<",
"e",
"end",
"else",
"processed",
"<<",
"c",
"end",
"end",
"@children",
"=",
"processed",
"end"
] |
Apply passed block to each String in the hierarchy.
|
[
"Apply",
"passed",
"block",
"to",
"each",
"String",
"in",
"the",
"hierarchy",
"."
] |
d939b7ed9a7b0e5a3d26e536b95149f88b64e3a9
|
https://github.com/michaeledgar/amp-front/blob/d939b7ed9a7b0e5a3d26e536b95149f88b64e3a9/lib/amp-front/third_party/maruku/structures_iterators.rb#L40-L58
|
9,334
|
philou/rspecproxies
|
lib/rspecproxies/proxies.rb
|
RSpecProxies.Proxies.and_before_calling_original
|
def and_before_calling_original
self.and_wrap_original do |m, *args, &block|
yield *args
m.call(*args, &block)
end
end
|
ruby
|
def and_before_calling_original
self.and_wrap_original do |m, *args, &block|
yield *args
m.call(*args, &block)
end
end
|
[
"def",
"and_before_calling_original",
"self",
".",
"and_wrap_original",
"do",
"|",
"m",
",",
"*",
"args",
",",
"&",
"block",
"|",
"yield",
"args",
"m",
".",
"call",
"(",
"args",
",",
"block",
")",
"end",
"end"
] |
Will call the given block with all the actual arguments every time
the method is called
|
[
"Will",
"call",
"the",
"given",
"block",
"with",
"all",
"the",
"actual",
"arguments",
"every",
"time",
"the",
"method",
"is",
"called"
] |
7bb32654f1c4d0316e9f89161a95583333a3a66f
|
https://github.com/philou/rspecproxies/blob/7bb32654f1c4d0316e9f89161a95583333a3a66f/lib/rspecproxies/proxies.rb#L8-L13
|
9,335
|
philou/rspecproxies
|
lib/rspecproxies/proxies.rb
|
RSpecProxies.Proxies.and_after_calling_original
|
def and_after_calling_original
self.and_wrap_original do |m, *args, &block|
result = m.call(*args, &block)
yield result
result
end
end
|
ruby
|
def and_after_calling_original
self.and_wrap_original do |m, *args, &block|
result = m.call(*args, &block)
yield result
result
end
end
|
[
"def",
"and_after_calling_original",
"self",
".",
"and_wrap_original",
"do",
"|",
"m",
",",
"*",
"args",
",",
"&",
"block",
"|",
"result",
"=",
"m",
".",
"call",
"(",
"args",
",",
"block",
")",
"yield",
"result",
"result",
"end",
"end"
] |
Will call the given block with it's result every time the method
returns
|
[
"Will",
"call",
"the",
"given",
"block",
"with",
"it",
"s",
"result",
"every",
"time",
"the",
"method",
"returns"
] |
7bb32654f1c4d0316e9f89161a95583333a3a66f
|
https://github.com/philou/rspecproxies/blob/7bb32654f1c4d0316e9f89161a95583333a3a66f/lib/rspecproxies/proxies.rb#L17-L23
|
9,336
|
pablogonzalezalba/acts_as_integer_infinitable
|
lib/acts_as_integer_infinitable.rb
|
ActsAsIntegerInfinitable.ClassMethods.acts_as_integer_infinitable
|
def acts_as_integer_infinitable(fields, options = {})
options[:infinity_value] = -1 unless options.key? :infinity_value
fields.each do |field|
define_method("#{field}=") do |value|
int_value = value == Float::INFINITY ? options[:infinity_value] : value
write_attribute(field, int_value)
end
define_method("#{field}") do
value = read_attribute(field)
value == options[:infinity_value] ? Float::INFINITY : value
end
end
end
|
ruby
|
def acts_as_integer_infinitable(fields, options = {})
options[:infinity_value] = -1 unless options.key? :infinity_value
fields.each do |field|
define_method("#{field}=") do |value|
int_value = value == Float::INFINITY ? options[:infinity_value] : value
write_attribute(field, int_value)
end
define_method("#{field}") do
value = read_attribute(field)
value == options[:infinity_value] ? Float::INFINITY : value
end
end
end
|
[
"def",
"acts_as_integer_infinitable",
"(",
"fields",
",",
"options",
"=",
"{",
"}",
")",
"options",
"[",
":infinity_value",
"]",
"=",
"-",
"1",
"unless",
"options",
".",
"key?",
":infinity_value",
"fields",
".",
"each",
"do",
"|",
"field",
"|",
"define_method",
"(",
"\"#{field}=\"",
")",
"do",
"|",
"value",
"|",
"int_value",
"=",
"value",
"==",
"Float",
"::",
"INFINITY",
"?",
"options",
"[",
":infinity_value",
"]",
":",
"value",
"write_attribute",
"(",
"field",
",",
"int_value",
")",
"end",
"define_method",
"(",
"\"#{field}\"",
")",
"do",
"value",
"=",
"read_attribute",
"(",
"field",
")",
"value",
"==",
"options",
"[",
":infinity_value",
"]",
"?",
"Float",
"::",
"INFINITY",
":",
"value",
"end",
"end",
"end"
] |
Allows the fields to store an Infinity value.
Overrides the setter and getter of those fields in order to capture
and return Infinity when appropiate.
Then you can use it as any other value and get the desired result, like
decrementing, incrementing, comparing with <, >, ==, etc.
Example:
class LibrarySubscription < ActiveRecord::Base
acts_as_integer_infinitable [:available_books]
def rent_book
# Do other things...
self.available_books -= 1
save
end
end
> simple_subscription = LibrarySubscription.new(available_books: 5)
> simple_subscription.available_books
=> 5
> simple_subscription.rent_book
> simple_subscription.available_books
=> 4
> complete_subscription = LibrarySubscription.new(available_books: Float::INFINITY)
> long_subscription.available_books
=> Infinity
> long_subscription.rent_book
> long_subscription.available_books
=> Infinity
== Parameters
* +fields+ - An Array with the fields that will be infinitable. They have
to be integers in the database.
== Options
* +:infinity_value+ - The value that will be converted to Infinity.
Default: -1. Another popular value is `nil`.
|
[
"Allows",
"the",
"fields",
"to",
"store",
"an",
"Infinity",
"value",
"."
] |
09dc8025a27524ce81fba2dca8a9263056e39cda
|
https://github.com/pablogonzalezalba/acts_as_integer_infinitable/blob/09dc8025a27524ce81fba2dca8a9263056e39cda/lib/acts_as_integer_infinitable.rb#L48-L62
|
9,337
|
caruby/core
|
lib/caruby/database/persistence_service.rb
|
CaRuby.PersistenceService.query
|
def query(template_or_hql, *path)
String === template_or_hql ? query_hql(template_or_hql) : query_template(template_or_hql, path)
end
|
ruby
|
def query(template_or_hql, *path)
String === template_or_hql ? query_hql(template_or_hql) : query_template(template_or_hql, path)
end
|
[
"def",
"query",
"(",
"template_or_hql",
",",
"*",
"path",
")",
"String",
"===",
"template_or_hql",
"?",
"query_hql",
"(",
"template_or_hql",
")",
":",
"query_template",
"(",
"template_or_hql",
",",
"path",
")",
"end"
] |
Creates a new PersistenceService with the specified application service name and options.
@param [String] the caBIG application service name
@param [{Symbol => Object}] opts the options
@option opts [String] :host the service host (default +localhost+)
@option opts [String] :version the caTissue version identifier
Database access methods
Returns an array of objects fetched from the database which match the given template_or_hql.
If template_or_hql is a String, then the HQL is submitted to the service.
Otherwise, the template_or_hql is a query template domain
object following the given attribute path. The query condition is determined by the values set in the
template. Every non-nil attribute in the template is used as a select condition.
@quirk caCORE this method returns the direct result of calling the +caCORE+ application service
search method. Calling reference attributes of this result is broken by +caCORE+ design.
|
[
"Creates",
"a",
"new",
"PersistenceService",
"with",
"the",
"specified",
"application",
"service",
"name",
"and",
"options",
"."
] |
a682dc57c6fa31aef765cdd206ed3d4b4c289c60
|
https://github.com/caruby/core/blob/a682dc57c6fa31aef765cdd206ed3d4b4c289c60/lib/caruby/database/persistence_service.rb#L44-L46
|
9,338
|
caruby/core
|
lib/caruby/database/persistence_service.rb
|
CaRuby.PersistenceService.query_hql
|
def query_hql(hql)
logger.debug { "Building HQLCriteria..." }
criteria = HQLCriteria.new(hql)
target = hql[/from\s+(\S+)/i, 1]
raise DatabaseError.new("HQL does not contain a FROM clause: #{hql}") unless target
logger.debug { "Submitting search on target class #{target} with the following HQL:\n #{hql}" }
begin
dispatch { |svc| svc.query(criteria, target) }
rescue Exception => e
logger.error("Error querying on HQL - #{$!}:\n#{hql}")
raise e
end
end
|
ruby
|
def query_hql(hql)
logger.debug { "Building HQLCriteria..." }
criteria = HQLCriteria.new(hql)
target = hql[/from\s+(\S+)/i, 1]
raise DatabaseError.new("HQL does not contain a FROM clause: #{hql}") unless target
logger.debug { "Submitting search on target class #{target} with the following HQL:\n #{hql}" }
begin
dispatch { |svc| svc.query(criteria, target) }
rescue Exception => e
logger.error("Error querying on HQL - #{$!}:\n#{hql}")
raise e
end
end
|
[
"def",
"query_hql",
"(",
"hql",
")",
"logger",
".",
"debug",
"{",
"\"Building HQLCriteria...\"",
"}",
"criteria",
"=",
"HQLCriteria",
".",
"new",
"(",
"hql",
")",
"target",
"=",
"hql",
"[",
"/",
"\\s",
"\\S",
"/i",
",",
"1",
"]",
"raise",
"DatabaseError",
".",
"new",
"(",
"\"HQL does not contain a FROM clause: #{hql}\"",
")",
"unless",
"target",
"logger",
".",
"debug",
"{",
"\"Submitting search on target class #{target} with the following HQL:\\n #{hql}\"",
"}",
"begin",
"dispatch",
"{",
"|",
"svc",
"|",
"svc",
".",
"query",
"(",
"criteria",
",",
"target",
")",
"}",
"rescue",
"Exception",
"=>",
"e",
"logger",
".",
"error",
"(",
"\"Error querying on HQL - #{$!}:\\n#{hql}\"",
")",
"raise",
"e",
"end",
"end"
] |
Dispatches the given HQL to the application service.
@quirk caCORE query target parameter is necessary for caCORE 3.x but deprecated in caCORE 4+.
@param [String] hql the HQL to submit
|
[
"Dispatches",
"the",
"given",
"HQL",
"to",
"the",
"application",
"service",
"."
] |
a682dc57c6fa31aef765cdd206ed3d4b4c289c60
|
https://github.com/caruby/core/blob/a682dc57c6fa31aef765cdd206ed3d4b4c289c60/lib/caruby/database/persistence_service.rb#L105-L117
|
9,339
|
caruby/core
|
lib/caruby/database/persistence_service.rb
|
CaRuby.PersistenceService.query_association_post_caCORE_v4
|
def query_association_post_caCORE_v4(obj, attribute)
assn = obj.class.association(attribute)
begin
result = dispatch { |svc| svc.association(obj, assn) }
rescue Exception => e
logger.error("Error fetching association #{obj} - #{e}")
raise
end
end
|
ruby
|
def query_association_post_caCORE_v4(obj, attribute)
assn = obj.class.association(attribute)
begin
result = dispatch { |svc| svc.association(obj, assn) }
rescue Exception => e
logger.error("Error fetching association #{obj} - #{e}")
raise
end
end
|
[
"def",
"query_association_post_caCORE_v4",
"(",
"obj",
",",
"attribute",
")",
"assn",
"=",
"obj",
".",
"class",
".",
"association",
"(",
"attribute",
")",
"begin",
"result",
"=",
"dispatch",
"{",
"|",
"svc",
"|",
"svc",
".",
"association",
"(",
"obj",
",",
"assn",
")",
"}",
"rescue",
"Exception",
"=>",
"e",
"logger",
".",
"error",
"(",
"\"Error fetching association #{obj} - #{e}\"",
")",
"raise",
"end",
"end"
] |
Returns an array of domain objects associated with obj through the specified attribute.
This method uses the +caCORE+ v. 4+ getAssociation application service method.
*Note*: this method is only available for caBIG application services which implement +getAssociation+.
Currently, this includes +caCORE+ v. 4.0 and above.
This method raises a DatabaseError if the application service does not implement +getAssociation+.
Raises DatabaseError if the attribute is not an a domain attribute or the associated objects were not fetched.
|
[
"Returns",
"an",
"array",
"of",
"domain",
"objects",
"associated",
"with",
"obj",
"through",
"the",
"specified",
"attribute",
".",
"This",
"method",
"uses",
"the",
"+",
"caCORE",
"+",
"v",
".",
"4",
"+",
"getAssociation",
"application",
"service",
"method",
"."
] |
a682dc57c6fa31aef765cdd206ed3d4b4c289c60
|
https://github.com/caruby/core/blob/a682dc57c6fa31aef765cdd206ed3d4b4c289c60/lib/caruby/database/persistence_service.rb#L152-L160
|
9,340
|
X0nic/guard-yardstick
|
lib/guard/yardstick.rb
|
Guard.Yardstick.run_partially
|
def run_partially(paths)
return if paths.empty?
displayed_paths = paths.map { |path| smart_path(path) }
UI.info "Inspecting Yarddocs: #{displayed_paths.join(' ')}"
inspect_with_yardstick(path: paths)
end
|
ruby
|
def run_partially(paths)
return if paths.empty?
displayed_paths = paths.map { |path| smart_path(path) }
UI.info "Inspecting Yarddocs: #{displayed_paths.join(' ')}"
inspect_with_yardstick(path: paths)
end
|
[
"def",
"run_partially",
"(",
"paths",
")",
"return",
"if",
"paths",
".",
"empty?",
"displayed_paths",
"=",
"paths",
".",
"map",
"{",
"|",
"path",
"|",
"smart_path",
"(",
"path",
")",
"}",
"UI",
".",
"info",
"\"Inspecting Yarddocs: #{displayed_paths.join(' ')}\"",
"inspect_with_yardstick",
"(",
"path",
":",
"paths",
")",
"end"
] |
Runs yardstick on a partial set of paths passed in by guard
@api private
@return [Void]
|
[
"Runs",
"yardstick",
"on",
"a",
"partial",
"set",
"of",
"paths",
"passed",
"in",
"by",
"guard"
] |
0a52568e1bf1458e611fad2367c41cd1728a9444
|
https://github.com/X0nic/guard-yardstick/blob/0a52568e1bf1458e611fad2367c41cd1728a9444/lib/guard/yardstick.rb#L68-L75
|
9,341
|
X0nic/guard-yardstick
|
lib/guard/yardstick.rb
|
Guard.Yardstick.inspect_with_yardstick
|
def inspect_with_yardstick(yardstick_options = {})
config = ::Yardstick::Config.coerce(yardstick_config(yardstick_options))
measurements = ::Yardstick.measure(config)
measurements.puts
rescue StandardError => error
UI.error 'The following exception occurred while running ' \
"guard-yardstick: #{error.backtrace.first} " \
"#{error.message} (#{error.class.name})"
end
|
ruby
|
def inspect_with_yardstick(yardstick_options = {})
config = ::Yardstick::Config.coerce(yardstick_config(yardstick_options))
measurements = ::Yardstick.measure(config)
measurements.puts
rescue StandardError => error
UI.error 'The following exception occurred while running ' \
"guard-yardstick: #{error.backtrace.first} " \
"#{error.message} (#{error.class.name})"
end
|
[
"def",
"inspect_with_yardstick",
"(",
"yardstick_options",
"=",
"{",
"}",
")",
"config",
"=",
"::",
"Yardstick",
"::",
"Config",
".",
"coerce",
"(",
"yardstick_config",
"(",
"yardstick_options",
")",
")",
"measurements",
"=",
"::",
"Yardstick",
".",
"measure",
"(",
"config",
")",
"measurements",
".",
"puts",
"rescue",
"StandardError",
"=>",
"error",
"UI",
".",
"error",
"'The following exception occurred while running '",
"\"guard-yardstick: #{error.backtrace.first} \"",
"\"#{error.message} (#{error.class.name})\"",
"end"
] |
Runs yardstick and outputs results to STDOUT
@api private
@return [Void]
|
[
"Runs",
"yardstick",
"and",
"outputs",
"results",
"to",
"STDOUT"
] |
0a52568e1bf1458e611fad2367c41cd1728a9444
|
https://github.com/X0nic/guard-yardstick/blob/0a52568e1bf1458e611fad2367c41cd1728a9444/lib/guard/yardstick.rb#L81-L89
|
9,342
|
X0nic/guard-yardstick
|
lib/guard/yardstick.rb
|
Guard.Yardstick.yardstick_config
|
def yardstick_config(extra_options = {})
return options unless options[:config]
yardstick_options = YAML.load_file(options[:config])
yardstick_options.merge(extra_options)
end
|
ruby
|
def yardstick_config(extra_options = {})
return options unless options[:config]
yardstick_options = YAML.load_file(options[:config])
yardstick_options.merge(extra_options)
end
|
[
"def",
"yardstick_config",
"(",
"extra_options",
"=",
"{",
"}",
")",
"return",
"options",
"unless",
"options",
"[",
":config",
"]",
"yardstick_options",
"=",
"YAML",
".",
"load_file",
"(",
"options",
"[",
":config",
"]",
")",
"yardstick_options",
".",
"merge",
"(",
"extra_options",
")",
"end"
] |
Merge further options with yardstick config file.
@api private
@return [Hash] Hash of options for yardstick measurement
|
[
"Merge",
"further",
"options",
"with",
"yardstick",
"config",
"file",
"."
] |
0a52568e1bf1458e611fad2367c41cd1728a9444
|
https://github.com/X0nic/guard-yardstick/blob/0a52568e1bf1458e611fad2367c41cd1728a9444/lib/guard/yardstick.rb#L107-L112
|
9,343
|
blambeau/domain
|
lib/domain/api.rb
|
Domain.API.domain_error!
|
def domain_error!(first, *args)
first = [first]+args unless args.empty?
raise TypeError, "Can't convert `#{first.inspect}` into #{self}", caller
end
|
ruby
|
def domain_error!(first, *args)
first = [first]+args unless args.empty?
raise TypeError, "Can't convert `#{first.inspect}` into #{self}", caller
end
|
[
"def",
"domain_error!",
"(",
"first",
",",
"*",
"args",
")",
"first",
"=",
"[",
"first",
"]",
"+",
"args",
"unless",
"args",
".",
"empty?",
"raise",
"TypeError",
",",
"\"Can't convert `#{first.inspect}` into #{self}\"",
",",
"caller",
"end"
] |
Raises a type error for `args`.
@param [Array] args
arguments passed to `new` or another factory method
@raise TypeError
@api protected
|
[
"Raises",
"a",
"type",
"error",
"for",
"args",
"."
] |
3fd010cbf2e156013e0ea9afa608ba9b44e7bc75
|
https://github.com/blambeau/domain/blob/3fd010cbf2e156013e0ea9afa608ba9b44e7bc75/lib/domain/api.rb#L11-L14
|
9,344
|
checkdin/checkdin-ruby
|
lib/checkdin/user_bridge.rb
|
Checkdin.UserBridge.login_url
|
def login_url options
email = options.delete(:email) or raise ArgumentError.new("No :email passed for user")
user_identifier = options.delete(:user_identifier) or raise ArgumentError.new("No :user_identifier passed for user")
authenticated_parameters = build_authenticated_parameters(email, user_identifier, options)
[checkdin_landing_url, authenticated_parameters.to_query].join
end
|
ruby
|
def login_url options
email = options.delete(:email) or raise ArgumentError.new("No :email passed for user")
user_identifier = options.delete(:user_identifier) or raise ArgumentError.new("No :user_identifier passed for user")
authenticated_parameters = build_authenticated_parameters(email, user_identifier, options)
[checkdin_landing_url, authenticated_parameters.to_query].join
end
|
[
"def",
"login_url",
"options",
"email",
"=",
"options",
".",
"delete",
"(",
":email",
")",
"or",
"raise",
"ArgumentError",
".",
"new",
"(",
"\"No :email passed for user\"",
")",
"user_identifier",
"=",
"options",
".",
"delete",
"(",
":user_identifier",
")",
"or",
"raise",
"ArgumentError",
".",
"new",
"(",
"\"No :user_identifier passed for user\"",
")",
"authenticated_parameters",
"=",
"build_authenticated_parameters",
"(",
"email",
",",
"user_identifier",
",",
"options",
")",
"[",
"checkdin_landing_url",
",",
"authenticated_parameters",
".",
"to_query",
"]",
".",
"join",
"end"
] |
Used to build the authenticated parameters for logging in an end-user on
checkd.in via a redirect.
options - a hash with a the following values defined:
:client_identifier - REQUIRED, the same client identifier used when accessing the regular
API methods.
:bridge_secret - REQUIRED, previously agreed upon shared secret for the user bridge.
This is NOT the shared secret used for accessing the backend API,
please do not confuse the two.
:checkdin_landing_url - OPTIONAL, the value will default to CHECKDIN_DEFAULT_LANDING
if not given. Please set this value as directed by Checkd In.
Examples
bridge = Checkdin::UserBridge.new(:client_identifier => 'YOUR_ASSIGNED_CLIENT_IDENTIFIER',
:bridge_secret => 'YOUR_ASSIGNED_BRIDGE_SECRET')
redirect_to bridge.login_url(:email => 'bob@example.com',
:user_identifier => '112-fixed-user-identifier')
Public: Build a full signed url for logging a specific user into checkd.in. Notice:
you MUST NOT reuse the result of this method, as it expires automatically based on time.
options - a hash with the following values defined:
email - REQUIRED, email address of the user, MAY have different values for a given
user over time.
user_identifier - REQUIRED, your unique identifier for the user, MUST NOT change over time.
authentication_action - OPTIONAL, the given action will be performed immediately,
and the user redirected back to your site afterwards.
referral_token - OPTIONAL, the referral token of the user that referred the user being created.
first_name - OPTIONAL
last_name - OPTIONAL
gender - OPTIONAL, format of male or female
birth_date - OPTIONAL, YYYY-MM-DD format
username - OPTIONAL
mobile_number - OPTIONAL, XXXYYYZZZZ format
postal_code_text - OPTIONAL, XXXXX format
classification - OPTIONAL, the internal group or classification a user belongs to
delivery_email - OPTIONAL, whether a user should receive email notifications
delivery_sms - OPTIONAL, whether a user should receive sms notifications
campaign_id - OPTIONAL, automatically join a user to this campaign, rewarding existing known actions
Returns a URL you can use for redirecting a user. Notice this will expire, so it should
be generated and used only when a user actually wants to log into checkd.in.
|
[
"Used",
"to",
"build",
"the",
"authenticated",
"parameters",
"for",
"logging",
"in",
"an",
"end",
"-",
"user",
"on",
"checkd",
".",
"in",
"via",
"a",
"redirect",
"."
] |
c3c4b38b0f8c710e1f805100dcf3a70649215b48
|
https://github.com/checkdin/checkdin-ruby/blob/c3c4b38b0f8c710e1f805100dcf3a70649215b48/lib/checkdin/user_bridge.rb#L59-L66
|
9,345
|
yogahp/meser_ongkir
|
lib/meser_ongkir/api.rb
|
MeserOngkir.Api.call
|
def call
url = URI(api_url)
http = Net::HTTP.new(url.host, url.port)
http.use_ssl = true
http.verify_mode = OpenSSL::SSL::VERIFY_NONE
url.query = URI.encode_www_form(@params) if @params
request = Net::HTTP::Get.new(url)
request['key'] = ENV['MESER_ONGKIR_API_KEY']
http.request(request)
end
|
ruby
|
def call
url = URI(api_url)
http = Net::HTTP.new(url.host, url.port)
http.use_ssl = true
http.verify_mode = OpenSSL::SSL::VERIFY_NONE
url.query = URI.encode_www_form(@params) if @params
request = Net::HTTP::Get.new(url)
request['key'] = ENV['MESER_ONGKIR_API_KEY']
http.request(request)
end
|
[
"def",
"call",
"url",
"=",
"URI",
"(",
"api_url",
")",
"http",
"=",
"Net",
"::",
"HTTP",
".",
"new",
"(",
"url",
".",
"host",
",",
"url",
".",
"port",
")",
"http",
".",
"use_ssl",
"=",
"true",
"http",
".",
"verify_mode",
"=",
"OpenSSL",
"::",
"SSL",
"::",
"VERIFY_NONE",
"url",
".",
"query",
"=",
"URI",
".",
"encode_www_form",
"(",
"@params",
")",
"if",
"@params",
"request",
"=",
"Net",
"::",
"HTTP",
"::",
"Get",
".",
"new",
"(",
"url",
")",
"request",
"[",
"'key'",
"]",
"=",
"ENV",
"[",
"'MESER_ONGKIR_API_KEY'",
"]",
"http",
".",
"request",
"(",
"request",
")",
"end"
] |
Creating new object
@param
account_type [String] it could be :starter
main_path [String] it could be :city, :province
params [Hash] it could be { id: id city / id province, province: id province }
@example
MeserOngkir::Api.new(account_type, main_path, params)
|
[
"Creating",
"new",
"object"
] |
b9fb3a925098c169793d1893ef00a0f2af222c16
|
https://github.com/yogahp/meser_ongkir/blob/b9fb3a925098c169793d1893ef00a0f2af222c16/lib/meser_ongkir/api.rb#L24-L35
|
9,346
|
tomas-stefano/rspec-i18n
|
lib/spec-i18n/matchers/method_missing.rb
|
Spec.Matchers.method_missing
|
def method_missing(sym, *args, &block) # :nodoc:\
matchers = natural_language.keywords['matchers']
be_word = matchers['be'] if matchers
sym = be_to_english(sym, be_word)
return Matchers::BePredicate.new(sym, *args, &block) if be_predicate?(sym)
return Matchers::Has.new(sym, *args, &block) if have_predicate?(sym)
end
|
ruby
|
def method_missing(sym, *args, &block) # :nodoc:\
matchers = natural_language.keywords['matchers']
be_word = matchers['be'] if matchers
sym = be_to_english(sym, be_word)
return Matchers::BePredicate.new(sym, *args, &block) if be_predicate?(sym)
return Matchers::Has.new(sym, *args, &block) if have_predicate?(sym)
end
|
[
"def",
"method_missing",
"(",
"sym",
",",
"*",
"args",
",",
"&",
"block",
")",
"# :nodoc:\\",
"matchers",
"=",
"natural_language",
".",
"keywords",
"[",
"'matchers'",
"]",
"be_word",
"=",
"matchers",
"[",
"'be'",
"]",
"if",
"matchers",
"sym",
"=",
"be_to_english",
"(",
"sym",
",",
"be_word",
")",
"return",
"Matchers",
"::",
"BePredicate",
".",
"new",
"(",
"sym",
",",
"args",
",",
"block",
")",
"if",
"be_predicate?",
"(",
"sym",
")",
"return",
"Matchers",
"::",
"Has",
".",
"new",
"(",
"sym",
",",
"args",
",",
"block",
")",
"if",
"have_predicate?",
"(",
"sym",
")",
"end"
] |
Method Missing that returns Predicate for the respective sym word
Search the translate be word in the languages.yml for the rspec-i18n try
to comunicate with the Rspec
|
[
"Method",
"Missing",
"that",
"returns",
"Predicate",
"for",
"the",
"respective",
"sym",
"word",
"Search",
"the",
"translate",
"be",
"word",
"in",
"the",
"languages",
".",
"yml",
"for",
"the",
"rspec",
"-",
"i18n",
"try",
"to",
"comunicate",
"with",
"the",
"Rspec"
] |
4383293c4c45ccbb02f42d79bf0fe208d1f913fb
|
https://github.com/tomas-stefano/rspec-i18n/blob/4383293c4c45ccbb02f42d79bf0fe208d1f913fb/lib/spec-i18n/matchers/method_missing.rb#L8-L14
|
9,347
|
SpeciesFileGroup/taxonifi
|
lib/taxonifi/export/format/species_file.rb
|
Taxonifi::Export.SpeciesFile.tblRefs
|
def tblRefs
sql = []
@headers = %w{RefID ActualYear Title PubID Verbatim}
@name_collection.ref_collection.collection.each_with_index do |r,i|
# Assumes the 0 "null" pub id is there
pub_id = @pub_collection[r.publication] ? @pub_collection[r.publication] : 0
# Build a note based on "unused" properties
note = []
if r.properties
r.properties.keys.each do |k|
note.push "#{k}: #{r.properties[k]}" if r.properties[k] && r.properties.length > 0
end
end
note = note.join("; ")
note = @empty_quotes if note.length == 0
cols = {
RefID: r.id,
ContainingRefID: 0,
Title: (r.title.nil? ? @empty_quotes : r.title),
PubID: pub_id,
Series: @empty_quotes,
Volume: (r.volume ? r.volume : @empty_quotes),
Issue: (r.number ? r.number : @empty_quotes),
RefPages: r.page_string, # always a strings
ActualYear: (r.year ? r.year : @empty_quotes),
StatedYear: @empty_quotes,
AccessCode: 0,
Flags: 0,
Note: note,
LastUpdate: @time,
LinkID: 0,
ModifiedBy: @authorized_user_id,
CiteDataStatus: 0,
Verbatim: (r.full_citation ? r.full_citation : @empty_quotes)
}
sql << sql_insert_statement('tblRefs', cols)
end
sql.join("\n")
end
|
ruby
|
def tblRefs
sql = []
@headers = %w{RefID ActualYear Title PubID Verbatim}
@name_collection.ref_collection.collection.each_with_index do |r,i|
# Assumes the 0 "null" pub id is there
pub_id = @pub_collection[r.publication] ? @pub_collection[r.publication] : 0
# Build a note based on "unused" properties
note = []
if r.properties
r.properties.keys.each do |k|
note.push "#{k}: #{r.properties[k]}" if r.properties[k] && r.properties.length > 0
end
end
note = note.join("; ")
note = @empty_quotes if note.length == 0
cols = {
RefID: r.id,
ContainingRefID: 0,
Title: (r.title.nil? ? @empty_quotes : r.title),
PubID: pub_id,
Series: @empty_quotes,
Volume: (r.volume ? r.volume : @empty_quotes),
Issue: (r.number ? r.number : @empty_quotes),
RefPages: r.page_string, # always a strings
ActualYear: (r.year ? r.year : @empty_quotes),
StatedYear: @empty_quotes,
AccessCode: 0,
Flags: 0,
Note: note,
LastUpdate: @time,
LinkID: 0,
ModifiedBy: @authorized_user_id,
CiteDataStatus: 0,
Verbatim: (r.full_citation ? r.full_citation : @empty_quotes)
}
sql << sql_insert_statement('tblRefs', cols)
end
sql.join("\n")
end
|
[
"def",
"tblRefs",
"sql",
"=",
"[",
"]",
"@headers",
"=",
"%w{",
"RefID",
"ActualYear",
"Title",
"PubID",
"Verbatim",
"}",
"@name_collection",
".",
"ref_collection",
".",
"collection",
".",
"each_with_index",
"do",
"|",
"r",
",",
"i",
"|",
"# Assumes the 0 \"null\" pub id is there",
"pub_id",
"=",
"@pub_collection",
"[",
"r",
".",
"publication",
"]",
"?",
"@pub_collection",
"[",
"r",
".",
"publication",
"]",
":",
"0",
"# Build a note based on \"unused\" properties",
"note",
"=",
"[",
"]",
"if",
"r",
".",
"properties",
"r",
".",
"properties",
".",
"keys",
".",
"each",
"do",
"|",
"k",
"|",
"note",
".",
"push",
"\"#{k}: #{r.properties[k]}\"",
"if",
"r",
".",
"properties",
"[",
"k",
"]",
"&&",
"r",
".",
"properties",
".",
"length",
">",
"0",
"end",
"end",
"note",
"=",
"note",
".",
"join",
"(",
"\"; \"",
")",
"note",
"=",
"@empty_quotes",
"if",
"note",
".",
"length",
"==",
"0",
"cols",
"=",
"{",
"RefID",
":",
"r",
".",
"id",
",",
"ContainingRefID",
":",
"0",
",",
"Title",
":",
"(",
"r",
".",
"title",
".",
"nil?",
"?",
"@empty_quotes",
":",
"r",
".",
"title",
")",
",",
"PubID",
":",
"pub_id",
",",
"Series",
":",
"@empty_quotes",
",",
"Volume",
":",
"(",
"r",
".",
"volume",
"?",
"r",
".",
"volume",
":",
"@empty_quotes",
")",
",",
"Issue",
":",
"(",
"r",
".",
"number",
"?",
"r",
".",
"number",
":",
"@empty_quotes",
")",
",",
"RefPages",
":",
"r",
".",
"page_string",
",",
"# always a strings",
"ActualYear",
":",
"(",
"r",
".",
"year",
"?",
"r",
".",
"year",
":",
"@empty_quotes",
")",
",",
"StatedYear",
":",
"@empty_quotes",
",",
"AccessCode",
":",
"0",
",",
"Flags",
":",
"0",
",",
"Note",
":",
"note",
",",
"LastUpdate",
":",
"@time",
",",
"LinkID",
":",
"0",
",",
"ModifiedBy",
":",
"@authorized_user_id",
",",
"CiteDataStatus",
":",
"0",
",",
"Verbatim",
":",
"(",
"r",
".",
"full_citation",
"?",
"r",
".",
"full_citation",
":",
"@empty_quotes",
")",
"}",
"sql",
"<<",
"sql_insert_statement",
"(",
"'tblRefs'",
",",
"cols",
")",
"end",
"sql",
".",
"join",
"(",
"\"\\n\"",
")",
"end"
] |
Generate a tblRefs string.
|
[
"Generate",
"a",
"tblRefs",
"string",
"."
] |
100dc94e7ffd378f6a81381c13768e35b2b65bf2
|
https://github.com/SpeciesFileGroup/taxonifi/blob/100dc94e7ffd378f6a81381c13768e35b2b65bf2/lib/taxonifi/export/format/species_file.rb#L202-L242
|
9,348
|
SpeciesFileGroup/taxonifi
|
lib/taxonifi/export/format/species_file.rb
|
Taxonifi::Export.SpeciesFile.tblPubs
|
def tblPubs
sql = []
@headers = %w{PubID PrefID PubType ShortName FullName Note LastUpdate ModifiedBy Publisher PlacePublished PubRegID Status StartYear EndYear BHL}
# Hackish should build this elsewhere, but degrades OK
pubs = @name_collection.ref_collection.collection.collect{|r| r.publication}.compact.uniq
pubs.each_with_index do |p, i|
cols = {
PubID: i + 1,
PrefID: 0,
PubType: 1,
ShortName: "unknown_#{i}", # Unique constraint
FullName: p,
Note: @empty_quotes,
LastUpdate: @time,
ModifiedBy: @authorized_user_id,
Publisher: @empty_quotes,
PlacePublished: @empty_quotes,
PubRegID: 0,
Status: 0,
StartYear: 0,
EndYear: 0,
BHL: 0
}
@pub_collection.merge!(p => i + 1)
sql << sql_insert_statement('tblPubs', cols)
end
sql.join("\n")
end
|
ruby
|
def tblPubs
sql = []
@headers = %w{PubID PrefID PubType ShortName FullName Note LastUpdate ModifiedBy Publisher PlacePublished PubRegID Status StartYear EndYear BHL}
# Hackish should build this elsewhere, but degrades OK
pubs = @name_collection.ref_collection.collection.collect{|r| r.publication}.compact.uniq
pubs.each_with_index do |p, i|
cols = {
PubID: i + 1,
PrefID: 0,
PubType: 1,
ShortName: "unknown_#{i}", # Unique constraint
FullName: p,
Note: @empty_quotes,
LastUpdate: @time,
ModifiedBy: @authorized_user_id,
Publisher: @empty_quotes,
PlacePublished: @empty_quotes,
PubRegID: 0,
Status: 0,
StartYear: 0,
EndYear: 0,
BHL: 0
}
@pub_collection.merge!(p => i + 1)
sql << sql_insert_statement('tblPubs', cols)
end
sql.join("\n")
end
|
[
"def",
"tblPubs",
"sql",
"=",
"[",
"]",
"@headers",
"=",
"%w{",
"PubID",
"PrefID",
"PubType",
"ShortName",
"FullName",
"Note",
"LastUpdate",
"ModifiedBy",
"Publisher",
"PlacePublished",
"PubRegID",
"Status",
"StartYear",
"EndYear",
"BHL",
"}",
"# Hackish should build this elsewhere, but degrades OK",
"pubs",
"=",
"@name_collection",
".",
"ref_collection",
".",
"collection",
".",
"collect",
"{",
"|",
"r",
"|",
"r",
".",
"publication",
"}",
".",
"compact",
".",
"uniq",
"pubs",
".",
"each_with_index",
"do",
"|",
"p",
",",
"i",
"|",
"cols",
"=",
"{",
"PubID",
":",
"i",
"+",
"1",
",",
"PrefID",
":",
"0",
",",
"PubType",
":",
"1",
",",
"ShortName",
":",
"\"unknown_#{i}\"",
",",
"# Unique constraint",
"FullName",
":",
"p",
",",
"Note",
":",
"@empty_quotes",
",",
"LastUpdate",
":",
"@time",
",",
"ModifiedBy",
":",
"@authorized_user_id",
",",
"Publisher",
":",
"@empty_quotes",
",",
"PlacePublished",
":",
"@empty_quotes",
",",
"PubRegID",
":",
"0",
",",
"Status",
":",
"0",
",",
"StartYear",
":",
"0",
",",
"EndYear",
":",
"0",
",",
"BHL",
":",
"0",
"}",
"@pub_collection",
".",
"merge!",
"(",
"p",
"=>",
"i",
"+",
"1",
")",
"sql",
"<<",
"sql_insert_statement",
"(",
"'tblPubs'",
",",
"cols",
")",
"end",
"sql",
".",
"join",
"(",
"\"\\n\"",
")",
"end"
] |
Generate tblPubs SQL
|
[
"Generate",
"tblPubs",
"SQL"
] |
100dc94e7ffd378f6a81381c13768e35b2b65bf2
|
https://github.com/SpeciesFileGroup/taxonifi/blob/100dc94e7ffd378f6a81381c13768e35b2b65bf2/lib/taxonifi/export/format/species_file.rb#L245-L274
|
9,349
|
SpeciesFileGroup/taxonifi
|
lib/taxonifi/export/format/species_file.rb
|
Taxonifi::Export.SpeciesFile.tblPeople
|
def tblPeople
@headers = %w{PersonID FamilyName GivenNames GivenInitials Suffix Role LastUpdate ModifiedBy}
sql = []
@name_collection.ref_collection.all_authors.each do |a|
cols = {
PersonID: a.id,
FamilyName: (a.last_name.length > 0 ? a.last_name : "Unknown"),
GivenNames: a.first_name || @empty_quotes,
GivenInitials: a.initials_string || @empty_quotes,
Suffix: a.suffix || @empty_quotes,
Role: 1, # authors
LastUpdate: @time,
ModifiedBy: @authorized_user_id
}
sql << sql_insert_statement('tblPeople', cols)
end
sql.join("\n")
end
|
ruby
|
def tblPeople
@headers = %w{PersonID FamilyName GivenNames GivenInitials Suffix Role LastUpdate ModifiedBy}
sql = []
@name_collection.ref_collection.all_authors.each do |a|
cols = {
PersonID: a.id,
FamilyName: (a.last_name.length > 0 ? a.last_name : "Unknown"),
GivenNames: a.first_name || @empty_quotes,
GivenInitials: a.initials_string || @empty_quotes,
Suffix: a.suffix || @empty_quotes,
Role: 1, # authors
LastUpdate: @time,
ModifiedBy: @authorized_user_id
}
sql << sql_insert_statement('tblPeople', cols)
end
sql.join("\n")
end
|
[
"def",
"tblPeople",
"@headers",
"=",
"%w{",
"PersonID",
"FamilyName",
"GivenNames",
"GivenInitials",
"Suffix",
"Role",
"LastUpdate",
"ModifiedBy",
"}",
"sql",
"=",
"[",
"]",
"@name_collection",
".",
"ref_collection",
".",
"all_authors",
".",
"each",
"do",
"|",
"a",
"|",
"cols",
"=",
"{",
"PersonID",
":",
"a",
".",
"id",
",",
"FamilyName",
":",
"(",
"a",
".",
"last_name",
".",
"length",
">",
"0",
"?",
"a",
".",
"last_name",
":",
"\"Unknown\"",
")",
",",
"GivenNames",
":",
"a",
".",
"first_name",
"||",
"@empty_quotes",
",",
"GivenInitials",
":",
"a",
".",
"initials_string",
"||",
"@empty_quotes",
",",
"Suffix",
":",
"a",
".",
"suffix",
"||",
"@empty_quotes",
",",
"Role",
":",
"1",
",",
"# authors ",
"LastUpdate",
":",
"@time",
",",
"ModifiedBy",
":",
"@authorized_user_id",
"}",
"sql",
"<<",
"sql_insert_statement",
"(",
"'tblPeople'",
",",
"cols",
")",
"end",
"sql",
".",
"join",
"(",
"\"\\n\"",
")",
"end"
] |
Generate tblPeople string.
|
[
"Generate",
"tblPeople",
"string",
"."
] |
100dc94e7ffd378f6a81381c13768e35b2b65bf2
|
https://github.com/SpeciesFileGroup/taxonifi/blob/100dc94e7ffd378f6a81381c13768e35b2b65bf2/lib/taxonifi/export/format/species_file.rb#L277-L294
|
9,350
|
SpeciesFileGroup/taxonifi
|
lib/taxonifi/export/format/species_file.rb
|
Taxonifi::Export.SpeciesFile.tblRefAuthors
|
def tblRefAuthors
@headers = %w{RefID PersonID SeqNum AuthorCount LastUpdate ModifiedBy}
sql = []
@name_collection.ref_collection.collection.each do |r|
r.authors.each_with_index do |x, i|
cols = {
RefID: r.id,
PersonID: x.id,
SeqNum: i + 1,
AuthorCount: r.authors.size + 1,
LastUpdate: @time,
ModifiedBy: @authorized_user_id
}
sql << sql_insert_statement('tblRefAuthors', cols)
end
end
sql.join("\n")
end
|
ruby
|
def tblRefAuthors
@headers = %w{RefID PersonID SeqNum AuthorCount LastUpdate ModifiedBy}
sql = []
@name_collection.ref_collection.collection.each do |r|
r.authors.each_with_index do |x, i|
cols = {
RefID: r.id,
PersonID: x.id,
SeqNum: i + 1,
AuthorCount: r.authors.size + 1,
LastUpdate: @time,
ModifiedBy: @authorized_user_id
}
sql << sql_insert_statement('tblRefAuthors', cols)
end
end
sql.join("\n")
end
|
[
"def",
"tblRefAuthors",
"@headers",
"=",
"%w{",
"RefID",
"PersonID",
"SeqNum",
"AuthorCount",
"LastUpdate",
"ModifiedBy",
"}",
"sql",
"=",
"[",
"]",
"@name_collection",
".",
"ref_collection",
".",
"collection",
".",
"each",
"do",
"|",
"r",
"|",
"r",
".",
"authors",
".",
"each_with_index",
"do",
"|",
"x",
",",
"i",
"|",
"cols",
"=",
"{",
"RefID",
":",
"r",
".",
"id",
",",
"PersonID",
":",
"x",
".",
"id",
",",
"SeqNum",
":",
"i",
"+",
"1",
",",
"AuthorCount",
":",
"r",
".",
"authors",
".",
"size",
"+",
"1",
",",
"LastUpdate",
":",
"@time",
",",
"ModifiedBy",
":",
"@authorized_user_id",
"}",
"sql",
"<<",
"sql_insert_statement",
"(",
"'tblRefAuthors'",
",",
"cols",
")",
"end",
"end",
"sql",
".",
"join",
"(",
"\"\\n\"",
")",
"end"
] |
Generate tblRefAuthors string.
|
[
"Generate",
"tblRefAuthors",
"string",
"."
] |
100dc94e7ffd378f6a81381c13768e35b2b65bf2
|
https://github.com/SpeciesFileGroup/taxonifi/blob/100dc94e7ffd378f6a81381c13768e35b2b65bf2/lib/taxonifi/export/format/species_file.rb#L297-L314
|
9,351
|
SpeciesFileGroup/taxonifi
|
lib/taxonifi/export/format/species_file.rb
|
Taxonifi::Export.SpeciesFile.tblCites
|
def tblCites
@headers = %w{TaxonNameID SeqNum RefID NomenclatorID LastUpdate ModifiedBy NewNameStatus CitePages Note TypeClarification CurrentConcept ConceptChange InfoFlags InfoFlagStatus PolynomialStatus}
sql = []
@name_collection.citations.keys.each do |name_id|
seq_num = 1
@name_collection.citations[name_id].each do |ref_id, nomenclator_index, properties|
cols = {
TaxonNameID: name_id,
SeqNum: seq_num,
RefID: ref_id,
NomenclatorID: nomenclator_index,
LastUpdate: @time,
ModifiedBy: @authorized_user_id,
CitePages: (properties[:cite_pages] ? properties[:cite_pages] : @empty_quotes),
NewNameStatus: 0,
Note: (properties[:note] ? properties[:note] : @empty_quotes),
TypeClarification: 0, # We might derive more data from this
CurrentConcept: (properties[:current_concept] == true ? 1 : 0), # Boolean, right?
ConceptChange: 0, # Unspecified
InfoFlags: 0, #
InfoFlagStatus: 1, # 1 => needs review
PolynomialStatus: 0
}
sql << sql_insert_statement('tblCites', cols)
seq_num += 1
end
end
sql.join("\n")
end
|
ruby
|
def tblCites
@headers = %w{TaxonNameID SeqNum RefID NomenclatorID LastUpdate ModifiedBy NewNameStatus CitePages Note TypeClarification CurrentConcept ConceptChange InfoFlags InfoFlagStatus PolynomialStatus}
sql = []
@name_collection.citations.keys.each do |name_id|
seq_num = 1
@name_collection.citations[name_id].each do |ref_id, nomenclator_index, properties|
cols = {
TaxonNameID: name_id,
SeqNum: seq_num,
RefID: ref_id,
NomenclatorID: nomenclator_index,
LastUpdate: @time,
ModifiedBy: @authorized_user_id,
CitePages: (properties[:cite_pages] ? properties[:cite_pages] : @empty_quotes),
NewNameStatus: 0,
Note: (properties[:note] ? properties[:note] : @empty_quotes),
TypeClarification: 0, # We might derive more data from this
CurrentConcept: (properties[:current_concept] == true ? 1 : 0), # Boolean, right?
ConceptChange: 0, # Unspecified
InfoFlags: 0, #
InfoFlagStatus: 1, # 1 => needs review
PolynomialStatus: 0
}
sql << sql_insert_statement('tblCites', cols)
seq_num += 1
end
end
sql.join("\n")
end
|
[
"def",
"tblCites",
"@headers",
"=",
"%w{",
"TaxonNameID",
"SeqNum",
"RefID",
"NomenclatorID",
"LastUpdate",
"ModifiedBy",
"NewNameStatus",
"CitePages",
"Note",
"TypeClarification",
"CurrentConcept",
"ConceptChange",
"InfoFlags",
"InfoFlagStatus",
"PolynomialStatus",
"}",
"sql",
"=",
"[",
"]",
"@name_collection",
".",
"citations",
".",
"keys",
".",
"each",
"do",
"|",
"name_id",
"|",
"seq_num",
"=",
"1",
"@name_collection",
".",
"citations",
"[",
"name_id",
"]",
".",
"each",
"do",
"|",
"ref_id",
",",
"nomenclator_index",
",",
"properties",
"|",
"cols",
"=",
"{",
"TaxonNameID",
":",
"name_id",
",",
"SeqNum",
":",
"seq_num",
",",
"RefID",
":",
"ref_id",
",",
"NomenclatorID",
":",
"nomenclator_index",
",",
"LastUpdate",
":",
"@time",
",",
"ModifiedBy",
":",
"@authorized_user_id",
",",
"CitePages",
":",
"(",
"properties",
"[",
":cite_pages",
"]",
"?",
"properties",
"[",
":cite_pages",
"]",
":",
"@empty_quotes",
")",
",",
"NewNameStatus",
":",
"0",
",",
"Note",
":",
"(",
"properties",
"[",
":note",
"]",
"?",
"properties",
"[",
":note",
"]",
":",
"@empty_quotes",
")",
",",
"TypeClarification",
":",
"0",
",",
"# We might derive more data from this",
"CurrentConcept",
":",
"(",
"properties",
"[",
":current_concept",
"]",
"==",
"true",
"?",
"1",
":",
"0",
")",
",",
"# Boolean, right?",
"ConceptChange",
":",
"0",
",",
"# Unspecified",
"InfoFlags",
":",
"0",
",",
"# ",
"InfoFlagStatus",
":",
"1",
",",
"# 1 => needs review",
"PolynomialStatus",
":",
"0",
"}",
"sql",
"<<",
"sql_insert_statement",
"(",
"'tblCites'",
",",
"cols",
")",
"seq_num",
"+=",
"1",
"end",
"end",
"sql",
".",
"join",
"(",
"\"\\n\"",
")",
"end"
] |
Generate tblCites string.
|
[
"Generate",
"tblCites",
"string",
"."
] |
100dc94e7ffd378f6a81381c13768e35b2b65bf2
|
https://github.com/SpeciesFileGroup/taxonifi/blob/100dc94e7ffd378f6a81381c13768e35b2b65bf2/lib/taxonifi/export/format/species_file.rb#L317-L346
|
9,352
|
SpeciesFileGroup/taxonifi
|
lib/taxonifi/export/format/species_file.rb
|
Taxonifi::Export.SpeciesFile.tblTypeSpecies
|
def tblTypeSpecies
@headers = %w{GenusNameID SpeciesNameID Reason AuthorityRefID FirstFamGrpNameID LastUpdate ModifiedBy NewID}
sql = []
names = @name_collection.names_at_rank('genus') + @name_collection.names_at_rank('subgenus')
names.each do |n|
if n.properties[:type_species_id]
ref = get_ref(n)
# ref = @by_author_reference_index[n.author_year_index]
next if ref.nil?
cols = {
GenusNameID: n.id ,
SpeciesNameID: n.properties[:type_species_id],
Reason: 0 ,
AuthorityRefID: 0 ,
FirstFamGrpNameID: 0 ,
LastUpdate: @time ,
ModifiedBy: @authorized_user_id ,
NewID: 0 # What is this?
}
sql << sql_insert_statement('tblTypeSpecies', cols)
end
end
sql.join("\n")
end
|
ruby
|
def tblTypeSpecies
@headers = %w{GenusNameID SpeciesNameID Reason AuthorityRefID FirstFamGrpNameID LastUpdate ModifiedBy NewID}
sql = []
names = @name_collection.names_at_rank('genus') + @name_collection.names_at_rank('subgenus')
names.each do |n|
if n.properties[:type_species_id]
ref = get_ref(n)
# ref = @by_author_reference_index[n.author_year_index]
next if ref.nil?
cols = {
GenusNameID: n.id ,
SpeciesNameID: n.properties[:type_species_id],
Reason: 0 ,
AuthorityRefID: 0 ,
FirstFamGrpNameID: 0 ,
LastUpdate: @time ,
ModifiedBy: @authorized_user_id ,
NewID: 0 # What is this?
}
sql << sql_insert_statement('tblTypeSpecies', cols)
end
end
sql.join("\n")
end
|
[
"def",
"tblTypeSpecies",
"@headers",
"=",
"%w{",
"GenusNameID",
"SpeciesNameID",
"Reason",
"AuthorityRefID",
"FirstFamGrpNameID",
"LastUpdate",
"ModifiedBy",
"NewID",
"}",
"sql",
"=",
"[",
"]",
"names",
"=",
"@name_collection",
".",
"names_at_rank",
"(",
"'genus'",
")",
"+",
"@name_collection",
".",
"names_at_rank",
"(",
"'subgenus'",
")",
"names",
".",
"each",
"do",
"|",
"n",
"|",
"if",
"n",
".",
"properties",
"[",
":type_species_id",
"]",
"ref",
"=",
"get_ref",
"(",
"n",
")",
"# ref = @by_author_reference_index[n.author_year_index]",
"next",
"if",
"ref",
".",
"nil?",
"cols",
"=",
"{",
"GenusNameID",
":",
"n",
".",
"id",
",",
"SpeciesNameID",
":",
"n",
".",
"properties",
"[",
":type_species_id",
"]",
",",
"Reason",
":",
"0",
",",
"AuthorityRefID",
":",
"0",
",",
"FirstFamGrpNameID",
":",
"0",
",",
"LastUpdate",
":",
"@time",
",",
"ModifiedBy",
":",
"@authorized_user_id",
",",
"NewID",
":",
"0",
"# What is this? ",
"}",
"sql",
"<<",
"sql_insert_statement",
"(",
"'tblTypeSpecies'",
",",
"cols",
")",
"end",
"end",
"sql",
".",
"join",
"(",
"\"\\n\"",
")",
"end"
] |
Generate tblTypeSpecies string.
|
[
"Generate",
"tblTypeSpecies",
"string",
"."
] |
100dc94e7ffd378f6a81381c13768e35b2b65bf2
|
https://github.com/SpeciesFileGroup/taxonifi/blob/100dc94e7ffd378f6a81381c13768e35b2b65bf2/lib/taxonifi/export/format/species_file.rb#L349-L374
|
9,353
|
SpeciesFileGroup/taxonifi
|
lib/taxonifi/export/format/species_file.rb
|
Taxonifi::Export.SpeciesFile.tblNomenclator
|
def tblNomenclator
@headers = %w{NomenclatorID GenusNameID SubgenusNameID SpeciesNameID SubspeciesNameID LastUpdate ModifiedBy SuitableForGenus SuitableForSpecies InfrasubspeciesNameID InfrasubKind}
sql = []
i = 1
# Ugh, move build from here
@name_collection.nomenclators.keys.each do |i|
name = @name_collection.nomenclators[i]
genus_id = @genus_names[name[0]]
genus_id ||= 0
subgenus_id = @genus_names[name[1]]
subgenus_id ||= 0
species_id = @species_names[name[2]]
species_id ||= 0
subspecies_id = @species_names[name[3]]
subspecies_id ||= 0
variety_id = @species_names[name[4]]
variety_id ||= 0
cols = {
NomenclatorID: i,
GenusNameID: genus_id,
SubgenusNameID: subgenus_id,
SpeciesNameID: species_id,
SubspeciesNameID: subspecies_id,
InfrasubspeciesNameID: variety_id,
InfrasubKind: (variety_id == 0 ? 0 : 2),
LastUpdate: @time,
ModifiedBy: @authorized_user_id,
SuitableForGenus: 0, # Set in SF w test
SuitableForSpecies: 0 # Set in SF w test
}
i += 1
sql << sql_insert_statement('tblNomenclator', cols)
end
sql.join("\n")
end
|
ruby
|
def tblNomenclator
@headers = %w{NomenclatorID GenusNameID SubgenusNameID SpeciesNameID SubspeciesNameID LastUpdate ModifiedBy SuitableForGenus SuitableForSpecies InfrasubspeciesNameID InfrasubKind}
sql = []
i = 1
# Ugh, move build from here
@name_collection.nomenclators.keys.each do |i|
name = @name_collection.nomenclators[i]
genus_id = @genus_names[name[0]]
genus_id ||= 0
subgenus_id = @genus_names[name[1]]
subgenus_id ||= 0
species_id = @species_names[name[2]]
species_id ||= 0
subspecies_id = @species_names[name[3]]
subspecies_id ||= 0
variety_id = @species_names[name[4]]
variety_id ||= 0
cols = {
NomenclatorID: i,
GenusNameID: genus_id,
SubgenusNameID: subgenus_id,
SpeciesNameID: species_id,
SubspeciesNameID: subspecies_id,
InfrasubspeciesNameID: variety_id,
InfrasubKind: (variety_id == 0 ? 0 : 2),
LastUpdate: @time,
ModifiedBy: @authorized_user_id,
SuitableForGenus: 0, # Set in SF w test
SuitableForSpecies: 0 # Set in SF w test
}
i += 1
sql << sql_insert_statement('tblNomenclator', cols)
end
sql.join("\n")
end
|
[
"def",
"tblNomenclator",
"@headers",
"=",
"%w{",
"NomenclatorID",
"GenusNameID",
"SubgenusNameID",
"SpeciesNameID",
"SubspeciesNameID",
"LastUpdate",
"ModifiedBy",
"SuitableForGenus",
"SuitableForSpecies",
"InfrasubspeciesNameID",
"InfrasubKind",
"}",
"sql",
"=",
"[",
"]",
"i",
"=",
"1",
"# Ugh, move build from here ",
"@name_collection",
".",
"nomenclators",
".",
"keys",
".",
"each",
"do",
"|",
"i",
"|",
"name",
"=",
"@name_collection",
".",
"nomenclators",
"[",
"i",
"]",
"genus_id",
"=",
"@genus_names",
"[",
"name",
"[",
"0",
"]",
"]",
"genus_id",
"||=",
"0",
"subgenus_id",
"=",
"@genus_names",
"[",
"name",
"[",
"1",
"]",
"]",
"subgenus_id",
"||=",
"0",
"species_id",
"=",
"@species_names",
"[",
"name",
"[",
"2",
"]",
"]",
"species_id",
"||=",
"0",
"subspecies_id",
"=",
"@species_names",
"[",
"name",
"[",
"3",
"]",
"]",
"subspecies_id",
"||=",
"0",
"variety_id",
"=",
"@species_names",
"[",
"name",
"[",
"4",
"]",
"]",
"variety_id",
"||=",
"0",
"cols",
"=",
"{",
"NomenclatorID",
":",
"i",
",",
"GenusNameID",
":",
"genus_id",
",",
"SubgenusNameID",
":",
"subgenus_id",
",",
"SpeciesNameID",
":",
"species_id",
",",
"SubspeciesNameID",
":",
"subspecies_id",
",",
"InfrasubspeciesNameID",
":",
"variety_id",
",",
"InfrasubKind",
":",
"(",
"variety_id",
"==",
"0",
"?",
"0",
":",
"2",
")",
",",
"LastUpdate",
":",
"@time",
",",
"ModifiedBy",
":",
"@authorized_user_id",
",",
"SuitableForGenus",
":",
"0",
",",
"# Set in SF w test",
"SuitableForSpecies",
":",
"0",
"# Set in SF w test",
"}",
"i",
"+=",
"1",
"sql",
"<<",
"sql_insert_statement",
"(",
"'tblNomenclator'",
",",
"cols",
")",
"end",
"sql",
".",
"join",
"(",
"\"\\n\"",
")",
"end"
] |
Must be called post tblGenusNames and tblSpeciesNames.
Some records are not used but can be cleaned by SF
|
[
"Must",
"be",
"called",
"post",
"tblGenusNames",
"and",
"tblSpeciesNames",
".",
"Some",
"records",
"are",
"not",
"used",
"but",
"can",
"be",
"cleaned",
"by",
"SF"
] |
100dc94e7ffd378f6a81381c13768e35b2b65bf2
|
https://github.com/SpeciesFileGroup/taxonifi/blob/100dc94e7ffd378f6a81381c13768e35b2b65bf2/lib/taxonifi/export/format/species_file.rb#L411-L448
|
9,354
|
jmcaffee/exceltocsv
|
lib/exceltocsv/excel_file.rb
|
ExcelToCsv.ExcelFile.empty_row?
|
def empty_row?(row)
is_empty = true
row.each do |item|
is_empty = false if item && !item.empty?
end
is_empty
end
|
ruby
|
def empty_row?(row)
is_empty = true
row.each do |item|
is_empty = false if item && !item.empty?
end
is_empty
end
|
[
"def",
"empty_row?",
"(",
"row",
")",
"is_empty",
"=",
"true",
"row",
".",
"each",
"do",
"|",
"item",
"|",
"is_empty",
"=",
"false",
"if",
"item",
"&&",
"!",
"item",
".",
"empty?",
"end",
"is_empty",
"end"
] |
Return true if row contains no data
|
[
"Return",
"true",
"if",
"row",
"contains",
"no",
"data"
] |
e93baed66baf4d7a0e341d8504bed3a9bf55ff55
|
https://github.com/jmcaffee/exceltocsv/blob/e93baed66baf4d7a0e341d8504bed3a9bf55ff55/lib/exceltocsv/excel_file.rb#L176-L182
|
9,355
|
jmcaffee/exceltocsv
|
lib/exceltocsv/excel_file.rb
|
ExcelToCsv.ExcelFile.truncate_decimal
|
def truncate_decimal(a_cell)
if(a_cell.is_a?(Numeric))
a_cell = truncate_decimal_to_string(a_cell, 3)
# Truncate zeros (unless there is only 1 decimal place)
# eg. 12.10 => 12.1
# 12.0 => 12.0
a_cell = BigDecimal.new(a_cell).to_s("F")
end
a_cell
end
|
ruby
|
def truncate_decimal(a_cell)
if(a_cell.is_a?(Numeric))
a_cell = truncate_decimal_to_string(a_cell, 3)
# Truncate zeros (unless there is only 1 decimal place)
# eg. 12.10 => 12.1
# 12.0 => 12.0
a_cell = BigDecimal.new(a_cell).to_s("F")
end
a_cell
end
|
[
"def",
"truncate_decimal",
"(",
"a_cell",
")",
"if",
"(",
"a_cell",
".",
"is_a?",
"(",
"Numeric",
")",
")",
"a_cell",
"=",
"truncate_decimal_to_string",
"(",
"a_cell",
",",
"3",
")",
"# Truncate zeros (unless there is only 1 decimal place)",
"# eg. 12.10 => 12.1",
"# 12.0 => 12.0",
"a_cell",
"=",
"BigDecimal",
".",
"new",
"(",
"a_cell",
")",
".",
"to_s",
"(",
"\"F\"",
")",
"end",
"a_cell",
"end"
] |
Truncates a decimal to 3 decimal places if numeric
and remove trailing zeros, if more than one decimal place.
returns a string
|
[
"Truncates",
"a",
"decimal",
"to",
"3",
"decimal",
"places",
"if",
"numeric",
"and",
"remove",
"trailing",
"zeros",
"if",
"more",
"than",
"one",
"decimal",
"place",
".",
"returns",
"a",
"string"
] |
e93baed66baf4d7a0e341d8504bed3a9bf55ff55
|
https://github.com/jmcaffee/exceltocsv/blob/e93baed66baf4d7a0e341d8504bed3a9bf55ff55/lib/exceltocsv/excel_file.rb#L206-L215
|
9,356
|
jmcaffee/exceltocsv
|
lib/exceltocsv/excel_file.rb
|
ExcelToCsv.ExcelFile.clean_int_value
|
def clean_int_value(a_cell)
if(a_cell.match(/\.[0]+$/))
cary = a_cell.split(".")
a_cell = cary[0]
end
a_cell
end
|
ruby
|
def clean_int_value(a_cell)
if(a_cell.match(/\.[0]+$/))
cary = a_cell.split(".")
a_cell = cary[0]
end
a_cell
end
|
[
"def",
"clean_int_value",
"(",
"a_cell",
")",
"if",
"(",
"a_cell",
".",
"match",
"(",
"/",
"\\.",
"/",
")",
")",
"cary",
"=",
"a_cell",
".",
"split",
"(",
"\".\"",
")",
"a_cell",
"=",
"cary",
"[",
"0",
"]",
"end",
"a_cell",
"end"
] |
If the result is n.000... Remove the unecessary zeros.
|
[
"If",
"the",
"result",
"is",
"n",
".",
"000",
"...",
"Remove",
"the",
"unecessary",
"zeros",
"."
] |
e93baed66baf4d7a0e341d8504bed3a9bf55ff55
|
https://github.com/jmcaffee/exceltocsv/blob/e93baed66baf4d7a0e341d8504bed3a9bf55ff55/lib/exceltocsv/excel_file.rb#L225-L231
|
9,357
|
rsb/fuelcell
|
lib/fuelcell/cli.rb
|
Fuelcell.Cli.parse
|
def parse(raw_args)
cmd_args = cmd_args_extractor.call(raw_args)
cmd = root.locate(cmd_args, raw_args)
root.add_global_options(cmd)
begin
parser.call(cmd, cmd_args, raw_args)
rescue => e
shell.error e.message
shell.failure_exit
end
end
|
ruby
|
def parse(raw_args)
cmd_args = cmd_args_extractor.call(raw_args)
cmd = root.locate(cmd_args, raw_args)
root.add_global_options(cmd)
begin
parser.call(cmd, cmd_args, raw_args)
rescue => e
shell.error e.message
shell.failure_exit
end
end
|
[
"def",
"parse",
"(",
"raw_args",
")",
"cmd_args",
"=",
"cmd_args_extractor",
".",
"call",
"(",
"raw_args",
")",
"cmd",
"=",
"root",
".",
"locate",
"(",
"cmd_args",
",",
"raw_args",
")",
"root",
".",
"add_global_options",
"(",
"cmd",
")",
"begin",
"parser",
".",
"call",
"(",
"cmd",
",",
"cmd_args",
",",
"raw_args",
")",
"rescue",
"=>",
"e",
"shell",
".",
"error",
"e",
".",
"message",
"shell",
".",
"failure_exit",
"end",
"end"
] |
Initializes with a root command object
When nothing is given we default to the script name otherwise you choose
the name of the root command or the command itself
Delegates all parsing responsiblities to a series of handlers, returning
a structured hash needed to execute a command. The command being executed
is determined by the CmdArgsStrategy unless you override it, it extracts
all args upto the first option or ignore. The RootCommand is used to find
the command using the extracted args, it accounts for sub commands. The
parser Parser::ParsingStategy handles processing opts, args and ignored
args
@param raw_args [Array] cli args usually from ARGV
@return [Hash] structured context for executing a command
|
[
"Initializes",
"with",
"a",
"root",
"command",
"object"
] |
2eaa994170fa2b9243e7dee6d7c2b21e12274f6e
|
https://github.com/rsb/fuelcell/blob/2eaa994170fa2b9243e7dee6d7c2b21e12274f6e/lib/fuelcell/cli.rb#L38-L48
|
9,358
|
rsb/fuelcell
|
lib/fuelcell/cli.rb
|
Fuelcell.Cli.execute
|
def execute(context)
cmd = context[:cmd]
opts = context[:opts] || {}
args = context[:args] || []
cmd_args = context[:cmd_args]
cli_shell = context[:shell] || shell
unless cmd.callable?
return root['help'].call(opts, cmd_args, shell)
end
cmd = handle_callable_option(root, cmd)
cmd.call(opts, args, cli_shell)
end
|
ruby
|
def execute(context)
cmd = context[:cmd]
opts = context[:opts] || {}
args = context[:args] || []
cmd_args = context[:cmd_args]
cli_shell = context[:shell] || shell
unless cmd.callable?
return root['help'].call(opts, cmd_args, shell)
end
cmd = handle_callable_option(root, cmd)
cmd.call(opts, args, cli_shell)
end
|
[
"def",
"execute",
"(",
"context",
")",
"cmd",
"=",
"context",
"[",
":cmd",
"]",
"opts",
"=",
"context",
"[",
":opts",
"]",
"||",
"{",
"}",
"args",
"=",
"context",
"[",
":args",
"]",
"||",
"[",
"]",
"cmd_args",
"=",
"context",
"[",
":cmd_args",
"]",
"cli_shell",
"=",
"context",
"[",
":shell",
"]",
"||",
"shell",
"unless",
"cmd",
".",
"callable?",
"return",
"root",
"[",
"'help'",
"]",
".",
"call",
"(",
"opts",
",",
"cmd_args",
",",
"shell",
")",
"end",
"cmd",
"=",
"handle_callable_option",
"(",
"root",
",",
"cmd",
")",
"cmd",
".",
"call",
"(",
"opts",
",",
"args",
",",
"cli_shell",
")",
"end"
] |
Executes the callable object in a command. All command callable object
expect to be called the the options hash, arg hash and shell object.
@param context [Hash]
@return [Integer]
|
[
"Executes",
"the",
"callable",
"object",
"in",
"a",
"command",
".",
"All",
"command",
"callable",
"object",
"expect",
"to",
"be",
"called",
"the",
"the",
"options",
"hash",
"arg",
"hash",
"and",
"shell",
"object",
"."
] |
2eaa994170fa2b9243e7dee6d7c2b21e12274f6e
|
https://github.com/rsb/fuelcell/blob/2eaa994170fa2b9243e7dee6d7c2b21e12274f6e/lib/fuelcell/cli.rb#L55-L69
|
9,359
|
gr4y/streambot
|
lib/streambot/oauth.rb
|
StreamBot.OAuth.get_access_token
|
def get_access_token
# get saved access token
if ::File.exists?(ACCESS_TOKEN)
@access_token = ::YAML.load_file(ACCESS_TOKEN)
end
# if access token is nil,
# then get a new initial token
if @access_token.nil?
get_initial_token
::File.open(ACCESS_TOKEN, 'w') do |out|
YAML.dump(@access_token, out)
end
end
end
|
ruby
|
def get_access_token
# get saved access token
if ::File.exists?(ACCESS_TOKEN)
@access_token = ::YAML.load_file(ACCESS_TOKEN)
end
# if access token is nil,
# then get a new initial token
if @access_token.nil?
get_initial_token
::File.open(ACCESS_TOKEN, 'w') do |out|
YAML.dump(@access_token, out)
end
end
end
|
[
"def",
"get_access_token",
"# get saved access token",
"if",
"::",
"File",
".",
"exists?",
"(",
"ACCESS_TOKEN",
")",
"@access_token",
"=",
"::",
"YAML",
".",
"load_file",
"(",
"ACCESS_TOKEN",
")",
"end",
"# if access token is nil,",
"# then get a new initial token",
"if",
"@access_token",
".",
"nil?",
"get_initial_token",
"::",
"File",
".",
"open",
"(",
"ACCESS_TOKEN",
",",
"'w'",
")",
"do",
"|",
"out",
"|",
"YAML",
".",
"dump",
"(",
"@access_token",
",",
"out",
")",
"end",
"end",
"end"
] |
get the access token
|
[
"get",
"the",
"access",
"token"
] |
3f454b62ea0c1e9eb29a3c7bf0d17f3caf14b375
|
https://github.com/gr4y/streambot/blob/3f454b62ea0c1e9eb29a3c7bf0d17f3caf14b375/lib/streambot/oauth.rb#L52-L65
|
9,360
|
gr4y/streambot
|
lib/streambot/oauth.rb
|
StreamBot.OAuth.get_initial_token
|
def get_initial_token
@request_token = get_request_token
puts "Place \"#{@request_token.authorize_url}\" in your browser"
print "Enter the number they give you: "
pin = STDIN.readline.chomp
@access_token = @request_token.get_access_token(:oauth_verifier => pin)
end
|
ruby
|
def get_initial_token
@request_token = get_request_token
puts "Place \"#{@request_token.authorize_url}\" in your browser"
print "Enter the number they give you: "
pin = STDIN.readline.chomp
@access_token = @request_token.get_access_token(:oauth_verifier => pin)
end
|
[
"def",
"get_initial_token",
"@request_token",
"=",
"get_request_token",
"puts",
"\"Place \\\"#{@request_token.authorize_url}\\\" in your browser\"",
"print",
"\"Enter the number they give you: \"",
"pin",
"=",
"STDIN",
".",
"readline",
".",
"chomp",
"@access_token",
"=",
"@request_token",
".",
"get_access_token",
"(",
":oauth_verifier",
"=>",
"pin",
")",
"end"
] |
get the initial access token
|
[
"get",
"the",
"initial",
"access",
"token"
] |
3f454b62ea0c1e9eb29a3c7bf0d17f3caf14b375
|
https://github.com/gr4y/streambot/blob/3f454b62ea0c1e9eb29a3c7bf0d17f3caf14b375/lib/streambot/oauth.rb#L68-L74
|
9,361
|
mccraigmccraig/rsxml
|
lib/rsxml/sexp.rb
|
Rsxml.Sexp.traverse
|
def traverse(sexp, visitor, context=Visitor::Context.new)
element_name, attrs, children = decompose_sexp(sexp)
non_ns_attrs, ns_bindings = Namespace::non_ns_attrs_ns_bindings(context.ns_stack, element_name, attrs)
context.ns_stack.push(ns_bindings)
eelement_name = Namespace::explode_qname(context.ns_stack, element_name)
eattrs = Namespace::explode_attr_qnames(context.ns_stack, non_ns_attrs)
begin
visitor.element(context, eelement_name, eattrs, ns_bindings) do
children.each_with_index do |child, i|
if child.is_a?(Array)
traverse(child, visitor, context)
else
visitor.text(context, child)
end
end
end
ensure
context.ns_stack.pop
end
visitor
end
|
ruby
|
def traverse(sexp, visitor, context=Visitor::Context.new)
element_name, attrs, children = decompose_sexp(sexp)
non_ns_attrs, ns_bindings = Namespace::non_ns_attrs_ns_bindings(context.ns_stack, element_name, attrs)
context.ns_stack.push(ns_bindings)
eelement_name = Namespace::explode_qname(context.ns_stack, element_name)
eattrs = Namespace::explode_attr_qnames(context.ns_stack, non_ns_attrs)
begin
visitor.element(context, eelement_name, eattrs, ns_bindings) do
children.each_with_index do |child, i|
if child.is_a?(Array)
traverse(child, visitor, context)
else
visitor.text(context, child)
end
end
end
ensure
context.ns_stack.pop
end
visitor
end
|
[
"def",
"traverse",
"(",
"sexp",
",",
"visitor",
",",
"context",
"=",
"Visitor",
"::",
"Context",
".",
"new",
")",
"element_name",
",",
"attrs",
",",
"children",
"=",
"decompose_sexp",
"(",
"sexp",
")",
"non_ns_attrs",
",",
"ns_bindings",
"=",
"Namespace",
"::",
"non_ns_attrs_ns_bindings",
"(",
"context",
".",
"ns_stack",
",",
"element_name",
",",
"attrs",
")",
"context",
".",
"ns_stack",
".",
"push",
"(",
"ns_bindings",
")",
"eelement_name",
"=",
"Namespace",
"::",
"explode_qname",
"(",
"context",
".",
"ns_stack",
",",
"element_name",
")",
"eattrs",
"=",
"Namespace",
"::",
"explode_attr_qnames",
"(",
"context",
".",
"ns_stack",
",",
"non_ns_attrs",
")",
"begin",
"visitor",
".",
"element",
"(",
"context",
",",
"eelement_name",
",",
"eattrs",
",",
"ns_bindings",
")",
"do",
"children",
".",
"each_with_index",
"do",
"|",
"child",
",",
"i",
"|",
"if",
"child",
".",
"is_a?",
"(",
"Array",
")",
"traverse",
"(",
"child",
",",
"visitor",
",",
"context",
")",
"else",
"visitor",
".",
"text",
"(",
"context",
",",
"child",
")",
"end",
"end",
"end",
"ensure",
"context",
".",
"ns_stack",
".",
"pop",
"end",
"visitor",
"end"
] |
pre-order traversal of the sexp, calling methods on
the visitor with each node
|
[
"pre",
"-",
"order",
"traversal",
"of",
"the",
"sexp",
"calling",
"methods",
"on",
"the",
"visitor",
"with",
"each",
"node"
] |
3699c186f01be476a5942d64cd5c39f4d6bbe175
|
https://github.com/mccraigmccraig/rsxml/blob/3699c186f01be476a5942d64cd5c39f4d6bbe175/lib/rsxml/sexp.rb#L8-L33
|
9,362
|
logankoester/errship
|
lib/errship.rb
|
Errship.Rescuers.errship_standard
|
def errship_standard(errship_scope = false)
flash[:error] ||= I18n.t('errship.standard')
render :template => '/errship/standard.html.erb',
:layout => 'application',
:locals => { :status_code => 500, :errship_scope => errship_scope },
:status => (Errship.status_code_success ? 200 : 500)
end
|
ruby
|
def errship_standard(errship_scope = false)
flash[:error] ||= I18n.t('errship.standard')
render :template => '/errship/standard.html.erb',
:layout => 'application',
:locals => { :status_code => 500, :errship_scope => errship_scope },
:status => (Errship.status_code_success ? 200 : 500)
end
|
[
"def",
"errship_standard",
"(",
"errship_scope",
"=",
"false",
")",
"flash",
"[",
":error",
"]",
"||=",
"I18n",
".",
"t",
"(",
"'errship.standard'",
")",
"render",
":template",
"=>",
"'/errship/standard.html.erb'",
",",
":layout",
"=>",
"'application'",
",",
":locals",
"=>",
"{",
":status_code",
"=>",
"500",
",",
":errship_scope",
"=>",
"errship_scope",
"}",
",",
":status",
"=>",
"(",
"Errship",
".",
"status_code_success",
"?",
"200",
":",
"500",
")",
"end"
] |
A blank page with just the layout and flash message, which can be redirected to when
all else fails.
|
[
"A",
"blank",
"page",
"with",
"just",
"the",
"layout",
"and",
"flash",
"message",
"which",
"can",
"be",
"redirected",
"to",
"when",
"all",
"else",
"fails",
"."
] |
9e344c25a5c6b619af1b9b177ad4f40b415b2182
|
https://github.com/logankoester/errship/blob/9e344c25a5c6b619af1b9b177ad4f40b415b2182/lib/errship.rb#L41-L47
|
9,363
|
logankoester/errship
|
lib/errship.rb
|
Errship.Rescuers.flashback
|
def flashback(error_message, exception = nil)
airbrake_class.send(:notify, exception) if airbrake_class
flash[:error] = error_message
begin
redirect_to :back
rescue ActionController::RedirectBackError
redirect_to error_path
end
end
|
ruby
|
def flashback(error_message, exception = nil)
airbrake_class.send(:notify, exception) if airbrake_class
flash[:error] = error_message
begin
redirect_to :back
rescue ActionController::RedirectBackError
redirect_to error_path
end
end
|
[
"def",
"flashback",
"(",
"error_message",
",",
"exception",
"=",
"nil",
")",
"airbrake_class",
".",
"send",
"(",
":notify",
",",
"exception",
")",
"if",
"airbrake_class",
"flash",
"[",
":error",
"]",
"=",
"error_message",
"begin",
"redirect_to",
":back",
"rescue",
"ActionController",
"::",
"RedirectBackError",
"redirect_to",
"error_path",
"end",
"end"
] |
Set the error flash and attempt to redirect back. If RedirectBackError is raised,
redirect to error_path instead.
|
[
"Set",
"the",
"error",
"flash",
"and",
"attempt",
"to",
"redirect",
"back",
".",
"If",
"RedirectBackError",
"is",
"raised",
"redirect",
"to",
"error_path",
"instead",
"."
] |
9e344c25a5c6b619af1b9b177ad4f40b415b2182
|
https://github.com/logankoester/errship/blob/9e344c25a5c6b619af1b9b177ad4f40b415b2182/lib/errship.rb#L51-L59
|
9,364
|
devver/sdbtools
|
lib/sdbtools/operation.rb
|
SDBTools.Operation.each
|
def each
Transaction.open(":#{method} operation") do |t|
next_token = starting_token
begin
args = @args.dup
args << next_token
results = @sdb.send(@method, *args)
yield(results, self)
next_token = results[:next_token]
end while next_token
end
end
|
ruby
|
def each
Transaction.open(":#{method} operation") do |t|
next_token = starting_token
begin
args = @args.dup
args << next_token
results = @sdb.send(@method, *args)
yield(results, self)
next_token = results[:next_token]
end while next_token
end
end
|
[
"def",
"each",
"Transaction",
".",
"open",
"(",
"\":#{method} operation\"",
")",
"do",
"|",
"t",
"|",
"next_token",
"=",
"starting_token",
"begin",
"args",
"=",
"@args",
".",
"dup",
"args",
"<<",
"next_token",
"results",
"=",
"@sdb",
".",
"send",
"(",
"@method",
",",
"args",
")",
"yield",
"(",
"results",
",",
"self",
")",
"next_token",
"=",
"results",
"[",
":next_token",
"]",
"end",
"while",
"next_token",
"end",
"end"
] |
Yields once for each result set, until there is no next token.
|
[
"Yields",
"once",
"for",
"each",
"result",
"set",
"until",
"there",
"is",
"no",
"next",
"token",
"."
] |
194c082bf3f67eac6d5eb40cbc392957db4da269
|
https://github.com/devver/sdbtools/blob/194c082bf3f67eac6d5eb40cbc392957db4da269/lib/sdbtools/operation.rb#L20-L31
|
9,365
|
populr/subdomainbox
|
lib/subdomainbox/secure_csrf_token.rb
|
ActionController.RequestForgeryProtection.form_authenticity_token
|
def form_authenticity_token
raise 'CSRF token secret must be defined' if CSRF_TOKEN_SECRET.nil? || CSRF_TOKEN_SECRET.empty?
if request.session_options[:id].nil? || request.session_options[:id].empty?
original_form_authenticity_token
else
Digest::SHA1.hexdigest("#{CSRF_TOKEN_SECRET}#{request.session_options[:id]}#{request.subdomain}")
end
end
|
ruby
|
def form_authenticity_token
raise 'CSRF token secret must be defined' if CSRF_TOKEN_SECRET.nil? || CSRF_TOKEN_SECRET.empty?
if request.session_options[:id].nil? || request.session_options[:id].empty?
original_form_authenticity_token
else
Digest::SHA1.hexdigest("#{CSRF_TOKEN_SECRET}#{request.session_options[:id]}#{request.subdomain}")
end
end
|
[
"def",
"form_authenticity_token",
"raise",
"'CSRF token secret must be defined'",
"if",
"CSRF_TOKEN_SECRET",
".",
"nil?",
"||",
"CSRF_TOKEN_SECRET",
".",
"empty?",
"if",
"request",
".",
"session_options",
"[",
":id",
"]",
".",
"nil?",
"||",
"request",
".",
"session_options",
"[",
":id",
"]",
".",
"empty?",
"original_form_authenticity_token",
"else",
"Digest",
"::",
"SHA1",
".",
"hexdigest",
"(",
"\"#{CSRF_TOKEN_SECRET}#{request.session_options[:id]}#{request.subdomain}\"",
")",
"end",
"end"
] |
Sets the token value for the current session.
|
[
"Sets",
"the",
"token",
"value",
"for",
"the",
"current",
"session",
"."
] |
b29730ba14a2fa0b62759422d1cef78646d96a93
|
https://github.com/populr/subdomainbox/blob/b29730ba14a2fa0b62759422d1cef78646d96a93/lib/subdomainbox/secure_csrf_token.rb#L11-L18
|
9,366
|
hubb/putio.rb
|
lib/putio/configurable.rb
|
Putio.Configurable.reset!
|
def reset!
Putio::Configurable.keys.each do |key|
public_send("#{key}=".to_sym, Putio::Defaults.options[key])
end
self
end
|
ruby
|
def reset!
Putio::Configurable.keys.each do |key|
public_send("#{key}=".to_sym, Putio::Defaults.options[key])
end
self
end
|
[
"def",
"reset!",
"Putio",
"::",
"Configurable",
".",
"keys",
".",
"each",
"do",
"|",
"key",
"|",
"public_send",
"(",
"\"#{key}=\"",
".",
"to_sym",
",",
"Putio",
"::",
"Defaults",
".",
"options",
"[",
"key",
"]",
")",
"end",
"self",
"end"
] |
Reset configuration options to default values
|
[
"Reset",
"configuration",
"options",
"to",
"default",
"values"
] |
83c12aa81cdb99aaeb767e9cd27bd92f14abffeb
|
https://github.com/hubb/putio.rb/blob/83c12aa81cdb99aaeb767e9cd27bd92f14abffeb/lib/putio/configurable.rb#L32-L37
|
9,367
|
petebrowne/machined
|
lib/machined/context.rb
|
Machined.Context.add_machined_helpers
|
def add_machined_helpers # :nodoc:
machined.context_helpers.each do |helper|
case helper
when Proc
instance_eval &helper
when Module
extend helper
end
end
end
|
ruby
|
def add_machined_helpers # :nodoc:
machined.context_helpers.each do |helper|
case helper
when Proc
instance_eval &helper
when Module
extend helper
end
end
end
|
[
"def",
"add_machined_helpers",
"# :nodoc:",
"machined",
".",
"context_helpers",
".",
"each",
"do",
"|",
"helper",
"|",
"case",
"helper",
"when",
"Proc",
"instance_eval",
"helper",
"when",
"Module",
"extend",
"helper",
"end",
"end",
"end"
] |
Loops through the helpers added to the Machined
environment and adds them to the Context. Supports
blocks and Modules.
|
[
"Loops",
"through",
"the",
"helpers",
"added",
"to",
"the",
"Machined",
"environment",
"and",
"adds",
"them",
"to",
"the",
"Context",
".",
"Supports",
"blocks",
"and",
"Modules",
"."
] |
4f3921bc5098104096474300e933f009f1b4f7dd
|
https://github.com/petebrowne/machined/blob/4f3921bc5098104096474300e933f009f1b4f7dd/lib/machined/context.rb#L43-L52
|
9,368
|
mgsnova/crisp
|
lib/crisp/shell.rb
|
Crisp.Shell.run
|
def run
runtime = Runtime.new
buffer = ''
while (line = Readline.readline(buffer.empty? ? ">> " : "?> ", true))
begin
buffer << line
ast = Parser.new.parse(buffer)
puts "=> " + runtime.run(ast).to_s
buffer = ''
rescue Crisp::SyntaxError => e
# noop
end
end
end
|
ruby
|
def run
runtime = Runtime.new
buffer = ''
while (line = Readline.readline(buffer.empty? ? ">> " : "?> ", true))
begin
buffer << line
ast = Parser.new.parse(buffer)
puts "=> " + runtime.run(ast).to_s
buffer = ''
rescue Crisp::SyntaxError => e
# noop
end
end
end
|
[
"def",
"run",
"runtime",
"=",
"Runtime",
".",
"new",
"buffer",
"=",
"''",
"while",
"(",
"line",
"=",
"Readline",
".",
"readline",
"(",
"buffer",
".",
"empty?",
"?",
"\">> \"",
":",
"\"?> \"",
",",
"true",
")",
")",
"begin",
"buffer",
"<<",
"line",
"ast",
"=",
"Parser",
".",
"new",
".",
"parse",
"(",
"buffer",
")",
"puts",
"\"=> \"",
"+",
"runtime",
".",
"run",
"(",
"ast",
")",
".",
"to_s",
"buffer",
"=",
"''",
"rescue",
"Crisp",
"::",
"SyntaxError",
"=>",
"e",
"# noop",
"end",
"end",
"end"
] |
start the shell
|
[
"start",
"the",
"shell"
] |
0b3695de59258971b8b39998602c5b6e9f10623b
|
https://github.com/mgsnova/crisp/blob/0b3695de59258971b8b39998602c5b6e9f10623b/lib/crisp/shell.rb#L9-L23
|
9,369
|
mtnsat/zerg
|
zerg/lib/zerg/gem_plugin.rb
|
ZergGemPlugin.Manager.load
|
def load(needs = {})
needs = needs.merge({"zergrush" => INCLUDE})
Gem::Specification.each { |gem|
# don't load gems more than once
next if @gems.has_key? gem.name
check = needs.dup
# rolls through the depends and inverts anything it finds
gem.dependencies.each do |dep|
# this will fail if a gem is depended more than once
if check.has_key? dep.name
check[dep.name] = !check[dep.name]
end
end
# now since excluded gems start as true, inverting them
# makes them false so we'll skip this gem if any excludes are found
if (check.select {|name,test| !test}).length == 0
# looks like no needs were set to false, so it's good
if gem.metadata["zergrushplugin"] != nil
require File.join(gem.gem_dir, "lib", gem.name, "init.rb")
@gems[gem.name] = gem.gem_dir
end
end
}
return nil
end
|
ruby
|
def load(needs = {})
needs = needs.merge({"zergrush" => INCLUDE})
Gem::Specification.each { |gem|
# don't load gems more than once
next if @gems.has_key? gem.name
check = needs.dup
# rolls through the depends and inverts anything it finds
gem.dependencies.each do |dep|
# this will fail if a gem is depended more than once
if check.has_key? dep.name
check[dep.name] = !check[dep.name]
end
end
# now since excluded gems start as true, inverting them
# makes them false so we'll skip this gem if any excludes are found
if (check.select {|name,test| !test}).length == 0
# looks like no needs were set to false, so it's good
if gem.metadata["zergrushplugin"] != nil
require File.join(gem.gem_dir, "lib", gem.name, "init.rb")
@gems[gem.name] = gem.gem_dir
end
end
}
return nil
end
|
[
"def",
"load",
"(",
"needs",
"=",
"{",
"}",
")",
"needs",
"=",
"needs",
".",
"merge",
"(",
"{",
"\"zergrush\"",
"=>",
"INCLUDE",
"}",
")",
"Gem",
"::",
"Specification",
".",
"each",
"{",
"|",
"gem",
"|",
"# don't load gems more than once",
"next",
"if",
"@gems",
".",
"has_key?",
"gem",
".",
"name",
"check",
"=",
"needs",
".",
"dup",
"# rolls through the depends and inverts anything it finds",
"gem",
".",
"dependencies",
".",
"each",
"do",
"|",
"dep",
"|",
"# this will fail if a gem is depended more than once",
"if",
"check",
".",
"has_key?",
"dep",
".",
"name",
"check",
"[",
"dep",
".",
"name",
"]",
"=",
"!",
"check",
"[",
"dep",
".",
"name",
"]",
"end",
"end",
"# now since excluded gems start as true, inverting them",
"# makes them false so we'll skip this gem if any excludes are found",
"if",
"(",
"check",
".",
"select",
"{",
"|",
"name",
",",
"test",
"|",
"!",
"test",
"}",
")",
".",
"length",
"==",
"0",
"# looks like no needs were set to false, so it's good",
"if",
"gem",
".",
"metadata",
"[",
"\"zergrushplugin\"",
"]",
"!=",
"nil",
"require",
"File",
".",
"join",
"(",
"gem",
".",
"gem_dir",
",",
"\"lib\"",
",",
"gem",
".",
"name",
",",
"\"init.rb\"",
")",
"@gems",
"[",
"gem",
".",
"name",
"]",
"=",
"gem",
".",
"gem_dir",
"end",
"end",
"}",
"return",
"nil",
"end"
] |
Responsible for going through the list of available gems and loading
any plugins requested. It keeps track of what it's loaded already
and won't load them again.
It accepts one parameter which is a hash of gem depends that should include
or exclude a gem from being loaded. A gem must depend on zergrush to be
considered, but then each system has to add it's own INCLUDE to make sure
that only plugins related to it are loaded.
An example again comes from Mongrel. In order to load all Mongrel plugins:
GemPlugin::Manager.instance.load "mongrel" => GemPlugin::INCLUDE
Which will load all plugins that depend on mongrel AND zergrush. Now, one
extra thing we do is we delay loading Rails Mongrel plugins until after rails
is configured. Do do this the mongrel_rails script has:
GemPlugin::Manager.instance.load "mongrel" => GemPlugin::INCLUDE, "rails" => GemPlugin::EXCLUDE
The only thing to remember is that this is saying "include a plugin if it
depends on zergrush, mongrel, but NOT rails". If a plugin also depends on other
stuff then it's loaded just fine. Only zergrush, mongrel, and rails are
ever used to determine if it should be included.
NOTE: Currently RubyGems will run autorequire on gems that get required AND
on their dependencies. This really messes with people running edge rails
since activerecord or other stuff gets loaded for just touching a gem plugin.
To prevent this load requires the full path to the "init.rb" file, which
avoids the RubyGems autorequire magic.
|
[
"Responsible",
"for",
"going",
"through",
"the",
"list",
"of",
"available",
"gems",
"and",
"loading",
"any",
"plugins",
"requested",
".",
"It",
"keeps",
"track",
"of",
"what",
"it",
"s",
"loaded",
"already",
"and",
"won",
"t",
"load",
"them",
"again",
"."
] |
dd497665795c7b51a984ae050987a9c5421cd5eb
|
https://github.com/mtnsat/zerg/blob/dd497665795c7b51a984ae050987a9c5421cd5eb/zerg/lib/zerg/gem_plugin.rb#L161-L189
|
9,370
|
jmettraux/rufus-cloche
|
lib/rufus/cloche.rb
|
Rufus.Cloche.put
|
def put(doc, opts={})
opts = opts.inject({}) { |h, (k, v)| h[k.to_s] = v; h }
doc = Rufus::Json.dup(doc) unless opts['update_rev']
# work with a copy, don't touch original
type, key = doc['type'], doc['_id']
raise(
ArgumentError.new("missing values for keys 'type' and/or '_id'")
) if type.nil? || key.nil?
rev = (doc['_rev'] ||= -1)
raise(
ArgumentError.new("values for '_rev' must be positive integers")
) if rev.class != Fixnum && rev.class != Bignum
r =
lock(rev == -1 ? :create : :write, type, key) do |file|
cur = do_get(file)
return cur if cur && cur['_rev'] != doc['_rev']
return true if cur.nil? && doc['_rev'] != -1
doc['_rev'] += 1
File.open(file.path, 'wb') { |io| io.write(Rufus::Json.encode(doc)) }
end
r == false ? true : nil
end
|
ruby
|
def put(doc, opts={})
opts = opts.inject({}) { |h, (k, v)| h[k.to_s] = v; h }
doc = Rufus::Json.dup(doc) unless opts['update_rev']
# work with a copy, don't touch original
type, key = doc['type'], doc['_id']
raise(
ArgumentError.new("missing values for keys 'type' and/or '_id'")
) if type.nil? || key.nil?
rev = (doc['_rev'] ||= -1)
raise(
ArgumentError.new("values for '_rev' must be positive integers")
) if rev.class != Fixnum && rev.class != Bignum
r =
lock(rev == -1 ? :create : :write, type, key) do |file|
cur = do_get(file)
return cur if cur && cur['_rev'] != doc['_rev']
return true if cur.nil? && doc['_rev'] != -1
doc['_rev'] += 1
File.open(file.path, 'wb') { |io| io.write(Rufus::Json.encode(doc)) }
end
r == false ? true : nil
end
|
[
"def",
"put",
"(",
"doc",
",",
"opts",
"=",
"{",
"}",
")",
"opts",
"=",
"opts",
".",
"inject",
"(",
"{",
"}",
")",
"{",
"|",
"h",
",",
"(",
"k",
",",
"v",
")",
"|",
"h",
"[",
"k",
".",
"to_s",
"]",
"=",
"v",
";",
"h",
"}",
"doc",
"=",
"Rufus",
"::",
"Json",
".",
"dup",
"(",
"doc",
")",
"unless",
"opts",
"[",
"'update_rev'",
"]",
"# work with a copy, don't touch original",
"type",
",",
"key",
"=",
"doc",
"[",
"'type'",
"]",
",",
"doc",
"[",
"'_id'",
"]",
"raise",
"(",
"ArgumentError",
".",
"new",
"(",
"\"missing values for keys 'type' and/or '_id'\"",
")",
")",
"if",
"type",
".",
"nil?",
"||",
"key",
".",
"nil?",
"rev",
"=",
"(",
"doc",
"[",
"'_rev'",
"]",
"||=",
"-",
"1",
")",
"raise",
"(",
"ArgumentError",
".",
"new",
"(",
"\"values for '_rev' must be positive integers\"",
")",
")",
"if",
"rev",
".",
"class",
"!=",
"Fixnum",
"&&",
"rev",
".",
"class",
"!=",
"Bignum",
"r",
"=",
"lock",
"(",
"rev",
"==",
"-",
"1",
"?",
":create",
":",
":write",
",",
"type",
",",
"key",
")",
"do",
"|",
"file",
"|",
"cur",
"=",
"do_get",
"(",
"file",
")",
"return",
"cur",
"if",
"cur",
"&&",
"cur",
"[",
"'_rev'",
"]",
"!=",
"doc",
"[",
"'_rev'",
"]",
"return",
"true",
"if",
"cur",
".",
"nil?",
"&&",
"doc",
"[",
"'_rev'",
"]",
"!=",
"-",
"1",
"doc",
"[",
"'_rev'",
"]",
"+=",
"1",
"File",
".",
"open",
"(",
"file",
".",
"path",
",",
"'wb'",
")",
"{",
"|",
"io",
"|",
"io",
".",
"write",
"(",
"Rufus",
"::",
"Json",
".",
"encode",
"(",
"doc",
")",
")",
"}",
"end",
"r",
"==",
"false",
"?",
"true",
":",
"nil",
"end"
] |
Creates a new 'cloche'.
There are 2 options :
* :dir : to specify the directory into which the cloche data is store
* :nolock : when set to true, no flock is used
On the Windows platform, :nolock is set to true automatically.
Puts a document (Hash) under the cloche.
If the document is brand new, it will be given a revision number '_rev'
of 0.
If the document already exists in the cloche and the version to put
has an older (different) revision number than the one currently stored,
put will fail and return the current version of the doc.
If the put is successful, nil is returned.
|
[
"Creates",
"a",
"new",
"cloche",
"."
] |
e038fa69ded7d3de85f151d12d111466aef97aab
|
https://github.com/jmettraux/rufus-cloche/blob/e038fa69ded7d3de85f151d12d111466aef97aab/lib/rufus/cloche.rb#L75-L108
|
9,371
|
jmettraux/rufus-cloche
|
lib/rufus/cloche.rb
|
Rufus.Cloche.get_many
|
def get_many(type, regex=nil, opts={})
opts = opts.inject({}) { |h, (k, v)| h[k.to_s] = v; h }
d = dir_for(type)
return (opts['count'] ? 0 : []) unless File.exist?(d)
regexes = regex ? Array(regex) : nil
docs = []
skipped = 0
limit = opts['limit']
skip = opts['skip']
count = opts['count'] ? 0 : nil
files = Dir[File.join(d, '**', '*.json')].sort_by { |f| File.basename(f) }
files = files.reverse if opts['descending']
files.each do |fn|
key = File.basename(fn, '.json')
if regexes.nil? or match?(key, regexes)
skipped = skipped + 1
next if skip and skipped <= skip
doc = get(type, key)
next unless doc
if count
count = count + 1
else
docs << doc
end
break if limit and docs.size >= limit
end
end
# WARNING : there is a twist here, the filenames may have a different
# sort order from actual _ids...
#docs.sort { |doc0, doc1| doc0['_id'] <=> doc1['_id'] }
# let's trust filename order
count ? count : docs
end
|
ruby
|
def get_many(type, regex=nil, opts={})
opts = opts.inject({}) { |h, (k, v)| h[k.to_s] = v; h }
d = dir_for(type)
return (opts['count'] ? 0 : []) unless File.exist?(d)
regexes = regex ? Array(regex) : nil
docs = []
skipped = 0
limit = opts['limit']
skip = opts['skip']
count = opts['count'] ? 0 : nil
files = Dir[File.join(d, '**', '*.json')].sort_by { |f| File.basename(f) }
files = files.reverse if opts['descending']
files.each do |fn|
key = File.basename(fn, '.json')
if regexes.nil? or match?(key, regexes)
skipped = skipped + 1
next if skip and skipped <= skip
doc = get(type, key)
next unless doc
if count
count = count + 1
else
docs << doc
end
break if limit and docs.size >= limit
end
end
# WARNING : there is a twist here, the filenames may have a different
# sort order from actual _ids...
#docs.sort { |doc0, doc1| doc0['_id'] <=> doc1['_id'] }
# let's trust filename order
count ? count : docs
end
|
[
"def",
"get_many",
"(",
"type",
",",
"regex",
"=",
"nil",
",",
"opts",
"=",
"{",
"}",
")",
"opts",
"=",
"opts",
".",
"inject",
"(",
"{",
"}",
")",
"{",
"|",
"h",
",",
"(",
"k",
",",
"v",
")",
"|",
"h",
"[",
"k",
".",
"to_s",
"]",
"=",
"v",
";",
"h",
"}",
"d",
"=",
"dir_for",
"(",
"type",
")",
"return",
"(",
"opts",
"[",
"'count'",
"]",
"?",
"0",
":",
"[",
"]",
")",
"unless",
"File",
".",
"exist?",
"(",
"d",
")",
"regexes",
"=",
"regex",
"?",
"Array",
"(",
"regex",
")",
":",
"nil",
"docs",
"=",
"[",
"]",
"skipped",
"=",
"0",
"limit",
"=",
"opts",
"[",
"'limit'",
"]",
"skip",
"=",
"opts",
"[",
"'skip'",
"]",
"count",
"=",
"opts",
"[",
"'count'",
"]",
"?",
"0",
":",
"nil",
"files",
"=",
"Dir",
"[",
"File",
".",
"join",
"(",
"d",
",",
"'**'",
",",
"'*.json'",
")",
"]",
".",
"sort_by",
"{",
"|",
"f",
"|",
"File",
".",
"basename",
"(",
"f",
")",
"}",
"files",
"=",
"files",
".",
"reverse",
"if",
"opts",
"[",
"'descending'",
"]",
"files",
".",
"each",
"do",
"|",
"fn",
"|",
"key",
"=",
"File",
".",
"basename",
"(",
"fn",
",",
"'.json'",
")",
"if",
"regexes",
".",
"nil?",
"or",
"match?",
"(",
"key",
",",
"regexes",
")",
"skipped",
"=",
"skipped",
"+",
"1",
"next",
"if",
"skip",
"and",
"skipped",
"<=",
"skip",
"doc",
"=",
"get",
"(",
"type",
",",
"key",
")",
"next",
"unless",
"doc",
"if",
"count",
"count",
"=",
"count",
"+",
"1",
"else",
"docs",
"<<",
"doc",
"end",
"break",
"if",
"limit",
"and",
"docs",
".",
"size",
">=",
"limit",
"end",
"end",
"# WARNING : there is a twist here, the filenames may have a different",
"# sort order from actual _ids...",
"#docs.sort { |doc0, doc1| doc0['_id'] <=> doc1['_id'] }",
"# let's trust filename order",
"count",
"?",
"count",
":",
"docs",
"end"
] |
Given a type, this method will return an array of all the documents for
that type.
A optional second parameter may be used to select, based on a regular
expression, which documents to include (match on the key '_id').
Will return an empty Hash if there is no documents for a given type.
== opts
:skip and :limit are understood (pagination).
If :count => true, the query will simply return the number of documents
that matched.
|
[
"Given",
"a",
"type",
"this",
"method",
"will",
"return",
"an",
"array",
"of",
"all",
"the",
"documents",
"for",
"that",
"type",
"."
] |
e038fa69ded7d3de85f151d12d111466aef97aab
|
https://github.com/jmettraux/rufus-cloche/blob/e038fa69ded7d3de85f151d12d111466aef97aab/lib/rufus/cloche.rb#L174-L223
|
9,372
|
Hermanverschooten/jquery_datepick
|
lib/jquery_datepick/form_helper.rb
|
JqueryDatepick.FormHelper.datepicker
|
def datepicker(object_name, method, options = {}, timepicker = false)
input_tag = JqueryDatepick::Tags.new(object_name, method, self, options)
dp_options, tf_options = input_tag.split_options(options)
tf_options[:value] = input_tag.format_date(tf_options[:value], String.new(dp_options[:dateFormat])) if tf_options[:value] && !tf_options[:value].empty? && dp_options.has_key?(:dateFormat)
html = input_tag.render
method = timepicker ? "datetimepicker" : "datepicker"
html += javascript_tag("jQuery(document).ready(function(){jQuery('##{input_tag.get_name_and_id(tf_options.stringify_keys)["id"]}').#{method}(#{dp_options.to_json})});")
html.html_safe
end
|
ruby
|
def datepicker(object_name, method, options = {}, timepicker = false)
input_tag = JqueryDatepick::Tags.new(object_name, method, self, options)
dp_options, tf_options = input_tag.split_options(options)
tf_options[:value] = input_tag.format_date(tf_options[:value], String.new(dp_options[:dateFormat])) if tf_options[:value] && !tf_options[:value].empty? && dp_options.has_key?(:dateFormat)
html = input_tag.render
method = timepicker ? "datetimepicker" : "datepicker"
html += javascript_tag("jQuery(document).ready(function(){jQuery('##{input_tag.get_name_and_id(tf_options.stringify_keys)["id"]}').#{method}(#{dp_options.to_json})});")
html.html_safe
end
|
[
"def",
"datepicker",
"(",
"object_name",
",",
"method",
",",
"options",
"=",
"{",
"}",
",",
"timepicker",
"=",
"false",
")",
"input_tag",
"=",
"JqueryDatepick",
"::",
"Tags",
".",
"new",
"(",
"object_name",
",",
"method",
",",
"self",
",",
"options",
")",
"dp_options",
",",
"tf_options",
"=",
"input_tag",
".",
"split_options",
"(",
"options",
")",
"tf_options",
"[",
":value",
"]",
"=",
"input_tag",
".",
"format_date",
"(",
"tf_options",
"[",
":value",
"]",
",",
"String",
".",
"new",
"(",
"dp_options",
"[",
":dateFormat",
"]",
")",
")",
"if",
"tf_options",
"[",
":value",
"]",
"&&",
"!",
"tf_options",
"[",
":value",
"]",
".",
"empty?",
"&&",
"dp_options",
".",
"has_key?",
"(",
":dateFormat",
")",
"html",
"=",
"input_tag",
".",
"render",
"method",
"=",
"timepicker",
"?",
"\"datetimepicker\"",
":",
"\"datepicker\"",
"html",
"+=",
"javascript_tag",
"(",
"\"jQuery(document).ready(function(){jQuery('##{input_tag.get_name_and_id(tf_options.stringify_keys)[\"id\"]}').#{method}(#{dp_options.to_json})});\"",
")",
"html",
".",
"html_safe",
"end"
] |
Mehtod that generates datepicker input field inside a form
|
[
"Mehtod",
"that",
"generates",
"datepicker",
"input",
"field",
"inside",
"a",
"form"
] |
22fd5f4a1d5a95fb942427ae08e5078b293c969b
|
https://github.com/Hermanverschooten/jquery_datepick/blob/22fd5f4a1d5a95fb942427ae08e5078b293c969b/lib/jquery_datepick/form_helper.rb#L8-L16
|
9,373
|
richo/twat
|
lib/twat/options.rb
|
Twat.Options.default=
|
def default=(value)
value = value.to_sym
unless config.accounts.include?(value)
raise NoSuchAccount
end
config[:default] = value
config.save!
end
|
ruby
|
def default=(value)
value = value.to_sym
unless config.accounts.include?(value)
raise NoSuchAccount
end
config[:default] = value
config.save!
end
|
[
"def",
"default",
"=",
"(",
"value",
")",
"value",
"=",
"value",
".",
"to_sym",
"unless",
"config",
".",
"accounts",
".",
"include?",
"(",
"value",
")",
"raise",
"NoSuchAccount",
"end",
"config",
"[",
":default",
"]",
"=",
"value",
"config",
".",
"save!",
"end"
] |
This is deliberately not abstracted (it could be easily accessed from
withing the method_missing method, but that will just lead to nastiness
later when I implement colors, for example.
|
[
"This",
"is",
"deliberately",
"not",
"abstracted",
"(",
"it",
"could",
"be",
"easily",
"accessed",
"from",
"withing",
"the",
"method_missing",
"method",
"but",
"that",
"will",
"just",
"lead",
"to",
"nastiness",
"later",
"when",
"I",
"implement",
"colors",
"for",
"example",
"."
] |
0354059c2d9643a8c3b855dbb18105fa80bf651e
|
https://github.com/richo/twat/blob/0354059c2d9643a8c3b855dbb18105fa80bf651e/lib/twat/options.rb#L55-L63
|
9,374
|
vojto/active_harmony
|
lib/active_harmony/queue.rb
|
ActiveHarmony.Queue.queue_push
|
def queue_push(object)
queue_item = QueueItem.new( :kind => "push",
:object_type => object.class.name,
:object_local_id => object.id,
:state => "new" )
queue_item.save
end
|
ruby
|
def queue_push(object)
queue_item = QueueItem.new( :kind => "push",
:object_type => object.class.name,
:object_local_id => object.id,
:state => "new" )
queue_item.save
end
|
[
"def",
"queue_push",
"(",
"object",
")",
"queue_item",
"=",
"QueueItem",
".",
"new",
"(",
":kind",
"=>",
"\"push\"",
",",
":object_type",
"=>",
"object",
".",
"class",
".",
"name",
",",
":object_local_id",
"=>",
"object",
".",
"id",
",",
":state",
"=>",
"\"new\"",
")",
"queue_item",
".",
"save",
"end"
] |
Queues object for push
@param [Object] Object
|
[
"Queues",
"object",
"for",
"push"
] |
03e5c67ea7a1f986c729001c4fec944bf116640f
|
https://github.com/vojto/active_harmony/blob/03e5c67ea7a1f986c729001c4fec944bf116640f/lib/active_harmony/queue.rb#L8-L14
|
9,375
|
vojto/active_harmony
|
lib/active_harmony/queue.rb
|
ActiveHarmony.Queue.queue_pull
|
def queue_pull(object_class, remote_id)
queue_item = QueueItem.new( :kind => "pull",
:object_type => object_class.name,
:object_remote_id => remote_id,
:state => "new" )
queue_item.save
end
|
ruby
|
def queue_pull(object_class, remote_id)
queue_item = QueueItem.new( :kind => "pull",
:object_type => object_class.name,
:object_remote_id => remote_id,
:state => "new" )
queue_item.save
end
|
[
"def",
"queue_pull",
"(",
"object_class",
",",
"remote_id",
")",
"queue_item",
"=",
"QueueItem",
".",
"new",
"(",
":kind",
"=>",
"\"pull\"",
",",
":object_type",
"=>",
"object_class",
".",
"name",
",",
":object_remote_id",
"=>",
"remote_id",
",",
":state",
"=>",
"\"new\"",
")",
"queue_item",
".",
"save",
"end"
] |
Queues object for pull
@param [Class] Class of object
@param [String] Remote ID for object
|
[
"Queues",
"object",
"for",
"pull"
] |
03e5c67ea7a1f986c729001c4fec944bf116640f
|
https://github.com/vojto/active_harmony/blob/03e5c67ea7a1f986c729001c4fec944bf116640f/lib/active_harmony/queue.rb#L20-L26
|
9,376
|
xufeisofly/organismo
|
lib/organismo/element_collection.rb
|
Organismo.ElementCollection.elements_by_source
|
def elements_by_source
source_items.map.with_index do |source_item, index|
Organismo::Element.new(source_item, index).create
end
end
|
ruby
|
def elements_by_source
source_items.map.with_index do |source_item, index|
Organismo::Element.new(source_item, index).create
end
end
|
[
"def",
"elements_by_source",
"source_items",
".",
"map",
".",
"with_index",
"do",
"|",
"source_item",
",",
"index",
"|",
"Organismo",
"::",
"Element",
".",
"new",
"(",
"source_item",
",",
"index",
")",
".",
"create",
"end",
"end"
] |
initialize elements items
|
[
"initialize",
"elements",
"items"
] |
cc133fc1c6206cb0efbff28daa7c9309481cd03e
|
https://github.com/xufeisofly/organismo/blob/cc133fc1c6206cb0efbff28daa7c9309481cd03e/lib/organismo/element_collection.rb#L16-L20
|
9,377
|
mntnorv/puttext
|
lib/puttext/po_entry.rb
|
PutText.POEntry.to_s
|
def to_s
str = String.new('')
# Add comments
str = add_comment(str, ':', @references.join(' ')) if references?
str = add_comment(str, ',', @flags.join("\n")) if flags?
# Add id and context
str = add_string(str, 'msgctxt', @msgctxt) if @msgctxt
str = add_string(str, 'msgid', @msgid)
str = add_string(str, 'msgid_plural', @msgid_plural) if plural?
str = add_translations(str)
str
end
|
ruby
|
def to_s
str = String.new('')
# Add comments
str = add_comment(str, ':', @references.join(' ')) if references?
str = add_comment(str, ',', @flags.join("\n")) if flags?
# Add id and context
str = add_string(str, 'msgctxt', @msgctxt) if @msgctxt
str = add_string(str, 'msgid', @msgid)
str = add_string(str, 'msgid_plural', @msgid_plural) if plural?
str = add_translations(str)
str
end
|
[
"def",
"to_s",
"str",
"=",
"String",
".",
"new",
"(",
"''",
")",
"# Add comments",
"str",
"=",
"add_comment",
"(",
"str",
",",
"':'",
",",
"@references",
".",
"join",
"(",
"' '",
")",
")",
"if",
"references?",
"str",
"=",
"add_comment",
"(",
"str",
",",
"','",
",",
"@flags",
".",
"join",
"(",
"\"\\n\"",
")",
")",
"if",
"flags?",
"# Add id and context",
"str",
"=",
"add_string",
"(",
"str",
",",
"'msgctxt'",
",",
"@msgctxt",
")",
"if",
"@msgctxt",
"str",
"=",
"add_string",
"(",
"str",
",",
"'msgid'",
",",
"@msgid",
")",
"str",
"=",
"add_string",
"(",
"str",
",",
"'msgid_plural'",
",",
"@msgid_plural",
")",
"if",
"plural?",
"str",
"=",
"add_translations",
"(",
"str",
")",
"str",
"end"
] |
Create a new POEntry
@param [Hash] attrs
@option attrs [String] :msgid the id of the string (the string that needs
to be translated). Can include a context, separated from the id by
{NS_SEPARATOR} or by the specified :separator.
@option attrs [String] :msgid_plural the pluralized id of the string (the
pluralized string that needs to be translated).
@option attrs [String] :msgctxt the context of the string.
@option attrs [Array<String>] :msgstr the translated strings.
@option attrs [Array<String>] :references a list of files with line
numbers, pointing to where the string was found.
@option attrs [Array<String>] :flags a list of flags for this entry.
@option attrs [String] :separator the separator of context from id in
:msgid.
Convert the entry to a string representation, to be written to a .po file
@return [String] a string representation of the entry.
|
[
"Create",
"a",
"new",
"POEntry"
] |
c5c210dff4e11f714418b6b426dc9e2739fe9876
|
https://github.com/mntnorv/puttext/blob/c5c210dff4e11f714418b6b426dc9e2739fe9876/lib/puttext/po_entry.rb#L52-L66
|
9,378
|
justinkim/tf2r
|
lib/tf2r/raffle.rb
|
TF2R.Raffle.info
|
def info
@info ||= {link_snippet: @link_snippet, title: title,
description: description, start_time: start_time,
end_time: end_time, win_chance: win_chance,
current_entries: current_entries, max_entries: max_entries,
is_done: is_done}
end
|
ruby
|
def info
@info ||= {link_snippet: @link_snippet, title: title,
description: description, start_time: start_time,
end_time: end_time, win_chance: win_chance,
current_entries: current_entries, max_entries: max_entries,
is_done: is_done}
end
|
[
"def",
"info",
"@info",
"||=",
"{",
"link_snippet",
":",
"@link_snippet",
",",
"title",
":",
"title",
",",
"description",
":",
"description",
",",
"start_time",
":",
"start_time",
",",
"end_time",
":",
"end_time",
",",
"win_chance",
":",
"win_chance",
",",
"current_entries",
":",
"current_entries",
",",
"max_entries",
":",
"max_entries",
",",
"is_done",
":",
"is_done",
"}",
"end"
] |
Gives information about the raffle.
@example
r = Raffle.new('kstzcbd')
r.info #=>
{:link_snippet=>"kstzcbd",
:title=>"Just one refined [1 hour]",
:description=>"Plain and simple.",
:start_time=>2012-10-29 09:51:45 -0400,
:end_time=>2012-10-29 09:53:01 -0400,
:win_chance=>0.1,
:current_entries=>10,
:max_entries=>10,
:is_done=>true}
@param page [Mechanize::Page] the raffle page.
@return [Hash] a representation of the raffle.
* :link_snippet (+String+) — the "raffle id" in the URL.
* :title (+String+) — the raffle's title.
* :description (+String+) — the raffle's "message".
* :start_time (+Time+) — the creation time of the raffle.
* :end_time (+Time+) — the projects/observed end time for the raffle.
* :win_chance (+Float+) — a participant's chance to win the raffle.
Rounded to 5 digits.
* :current_entries (+Fixnum+) — the current number of participants.
* :max_entries (+Fixnum+) — the maximum number of particpants allowed.
* :is_done (+Boolean+) — whether new users can enter the raffle.
|
[
"Gives",
"information",
"about",
"the",
"raffle",
"."
] |
20d9648fe1048d9b2a34064821d8c95aaff505da
|
https://github.com/justinkim/tf2r/blob/20d9648fe1048d9b2a34064821d8c95aaff505da/lib/tf2r/raffle.rb#L46-L52
|
9,379
|
justinkim/tf2r
|
lib/tf2r/raffle.rb
|
TF2R.Raffle.populate_raffle_info
|
def populate_raffle_info
threads = []
threads << Thread.new do
@api_info = API.raffle_info(@link_snippet)
end
threads << Thread.new do
page = @scraper.fetch(raffle_link(@link_snippet))
@scraper_info = @scraper.scrape_raffle(page)
end
threads.each { |t| t.join }
end
|
ruby
|
def populate_raffle_info
threads = []
threads << Thread.new do
@api_info = API.raffle_info(@link_snippet)
end
threads << Thread.new do
page = @scraper.fetch(raffle_link(@link_snippet))
@scraper_info = @scraper.scrape_raffle(page)
end
threads.each { |t| t.join }
end
|
[
"def",
"populate_raffle_info",
"threads",
"=",
"[",
"]",
"threads",
"<<",
"Thread",
".",
"new",
"do",
"@api_info",
"=",
"API",
".",
"raffle_info",
"(",
"@link_snippet",
")",
"end",
"threads",
"<<",
"Thread",
".",
"new",
"do",
"page",
"=",
"@scraper",
".",
"fetch",
"(",
"raffle_link",
"(",
"@link_snippet",
")",
")",
"@scraper_info",
"=",
"@scraper",
".",
"scrape_raffle",
"(",
"page",
")",
"end",
"threads",
".",
"each",
"{",
"|",
"t",
"|",
"t",
".",
"join",
"}",
"end"
] |
Asynchronously makes network connections to TF2R to query its API and
scrape the raffle page.
|
[
"Asynchronously",
"makes",
"network",
"connections",
"to",
"TF2R",
"to",
"query",
"its",
"API",
"and",
"scrape",
"the",
"raffle",
"page",
"."
] |
20d9648fe1048d9b2a34064821d8c95aaff505da
|
https://github.com/justinkim/tf2r/blob/20d9648fe1048d9b2a34064821d8c95aaff505da/lib/tf2r/raffle.rb#L76-L87
|
9,380
|
justinkim/tf2r
|
lib/tf2r/raffle.rb
|
TF2R.Raffle.normalize_entries
|
def normalize_entries(entries)
entries.map do |entry|
entry[:steam_id] = extract_steam_id entry.delete('link')
entry[:username] = entry.delete('name')
entry[:color] = entry.delete('color').downcase.strip
entry[:avatar_link] = entry.delete('avatar')
end
entries
end
|
ruby
|
def normalize_entries(entries)
entries.map do |entry|
entry[:steam_id] = extract_steam_id entry.delete('link')
entry[:username] = entry.delete('name')
entry[:color] = entry.delete('color').downcase.strip
entry[:avatar_link] = entry.delete('avatar')
end
entries
end
|
[
"def",
"normalize_entries",
"(",
"entries",
")",
"entries",
".",
"map",
"do",
"|",
"entry",
"|",
"entry",
"[",
":steam_id",
"]",
"=",
"extract_steam_id",
"entry",
".",
"delete",
"(",
"'link'",
")",
"entry",
"[",
":username",
"]",
"=",
"entry",
".",
"delete",
"(",
"'name'",
")",
"entry",
"[",
":color",
"]",
"=",
"entry",
".",
"delete",
"(",
"'color'",
")",
".",
"downcase",
".",
"strip",
"entry",
"[",
":avatar_link",
"]",
"=",
"entry",
".",
"delete",
"(",
"'avatar'",
")",
"end",
"entries",
"end"
] |
Converts the representation of participants by TF2R's API into our own
standard representation.
|
[
"Converts",
"the",
"representation",
"of",
"participants",
"by",
"TF2R",
"s",
"API",
"into",
"our",
"own",
"standard",
"representation",
"."
] |
20d9648fe1048d9b2a34064821d8c95aaff505da
|
https://github.com/justinkim/tf2r/blob/20d9648fe1048d9b2a34064821d8c95aaff505da/lib/tf2r/raffle.rb#L96-L104
|
9,381
|
moviepilot/andromeda
|
lib/andromeda/spot.rb
|
Andromeda.Spot.post_to
|
def post_to(track, data, tags_in = {})
tags_in = (here.tags.identical_copy.update(tags_in) rescue tags_in) if here
plan.post_data self, track, data, tags_in
self
end
|
ruby
|
def post_to(track, data, tags_in = {})
tags_in = (here.tags.identical_copy.update(tags_in) rescue tags_in) if here
plan.post_data self, track, data, tags_in
self
end
|
[
"def",
"post_to",
"(",
"track",
",",
"data",
",",
"tags_in",
"=",
"{",
"}",
")",
"tags_in",
"=",
"(",
"here",
".",
"tags",
".",
"identical_copy",
".",
"update",
"(",
"tags_in",
")",
"rescue",
"tags_in",
")",
"if",
"here",
"plan",
".",
"post_data",
"self",
",",
"track",
",",
"data",
",",
"tags_in",
"self",
"end"
] |
Post data with the associated tags_in to this's spot's plan's method spot with name name
and hint that the caller requested the spot activation to be executed on track tack
@param [Track] track requested target track
@param [Any] data any data event
@param [Hash] tags to be passed along
@return [self]
|
[
"Post",
"data",
"with",
"the",
"associated",
"tags_in",
"to",
"this",
"s",
"spot",
"s",
"plan",
"s",
"method",
"spot",
"with",
"name",
"name",
"and",
"hint",
"that",
"the",
"caller",
"requested",
"the",
"spot",
"activation",
"to",
"be",
"executed",
"on",
"track",
"tack"
] |
68e6bac3cdb798046dbfa0e08314e7a40c938927
|
https://github.com/moviepilot/andromeda/blob/68e6bac3cdb798046dbfa0e08314e7a40c938927/lib/andromeda/spot.rb#L83-L87
|
9,382
|
fenton-project/fenton_shell
|
lib/fenton_shell/organization.rb
|
FentonShell.Organization.organization_create
|
def organization_create(global_options, options)
result = Excon.post(
"#{global_options[:fenton_server_url]}/organizations.json",
body: organization_json(options),
headers: { 'Content-Type' => 'application/json' }
)
[result.status, JSON.parse(result.body)]
end
|
ruby
|
def organization_create(global_options, options)
result = Excon.post(
"#{global_options[:fenton_server_url]}/organizations.json",
body: organization_json(options),
headers: { 'Content-Type' => 'application/json' }
)
[result.status, JSON.parse(result.body)]
end
|
[
"def",
"organization_create",
"(",
"global_options",
",",
"options",
")",
"result",
"=",
"Excon",
".",
"post",
"(",
"\"#{global_options[:fenton_server_url]}/organizations.json\"",
",",
"body",
":",
"organization_json",
"(",
"options",
")",
",",
"headers",
":",
"{",
"'Content-Type'",
"=>",
"'application/json'",
"}",
")",
"[",
"result",
".",
"status",
",",
"JSON",
".",
"parse",
"(",
"result",
".",
"body",
")",
"]",
"end"
] |
Sends a post request with json from the command line organization
@param global_options [Hash] global command line options
@param options [Hash] json fields to send to fenton server
@return [Fixnum] http status code
@return [String] message back from fenton server
|
[
"Sends",
"a",
"post",
"request",
"with",
"json",
"from",
"the",
"command",
"line",
"organization"
] |
6e1d76186fa7ee7a3be141afad9361e3a3e0ec91
|
https://github.com/fenton-project/fenton_shell/blob/6e1d76186fa7ee7a3be141afad9361e3a3e0ec91/lib/fenton_shell/organization.rb#L35-L43
|
9,383
|
futurechimp/drafter
|
lib/drafter/creation.rb
|
Drafter.Creation.save_draft
|
def save_draft(parent_draft=nil, parent_association_name=nil)
if valid?
do_create_draft(parent_draft, parent_association_name)
create_subdrafts
end
return self.draft.reload if self.draft
end
|
ruby
|
def save_draft(parent_draft=nil, parent_association_name=nil)
if valid?
do_create_draft(parent_draft, parent_association_name)
create_subdrafts
end
return self.draft.reload if self.draft
end
|
[
"def",
"save_draft",
"(",
"parent_draft",
"=",
"nil",
",",
"parent_association_name",
"=",
"nil",
")",
"if",
"valid?",
"do_create_draft",
"(",
"parent_draft",
",",
"parent_association_name",
")",
"create_subdrafts",
"end",
"return",
"self",
".",
"draft",
".",
"reload",
"if",
"self",
".",
"draft",
"end"
] |
Build and save the draft when told to do so.
|
[
"Build",
"and",
"save",
"the",
"draft",
"when",
"told",
"to",
"do",
"so",
"."
] |
8308b922148a6a44280023b0ef33d48a41f2e83e
|
https://github.com/futurechimp/drafter/blob/8308b922148a6a44280023b0ef33d48a41f2e83e/lib/drafter/creation.rb#L14-L20
|
9,384
|
futurechimp/drafter
|
lib/drafter/creation.rb
|
Drafter.Creation.build_draft_uploads
|
def build_draft_uploads
self.attributes.keys.each do |key|
if (self.respond_to?(key) &&
self.send(key).is_a?(CarrierWave::Uploader::Base) &&
self.send(key).file)
self.draft.draft_uploads << build_draft_upload(key)
end
end
end
|
ruby
|
def build_draft_uploads
self.attributes.keys.each do |key|
if (self.respond_to?(key) &&
self.send(key).is_a?(CarrierWave::Uploader::Base) &&
self.send(key).file)
self.draft.draft_uploads << build_draft_upload(key)
end
end
end
|
[
"def",
"build_draft_uploads",
"self",
".",
"attributes",
".",
"keys",
".",
"each",
"do",
"|",
"key",
"|",
"if",
"(",
"self",
".",
"respond_to?",
"(",
"key",
")",
"&&",
"self",
".",
"send",
"(",
"key",
")",
".",
"is_a?",
"(",
"CarrierWave",
"::",
"Uploader",
"::",
"Base",
")",
"&&",
"self",
".",
"send",
"(",
"key",
")",
".",
"file",
")",
"self",
".",
"draft",
".",
"draft_uploads",
"<<",
"build_draft_upload",
"(",
"key",
")",
"end",
"end",
"end"
] |
Loop through and create DraftUpload objects for any Carrierwave
uploaders mounted on this draftable object.
@param [Hash] attrs the attributes to loop through
@return [Array<DraftUpload>] an array of unsaved DraftUpload objects.
|
[
"Loop",
"through",
"and",
"create",
"DraftUpload",
"objects",
"for",
"any",
"Carrierwave",
"uploaders",
"mounted",
"on",
"this",
"draftable",
"object",
"."
] |
8308b922148a6a44280023b0ef33d48a41f2e83e
|
https://github.com/futurechimp/drafter/blob/8308b922148a6a44280023b0ef33d48a41f2e83e/lib/drafter/creation.rb#L54-L62
|
9,385
|
futurechimp/drafter
|
lib/drafter/creation.rb
|
Drafter.Creation.build_draft_upload
|
def build_draft_upload(key)
cw_uploader = self.send(key)
file = File.new(cw_uploader.file.path) if cw_uploader.file
existing_upload = self.draft.draft_uploads.where(:draftable_mount_column => key).first
draft_upload = existing_upload.nil? ? DraftUpload.new : existing_upload
draft_upload.file_data = file
draft_upload.draftable_mount_column = key
draft_upload
end
|
ruby
|
def build_draft_upload(key)
cw_uploader = self.send(key)
file = File.new(cw_uploader.file.path) if cw_uploader.file
existing_upload = self.draft.draft_uploads.where(:draftable_mount_column => key).first
draft_upload = existing_upload.nil? ? DraftUpload.new : existing_upload
draft_upload.file_data = file
draft_upload.draftable_mount_column = key
draft_upload
end
|
[
"def",
"build_draft_upload",
"(",
"key",
")",
"cw_uploader",
"=",
"self",
".",
"send",
"(",
"key",
")",
"file",
"=",
"File",
".",
"new",
"(",
"cw_uploader",
".",
"file",
".",
"path",
")",
"if",
"cw_uploader",
".",
"file",
"existing_upload",
"=",
"self",
".",
"draft",
".",
"draft_uploads",
".",
"where",
"(",
":draftable_mount_column",
"=>",
"key",
")",
".",
"first",
"draft_upload",
"=",
"existing_upload",
".",
"nil?",
"?",
"DraftUpload",
".",
"new",
":",
"existing_upload",
"draft_upload",
".",
"file_data",
"=",
"file",
"draft_upload",
".",
"draftable_mount_column",
"=",
"key",
"draft_upload",
"end"
] |
Get a reference to the CarrierWave uploader mounted on the
current draftable object, grab the file in it, and shove
that file into a new DraftUpload.
@param [String] key the attribute where the CarrierWave uploader
is mounted.
@return [DraftUpload] containing the file in the uploader.
|
[
"Get",
"a",
"reference",
"to",
"the",
"CarrierWave",
"uploader",
"mounted",
"on",
"the",
"current",
"draftable",
"object",
"grab",
"the",
"file",
"in",
"it",
"and",
"shove",
"that",
"file",
"into",
"a",
"new",
"DraftUpload",
"."
] |
8308b922148a6a44280023b0ef33d48a41f2e83e
|
https://github.com/futurechimp/drafter/blob/8308b922148a6a44280023b0ef33d48a41f2e83e/lib/drafter/creation.rb#L71-L79
|
9,386
|
jnicklas/eb_nested_set
|
lib/eb_nested_set.rb
|
EvenBetterNestedSet.NestedSet.root
|
def root(force_reload=nil)
@root = nil if force_reload
@root ||= transaction do
reload_boundaries
base_class.roots.find(:first, :conditions => ["#{nested_set_column(:left)} <= ? AND #{nested_set_column(:right)} >= ?", left, right])
end
end
|
ruby
|
def root(force_reload=nil)
@root = nil if force_reload
@root ||= transaction do
reload_boundaries
base_class.roots.find(:first, :conditions => ["#{nested_set_column(:left)} <= ? AND #{nested_set_column(:right)} >= ?", left, right])
end
end
|
[
"def",
"root",
"(",
"force_reload",
"=",
"nil",
")",
"@root",
"=",
"nil",
"if",
"force_reload",
"@root",
"||=",
"transaction",
"do",
"reload_boundaries",
"base_class",
".",
"roots",
".",
"find",
"(",
":first",
",",
":conditions",
"=>",
"[",
"\"#{nested_set_column(:left)} <= ? AND #{nested_set_column(:right)} >= ?\"",
",",
"left",
",",
"right",
"]",
")",
"end",
"end"
] |
Finds the root node that this node descends from
@param [Boolean] force_reload forces the root node to be reloaded
@return [ActiveRecord::Base] node the root node this descends from
|
[
"Finds",
"the",
"root",
"node",
"that",
"this",
"node",
"descends",
"from"
] |
71b7b71030116097e79a7bef02e77daedf9d3eae
|
https://github.com/jnicklas/eb_nested_set/blob/71b7b71030116097e79a7bef02e77daedf9d3eae/lib/eb_nested_set.rb#L206-L212
|
9,387
|
jnicklas/eb_nested_set
|
lib/eb_nested_set.rb
|
EvenBetterNestedSet.NestedSet.family_ids
|
def family_ids(force_reload=false)
return @family_ids unless @family_ids.nil? or force_reload
transaction do
reload_boundaries
query = "SELECT id FROM #{self.class.quote_db_property(base_class.table_name)} " +
"WHERE #{nested_set_column(:left)} >= #{left} AND #{nested_set_column(:right)} <= #{right} " +
"ORDER BY #{nested_set_column(:left)}"
@family_ids = base_class.connection.select_values(query).map(&:to_i)
end
end
|
ruby
|
def family_ids(force_reload=false)
return @family_ids unless @family_ids.nil? or force_reload
transaction do
reload_boundaries
query = "SELECT id FROM #{self.class.quote_db_property(base_class.table_name)} " +
"WHERE #{nested_set_column(:left)} >= #{left} AND #{nested_set_column(:right)} <= #{right} " +
"ORDER BY #{nested_set_column(:left)}"
@family_ids = base_class.connection.select_values(query).map(&:to_i)
end
end
|
[
"def",
"family_ids",
"(",
"force_reload",
"=",
"false",
")",
"return",
"@family_ids",
"unless",
"@family_ids",
".",
"nil?",
"or",
"force_reload",
"transaction",
"do",
"reload_boundaries",
"query",
"=",
"\"SELECT id FROM #{self.class.quote_db_property(base_class.table_name)} \"",
"+",
"\"WHERE #{nested_set_column(:left)} >= #{left} AND #{nested_set_column(:right)} <= #{right} \"",
"+",
"\"ORDER BY #{nested_set_column(:left)}\"",
"@family_ids",
"=",
"base_class",
".",
"connection",
".",
"select_values",
"(",
"query",
")",
".",
"map",
"(",
":to_i",
")",
"end",
"end"
] |
Returns the ids of the node and all nodes that descend from it.
@return [Array[Integer]]
|
[
"Returns",
"the",
"ids",
"of",
"the",
"node",
"and",
"all",
"nodes",
"that",
"descend",
"from",
"it",
"."
] |
71b7b71030116097e79a7bef02e77daedf9d3eae
|
https://github.com/jnicklas/eb_nested_set/blob/71b7b71030116097e79a7bef02e77daedf9d3eae/lib/eb_nested_set.rb#L279-L289
|
9,388
|
jnicklas/eb_nested_set
|
lib/eb_nested_set.rb
|
EvenBetterNestedSet.NestedSet.recalculate_nested_set
|
def recalculate_nested_set(left) #:nodoc:
child_left = left + 1
children.each do |child|
child_left = child.recalculate_nested_set(child_left)
end
set_boundaries(left, child_left)
save_without_validation!
right + 1
end
|
ruby
|
def recalculate_nested_set(left) #:nodoc:
child_left = left + 1
children.each do |child|
child_left = child.recalculate_nested_set(child_left)
end
set_boundaries(left, child_left)
save_without_validation!
right + 1
end
|
[
"def",
"recalculate_nested_set",
"(",
"left",
")",
"#:nodoc:",
"child_left",
"=",
"left",
"+",
"1",
"children",
".",
"each",
"do",
"|",
"child",
"|",
"child_left",
"=",
"child",
".",
"recalculate_nested_set",
"(",
"child_left",
")",
"end",
"set_boundaries",
"(",
"left",
",",
"child_left",
")",
"save_without_validation!",
"right",
"+",
"1",
"end"
] |
Rebuild this node's childrens boundaries
|
[
"Rebuild",
"this",
"node",
"s",
"childrens",
"boundaries"
] |
71b7b71030116097e79a7bef02e77daedf9d3eae
|
https://github.com/jnicklas/eb_nested_set/blob/71b7b71030116097e79a7bef02e77daedf9d3eae/lib/eb_nested_set.rb#L363-L372
|
9,389
|
mabarroso/lleidasms
|
lib/lleidasms/client.rb
|
Lleidasms.Client.send_waplink
|
def send_waplink number, url, message
cmd_waplink number, url, message
if wait
wait_for last_label
return false if @response_cmd.eql? 'NOOK'
return "#{@response_args[0]}.#{@response_args[1]}".to_f
end
end
|
ruby
|
def send_waplink number, url, message
cmd_waplink number, url, message
if wait
wait_for last_label
return false if @response_cmd.eql? 'NOOK'
return "#{@response_args[0]}.#{@response_args[1]}".to_f
end
end
|
[
"def",
"send_waplink",
"number",
",",
"url",
",",
"message",
"cmd_waplink",
"number",
",",
"url",
",",
"message",
"if",
"wait",
"wait_for",
"last_label",
"return",
"false",
"if",
"@response_cmd",
".",
"eql?",
"'NOOK'",
"return",
"\"#{@response_args[0]}.#{@response_args[1]}\"",
".",
"to_f",
"end",
"end"
] |
number
The telephone number
url
The URL to content. Usually a image, tone or application
message
Information text before downloading content
|
[
"number",
"The",
"telephone",
"number",
"url",
"The",
"URL",
"to",
"content",
".",
"Usually",
"a",
"image",
"tone",
"or",
"application",
"message",
"Information",
"text",
"before",
"downloading",
"content"
] |
419d37d9a25cc73548e5d9e8ac86bc24f35793ee
|
https://github.com/mabarroso/lleidasms/blob/419d37d9a25cc73548e5d9e8ac86bc24f35793ee/lib/lleidasms/client.rb#L100-L108
|
9,390
|
mabarroso/lleidasms
|
lib/lleidasms/client.rb
|
Lleidasms.Client.add_addressee
|
def add_addressee addressees, wait = true
@addressees_accepted = false
@addressees_rejected = false
if addressees.kind_of?(Array)
addressees = addressees.join ' '
end
cmd_dst addressees
while wait && !@addressees_accepted
wait_for last_label
return false if !add_addressee_results
end
end
|
ruby
|
def add_addressee addressees, wait = true
@addressees_accepted = false
@addressees_rejected = false
if addressees.kind_of?(Array)
addressees = addressees.join ' '
end
cmd_dst addressees
while wait && !@addressees_accepted
wait_for last_label
return false if !add_addressee_results
end
end
|
[
"def",
"add_addressee",
"addressees",
",",
"wait",
"=",
"true",
"@addressees_accepted",
"=",
"false",
"@addressees_rejected",
"=",
"false",
"if",
"addressees",
".",
"kind_of?",
"(",
"Array",
")",
"addressees",
"=",
"addressees",
".",
"join",
"' '",
"end",
"cmd_dst",
"addressees",
"while",
"wait",
"&&",
"!",
"@addressees_accepted",
"wait_for",
"last_label",
"return",
"false",
"if",
"!",
"add_addressee_results",
"end",
"end"
] |
Add telephone numbers into the massive send list.
It is recommended not to send more than 50 in each call
Return TRUE if ok
- see accepted in *last_addressees_accepted*
- see rejected in *last_addressees_rejected*
|
[
"Add",
"telephone",
"numbers",
"into",
"the",
"massive",
"send",
"list",
".",
"It",
"is",
"recommended",
"not",
"to",
"send",
"more",
"than",
"50",
"in",
"each",
"call"
] |
419d37d9a25cc73548e5d9e8ac86bc24f35793ee
|
https://github.com/mabarroso/lleidasms/blob/419d37d9a25cc73548e5d9e8ac86bc24f35793ee/lib/lleidasms/client.rb#L116-L129
|
9,391
|
mabarroso/lleidasms
|
lib/lleidasms/client.rb
|
Lleidasms.Client.msg
|
def msg message, wait = true
cmd_msg message
return false unless wait_for(last_label) if wait
return @response_args
end
|
ruby
|
def msg message, wait = true
cmd_msg message
return false unless wait_for(last_label) if wait
return @response_args
end
|
[
"def",
"msg",
"message",
",",
"wait",
"=",
"true",
"cmd_msg",
"message",
"return",
"false",
"unless",
"wait_for",
"(",
"last_label",
")",
"if",
"wait",
"return",
"@response_args",
"end"
] |
Set the message for the massive send list
|
[
"Set",
"the",
"message",
"for",
"the",
"massive",
"send",
"list"
] |
419d37d9a25cc73548e5d9e8ac86bc24f35793ee
|
https://github.com/mabarroso/lleidasms/blob/419d37d9a25cc73548e5d9e8ac86bc24f35793ee/lib/lleidasms/client.rb#L140-L144
|
9,392
|
astjohn/cornerstone
|
app/mailers/cornerstone/cornerstone_mailer.rb
|
Cornerstone.CornerstoneMailer.new_post
|
def new_post(name, email, post, discussion)
@post = post
@discussion = discussion
@name = name
mail :to => email,
:subject => I18n.t('cornerstone.cornerstone_mailer.new_post.subject',
:topic => @discussion.subject)
end
|
ruby
|
def new_post(name, email, post, discussion)
@post = post
@discussion = discussion
@name = name
mail :to => email,
:subject => I18n.t('cornerstone.cornerstone_mailer.new_post.subject',
:topic => @discussion.subject)
end
|
[
"def",
"new_post",
"(",
"name",
",",
"email",
",",
"post",
",",
"discussion",
")",
"@post",
"=",
"post",
"@discussion",
"=",
"discussion",
"@name",
"=",
"name",
"mail",
":to",
"=>",
"email",
",",
":subject",
"=>",
"I18n",
".",
"t",
"(",
"'cornerstone.cornerstone_mailer.new_post.subject'",
",",
":topic",
"=>",
"@discussion",
".",
"subject",
")",
"end"
] |
Email a single participant within a discussion - refer to post observer
|
[
"Email",
"a",
"single",
"participant",
"within",
"a",
"discussion",
"-",
"refer",
"to",
"post",
"observer"
] |
d7af7c06288477c961f3e328b8640df4be337301
|
https://github.com/astjohn/cornerstone/blob/d7af7c06288477c961f3e328b8640df4be337301/app/mailers/cornerstone/cornerstone_mailer.rb#L20-L28
|
9,393
|
gouravtiwari/beam
|
lib/beam/upload.rb
|
Beam.Upload.validate_record
|
def validate_record(errors_count, row_hash, index)
record = new(row_hash)
unless record.valid?
errors_count += 1
[nil, errors_count, log_and_return_validation_error(record, row_hash, index)]
else
[record, errors_count, nil]
end
end
|
ruby
|
def validate_record(errors_count, row_hash, index)
record = new(row_hash)
unless record.valid?
errors_count += 1
[nil, errors_count, log_and_return_validation_error(record, row_hash, index)]
else
[record, errors_count, nil]
end
end
|
[
"def",
"validate_record",
"(",
"errors_count",
",",
"row_hash",
",",
"index",
")",
"record",
"=",
"new",
"(",
"row_hash",
")",
"unless",
"record",
".",
"valid?",
"errors_count",
"+=",
"1",
"[",
"nil",
",",
"errors_count",
",",
"log_and_return_validation_error",
"(",
"record",
",",
"row_hash",
",",
"index",
")",
"]",
"else",
"[",
"record",
",",
"errors_count",
",",
"nil",
"]",
"end",
"end"
] |
Validates each record and returns error count if record is invalid
|
[
"Validates",
"each",
"record",
"and",
"returns",
"error",
"count",
"if",
"record",
"is",
"invalid"
] |
074f0d515b84cde319e95b18bd55e456400c3ab6
|
https://github.com/gouravtiwari/beam/blob/074f0d515b84cde319e95b18bd55e456400c3ab6/lib/beam/upload.rb#L82-L90
|
9,394
|
webco/tuiter
|
lib/tuiter/utils.rb
|
Tuiter.Request.create_http_request
|
def create_http_request(http_method, path, *arguments)
http_method = http_method.to_sym
if [:post, :put].include?(http_method)
data = arguments.shift
end
headers = arguments.first.is_a?(Hash) ? arguments.shift : {}
case http_method
when :post
request = Net::HTTP::Post.new(path,headers)
request["Content-Length"] = 0 # Default to 0
when :put
request = Net::HTTP::Put.new(path,headers)
request["Content-Length"] = 0 # Default to 0
when :get
request = Net::HTTP::Get.new(path,headers)
when :delete
request = Net::HTTP::Delete.new(path,headers)
else
raise ArgumentError, "Don't know how to handle http_method: :#{http_method.to_s}"
end
# handling basic http auth
request.basic_auth @config[:username], @config[:password]
if data.is_a?(Hash)
request.set_form_data(data)
elsif data
request.body = data.to_s
request["Content-Length"] = request.body.length
end
request
end
|
ruby
|
def create_http_request(http_method, path, *arguments)
http_method = http_method.to_sym
if [:post, :put].include?(http_method)
data = arguments.shift
end
headers = arguments.first.is_a?(Hash) ? arguments.shift : {}
case http_method
when :post
request = Net::HTTP::Post.new(path,headers)
request["Content-Length"] = 0 # Default to 0
when :put
request = Net::HTTP::Put.new(path,headers)
request["Content-Length"] = 0 # Default to 0
when :get
request = Net::HTTP::Get.new(path,headers)
when :delete
request = Net::HTTP::Delete.new(path,headers)
else
raise ArgumentError, "Don't know how to handle http_method: :#{http_method.to_s}"
end
# handling basic http auth
request.basic_auth @config[:username], @config[:password]
if data.is_a?(Hash)
request.set_form_data(data)
elsif data
request.body = data.to_s
request["Content-Length"] = request.body.length
end
request
end
|
[
"def",
"create_http_request",
"(",
"http_method",
",",
"path",
",",
"*",
"arguments",
")",
"http_method",
"=",
"http_method",
".",
"to_sym",
"if",
"[",
":post",
",",
":put",
"]",
".",
"include?",
"(",
"http_method",
")",
"data",
"=",
"arguments",
".",
"shift",
"end",
"headers",
"=",
"arguments",
".",
"first",
".",
"is_a?",
"(",
"Hash",
")",
"?",
"arguments",
".",
"shift",
":",
"{",
"}",
"case",
"http_method",
"when",
":post",
"request",
"=",
"Net",
"::",
"HTTP",
"::",
"Post",
".",
"new",
"(",
"path",
",",
"headers",
")",
"request",
"[",
"\"Content-Length\"",
"]",
"=",
"0",
"# Default to 0",
"when",
":put",
"request",
"=",
"Net",
"::",
"HTTP",
"::",
"Put",
".",
"new",
"(",
"path",
",",
"headers",
")",
"request",
"[",
"\"Content-Length\"",
"]",
"=",
"0",
"# Default to 0",
"when",
":get",
"request",
"=",
"Net",
"::",
"HTTP",
"::",
"Get",
".",
"new",
"(",
"path",
",",
"headers",
")",
"when",
":delete",
"request",
"=",
"Net",
"::",
"HTTP",
"::",
"Delete",
".",
"new",
"(",
"path",
",",
"headers",
")",
"else",
"raise",
"ArgumentError",
",",
"\"Don't know how to handle http_method: :#{http_method.to_s}\"",
"end",
"# handling basic http auth",
"request",
".",
"basic_auth",
"@config",
"[",
":username",
"]",
",",
"@config",
"[",
":password",
"]",
"if",
"data",
".",
"is_a?",
"(",
"Hash",
")",
"request",
".",
"set_form_data",
"(",
"data",
")",
"elsif",
"data",
"request",
".",
"body",
"=",
"data",
".",
"to_s",
"request",
"[",
"\"Content-Length\"",
"]",
"=",
"request",
".",
"body",
".",
"length",
"end",
"request",
"end"
] |
snippet based on oauth gem
|
[
"snippet",
"based",
"on",
"oauth",
"gem"
] |
ace7b8f8fc973ec3dbb59e6f80cf98f9f705d777
|
https://github.com/webco/tuiter/blob/ace7b8f8fc973ec3dbb59e6f80cf98f9f705d777/lib/tuiter/utils.rb#L95-L130
|
9,395
|
fotonauts/activr
|
lib/activr/registry.rb
|
Activr.Registry.timeline_entries
|
def timeline_entries
@timeline_entries ||= begin
result = { }
self.timelines.each do |(timeline_kind, timeline_class)|
dir_name = Activr::Utils.kind_for_class(timeline_class)
dir_path = File.join(Activr.timelines_path, dir_name)
if !File.directory?(dir_path)
dir_name = Activr::Utils.kind_for_class(timeline_class, 'timeline')
dir_path = File.join(Activr.timelines_path, dir_name)
end
if File.directory?(dir_path)
result[timeline_kind] = { }
Dir["#{dir_path}/*.rb"].sort.inject(result[timeline_kind]) do |memo, file_path|
base_name = File.basename(file_path, '.rb')
# skip base class
if (base_name != "base_timeline_entry")
klass = "#{timeline_class.name}::#{base_name.camelize}".constantize
route_kind = if (match_data = base_name.match(/(.+)_timeline_entry$/))
match_data[1]
else
base_name
end
route = timeline_class.routes.find do |timeline_route|
timeline_route.kind == route_kind
end
raise "Timeline entry class found for an unspecified timeline route: #{file_path} / routes: #{timeline_class.routes.inspect}" unless route
memo[route_kind] = klass
end
memo
end
end
end
result
end
end
|
ruby
|
def timeline_entries
@timeline_entries ||= begin
result = { }
self.timelines.each do |(timeline_kind, timeline_class)|
dir_name = Activr::Utils.kind_for_class(timeline_class)
dir_path = File.join(Activr.timelines_path, dir_name)
if !File.directory?(dir_path)
dir_name = Activr::Utils.kind_for_class(timeline_class, 'timeline')
dir_path = File.join(Activr.timelines_path, dir_name)
end
if File.directory?(dir_path)
result[timeline_kind] = { }
Dir["#{dir_path}/*.rb"].sort.inject(result[timeline_kind]) do |memo, file_path|
base_name = File.basename(file_path, '.rb')
# skip base class
if (base_name != "base_timeline_entry")
klass = "#{timeline_class.name}::#{base_name.camelize}".constantize
route_kind = if (match_data = base_name.match(/(.+)_timeline_entry$/))
match_data[1]
else
base_name
end
route = timeline_class.routes.find do |timeline_route|
timeline_route.kind == route_kind
end
raise "Timeline entry class found for an unspecified timeline route: #{file_path} / routes: #{timeline_class.routes.inspect}" unless route
memo[route_kind] = klass
end
memo
end
end
end
result
end
end
|
[
"def",
"timeline_entries",
"@timeline_entries",
"||=",
"begin",
"result",
"=",
"{",
"}",
"self",
".",
"timelines",
".",
"each",
"do",
"|",
"(",
"timeline_kind",
",",
"timeline_class",
")",
"|",
"dir_name",
"=",
"Activr",
"::",
"Utils",
".",
"kind_for_class",
"(",
"timeline_class",
")",
"dir_path",
"=",
"File",
".",
"join",
"(",
"Activr",
".",
"timelines_path",
",",
"dir_name",
")",
"if",
"!",
"File",
".",
"directory?",
"(",
"dir_path",
")",
"dir_name",
"=",
"Activr",
"::",
"Utils",
".",
"kind_for_class",
"(",
"timeline_class",
",",
"'timeline'",
")",
"dir_path",
"=",
"File",
".",
"join",
"(",
"Activr",
".",
"timelines_path",
",",
"dir_name",
")",
"end",
"if",
"File",
".",
"directory?",
"(",
"dir_path",
")",
"result",
"[",
"timeline_kind",
"]",
"=",
"{",
"}",
"Dir",
"[",
"\"#{dir_path}/*.rb\"",
"]",
".",
"sort",
".",
"inject",
"(",
"result",
"[",
"timeline_kind",
"]",
")",
"do",
"|",
"memo",
",",
"file_path",
"|",
"base_name",
"=",
"File",
".",
"basename",
"(",
"file_path",
",",
"'.rb'",
")",
"# skip base class",
"if",
"(",
"base_name",
"!=",
"\"base_timeline_entry\"",
")",
"klass",
"=",
"\"#{timeline_class.name}::#{base_name.camelize}\"",
".",
"constantize",
"route_kind",
"=",
"if",
"(",
"match_data",
"=",
"base_name",
".",
"match",
"(",
"/",
"/",
")",
")",
"match_data",
"[",
"1",
"]",
"else",
"base_name",
"end",
"route",
"=",
"timeline_class",
".",
"routes",
".",
"find",
"do",
"|",
"timeline_route",
"|",
"timeline_route",
".",
"kind",
"==",
"route_kind",
"end",
"raise",
"\"Timeline entry class found for an unspecified timeline route: #{file_path} / routes: #{timeline_class.routes.inspect}\"",
"unless",
"route",
"memo",
"[",
"route_kind",
"]",
"=",
"klass",
"end",
"memo",
"end",
"end",
"end",
"result",
"end",
"end"
] |
Get all registered timeline entries
@return [Hash{String=>Hash{String=>Class}}] A hash of `<timeline kind> => { <route kind> => <timeline entry class>, ... }`
|
[
"Get",
"all",
"registered",
"timeline",
"entries"
] |
92c071ad18a76d4130661da3ce47c1f0fb8ae913
|
https://github.com/fotonauts/activr/blob/92c071ad18a76d4130661da3ce47c1f0fb8ae913/lib/activr/registry.rb#L70-L114
|
9,396
|
fotonauts/activr
|
lib/activr/registry.rb
|
Activr.Registry.class_for_timeline_entry
|
def class_for_timeline_entry(timeline_kind, route_kind)
(self.timeline_entries[timeline_kind] && self.timeline_entries[timeline_kind][route_kind]) || Activr::Timeline::Entry
end
|
ruby
|
def class_for_timeline_entry(timeline_kind, route_kind)
(self.timeline_entries[timeline_kind] && self.timeline_entries[timeline_kind][route_kind]) || Activr::Timeline::Entry
end
|
[
"def",
"class_for_timeline_entry",
"(",
"timeline_kind",
",",
"route_kind",
")",
"(",
"self",
".",
"timeline_entries",
"[",
"timeline_kind",
"]",
"&&",
"self",
".",
"timeline_entries",
"[",
"timeline_kind",
"]",
"[",
"route_kind",
"]",
")",
"||",
"Activr",
"::",
"Timeline",
"::",
"Entry",
"end"
] |
Get class for timeline entry corresponding to given route in given timeline
@param timeline_kind [String] Timeline kind
@param route_kind [String] Route kind
@return [Class] Timeline entry class
|
[
"Get",
"class",
"for",
"timeline",
"entry",
"corresponding",
"to",
"given",
"route",
"in",
"given",
"timeline"
] |
92c071ad18a76d4130661da3ce47c1f0fb8ae913
|
https://github.com/fotonauts/activr/blob/92c071ad18a76d4130661da3ce47c1f0fb8ae913/lib/activr/registry.rb#L121-L123
|
9,397
|
fotonauts/activr
|
lib/activr/registry.rb
|
Activr.Registry.add_entity
|
def add_entity(entity_name, entity_options, activity_klass)
entity_name = entity_name.to_sym
if @entity_classes[entity_name] && (@entity_classes[entity_name].name != entity_options[:class].name)
# otherwise this would break timeline entries deletion mecanism
raise "Entity name #{entity_name} already used with class #{@entity_classes[entity_name]}, can't redefine it with class #{entity_options[:class]}"
end
# class for entity
@entity_classes[entity_name] = entity_options[:class]
# entities for activity
@activity_entities[activity_klass] ||= [ ]
@activity_entities[activity_klass] << entity_name
# entities
@entities ||= { }
@entities[entity_name] ||= { }
if !@entities[entity_name][activity_klass].blank?
raise "Entity name #{entity_name} already used for activity: #{activity_klass}"
end
@entities[entity_name][activity_klass] = entity_options
end
|
ruby
|
def add_entity(entity_name, entity_options, activity_klass)
entity_name = entity_name.to_sym
if @entity_classes[entity_name] && (@entity_classes[entity_name].name != entity_options[:class].name)
# otherwise this would break timeline entries deletion mecanism
raise "Entity name #{entity_name} already used with class #{@entity_classes[entity_name]}, can't redefine it with class #{entity_options[:class]}"
end
# class for entity
@entity_classes[entity_name] = entity_options[:class]
# entities for activity
@activity_entities[activity_klass] ||= [ ]
@activity_entities[activity_klass] << entity_name
# entities
@entities ||= { }
@entities[entity_name] ||= { }
if !@entities[entity_name][activity_klass].blank?
raise "Entity name #{entity_name} already used for activity: #{activity_klass}"
end
@entities[entity_name][activity_klass] = entity_options
end
|
[
"def",
"add_entity",
"(",
"entity_name",
",",
"entity_options",
",",
"activity_klass",
")",
"entity_name",
"=",
"entity_name",
".",
"to_sym",
"if",
"@entity_classes",
"[",
"entity_name",
"]",
"&&",
"(",
"@entity_classes",
"[",
"entity_name",
"]",
".",
"name",
"!=",
"entity_options",
"[",
":class",
"]",
".",
"name",
")",
"# otherwise this would break timeline entries deletion mecanism",
"raise",
"\"Entity name #{entity_name} already used with class #{@entity_classes[entity_name]}, can't redefine it with class #{entity_options[:class]}\"",
"end",
"# class for entity",
"@entity_classes",
"[",
"entity_name",
"]",
"=",
"entity_options",
"[",
":class",
"]",
"# entities for activity",
"@activity_entities",
"[",
"activity_klass",
"]",
"||=",
"[",
"]",
"@activity_entities",
"[",
"activity_klass",
"]",
"<<",
"entity_name",
"# entities",
"@entities",
"||=",
"{",
"}",
"@entities",
"[",
"entity_name",
"]",
"||=",
"{",
"}",
"if",
"!",
"@entities",
"[",
"entity_name",
"]",
"[",
"activity_klass",
"]",
".",
"blank?",
"raise",
"\"Entity name #{entity_name} already used for activity: #{activity_klass}\"",
"end",
"@entities",
"[",
"entity_name",
"]",
"[",
"activity_klass",
"]",
"=",
"entity_options",
"end"
] |
Register an entity
@param entity_name [Symbol] Entity name
@param entity_options [Hash] Entity options
@param activity_klass [Class] Activity class that uses that entity
|
[
"Register",
"an",
"entity"
] |
92c071ad18a76d4130661da3ce47c1f0fb8ae913
|
https://github.com/fotonauts/activr/blob/92c071ad18a76d4130661da3ce47c1f0fb8ae913/lib/activr/registry.rb#L164-L188
|
9,398
|
fotonauts/activr
|
lib/activr/registry.rb
|
Activr.Registry.activity_entities_for_model
|
def activity_entities_for_model(model_class)
@activity_entities_for_model[model_class] ||= begin
result = [ ]
@entity_classes.each do |entity_name, entity_class|
result << entity_name if (entity_class == model_class)
end
result
end
end
|
ruby
|
def activity_entities_for_model(model_class)
@activity_entities_for_model[model_class] ||= begin
result = [ ]
@entity_classes.each do |entity_name, entity_class|
result << entity_name if (entity_class == model_class)
end
result
end
end
|
[
"def",
"activity_entities_for_model",
"(",
"model_class",
")",
"@activity_entities_for_model",
"[",
"model_class",
"]",
"||=",
"begin",
"result",
"=",
"[",
"]",
"@entity_classes",
".",
"each",
"do",
"|",
"entity_name",
",",
"entity_class",
"|",
"result",
"<<",
"entity_name",
"if",
"(",
"entity_class",
"==",
"model_class",
")",
"end",
"result",
"end",
"end"
] |
Get all entities names for given model class
|
[
"Get",
"all",
"entities",
"names",
"for",
"given",
"model",
"class"
] |
92c071ad18a76d4130661da3ce47c1f0fb8ae913
|
https://github.com/fotonauts/activr/blob/92c071ad18a76d4130661da3ce47c1f0fb8ae913/lib/activr/registry.rb#L209-L219
|
9,399
|
fotonauts/activr
|
lib/activr/registry.rb
|
Activr.Registry.timeline_entities_for_model
|
def timeline_entities_for_model(model_class)
@timeline_entities_for_model[model_class] ||= begin
result = { }
self.timelines.each do |timeline_kind, timeline_class|
result[timeline_class] = [ ]
timeline_class.routes.each do |route|
entities_ary = @activity_entities[route.activity_class]
(entities_ary || [ ]).each do |entity_name|
result[timeline_class] << entity_name if (@entity_classes[entity_name] == model_class)
end
end
result[timeline_class].uniq!
end
result
end
end
|
ruby
|
def timeline_entities_for_model(model_class)
@timeline_entities_for_model[model_class] ||= begin
result = { }
self.timelines.each do |timeline_kind, timeline_class|
result[timeline_class] = [ ]
timeline_class.routes.each do |route|
entities_ary = @activity_entities[route.activity_class]
(entities_ary || [ ]).each do |entity_name|
result[timeline_class] << entity_name if (@entity_classes[entity_name] == model_class)
end
end
result[timeline_class].uniq!
end
result
end
end
|
[
"def",
"timeline_entities_for_model",
"(",
"model_class",
")",
"@timeline_entities_for_model",
"[",
"model_class",
"]",
"||=",
"begin",
"result",
"=",
"{",
"}",
"self",
".",
"timelines",
".",
"each",
"do",
"|",
"timeline_kind",
",",
"timeline_class",
"|",
"result",
"[",
"timeline_class",
"]",
"=",
"[",
"]",
"timeline_class",
".",
"routes",
".",
"each",
"do",
"|",
"route",
"|",
"entities_ary",
"=",
"@activity_entities",
"[",
"route",
".",
"activity_class",
"]",
"(",
"entities_ary",
"||",
"[",
"]",
")",
".",
"each",
"do",
"|",
"entity_name",
"|",
"result",
"[",
"timeline_class",
"]",
"<<",
"entity_name",
"if",
"(",
"@entity_classes",
"[",
"entity_name",
"]",
"==",
"model_class",
")",
"end",
"end",
"result",
"[",
"timeline_class",
"]",
".",
"uniq!",
"end",
"result",
"end",
"end"
] |
Get all entities names by timelines that can have a reference to given model class
@param model_class [Class] Model class
@return [Hash{Class=>Array<Symbol>}] Lists of entities names indexed by timeline class
|
[
"Get",
"all",
"entities",
"names",
"by",
"timelines",
"that",
"can",
"have",
"a",
"reference",
"to",
"given",
"model",
"class"
] |
92c071ad18a76d4130661da3ce47c1f0fb8ae913
|
https://github.com/fotonauts/activr/blob/92c071ad18a76d4130661da3ce47c1f0fb8ae913/lib/activr/registry.rb#L225-L244
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.