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,000
|
npepinpe/redstruct
|
lib/redstruct/factory.rb
|
Redstruct.Factory.delete
|
def delete(options = {})
return each({ match: '*', count: 500, max_iterations: 1_000_000, batch_size: 500 }.merge(options)) do |keys|
@connection.del(*keys)
end
end
|
ruby
|
def delete(options = {})
return each({ match: '*', count: 500, max_iterations: 1_000_000, batch_size: 500 }.merge(options)) do |keys|
@connection.del(*keys)
end
end
|
[
"def",
"delete",
"(",
"options",
"=",
"{",
"}",
")",
"return",
"each",
"(",
"{",
"match",
":",
"'*'",
",",
"count",
":",
"500",
",",
"max_iterations",
":",
"1_000_000",
",",
"batch_size",
":",
"500",
"}",
".",
"merge",
"(",
"options",
")",
")",
"do",
"|",
"keys",
"|",
"@connection",
".",
"del",
"(",
"keys",
")",
"end",
"end"
] |
Deletes all keys created by the factory. By defaults will iterate at most of 500 million keys
@param [Hash] options accepts the options as given in each
@see Redstruct::Factory#each
|
[
"Deletes",
"all",
"keys",
"created",
"by",
"the",
"factory",
".",
"By",
"defaults",
"will",
"iterate",
"at",
"most",
"of",
"500",
"million",
"keys"
] |
c97b45e7227f8ed9029f0effff352fc4d82dc3cb
|
https://github.com/npepinpe/redstruct/blob/c97b45e7227f8ed9029f0effff352fc4d82dc3cb/lib/redstruct/factory.rb#L60-L64
|
9,001
|
npepinpe/redstruct
|
lib/redstruct/factory.rb
|
Redstruct.Factory.script
|
def script(script, **options)
return Redstruct::Script.new(script: script, connection: @connection, **options)
end
|
ruby
|
def script(script, **options)
return Redstruct::Script.new(script: script, connection: @connection, **options)
end
|
[
"def",
"script",
"(",
"script",
",",
"**",
"options",
")",
"return",
"Redstruct",
"::",
"Script",
".",
"new",
"(",
"script",
":",
"script",
",",
"connection",
":",
"@connection",
",",
"**",
"options",
")",
"end"
] |
Creates using this factory's connection
@see Redstruct::Script#new
@return [Redstruct::Script] script sharing the factory connection
|
[
"Creates",
"using",
"this",
"factory",
"s",
"connection"
] |
c97b45e7227f8ed9029f0effff352fc4d82dc3cb
|
https://github.com/npepinpe/redstruct/blob/c97b45e7227f8ed9029f0effff352fc4d82dc3cb/lib/redstruct/factory.rb#L79-L81
|
9,002
|
evg2108/rails-carrierwave-focuspoint
|
lib/rails-carrierwave-focuspoint/uploader_additions.rb
|
FocuspointRails.UploaderAdditions.crop_with_focuspoint
|
def crop_with_focuspoint(width = nil, height = nil)
if self.respond_to? "resize_to_limit"
begin
x = model.focus_x || 0
y = -(model.focus_y || 0)
manipulate! do |img|
orig_w = img['width']
orig_h = img['height']
ratio = width.to_f / height
orig_ratio = orig_w.to_f / orig_h
x_offset = 0
y_offset = 0
w = orig_w
h = orig_h
if ratio < orig_ratio
w = orig_h * ratio
half_w = w / 2.0
half_orig_w = orig_w / 2.0
x_offset = x * half_orig_w
x_offset = (x <=> 0.0) * (half_orig_w - half_w) if x != 0 && x_offset.abs > half_orig_w - half_w
elsif ratio > orig_ratio
h = orig_w / ratio
half_h = h / 2.0
half_orig_h = orig_h / 2.0
y_offset = y * half_orig_h
y_offset = (y <=> 0.0) * (half_orig_h - half_h) if y != 0 && y_offset.abs > half_orig_h - half_h
end
img.combine_options do |op|
op.crop "#{w.to_i}x#{h.to_i}#{'%+d' % x_offset.round}#{'%+d' % y_offset.round}"
op.gravity 'Center'
end
img.resize("#{width}x#{height}")
img
end
rescue Exception => e
raise "Failed to crop - #{e.message}"
end
else
raise "Failed to crop #{attachment}. Add mini_magick."
end
end
|
ruby
|
def crop_with_focuspoint(width = nil, height = nil)
if self.respond_to? "resize_to_limit"
begin
x = model.focus_x || 0
y = -(model.focus_y || 0)
manipulate! do |img|
orig_w = img['width']
orig_h = img['height']
ratio = width.to_f / height
orig_ratio = orig_w.to_f / orig_h
x_offset = 0
y_offset = 0
w = orig_w
h = orig_h
if ratio < orig_ratio
w = orig_h * ratio
half_w = w / 2.0
half_orig_w = orig_w / 2.0
x_offset = x * half_orig_w
x_offset = (x <=> 0.0) * (half_orig_w - half_w) if x != 0 && x_offset.abs > half_orig_w - half_w
elsif ratio > orig_ratio
h = orig_w / ratio
half_h = h / 2.0
half_orig_h = orig_h / 2.0
y_offset = y * half_orig_h
y_offset = (y <=> 0.0) * (half_orig_h - half_h) if y != 0 && y_offset.abs > half_orig_h - half_h
end
img.combine_options do |op|
op.crop "#{w.to_i}x#{h.to_i}#{'%+d' % x_offset.round}#{'%+d' % y_offset.round}"
op.gravity 'Center'
end
img.resize("#{width}x#{height}")
img
end
rescue Exception => e
raise "Failed to crop - #{e.message}"
end
else
raise "Failed to crop #{attachment}. Add mini_magick."
end
end
|
[
"def",
"crop_with_focuspoint",
"(",
"width",
"=",
"nil",
",",
"height",
"=",
"nil",
")",
"if",
"self",
".",
"respond_to?",
"\"resize_to_limit\"",
"begin",
"x",
"=",
"model",
".",
"focus_x",
"||",
"0",
"y",
"=",
"-",
"(",
"model",
".",
"focus_y",
"||",
"0",
")",
"manipulate!",
"do",
"|",
"img",
"|",
"orig_w",
"=",
"img",
"[",
"'width'",
"]",
"orig_h",
"=",
"img",
"[",
"'height'",
"]",
"ratio",
"=",
"width",
".",
"to_f",
"/",
"height",
"orig_ratio",
"=",
"orig_w",
".",
"to_f",
"/",
"orig_h",
"x_offset",
"=",
"0",
"y_offset",
"=",
"0",
"w",
"=",
"orig_w",
"h",
"=",
"orig_h",
"if",
"ratio",
"<",
"orig_ratio",
"w",
"=",
"orig_h",
"*",
"ratio",
"half_w",
"=",
"w",
"/",
"2.0",
"half_orig_w",
"=",
"orig_w",
"/",
"2.0",
"x_offset",
"=",
"x",
"*",
"half_orig_w",
"x_offset",
"=",
"(",
"x",
"<=>",
"0.0",
")",
"*",
"(",
"half_orig_w",
"-",
"half_w",
")",
"if",
"x",
"!=",
"0",
"&&",
"x_offset",
".",
"abs",
">",
"half_orig_w",
"-",
"half_w",
"elsif",
"ratio",
">",
"orig_ratio",
"h",
"=",
"orig_w",
"/",
"ratio",
"half_h",
"=",
"h",
"/",
"2.0",
"half_orig_h",
"=",
"orig_h",
"/",
"2.0",
"y_offset",
"=",
"y",
"*",
"half_orig_h",
"y_offset",
"=",
"(",
"y",
"<=>",
"0.0",
")",
"*",
"(",
"half_orig_h",
"-",
"half_h",
")",
"if",
"y",
"!=",
"0",
"&&",
"y_offset",
".",
"abs",
">",
"half_orig_h",
"-",
"half_h",
"end",
"img",
".",
"combine_options",
"do",
"|",
"op",
"|",
"op",
".",
"crop",
"\"#{w.to_i}x#{h.to_i}#{'%+d' % x_offset.round}#{'%+d' % y_offset.round}\"",
"op",
".",
"gravity",
"'Center'",
"end",
"img",
".",
"resize",
"(",
"\"#{width}x#{height}\"",
")",
"img",
"end",
"rescue",
"Exception",
"=>",
"e",
"raise",
"\"Failed to crop - #{e.message}\"",
"end",
"else",
"raise",
"\"Failed to crop #{attachment}. Add mini_magick.\"",
"end",
"end"
] |
Performs cropping with focuspoint
|
[
"Performs",
"cropping",
"with",
"focuspoint"
] |
75bf387ac6c1a8f2e4c3fcfdf65d6666ea93edd7
|
https://github.com/evg2108/rails-carrierwave-focuspoint/blob/75bf387ac6c1a8f2e4c3fcfdf65d6666ea93edd7/lib/rails-carrierwave-focuspoint/uploader_additions.rb#L4-L56
|
9,003
|
markus/breeze
|
lib/breeze/veur.rb
|
Breeze.Veur.report
|
def report(title, columns, rows)
table = capture_table([columns] + rows)
title = "=== #{title} "
title << "=" * [(table.split($/).max{|a,b| a.size <=> b.size }.size - title.size), 3].max
puts title
puts table
end
|
ruby
|
def report(title, columns, rows)
table = capture_table([columns] + rows)
title = "=== #{title} "
title << "=" * [(table.split($/).max{|a,b| a.size <=> b.size }.size - title.size), 3].max
puts title
puts table
end
|
[
"def",
"report",
"(",
"title",
",",
"columns",
",",
"rows",
")",
"table",
"=",
"capture_table",
"(",
"[",
"columns",
"]",
"+",
"rows",
")",
"title",
"=",
"\"=== #{title} \"",
"title",
"<<",
"\"=\"",
"*",
"[",
"(",
"table",
".",
"split",
"(",
"$/",
")",
".",
"max",
"{",
"|",
"a",
",",
"b",
"|",
"a",
".",
"size",
"<=>",
"b",
".",
"size",
"}",
".",
"size",
"-",
"title",
".",
"size",
")",
",",
"3",
"]",
".",
"max",
"puts",
"title",
"puts",
"table",
"end"
] |
Print a table with a title and a top border of matching width.
|
[
"Print",
"a",
"table",
"with",
"a",
"title",
"and",
"a",
"top",
"border",
"of",
"matching",
"width",
"."
] |
a633783946ed4270354fa1491a9beda4f2bac1f6
|
https://github.com/markus/breeze/blob/a633783946ed4270354fa1491a9beda4f2bac1f6/lib/breeze/veur.rb#L59-L65
|
9,004
|
markus/breeze
|
lib/breeze/veur.rb
|
Breeze.Veur.capture_table
|
def capture_table(table)
return 'none' if table.size == 1 # the first row is for column titles
$stdout = StringIO.new # start capturing the output
print_table(table.map{ |row| row.map(&:to_s) })
output = $stdout
$stdout = STDOUT # restore normal output
return output.string
end
|
ruby
|
def capture_table(table)
return 'none' if table.size == 1 # the first row is for column titles
$stdout = StringIO.new # start capturing the output
print_table(table.map{ |row| row.map(&:to_s) })
output = $stdout
$stdout = STDOUT # restore normal output
return output.string
end
|
[
"def",
"capture_table",
"(",
"table",
")",
"return",
"'none'",
"if",
"table",
".",
"size",
"==",
"1",
"# the first row is for column titles",
"$stdout",
"=",
"StringIO",
".",
"new",
"# start capturing the output",
"print_table",
"(",
"table",
".",
"map",
"{",
"|",
"row",
"|",
"row",
".",
"map",
"(",
":to_s",
")",
"}",
")",
"output",
"=",
"$stdout",
"$stdout",
"=",
"STDOUT",
"# restore normal output",
"return",
"output",
".",
"string",
"end"
] |
capture table in order to determine its width
|
[
"capture",
"table",
"in",
"order",
"to",
"determine",
"its",
"width"
] |
a633783946ed4270354fa1491a9beda4f2bac1f6
|
https://github.com/markus/breeze/blob/a633783946ed4270354fa1491a9beda4f2bac1f6/lib/breeze/veur.rb#L68-L75
|
9,005
|
bcobb/and_feathers
|
lib/and_feathers/archive.rb
|
AndFeathers.Archive.to_io
|
def to_io(package_type, traversal = :each)
package_type.open do |package|
package.add_directory(@initial_version)
send(traversal) do |child|
case child
when File
package.add_file(child)
when Directory
package.add_directory(child)
end
end
end
end
|
ruby
|
def to_io(package_type, traversal = :each)
package_type.open do |package|
package.add_directory(@initial_version)
send(traversal) do |child|
case child
when File
package.add_file(child)
when Directory
package.add_directory(child)
end
end
end
end
|
[
"def",
"to_io",
"(",
"package_type",
",",
"traversal",
"=",
":each",
")",
"package_type",
".",
"open",
"do",
"|",
"package",
"|",
"package",
".",
"add_directory",
"(",
"@initial_version",
")",
"send",
"(",
"traversal",
")",
"do",
"|",
"child",
"|",
"case",
"child",
"when",
"File",
"package",
".",
"add_file",
"(",
"child",
")",
"when",
"Directory",
"package",
".",
"add_directory",
"(",
"child",
")",
"end",
"end",
"end",
"end"
] |
Returns this +Archive+ as a package of the given +package_type+
@example
require 'and_feathers/gzipped_tarball'
format = AndFeathers::GzippedTarball
AndFeathers::Archive.new('test', 16877).to_io(format)
@see https://github.com/bcobb/and_feathers-gzipped_tarball
@see https://github.com/bcobb/and_feathers-zip
@param package_type [.open,#add_file,#add_directory]
@return [StringIO]
|
[
"Returns",
"this",
"+",
"Archive",
"+",
"as",
"a",
"package",
"of",
"the",
"given",
"+",
"package_type",
"+"
] |
f35b156f8ae6930851712bbaf502f97b3aa9a1b1
|
https://github.com/bcobb/and_feathers/blob/f35b156f8ae6930851712bbaf502f97b3aa9a1b1/lib/and_feathers/archive.rb#L84-L97
|
9,006
|
mkj-is/Truty
|
lib/truty/conversion.rb
|
Truty.Conversion.czech_html
|
def czech_html(input)
coder = HTMLEntities.new
encoded = coder.encode(input, :named, :decimal)
czech_diacritics.each { |k, v| encoded.gsub!(k, v) }
encoded
end
|
ruby
|
def czech_html(input)
coder = HTMLEntities.new
encoded = coder.encode(input, :named, :decimal)
czech_diacritics.each { |k, v| encoded.gsub!(k, v) }
encoded
end
|
[
"def",
"czech_html",
"(",
"input",
")",
"coder",
"=",
"HTMLEntities",
".",
"new",
"encoded",
"=",
"coder",
".",
"encode",
"(",
"input",
",",
":named",
",",
":decimal",
")",
"czech_diacritics",
".",
"each",
"{",
"|",
"k",
",",
"v",
"|",
"encoded",
".",
"gsub!",
"(",
"k",
",",
"v",
")",
"}",
"encoded",
"end"
] |
Escapes string to readable Czech HTML entities.
@param input [String] Text input.
@return [String] Text with HTML entities.
|
[
"Escapes",
"string",
"to",
"readable",
"Czech",
"HTML",
"entities",
"."
] |
315f49ad73cc2fa814a7793aa1b19657870ce98f
|
https://github.com/mkj-is/Truty/blob/315f49ad73cc2fa814a7793aa1b19657870ce98f/lib/truty/conversion.rb#L59-L64
|
9,007
|
malev/freeling-client
|
lib/freeling_client/client.rb
|
FreelingClient.Client.call
|
def call(text)
output = []
file = Tempfile.new('foo', encoding: 'utf-8')
begin
file.write(text)
file.close
stdin, stdout, stderr = Open3.popen3(command(file.path))
Timeout::timeout(@timeout) {
until (line = stdout.gets).nil?
output << line.chomp
end
message = stderr.readlines
unless message.empty?
raise ExtractionError, message.join("\n")
end
}
rescue Timeout::Error
raise ExtractionError, "Timeout"
ensure
file.close
file.unlink
end
output
end
|
ruby
|
def call(text)
output = []
file = Tempfile.new('foo', encoding: 'utf-8')
begin
file.write(text)
file.close
stdin, stdout, stderr = Open3.popen3(command(file.path))
Timeout::timeout(@timeout) {
until (line = stdout.gets).nil?
output << line.chomp
end
message = stderr.readlines
unless message.empty?
raise ExtractionError, message.join("\n")
end
}
rescue Timeout::Error
raise ExtractionError, "Timeout"
ensure
file.close
file.unlink
end
output
end
|
[
"def",
"call",
"(",
"text",
")",
"output",
"=",
"[",
"]",
"file",
"=",
"Tempfile",
".",
"new",
"(",
"'foo'",
",",
"encoding",
":",
"'utf-8'",
")",
"begin",
"file",
".",
"write",
"(",
"text",
")",
"file",
".",
"close",
"stdin",
",",
"stdout",
",",
"stderr",
"=",
"Open3",
".",
"popen3",
"(",
"command",
"(",
"file",
".",
"path",
")",
")",
"Timeout",
"::",
"timeout",
"(",
"@timeout",
")",
"{",
"until",
"(",
"line",
"=",
"stdout",
".",
"gets",
")",
".",
"nil?",
"output",
"<<",
"line",
".",
"chomp",
"end",
"message",
"=",
"stderr",
".",
"readlines",
"unless",
"message",
".",
"empty?",
"raise",
"ExtractionError",
",",
"message",
".",
"join",
"(",
"\"\\n\"",
")",
"end",
"}",
"rescue",
"Timeout",
"::",
"Error",
"raise",
"ExtractionError",
",",
"\"Timeout\"",
"ensure",
"file",
".",
"close",
"file",
".",
"unlink",
"end",
"output",
"end"
] |
Initializes the client
Example:
>> client = FreelingClient::Client.new
Arguments:
server: (String)
port: (String)
timeout: (Integer)
Calls the server with a given text
Example:
>> client = FreelingClient::Client.new
>> client.call("Este texto está en español.")
Arguments:
text: (String)
|
[
"Initializes",
"the",
"client"
] |
1ca32aa9edf8fbc60a48cf23bf298db38b84fc8c
|
https://github.com/malev/freeling-client/blob/1ca32aa9edf8fbc60a48cf23bf298db38b84fc8c/lib/freeling_client/client.rb#L35-L61
|
9,008
|
mobyinc/Cathode
|
lib/cathode/version.rb
|
Cathode.Version.action?
|
def action?(resource, action)
resource = resource.to_sym
action = action.to_sym
return false unless resource?(resource)
_resources.find(resource).actions.names.include? action
end
|
ruby
|
def action?(resource, action)
resource = resource.to_sym
action = action.to_sym
return false unless resource?(resource)
_resources.find(resource).actions.names.include? action
end
|
[
"def",
"action?",
"(",
"resource",
",",
"action",
")",
"resource",
"=",
"resource",
".",
"to_sym",
"action",
"=",
"action",
".",
"to_sym",
"return",
"false",
"unless",
"resource?",
"(",
"resource",
")",
"_resources",
".",
"find",
"(",
"resource",
")",
".",
"actions",
".",
"names",
".",
"include?",
"action",
"end"
] |
Whether an action is defined on a resource on the version.
@param resource [Symbol] The resource's name
@param action [Symbol] The action's name
@return [Boolean]
|
[
"Whether",
"an",
"action",
"is",
"defined",
"on",
"a",
"resource",
"on",
"the",
"version",
"."
] |
e17be4fb62ad61417e2a3a0a77406459015468a1
|
https://github.com/mobyinc/Cathode/blob/e17be4fb62ad61417e2a3a0a77406459015468a1/lib/cathode/version.rb#L96-L103
|
9,009
|
billdueber/ruby-marc-marc4j
|
lib/marc/marc4j.rb
|
MARC.MARC4J.marc4j_to_rubymarc
|
def marc4j_to_rubymarc(marc4j)
rmarc = MARC::Record.new
rmarc.leader = marc4j.getLeader.marshal
marc4j.getControlFields.each do |marc4j_control|
rmarc.append( MARC::ControlField.new(marc4j_control.getTag(), marc4j_control.getData ) )
end
marc4j.getDataFields.each do |marc4j_data|
rdata = MARC::DataField.new( marc4j_data.getTag, marc4j_data.getIndicator1.chr, marc4j_data.getIndicator2.chr )
marc4j_data.getSubfields.each do |subfield|
# We assume Marc21, skip corrupted data
# if subfield.getCode is more than 255, subsequent .chr
# would raise.
if subfield.getCode > 255
if @logger
@logger.warn("Marc4JReader: Corrupted MARC data, record id #{marc4j.getControlNumber}, field #{marc4j_data.tag}, corrupt subfield code byte #{subfield.getCode}. Skipping subfield, but continuing with record.")
end
next
end
rsubfield = MARC::Subfield.new(subfield.getCode.chr, subfield.getData)
rdata.append rsubfield
end
rmarc.append rdata
end
return rmarc
end
|
ruby
|
def marc4j_to_rubymarc(marc4j)
rmarc = MARC::Record.new
rmarc.leader = marc4j.getLeader.marshal
marc4j.getControlFields.each do |marc4j_control|
rmarc.append( MARC::ControlField.new(marc4j_control.getTag(), marc4j_control.getData ) )
end
marc4j.getDataFields.each do |marc4j_data|
rdata = MARC::DataField.new( marc4j_data.getTag, marc4j_data.getIndicator1.chr, marc4j_data.getIndicator2.chr )
marc4j_data.getSubfields.each do |subfield|
# We assume Marc21, skip corrupted data
# if subfield.getCode is more than 255, subsequent .chr
# would raise.
if subfield.getCode > 255
if @logger
@logger.warn("Marc4JReader: Corrupted MARC data, record id #{marc4j.getControlNumber}, field #{marc4j_data.tag}, corrupt subfield code byte #{subfield.getCode}. Skipping subfield, but continuing with record.")
end
next
end
rsubfield = MARC::Subfield.new(subfield.getCode.chr, subfield.getData)
rdata.append rsubfield
end
rmarc.append rdata
end
return rmarc
end
|
[
"def",
"marc4j_to_rubymarc",
"(",
"marc4j",
")",
"rmarc",
"=",
"MARC",
"::",
"Record",
".",
"new",
"rmarc",
".",
"leader",
"=",
"marc4j",
".",
"getLeader",
".",
"marshal",
"marc4j",
".",
"getControlFields",
".",
"each",
"do",
"|",
"marc4j_control",
"|",
"rmarc",
".",
"append",
"(",
"MARC",
"::",
"ControlField",
".",
"new",
"(",
"marc4j_control",
".",
"getTag",
"(",
")",
",",
"marc4j_control",
".",
"getData",
")",
")",
"end",
"marc4j",
".",
"getDataFields",
".",
"each",
"do",
"|",
"marc4j_data",
"|",
"rdata",
"=",
"MARC",
"::",
"DataField",
".",
"new",
"(",
"marc4j_data",
".",
"getTag",
",",
"marc4j_data",
".",
"getIndicator1",
".",
"chr",
",",
"marc4j_data",
".",
"getIndicator2",
".",
"chr",
")",
"marc4j_data",
".",
"getSubfields",
".",
"each",
"do",
"|",
"subfield",
"|",
"# We assume Marc21, skip corrupted data",
"# if subfield.getCode is more than 255, subsequent .chr",
"# would raise.",
"if",
"subfield",
".",
"getCode",
">",
"255",
"if",
"@logger",
"@logger",
".",
"warn",
"(",
"\"Marc4JReader: Corrupted MARC data, record id #{marc4j.getControlNumber}, field #{marc4j_data.tag}, corrupt subfield code byte #{subfield.getCode}. Skipping subfield, but continuing with record.\"",
")",
"end",
"next",
"end",
"rsubfield",
"=",
"MARC",
"::",
"Subfield",
".",
"new",
"(",
"subfield",
".",
"getCode",
".",
"chr",
",",
"subfield",
".",
"getData",
")",
"rdata",
".",
"append",
"rsubfield",
"end",
"rmarc",
".",
"append",
"rdata",
"end",
"return",
"rmarc",
"end"
] |
Get a new coverter
Given a marc4j record, return a rubymarc record
|
[
"Get",
"a",
"new",
"coverter",
"Given",
"a",
"marc4j",
"record",
"return",
"a",
"rubymarc",
"record"
] |
b6eaf1a2de8b82b53424d409fc1fbf4191a4fd9c
|
https://github.com/billdueber/ruby-marc-marc4j/blob/b6eaf1a2de8b82b53424d409fc1fbf4191a4fd9c/lib/marc/marc4j.rb#L20-L51
|
9,010
|
billdueber/ruby-marc-marc4j
|
lib/marc/marc4j.rb
|
MARC.MARC4J.rubymarc_to_marc4j
|
def rubymarc_to_marc4j(rmarc)
marc4j = @factory.newRecord(rmarc.leader)
rmarc.each do |f|
if f.is_a? MARC::ControlField
new_field = @factory.newControlField(f.tag, f.value)
else
new_field = @factory.new_data_field(f.tag, f.indicator1.ord, f.indicator2.ord)
f.each do |sf|
new_field.add_subfield(@factory.new_subfield(sf.code.ord, sf.value))
end
end
marc4j.add_variable_field(new_field)
end
return marc4j
end
|
ruby
|
def rubymarc_to_marc4j(rmarc)
marc4j = @factory.newRecord(rmarc.leader)
rmarc.each do |f|
if f.is_a? MARC::ControlField
new_field = @factory.newControlField(f.tag, f.value)
else
new_field = @factory.new_data_field(f.tag, f.indicator1.ord, f.indicator2.ord)
f.each do |sf|
new_field.add_subfield(@factory.new_subfield(sf.code.ord, sf.value))
end
end
marc4j.add_variable_field(new_field)
end
return marc4j
end
|
[
"def",
"rubymarc_to_marc4j",
"(",
"rmarc",
")",
"marc4j",
"=",
"@factory",
".",
"newRecord",
"(",
"rmarc",
".",
"leader",
")",
"rmarc",
".",
"each",
"do",
"|",
"f",
"|",
"if",
"f",
".",
"is_a?",
"MARC",
"::",
"ControlField",
"new_field",
"=",
"@factory",
".",
"newControlField",
"(",
"f",
".",
"tag",
",",
"f",
".",
"value",
")",
"else",
"new_field",
"=",
"@factory",
".",
"new_data_field",
"(",
"f",
".",
"tag",
",",
"f",
".",
"indicator1",
".",
"ord",
",",
"f",
".",
"indicator2",
".",
"ord",
")",
"f",
".",
"each",
"do",
"|",
"sf",
"|",
"new_field",
".",
"add_subfield",
"(",
"@factory",
".",
"new_subfield",
"(",
"sf",
".",
"code",
".",
"ord",
",",
"sf",
".",
"value",
")",
")",
"end",
"end",
"marc4j",
".",
"add_variable_field",
"(",
"new_field",
")",
"end",
"return",
"marc4j",
"end"
] |
Given a rubymarc record, return a marc4j record
|
[
"Given",
"a",
"rubymarc",
"record",
"return",
"a",
"marc4j",
"record"
] |
b6eaf1a2de8b82b53424d409fc1fbf4191a4fd9c
|
https://github.com/billdueber/ruby-marc-marc4j/blob/b6eaf1a2de8b82b53424d409fc1fbf4191a4fd9c/lib/marc/marc4j.rb#L55-L69
|
9,011
|
billdueber/ruby-marc-marc4j
|
lib/marc/marc4j.rb
|
MARC.MARC4J.require_marc4j_jar
|
def require_marc4j_jar(jardir)
unless defined? JRUBY_VERSION
raise LoadError.new, "MARC::MARC4J requires the use of JRuby", nil
end
if jardir
Dir.glob("#{jardir}/*.jar") do |x|
require x
end
else
Dir.glob(File.join(DEFAULT_JAR_RELATIVE_DIR, "*.jar")) do |x|
require x
end
end
end
|
ruby
|
def require_marc4j_jar(jardir)
unless defined? JRUBY_VERSION
raise LoadError.new, "MARC::MARC4J requires the use of JRuby", nil
end
if jardir
Dir.glob("#{jardir}/*.jar") do |x|
require x
end
else
Dir.glob(File.join(DEFAULT_JAR_RELATIVE_DIR, "*.jar")) do |x|
require x
end
end
end
|
[
"def",
"require_marc4j_jar",
"(",
"jardir",
")",
"unless",
"defined?",
"JRUBY_VERSION",
"raise",
"LoadError",
".",
"new",
",",
"\"MARC::MARC4J requires the use of JRuby\"",
",",
"nil",
"end",
"if",
"jardir",
"Dir",
".",
"glob",
"(",
"\"#{jardir}/*.jar\"",
")",
"do",
"|",
"x",
"|",
"require",
"x",
"end",
"else",
"Dir",
".",
"glob",
"(",
"File",
".",
"join",
"(",
"DEFAULT_JAR_RELATIVE_DIR",
",",
"\"*.jar\"",
")",
")",
"do",
"|",
"x",
"|",
"require",
"x",
"end",
"end",
"end"
] |
Try to get the specified jarfile, or the bundled one if nothing is specified
|
[
"Try",
"to",
"get",
"the",
"specified",
"jarfile",
"or",
"the",
"bundled",
"one",
"if",
"nothing",
"is",
"specified"
] |
b6eaf1a2de8b82b53424d409fc1fbf4191a4fd9c
|
https://github.com/billdueber/ruby-marc-marc4j/blob/b6eaf1a2de8b82b53424d409fc1fbf4191a4fd9c/lib/marc/marc4j.rb#L81-L94
|
9,012
|
keita/temppath
|
lib/temppath.rb
|
Temppath.Generator.mkdir
|
def mkdir(option={})
mode = option[:mode] || 0700
path = create(option)
path.mkdir(mode)
return path
end
|
ruby
|
def mkdir(option={})
mode = option[:mode] || 0700
path = create(option)
path.mkdir(mode)
return path
end
|
[
"def",
"mkdir",
"(",
"option",
"=",
"{",
"}",
")",
"mode",
"=",
"option",
"[",
":mode",
"]",
"||",
"0700",
"path",
"=",
"create",
"(",
"option",
")",
"path",
".",
"mkdir",
"(",
"mode",
")",
"return",
"path",
"end"
] |
Create a temporary directory.
@param option [Hash]
@option option [Integer] :mode
mode for the directory permission
@option option [String] :basename
prefix of directory name
@option option [Pathname] :basedir
pathname of base directory
|
[
"Create",
"a",
"temporary",
"directory",
"."
] |
27d24d23c1f076733e9dc5cbc2f7a7826963a97c
|
https://github.com/keita/temppath/blob/27d24d23c1f076733e9dc5cbc2f7a7826963a97c/lib/temppath.rb#L169-L174
|
9,013
|
keita/temppath
|
lib/temppath.rb
|
Temppath.Generator.touch
|
def touch(option={})
mode = option[:mode] || 0600
path = create(option)
path.open("w", mode)
return path
end
|
ruby
|
def touch(option={})
mode = option[:mode] || 0600
path = create(option)
path.open("w", mode)
return path
end
|
[
"def",
"touch",
"(",
"option",
"=",
"{",
"}",
")",
"mode",
"=",
"option",
"[",
":mode",
"]",
"||",
"0600",
"path",
"=",
"create",
"(",
"option",
")",
"path",
".",
"open",
"(",
"\"w\"",
",",
"mode",
")",
"return",
"path",
"end"
] |
Create a empty file.
@param option [Hash]
@option option [Integer] :mode
mode for the file permission
@option option [String] :basename
prefix of filename
@option option [Pathname] :basedir
pathname of base directory
|
[
"Create",
"a",
"empty",
"file",
"."
] |
27d24d23c1f076733e9dc5cbc2f7a7826963a97c
|
https://github.com/keita/temppath/blob/27d24d23c1f076733e9dc5cbc2f7a7826963a97c/lib/temppath.rb#L185-L190
|
9,014
|
ramz15/voter_love
|
lib/voter_love/voter.rb
|
VoterLove.Voter.up_vote
|
def up_vote(votable)
is_votable?(votable)
vote = get_vote(votable)
if vote
if vote.up_vote
raise Exceptions::AlreadyVotedError.new(true)
else
vote.up_vote = true
votable.down_votes -= 1
self.down_votes -= 1 if has_attribute?(:down_votes)
end
else
vote = Vote.create(:votable => votable, :voter => self, :up_vote => true)
end
votable.up_votes += 1
self.up_votes += 1 if has_attribute?(:up_votes)
Vote.transaction do
save
votable.save
vote.save
end
true
end
|
ruby
|
def up_vote(votable)
is_votable?(votable)
vote = get_vote(votable)
if vote
if vote.up_vote
raise Exceptions::AlreadyVotedError.new(true)
else
vote.up_vote = true
votable.down_votes -= 1
self.down_votes -= 1 if has_attribute?(:down_votes)
end
else
vote = Vote.create(:votable => votable, :voter => self, :up_vote => true)
end
votable.up_votes += 1
self.up_votes += 1 if has_attribute?(:up_votes)
Vote.transaction do
save
votable.save
vote.save
end
true
end
|
[
"def",
"up_vote",
"(",
"votable",
")",
"is_votable?",
"(",
"votable",
")",
"vote",
"=",
"get_vote",
"(",
"votable",
")",
"if",
"vote",
"if",
"vote",
".",
"up_vote",
"raise",
"Exceptions",
"::",
"AlreadyVotedError",
".",
"new",
"(",
"true",
")",
"else",
"vote",
".",
"up_vote",
"=",
"true",
"votable",
".",
"down_votes",
"-=",
"1",
"self",
".",
"down_votes",
"-=",
"1",
"if",
"has_attribute?",
"(",
":down_votes",
")",
"end",
"else",
"vote",
"=",
"Vote",
".",
"create",
"(",
":votable",
"=>",
"votable",
",",
":voter",
"=>",
"self",
",",
":up_vote",
"=>",
"true",
")",
"end",
"votable",
".",
"up_votes",
"+=",
"1",
"self",
".",
"up_votes",
"+=",
"1",
"if",
"has_attribute?",
"(",
":up_votes",
")",
"Vote",
".",
"transaction",
"do",
"save",
"votable",
".",
"save",
"vote",
".",
"save",
"end",
"true",
"end"
] |
Up vote any "votable" object.
Raises an AlreadyVotedError if the voter already voted on the object.
|
[
"Up",
"vote",
"any",
"votable",
"object",
".",
"Raises",
"an",
"AlreadyVotedError",
"if",
"the",
"voter",
"already",
"voted",
"on",
"the",
"object",
"."
] |
99e97562e31c1bd0498c7f7a9b8a209af14a22f5
|
https://github.com/ramz15/voter_love/blob/99e97562e31c1bd0498c7f7a9b8a209af14a22f5/lib/voter_love/voter.rb#L17-L44
|
9,015
|
ramz15/voter_love
|
lib/voter_love/voter.rb
|
VoterLove.Voter.up_vote!
|
def up_vote!(votable)
begin
up_vote(votable)
success = true
rescue Exceptions::AlreadyVotedError
success = false
end
success
end
|
ruby
|
def up_vote!(votable)
begin
up_vote(votable)
success = true
rescue Exceptions::AlreadyVotedError
success = false
end
success
end
|
[
"def",
"up_vote!",
"(",
"votable",
")",
"begin",
"up_vote",
"(",
"votable",
")",
"success",
"=",
"true",
"rescue",
"Exceptions",
"::",
"AlreadyVotedError",
"success",
"=",
"false",
"end",
"success",
"end"
] |
Up vote any "votable" object without raising an error. Vote is ignored.
|
[
"Up",
"vote",
"any",
"votable",
"object",
"without",
"raising",
"an",
"error",
".",
"Vote",
"is",
"ignored",
"."
] |
99e97562e31c1bd0498c7f7a9b8a209af14a22f5
|
https://github.com/ramz15/voter_love/blob/99e97562e31c1bd0498c7f7a9b8a209af14a22f5/lib/voter_love/voter.rb#L47-L55
|
9,016
|
ramz15/voter_love
|
lib/voter_love/voter.rb
|
VoterLove.Voter.down_vote!
|
def down_vote!(votable)
begin
down_vote(votable)
success = true
rescue Exceptions::AlreadyVotedError
success = false
end
success
end
|
ruby
|
def down_vote!(votable)
begin
down_vote(votable)
success = true
rescue Exceptions::AlreadyVotedError
success = false
end
success
end
|
[
"def",
"down_vote!",
"(",
"votable",
")",
"begin",
"down_vote",
"(",
"votable",
")",
"success",
"=",
"true",
"rescue",
"Exceptions",
"::",
"AlreadyVotedError",
"success",
"=",
"false",
"end",
"success",
"end"
] |
Down vote a "votable" object without raising an error. Vote is ignored.
|
[
"Down",
"vote",
"a",
"votable",
"object",
"without",
"raising",
"an",
"error",
".",
"Vote",
"is",
"ignored",
"."
] |
99e97562e31c1bd0498c7f7a9b8a209af14a22f5
|
https://github.com/ramz15/voter_love/blob/99e97562e31c1bd0498c7f7a9b8a209af14a22f5/lib/voter_love/voter.rb#L89-L97
|
9,017
|
ramz15/voter_love
|
lib/voter_love/voter.rb
|
VoterLove.Voter.up_voted?
|
def up_voted?(votable)
is_votable?(votable)
vote = get_vote(votable)
return false if vote.nil?
return true if vote.has_attribute?(:up_vote) && vote.up_vote
false
end
|
ruby
|
def up_voted?(votable)
is_votable?(votable)
vote = get_vote(votable)
return false if vote.nil?
return true if vote.has_attribute?(:up_vote) && vote.up_vote
false
end
|
[
"def",
"up_voted?",
"(",
"votable",
")",
"is_votable?",
"(",
"votable",
")",
"vote",
"=",
"get_vote",
"(",
"votable",
")",
"return",
"false",
"if",
"vote",
".",
"nil?",
"return",
"true",
"if",
"vote",
".",
"has_attribute?",
"(",
":up_vote",
")",
"&&",
"vote",
".",
"up_vote",
"false",
"end"
] |
Returns true if the voter up voted the "votable".
|
[
"Returns",
"true",
"if",
"the",
"voter",
"up",
"voted",
"the",
"votable",
"."
] |
99e97562e31c1bd0498c7f7a9b8a209af14a22f5
|
https://github.com/ramz15/voter_love/blob/99e97562e31c1bd0498c7f7a9b8a209af14a22f5/lib/voter_love/voter.rb#L107-L113
|
9,018
|
jimjh/genie-parser
|
lib/spirit/manifest.rb
|
Spirit.Manifest.check_types
|
def check_types(key='root', expected=TYPES, actual=self, opts={})
bad_type(key, expected, actual, opts) unless actual.is_a? expected.class
case actual
when Hash then actual.each { |k, v| check_types(k, expected[k], v) }
when Enumerable then actual.each { |v| check_types(key, expected.first, v, enum: true) }
end
end
|
ruby
|
def check_types(key='root', expected=TYPES, actual=self, opts={})
bad_type(key, expected, actual, opts) unless actual.is_a? expected.class
case actual
when Hash then actual.each { |k, v| check_types(k, expected[k], v) }
when Enumerable then actual.each { |v| check_types(key, expected.first, v, enum: true) }
end
end
|
[
"def",
"check_types",
"(",
"key",
"=",
"'root'",
",",
"expected",
"=",
"TYPES",
",",
"actual",
"=",
"self",
",",
"opts",
"=",
"{",
"}",
")",
"bad_type",
"(",
"key",
",",
"expected",
",",
"actual",
",",
"opts",
")",
"unless",
"actual",
".",
"is_a?",
"expected",
".",
"class",
"case",
"actual",
"when",
"Hash",
"then",
"actual",
".",
"each",
"{",
"|",
"k",
",",
"v",
"|",
"check_types",
"(",
"k",
",",
"expected",
"[",
"k",
"]",
",",
"v",
")",
"}",
"when",
"Enumerable",
"then",
"actual",
".",
"each",
"{",
"|",
"v",
"|",
"check_types",
"(",
"key",
",",
"expected",
".",
"first",
",",
"v",
",",
"enum",
":",
"true",
")",
"}",
"end",
"end"
] |
Checks that the given hash has the valid types for each value, if they
exist.
@raise [ManifestError] if a bad type is encountered.
|
[
"Checks",
"that",
"the",
"given",
"hash",
"has",
"the",
"valid",
"types",
"for",
"each",
"value",
"if",
"they",
"exist",
"."
] |
d627c1c1cc07c0ea082a2599ee45cd7e7ba9c932
|
https://github.com/jimjh/genie-parser/blob/d627c1c1cc07c0ea082a2599ee45cd7e7ba9c932/lib/spirit/manifest.rb#L54-L60
|
9,019
|
lkdjiin/cellula
|
lib/cellula/rules/wolfram_code_rule.rb
|
Cellula.WolframCodeRule.next_generation_cell
|
def next_generation_cell(left, middle, right)
case [left, middle, right]
when [1,1,1] then @binary_string[0].to_i
when [1,1,0] then @binary_string[1].to_i
when [1,0,1] then @binary_string[2].to_i
when [1,0,0] then @binary_string[3].to_i
when [0,1,1] then @binary_string[4].to_i
when [0,1,0] then @binary_string[5].to_i
when [0,0,1] then @binary_string[6].to_i
when [0,0,0] then @binary_string[7].to_i
end
end
|
ruby
|
def next_generation_cell(left, middle, right)
case [left, middle, right]
when [1,1,1] then @binary_string[0].to_i
when [1,1,0] then @binary_string[1].to_i
when [1,0,1] then @binary_string[2].to_i
when [1,0,0] then @binary_string[3].to_i
when [0,1,1] then @binary_string[4].to_i
when [0,1,0] then @binary_string[5].to_i
when [0,0,1] then @binary_string[6].to_i
when [0,0,0] then @binary_string[7].to_i
end
end
|
[
"def",
"next_generation_cell",
"(",
"left",
",",
"middle",
",",
"right",
")",
"case",
"[",
"left",
",",
"middle",
",",
"right",
"]",
"when",
"[",
"1",
",",
"1",
",",
"1",
"]",
"then",
"@binary_string",
"[",
"0",
"]",
".",
"to_i",
"when",
"[",
"1",
",",
"1",
",",
"0",
"]",
"then",
"@binary_string",
"[",
"1",
"]",
".",
"to_i",
"when",
"[",
"1",
",",
"0",
",",
"1",
"]",
"then",
"@binary_string",
"[",
"2",
"]",
".",
"to_i",
"when",
"[",
"1",
",",
"0",
",",
"0",
"]",
"then",
"@binary_string",
"[",
"3",
"]",
".",
"to_i",
"when",
"[",
"0",
",",
"1",
",",
"1",
"]",
"then",
"@binary_string",
"[",
"4",
"]",
".",
"to_i",
"when",
"[",
"0",
",",
"1",
",",
"0",
"]",
"then",
"@binary_string",
"[",
"5",
"]",
".",
"to_i",
"when",
"[",
"0",
",",
"0",
",",
"1",
"]",
"then",
"@binary_string",
"[",
"6",
"]",
".",
"to_i",
"when",
"[",
"0",
",",
"0",
",",
"0",
"]",
"then",
"@binary_string",
"[",
"7",
"]",
".",
"to_i",
"end",
"end"
] |
Returns 0 or 1.
|
[
"Returns",
"0",
"or",
"1",
"."
] |
32ad29d9daaeeddc36432eaf350818f2461f9434
|
https://github.com/lkdjiin/cellula/blob/32ad29d9daaeeddc36432eaf350818f2461f9434/lib/cellula/rules/wolfram_code_rule.rb#L102-L113
|
9,020
|
filipjakubowski/jira_issues
|
lib/jira_issues/jira_issue_mapper.rb
|
JiraIssues.JiraIssueMapper.call
|
def call(issue)
status = decode_status(issue)
{
key: issue.key,
type: issue.issuetype.name,
priority: issue.priority.name,
status: status,
#description: i.description,
summary: issue.summary,
created_date: issue.created,
closed_date: issue.resolutiondate
}
end
|
ruby
|
def call(issue)
status = decode_status(issue)
{
key: issue.key,
type: issue.issuetype.name,
priority: issue.priority.name,
status: status,
#description: i.description,
summary: issue.summary,
created_date: issue.created,
closed_date: issue.resolutiondate
}
end
|
[
"def",
"call",
"(",
"issue",
")",
"status",
"=",
"decode_status",
"(",
"issue",
")",
"{",
"key",
":",
"issue",
".",
"key",
",",
"type",
":",
"issue",
".",
"issuetype",
".",
"name",
",",
"priority",
":",
"issue",
".",
"priority",
".",
"name",
",",
"status",
":",
"status",
",",
"#description: i.description,",
"summary",
":",
"issue",
".",
"summary",
",",
"created_date",
":",
"issue",
".",
"created",
",",
"closed_date",
":",
"issue",
".",
"resolutiondate",
"}",
"end"
] |
WIP
ATM mapper serialises issue to JSON
We might consider using objects
|
[
"WIP",
"ATM",
"mapper",
"serialises",
"issue",
"to",
"JSON",
"We",
"might",
"consider",
"using",
"objects"
] |
6545c1c2b3a72226ad309386d74ca86d35ff8bb1
|
https://github.com/filipjakubowski/jira_issues/blob/6545c1c2b3a72226ad309386d74ca86d35ff8bb1/lib/jira_issues/jira_issue_mapper.rb#L7-L19
|
9,021
|
bcobb/and_feathers
|
lib/and_feathers/directory.rb
|
AndFeathers.Directory.path
|
def path
if @parent
::File.join(@parent.path, name)
else
if name != '.'
::File.join('.', name)
else
name
end
end
end
|
ruby
|
def path
if @parent
::File.join(@parent.path, name)
else
if name != '.'
::File.join('.', name)
else
name
end
end
end
|
[
"def",
"path",
"if",
"@parent",
"::",
"File",
".",
"join",
"(",
"@parent",
".",
"path",
",",
"name",
")",
"else",
"if",
"name",
"!=",
"'.'",
"::",
"File",
".",
"join",
"(",
"'.'",
",",
"name",
")",
"else",
"name",
"end",
"end",
"end"
] |
This +Directory+'s path
@return [String]
|
[
"This",
"+",
"Directory",
"+",
"s",
"path"
] |
f35b156f8ae6930851712bbaf502f97b3aa9a1b1
|
https://github.com/bcobb/and_feathers/blob/f35b156f8ae6930851712bbaf502f97b3aa9a1b1/lib/and_feathers/directory.rb#L66-L76
|
9,022
|
bcobb/and_feathers
|
lib/and_feathers/directory.rb
|
AndFeathers.Directory.|
|
def |(other)
if !other.is_a?(Directory)
raise ArgumentError, "#{other} is not a Directory"
end
dup.tap do |directory|
other.files.each do |file|
directory.add_file(file.dup)
end
other.directories.each do |new_directory|
existing_directory = @directories[new_directory.name]
if existing_directory.nil?
directory.add_directory(new_directory.dup)
else
directory.add_directory(new_directory | existing_directory)
end
end
end
end
|
ruby
|
def |(other)
if !other.is_a?(Directory)
raise ArgumentError, "#{other} is not a Directory"
end
dup.tap do |directory|
other.files.each do |file|
directory.add_file(file.dup)
end
other.directories.each do |new_directory|
existing_directory = @directories[new_directory.name]
if existing_directory.nil?
directory.add_directory(new_directory.dup)
else
directory.add_directory(new_directory | existing_directory)
end
end
end
end
|
[
"def",
"|",
"(",
"other",
")",
"if",
"!",
"other",
".",
"is_a?",
"(",
"Directory",
")",
"raise",
"ArgumentError",
",",
"\"#{other} is not a Directory\"",
"end",
"dup",
".",
"tap",
"do",
"|",
"directory",
"|",
"other",
".",
"files",
".",
"each",
"do",
"|",
"file",
"|",
"directory",
".",
"add_file",
"(",
"file",
".",
"dup",
")",
"end",
"other",
".",
"directories",
".",
"each",
"do",
"|",
"new_directory",
"|",
"existing_directory",
"=",
"@directories",
"[",
"new_directory",
".",
"name",
"]",
"if",
"existing_directory",
".",
"nil?",
"directory",
".",
"add_directory",
"(",
"new_directory",
".",
"dup",
")",
"else",
"directory",
".",
"add_directory",
"(",
"new_directory",
"|",
"existing_directory",
")",
"end",
"end",
"end",
"end"
] |
Computes the union of this +Directory+ with another +Directory+. If the
two directories have a file path in common, the file in the +other+
+Directory+ takes precedence. If the two directories have a sub-directory
path in common, the union's sub-directory path will be the union of those
two sub-directories.
@raise [ArgumentError] if the +other+ parameter is not a +Directory+
@param other [Directory]
@return [Directory]
|
[
"Computes",
"the",
"union",
"of",
"this",
"+",
"Directory",
"+",
"with",
"another",
"+",
"Directory",
"+",
".",
"If",
"the",
"two",
"directories",
"have",
"a",
"file",
"path",
"in",
"common",
"the",
"file",
"in",
"the",
"+",
"other",
"+",
"+",
"Directory",
"+",
"takes",
"precedence",
".",
"If",
"the",
"two",
"directories",
"have",
"a",
"sub",
"-",
"directory",
"path",
"in",
"common",
"the",
"union",
"s",
"sub",
"-",
"directory",
"path",
"will",
"be",
"the",
"union",
"of",
"those",
"two",
"sub",
"-",
"directories",
"."
] |
f35b156f8ae6930851712bbaf502f97b3aa9a1b1
|
https://github.com/bcobb/and_feathers/blob/f35b156f8ae6930851712bbaf502f97b3aa9a1b1/lib/and_feathers/directory.rb#L100-L120
|
9,023
|
bcobb/and_feathers
|
lib/and_feathers/directory.rb
|
AndFeathers.Directory.each
|
def each(&block)
files.each(&block)
directories.each do |subdirectory|
block.call(subdirectory)
subdirectory.each(&block)
end
end
|
ruby
|
def each(&block)
files.each(&block)
directories.each do |subdirectory|
block.call(subdirectory)
subdirectory.each(&block)
end
end
|
[
"def",
"each",
"(",
"&",
"block",
")",
"files",
".",
"each",
"(",
"block",
")",
"directories",
".",
"each",
"do",
"|",
"subdirectory",
"|",
"block",
".",
"call",
"(",
"subdirectory",
")",
"subdirectory",
".",
"each",
"(",
"block",
")",
"end",
"end"
] |
Iterates through this +Directory+'s children depth-first
@yieldparam child [File, Directory]
|
[
"Iterates",
"through",
"this",
"+",
"Directory",
"+",
"s",
"children",
"depth",
"-",
"first"
] |
f35b156f8ae6930851712bbaf502f97b3aa9a1b1
|
https://github.com/bcobb/and_feathers/blob/f35b156f8ae6930851712bbaf502f97b3aa9a1b1/lib/and_feathers/directory.rb#L145-L153
|
9,024
|
seamusabshere/characterizable
|
lib/characterizable/better_hash.rb
|
Characterizable.BetterHash.slice
|
def slice(*keep)
inject(Characterizable::BetterHash.new) do |memo, ary|
if keep.include?(ary[0])
memo[ary[0]] = ary[1]
end
memo
end
end
|
ruby
|
def slice(*keep)
inject(Characterizable::BetterHash.new) do |memo, ary|
if keep.include?(ary[0])
memo[ary[0]] = ary[1]
end
memo
end
end
|
[
"def",
"slice",
"(",
"*",
"keep",
")",
"inject",
"(",
"Characterizable",
"::",
"BetterHash",
".",
"new",
")",
"do",
"|",
"memo",
",",
"ary",
"|",
"if",
"keep",
".",
"include?",
"(",
"ary",
"[",
"0",
"]",
")",
"memo",
"[",
"ary",
"[",
"0",
"]",
"]",
"=",
"ary",
"[",
"1",
"]",
"end",
"memo",
"end",
"end"
] |
I need this because otherwise it will try to do self.class.new on subclasses
which would get "0 for 1" arguments error with Snapshot, among other things
|
[
"I",
"need",
"this",
"because",
"otherwise",
"it",
"will",
"try",
"to",
"do",
"self",
".",
"class",
".",
"new",
"on",
"subclasses",
"which",
"would",
"get",
"0",
"for",
"1",
"arguments",
"error",
"with",
"Snapshot",
"among",
"other",
"things"
] |
2b0f67b2137eb9b02c7ee36e3295f94c1eb90c18
|
https://github.com/seamusabshere/characterizable/blob/2b0f67b2137eb9b02c7ee36e3295f94c1eb90c18/lib/characterizable/better_hash.rb#L29-L36
|
9,025
|
quixoten/queue_to_the_future
|
lib/queue_to_the_future/job.rb
|
QueueToTheFuture.Job.method_missing
|
def method_missing(*args, &block)
Thread.pass until defined?(@result)
case @result
when Exception
def self.method_missing(*args, &block); raise @result; end
else
def self.method_missing(*args, &block); @result.send(*args, &block); end
end
self.method_missing(*args, &block)
end
|
ruby
|
def method_missing(*args, &block)
Thread.pass until defined?(@result)
case @result
when Exception
def self.method_missing(*args, &block); raise @result; end
else
def self.method_missing(*args, &block); @result.send(*args, &block); end
end
self.method_missing(*args, &block)
end
|
[
"def",
"method_missing",
"(",
"*",
"args",
",",
"&",
"block",
")",
"Thread",
".",
"pass",
"until",
"defined?",
"(",
"@result",
")",
"case",
"@result",
"when",
"Exception",
"def",
"self",
".",
"method_missing",
"(",
"*",
"args",
",",
"&",
"block",
")",
";",
"raise",
"@result",
";",
"end",
"else",
"def",
"self",
".",
"method_missing",
"(",
"*",
"args",
",",
"&",
"block",
")",
";",
"@result",
".",
"send",
"(",
"args",
",",
"block",
")",
";",
"end",
"end",
"self",
".",
"method_missing",
"(",
"args",
",",
"block",
")",
"end"
] |
Allows the job to behave as the return value of the block.
Accessing any method on the job will cause code to block
until the job is completed.
|
[
"Allows",
"the",
"job",
"to",
"behave",
"as",
"the",
"return",
"value",
"of",
"the",
"block",
"."
] |
dd8260fa165ee42b95e6d76bc665fdf68339dfd6
|
https://github.com/quixoten/queue_to_the_future/blob/dd8260fa165ee42b95e6d76bc665fdf68339dfd6/lib/queue_to_the_future/job.rb#L34-L45
|
9,026
|
pluginaweek/enumerate_by
|
lib/enumerate_by.rb
|
EnumerateBy.MacroMethods.enumerate_by
|
def enumerate_by(attribute = :name, options = {})
options.reverse_merge!(:cache => true)
options.assert_valid_keys(:cache)
extend EnumerateBy::ClassMethods
extend EnumerateBy::Bootstrapped
include EnumerateBy::InstanceMethods
# The attribute representing a record's enumerator
cattr_accessor :enumerator_attribute
self.enumerator_attribute = attribute
# Whether to perform caching of enumerators within finder queries
cattr_accessor :perform_enumerator_caching
self.perform_enumerator_caching = options[:cache]
# The cache store to use for queries (default is a memory store)
cattr_accessor :enumerator_cache_store
self.enumerator_cache_store = ActiveSupport::Cache::MemoryStore.new
validates_presence_of attribute
validates_uniqueness_of attribute
end
|
ruby
|
def enumerate_by(attribute = :name, options = {})
options.reverse_merge!(:cache => true)
options.assert_valid_keys(:cache)
extend EnumerateBy::ClassMethods
extend EnumerateBy::Bootstrapped
include EnumerateBy::InstanceMethods
# The attribute representing a record's enumerator
cattr_accessor :enumerator_attribute
self.enumerator_attribute = attribute
# Whether to perform caching of enumerators within finder queries
cattr_accessor :perform_enumerator_caching
self.perform_enumerator_caching = options[:cache]
# The cache store to use for queries (default is a memory store)
cattr_accessor :enumerator_cache_store
self.enumerator_cache_store = ActiveSupport::Cache::MemoryStore.new
validates_presence_of attribute
validates_uniqueness_of attribute
end
|
[
"def",
"enumerate_by",
"(",
"attribute",
"=",
":name",
",",
"options",
"=",
"{",
"}",
")",
"options",
".",
"reverse_merge!",
"(",
":cache",
"=>",
"true",
")",
"options",
".",
"assert_valid_keys",
"(",
":cache",
")",
"extend",
"EnumerateBy",
"::",
"ClassMethods",
"extend",
"EnumerateBy",
"::",
"Bootstrapped",
"include",
"EnumerateBy",
"::",
"InstanceMethods",
"# The attribute representing a record's enumerator",
"cattr_accessor",
":enumerator_attribute",
"self",
".",
"enumerator_attribute",
"=",
"attribute",
"# Whether to perform caching of enumerators within finder queries",
"cattr_accessor",
":perform_enumerator_caching",
"self",
".",
"perform_enumerator_caching",
"=",
"options",
"[",
":cache",
"]",
"# The cache store to use for queries (default is a memory store)",
"cattr_accessor",
":enumerator_cache_store",
"self",
".",
"enumerator_cache_store",
"=",
"ActiveSupport",
"::",
"Cache",
"::",
"MemoryStore",
".",
"new",
"validates_presence_of",
"attribute",
"validates_uniqueness_of",
"attribute",
"end"
] |
Indicates that this class is an enumeration.
The default attribute used to enumerate the class is +name+. You can
override this by specifying a custom attribute that will be used to
*uniquely* reference a record.
*Note* that a presence and uniqueness validation is automatically
defined for the given attribute since all records must have this value
in order to be properly enumerated.
Configuration options:
* <tt>:cache</tt> - Whether to cache all finder queries for this
enumeration. Default is true.
== Defining enumerators
The enumerators of the class uniquely identify each record in the
table. The enumerator value is based on the attribute described above.
In scenarios where the records are managed in code (like colors,
countries, states, etc.), records can be automatically synchronized
via #bootstrap.
== Accessing records
The actual records for an enumeration can be accessed via shortcut
helpers like so:
Color['red'] # => #<Color id: 1, name: "red">
Color['green'] # => #<Color id: 2, name: "green">
When caching is enabled, these lookup queries are cached so that there
is no performance hit.
== Associations
When using enumerations together with +belongs_to+ associations, the
enumerator value can be used as a shortcut for assigning the association.
In addition, the enumerator value is automatically used during
serialization (xml and json) of the associated record instead of the
foreign key for the association.
For more information about how to use enumerations with associations,
see EnumerateBy::Extensions::Associations and EnumerateBy::Extensions::Serializer.
=== Finders
In order to be consistent by always using enumerators to reference
records, a set of finder extensions are added to allow searching
for records like so:
class Car < ActiveRecord::Base
belongs_to :color
end
Car.find_by_color('red')
Car.all(:conditions => {:color => 'red'})
For more information about finders, see EnumerateBy::Extensions::BaseConditions.
|
[
"Indicates",
"that",
"this",
"class",
"is",
"an",
"enumeration",
"."
] |
6a7c1ce54602a352b3286dee633c3dc7f687ea97
|
https://github.com/pluginaweek/enumerate_by/blob/6a7c1ce54602a352b3286dee633c3dc7f687ea97/lib/enumerate_by.rb#L87-L109
|
9,027
|
pluginaweek/enumerate_by
|
lib/enumerate_by.rb
|
EnumerateBy.ClassMethods.typecast_enumerator
|
def typecast_enumerator(enumerator)
if enumerator.is_a?(Array)
enumerator.flatten!
enumerator.map! {|value| typecast_enumerator(value)}
enumerator
else
enumerator.is_a?(Symbol) ? enumerator.to_s : enumerator
end
end
|
ruby
|
def typecast_enumerator(enumerator)
if enumerator.is_a?(Array)
enumerator.flatten!
enumerator.map! {|value| typecast_enumerator(value)}
enumerator
else
enumerator.is_a?(Symbol) ? enumerator.to_s : enumerator
end
end
|
[
"def",
"typecast_enumerator",
"(",
"enumerator",
")",
"if",
"enumerator",
".",
"is_a?",
"(",
"Array",
")",
"enumerator",
".",
"flatten!",
"enumerator",
".",
"map!",
"{",
"|",
"value",
"|",
"typecast_enumerator",
"(",
"value",
")",
"}",
"enumerator",
"else",
"enumerator",
".",
"is_a?",
"(",
"Symbol",
")",
"?",
"enumerator",
".",
"to_s",
":",
"enumerator",
"end",
"end"
] |
Typecasts the given enumerator to its actual value stored in the
database. This will only convert symbols to strings. All other values
will remain in the same type.
|
[
"Typecasts",
"the",
"given",
"enumerator",
"to",
"its",
"actual",
"value",
"stored",
"in",
"the",
"database",
".",
"This",
"will",
"only",
"convert",
"symbols",
"to",
"strings",
".",
"All",
"other",
"values",
"will",
"remain",
"in",
"the",
"same",
"type",
"."
] |
6a7c1ce54602a352b3286dee633c3dc7f687ea97
|
https://github.com/pluginaweek/enumerate_by/blob/6a7c1ce54602a352b3286dee633c3dc7f687ea97/lib/enumerate_by.rb#L207-L215
|
9,028
|
humpyard/humpyard
|
app/models/humpyard/page.rb
|
Humpyard.Page.root_elements
|
def root_elements(yield_name = 'main')
# my own elements
ret = elements.where('container_id IS NULL and page_yield_name = ?', yield_name.to_s).order('position ASC')
# sibling shared elements
unless siblings.empty?
ret += Humpyard::Element.where('container_id IS NULL and page_id in (?) and page_yield_name = ? and shared_state = ?', siblings, yield_name.to_s, Humpyard::Element::SHARED_STATES[:shared_on_siblings]).order('position ASC')
end
# ancestors shared elements
unless ancestor_pages.empty?
ret += Humpyard::Element.where('container_id IS NULL and page_id in (?) and page_yield_name = ? and shared_state = ?', ancestor_pages, yield_name.to_s, Humpyard::Element::SHARED_STATES[:shared_on_children]).order('position ASC')
end
ret
end
|
ruby
|
def root_elements(yield_name = 'main')
# my own elements
ret = elements.where('container_id IS NULL and page_yield_name = ?', yield_name.to_s).order('position ASC')
# sibling shared elements
unless siblings.empty?
ret += Humpyard::Element.where('container_id IS NULL and page_id in (?) and page_yield_name = ? and shared_state = ?', siblings, yield_name.to_s, Humpyard::Element::SHARED_STATES[:shared_on_siblings]).order('position ASC')
end
# ancestors shared elements
unless ancestor_pages.empty?
ret += Humpyard::Element.where('container_id IS NULL and page_id in (?) and page_yield_name = ? and shared_state = ?', ancestor_pages, yield_name.to_s, Humpyard::Element::SHARED_STATES[:shared_on_children]).order('position ASC')
end
ret
end
|
[
"def",
"root_elements",
"(",
"yield_name",
"=",
"'main'",
")",
"# my own elements",
"ret",
"=",
"elements",
".",
"where",
"(",
"'container_id IS NULL and page_yield_name = ?'",
",",
"yield_name",
".",
"to_s",
")",
".",
"order",
"(",
"'position ASC'",
")",
"# sibling shared elements",
"unless",
"siblings",
".",
"empty?",
"ret",
"+=",
"Humpyard",
"::",
"Element",
".",
"where",
"(",
"'container_id IS NULL and page_id in (?) and page_yield_name = ? and shared_state = ?'",
",",
"siblings",
",",
"yield_name",
".",
"to_s",
",",
"Humpyard",
"::",
"Element",
"::",
"SHARED_STATES",
"[",
":shared_on_siblings",
"]",
")",
".",
"order",
"(",
"'position ASC'",
")",
"end",
"# ancestors shared elements",
"unless",
"ancestor_pages",
".",
"empty?",
"ret",
"+=",
"Humpyard",
"::",
"Element",
".",
"where",
"(",
"'container_id IS NULL and page_id in (?) and page_yield_name = ? and shared_state = ?'",
",",
"ancestor_pages",
",",
"yield_name",
".",
"to_s",
",",
"Humpyard",
"::",
"Element",
"::",
"SHARED_STATES",
"[",
":shared_on_children",
"]",
")",
".",
"order",
"(",
"'position ASC'",
")",
"end",
"ret",
"end"
] |
Return the elements on a yield container. Includes shared elemenents from siblings or parents
|
[
"Return",
"the",
"elements",
"on",
"a",
"yield",
"container",
".",
"Includes",
"shared",
"elemenents",
"from",
"siblings",
"or",
"parents"
] |
f344ab851f1dfd824c1e4cb4b92f7c62ac0acefd
|
https://github.com/humpyard/humpyard/blob/f344ab851f1dfd824c1e4cb4b92f7c62ac0acefd/app/models/humpyard/page.rb#L43-L55
|
9,029
|
humpyard/humpyard
|
app/models/humpyard/page.rb
|
Humpyard.Page.child_pages
|
def child_pages options={}
if content_data.is_humpyard_dynamic_page?
content_data.child_pages
else
if options[:single_root] and is_root_page?
Page.where(["parent_id = ? or parent_id IS NULL and NOT id = ?", id, id])
else
children
end
end
end
|
ruby
|
def child_pages options={}
if content_data.is_humpyard_dynamic_page?
content_data.child_pages
else
if options[:single_root] and is_root_page?
Page.where(["parent_id = ? or parent_id IS NULL and NOT id = ?", id, id])
else
children
end
end
end
|
[
"def",
"child_pages",
"options",
"=",
"{",
"}",
"if",
"content_data",
".",
"is_humpyard_dynamic_page?",
"content_data",
".",
"child_pages",
"else",
"if",
"options",
"[",
":single_root",
"]",
"and",
"is_root_page?",
"Page",
".",
"where",
"(",
"[",
"\"parent_id = ? or parent_id IS NULL and NOT id = ?\"",
",",
"id",
",",
"id",
"]",
")",
"else",
"children",
"end",
"end",
"end"
] |
Find the child pages
|
[
"Find",
"the",
"child",
"pages"
] |
f344ab851f1dfd824c1e4cb4b92f7c62ac0acefd
|
https://github.com/humpyard/humpyard/blob/f344ab851f1dfd824c1e4cb4b92f7c62ac0acefd/app/models/humpyard/page.rb#L101-L111
|
9,030
|
humpyard/humpyard
|
app/models/humpyard/page.rb
|
Humpyard.Page.last_modified
|
def last_modified options = {}
changed_at = [Time.zone.at(::File.new("#{Rails.root}").mtime), created_at, updated_at, modified_at]
if(options[:include_pages])
changed_at << Humpyard::Page.select('updated_at').order('updated_at DESC').first.updated_at
end
(changed_at - [nil]).max.utc
end
|
ruby
|
def last_modified options = {}
changed_at = [Time.zone.at(::File.new("#{Rails.root}").mtime), created_at, updated_at, modified_at]
if(options[:include_pages])
changed_at << Humpyard::Page.select('updated_at').order('updated_at DESC').first.updated_at
end
(changed_at - [nil]).max.utc
end
|
[
"def",
"last_modified",
"options",
"=",
"{",
"}",
"changed_at",
"=",
"[",
"Time",
".",
"zone",
".",
"at",
"(",
"::",
"File",
".",
"new",
"(",
"\"#{Rails.root}\"",
")",
".",
"mtime",
")",
",",
"created_at",
",",
"updated_at",
",",
"modified_at",
"]",
"if",
"(",
"options",
"[",
":include_pages",
"]",
")",
"changed_at",
"<<",
"Humpyard",
"::",
"Page",
".",
"select",
"(",
"'updated_at'",
")",
".",
"order",
"(",
"'updated_at DESC'",
")",
".",
"first",
".",
"updated_at",
"end",
"(",
"changed_at",
"-",
"[",
"nil",
"]",
")",
".",
"max",
".",
"utc",
"end"
] |
Return the logical modification time for the page, suitable for http caching, generational cache keys, etc.
|
[
"Return",
"the",
"logical",
"modification",
"time",
"for",
"the",
"page",
"suitable",
"for",
"http",
"caching",
"generational",
"cache",
"keys",
"etc",
"."
] |
f344ab851f1dfd824c1e4cb4b92f7c62ac0acefd
|
https://github.com/humpyard/humpyard/blob/f344ab851f1dfd824c1e4cb4b92f7c62ac0acefd/app/models/humpyard/page.rb#L143-L151
|
9,031
|
dleavitt/dragonfly-dropbox_data_store
|
lib/dragonfly/dropbox_data_store.rb
|
Dragonfly.DropboxDataStore.url_for
|
def url_for(path, opts = {})
path = absolute(path)
(opts[:expires] ? storage.media(path) : storage.shares(path))['url']
end
|
ruby
|
def url_for(path, opts = {})
path = absolute(path)
(opts[:expires] ? storage.media(path) : storage.shares(path))['url']
end
|
[
"def",
"url_for",
"(",
"path",
",",
"opts",
"=",
"{",
"}",
")",
"path",
"=",
"absolute",
"(",
"path",
")",
"(",
"opts",
"[",
":expires",
"]",
"?",
"storage",
".",
"media",
"(",
"path",
")",
":",
"storage",
".",
"shares",
"(",
"path",
")",
")",
"[",
"'url'",
"]",
"end"
] |
Only option is "expires" and it's a boolean
|
[
"Only",
"option",
"is",
"expires",
"and",
"it",
"s",
"a",
"boolean"
] |
30fe8c7edd32e7b21d62bcb20af31097aa382e29
|
https://github.com/dleavitt/dragonfly-dropbox_data_store/blob/30fe8c7edd32e7b21d62bcb20af31097aa382e29/lib/dragonfly/dropbox_data_store.rb#L55-L58
|
9,032
|
mrlhumphreys/board_game_grid
|
lib/board_game_grid/square.rb
|
BoardGameGrid.Square.attribute_match?
|
def attribute_match?(attribute, value)
hash_obj_matcher = lambda do |obj, k, v|
value = obj.send(k)
if !value.nil? && v.is_a?(Hash)
v.all? { |k2,v2| hash_obj_matcher.call(value, k2, v2) }
else
value == v
end
end
hash_obj_matcher.call(self, attribute, value)
end
|
ruby
|
def attribute_match?(attribute, value)
hash_obj_matcher = lambda do |obj, k, v|
value = obj.send(k)
if !value.nil? && v.is_a?(Hash)
v.all? { |k2,v2| hash_obj_matcher.call(value, k2, v2) }
else
value == v
end
end
hash_obj_matcher.call(self, attribute, value)
end
|
[
"def",
"attribute_match?",
"(",
"attribute",
",",
"value",
")",
"hash_obj_matcher",
"=",
"lambda",
"do",
"|",
"obj",
",",
"k",
",",
"v",
"|",
"value",
"=",
"obj",
".",
"send",
"(",
"k",
")",
"if",
"!",
"value",
".",
"nil?",
"&&",
"v",
".",
"is_a?",
"(",
"Hash",
")",
"v",
".",
"all?",
"{",
"|",
"k2",
",",
"v2",
"|",
"hash_obj_matcher",
".",
"call",
"(",
"value",
",",
"k2",
",",
"v2",
")",
"}",
"else",
"value",
"==",
"v",
"end",
"end",
"hash_obj_matcher",
".",
"call",
"(",
"self",
",",
"attribute",
",",
"value",
")",
"end"
] |
checks if the square matches the attributes passed.
@param [Symbol] attribute
the square's attribute.
@param [Object,Hash] value
a value to match on. Can be a hash of attribute/value pairs for deep matching
==== Example:
# Check if square has a piece owned by player 1
square.attribute_match?(:piece, player_number: 1)
|
[
"checks",
"if",
"the",
"square",
"matches",
"the",
"attributes",
"passed",
"."
] |
df07a84c7f7db076d055c6063f1e418f0c8ed288
|
https://github.com/mrlhumphreys/board_game_grid/blob/df07a84c7f7db076d055c6063f1e418f0c8ed288/lib/board_game_grid/square.rb#L62-L73
|
9,033
|
ryym/dio
|
lib/dio/module_base.rb
|
Dio.ModuleBase.included
|
def included(base)
my_injector = injector
injector_holder = Module.new do
define_method :__dio_injector__ do
my_injector
end
end
base.extend(ClassMethods, injector_holder)
base.include(InstanceMethods)
end
|
ruby
|
def included(base)
my_injector = injector
injector_holder = Module.new do
define_method :__dio_injector__ do
my_injector
end
end
base.extend(ClassMethods, injector_holder)
base.include(InstanceMethods)
end
|
[
"def",
"included",
"(",
"base",
")",
"my_injector",
"=",
"injector",
"injector_holder",
"=",
"Module",
".",
"new",
"do",
"define_method",
":__dio_injector__",
"do",
"my_injector",
"end",
"end",
"base",
".",
"extend",
"(",
"ClassMethods",
",",
"injector_holder",
")",
"base",
".",
"include",
"(",
"InstanceMethods",
")",
"end"
] |
Add some methods to a class which includes Dio module.
|
[
"Add",
"some",
"methods",
"to",
"a",
"class",
"which",
"includes",
"Dio",
"module",
"."
] |
4547c3e75d43be7bd73335576e5e5dc3a8fa7efd
|
https://github.com/ryym/dio/blob/4547c3e75d43be7bd73335576e5e5dc3a8fa7efd/lib/dio/module_base.rb#L68-L77
|
9,034
|
smsified/smsified-ruby
|
lib/smsified/oneapi.rb
|
Smsified.OneAPI.send_sms
|
def send_sms(options)
raise ArgumentError, 'an options Hash is required' if !options.instance_of?(Hash)
raise ArgumentError, ':sender_address is required' if options[:sender_address].nil? && @sender_address.nil?
raise ArgumentError, ':address is required' if options[:address].nil?
raise ArgumentError, ':message is required' if options[:message].nil?
options[:sender_address] = options[:sender_address] || @sender_address
query_options = options.clone
query_options.delete(:sender_address)
query_options = camelcase_keys(query_options)
Response.new self.class.post("/smsmessaging/outbound/#{options[:sender_address]}/requests",
:body => build_query_string(query_options),
:basic_auth => @auth,
:headers => SMSIFIED_HTTP_HEADERS)
end
|
ruby
|
def send_sms(options)
raise ArgumentError, 'an options Hash is required' if !options.instance_of?(Hash)
raise ArgumentError, ':sender_address is required' if options[:sender_address].nil? && @sender_address.nil?
raise ArgumentError, ':address is required' if options[:address].nil?
raise ArgumentError, ':message is required' if options[:message].nil?
options[:sender_address] = options[:sender_address] || @sender_address
query_options = options.clone
query_options.delete(:sender_address)
query_options = camelcase_keys(query_options)
Response.new self.class.post("/smsmessaging/outbound/#{options[:sender_address]}/requests",
:body => build_query_string(query_options),
:basic_auth => @auth,
:headers => SMSIFIED_HTTP_HEADERS)
end
|
[
"def",
"send_sms",
"(",
"options",
")",
"raise",
"ArgumentError",
",",
"'an options Hash is required'",
"if",
"!",
"options",
".",
"instance_of?",
"(",
"Hash",
")",
"raise",
"ArgumentError",
",",
"':sender_address is required'",
"if",
"options",
"[",
":sender_address",
"]",
".",
"nil?",
"&&",
"@sender_address",
".",
"nil?",
"raise",
"ArgumentError",
",",
"':address is required'",
"if",
"options",
"[",
":address",
"]",
".",
"nil?",
"raise",
"ArgumentError",
",",
"':message is required'",
"if",
"options",
"[",
":message",
"]",
".",
"nil?",
"options",
"[",
":sender_address",
"]",
"=",
"options",
"[",
":sender_address",
"]",
"||",
"@sender_address",
"query_options",
"=",
"options",
".",
"clone",
"query_options",
".",
"delete",
"(",
":sender_address",
")",
"query_options",
"=",
"camelcase_keys",
"(",
"query_options",
")",
"Response",
".",
"new",
"self",
".",
"class",
".",
"post",
"(",
"\"/smsmessaging/outbound/#{options[:sender_address]}/requests\"",
",",
":body",
"=>",
"build_query_string",
"(",
"query_options",
")",
",",
":basic_auth",
"=>",
"@auth",
",",
":headers",
"=>",
"SMSIFIED_HTTP_HEADERS",
")",
"end"
] |
Intantiate a new class to work with OneAPI
@param [required, Hash] params to create the user
@option params [required, String] :username username to authenticate with
@option params [required, String] :password to authenticate with
@option params [optional, String] :base_uri of an alternative location of SMSified
@option params [optional, String] :destination_address to use with subscriptions
@option params [optional, String] :sender_address to use with subscriptions
@option params [optional, Boolean] :debug to turn on the HTTparty debugging to stdout
@raise [ArgumentError] if :username is not passed as an option
@raise [ArgumentError] if :password is not passed as an option
@example
one_api = OneAPI.new :username => 'user', :password => '123'
Send an SMS to one or more addresses
@param [required, Hash] params to send an sms
@option params [required, String] :address to send the SMS to
@option params [required, String] :message to send with the SMS
@option params [optional, String] :sender_address to use with subscriptions, required if not provided on initialization of OneAPI
@option params [optional, String] :notify_url to send callbacks to
@return [Object] A Response Object with http and data instance methods
@raise [ArgumentError] if :sender_address is not passed as an option when not passed on object creation
@raise [ArgumentError] if :address is not provided as an option
@raise [ArgumentError] if :message is not provided as an option
@example
one_api.send_sms :address => '14155551212', :message => 'Hi there!', :sender_address => '13035551212'
one_api.send_sms :address => ['14155551212', '13035551212'], :message => 'Hi there!', :sender_address => '13035551212'
|
[
"Intantiate",
"a",
"new",
"class",
"to",
"work",
"with",
"OneAPI"
] |
1c7a0f445ffe7fe0fb035a1faf44ac55687a4488
|
https://github.com/smsified/smsified-ruby/blob/1c7a0f445ffe7fe0fb035a1faf44ac55687a4488/lib/smsified/oneapi.rb#L56-L71
|
9,035
|
smsified/smsified-ruby
|
lib/smsified/oneapi.rb
|
Smsified.OneAPI.method_missing
|
def method_missing(method, *args)
if method.to_s.match /subscription/
if args.size == 2
@subscriptions.send method, args[0], args[1]
else
@subscriptions.send method, args[0]
end
else
if method == :delivery_status || method == :retrieve_sms || method == :search_sms
@reporting.send method, args[0]
else
raise RuntimeError, 'Unknown method'
end
end
end
|
ruby
|
def method_missing(method, *args)
if method.to_s.match /subscription/
if args.size == 2
@subscriptions.send method, args[0], args[1]
else
@subscriptions.send method, args[0]
end
else
if method == :delivery_status || method == :retrieve_sms || method == :search_sms
@reporting.send method, args[0]
else
raise RuntimeError, 'Unknown method'
end
end
end
|
[
"def",
"method_missing",
"(",
"method",
",",
"*",
"args",
")",
"if",
"method",
".",
"to_s",
".",
"match",
"/",
"/",
"if",
"args",
".",
"size",
"==",
"2",
"@subscriptions",
".",
"send",
"method",
",",
"args",
"[",
"0",
"]",
",",
"args",
"[",
"1",
"]",
"else",
"@subscriptions",
".",
"send",
"method",
",",
"args",
"[",
"0",
"]",
"end",
"else",
"if",
"method",
"==",
":delivery_status",
"||",
"method",
"==",
":retrieve_sms",
"||",
"method",
"==",
":search_sms",
"@reporting",
".",
"send",
"method",
",",
"args",
"[",
"0",
"]",
"else",
"raise",
"RuntimeError",
",",
"'Unknown method'",
"end",
"end",
"end"
] |
Dispatches method calls to other objects for subscriptions and reporting
|
[
"Dispatches",
"method",
"calls",
"to",
"other",
"objects",
"for",
"subscriptions",
"and",
"reporting"
] |
1c7a0f445ffe7fe0fb035a1faf44ac55687a4488
|
https://github.com/smsified/smsified-ruby/blob/1c7a0f445ffe7fe0fb035a1faf44ac55687a4488/lib/smsified/oneapi.rb#L75-L89
|
9,036
|
NUBIC/aker
|
lib/aker/authorities/automatic_access.rb
|
Aker::Authorities.AutomaticAccess.amplify!
|
def amplify!(user)
user.portals << @portal unless user.portals.include?(@portal)
user.default_portal = @portal unless user.default_portal
user
end
|
ruby
|
def amplify!(user)
user.portals << @portal unless user.portals.include?(@portal)
user.default_portal = @portal unless user.default_portal
user
end
|
[
"def",
"amplify!",
"(",
"user",
")",
"user",
".",
"portals",
"<<",
"@portal",
"unless",
"user",
".",
"portals",
".",
"include?",
"(",
"@portal",
")",
"user",
".",
"default_portal",
"=",
"@portal",
"unless",
"user",
".",
"default_portal",
"user",
"end"
] |
Adds the configured portal to the user if necessary.
@return [Aker::User]
|
[
"Adds",
"the",
"configured",
"portal",
"to",
"the",
"user",
"if",
"necessary",
"."
] |
ff43606a8812e38f96bbe71b46e7f631cbeacf1c
|
https://github.com/NUBIC/aker/blob/ff43606a8812e38f96bbe71b46e7f631cbeacf1c/lib/aker/authorities/automatic_access.rb#L30-L34
|
9,037
|
akwiatkowski/simple_metar_parser
|
lib/simple_metar_parser/metar.rb
|
SimpleMetarParser.Metar.decode
|
def decode
self.raw_splits.each do |split|
self.modules.each do |m|
m.decode_split(split)
end
end
end
|
ruby
|
def decode
self.raw_splits.each do |split|
self.modules.each do |m|
m.decode_split(split)
end
end
end
|
[
"def",
"decode",
"self",
".",
"raw_splits",
".",
"each",
"do",
"|",
"split",
"|",
"self",
".",
"modules",
".",
"each",
"do",
"|",
"m",
"|",
"m",
".",
"decode_split",
"(",
"split",
")",
"end",
"end",
"end"
] |
Decode all string fragments
|
[
"Decode",
"all",
"string",
"fragments"
] |
ff8ea6162c7be6137c8e56b768784e58d7c8ad01
|
https://github.com/akwiatkowski/simple_metar_parser/blob/ff8ea6162c7be6137c8e56b768784e58d7c8ad01/lib/simple_metar_parser/metar.rb#L81-L87
|
9,038
|
blambeau/domain
|
lib/domain/factory.rb
|
Domain.Factory.sbyc
|
def sbyc(super_domain = Object, &pred)
Class.new(super_domain){ extend SByC.new(super_domain, pred) }
end
|
ruby
|
def sbyc(super_domain = Object, &pred)
Class.new(super_domain){ extend SByC.new(super_domain, pred) }
end
|
[
"def",
"sbyc",
"(",
"super_domain",
"=",
"Object",
",",
"&",
"pred",
")",
"Class",
".",
"new",
"(",
"super_domain",
")",
"{",
"extend",
"SByC",
".",
"new",
"(",
"super_domain",
",",
"pred",
")",
"}",
"end"
] |
Creates a domain through specialization by constraint
@param [Class] super_domain
the super_domain of the factored domain
@param [Proc] pred
the domain predicate
@return [Class]
the created domain as a ruby Class
@api public
|
[
"Creates",
"a",
"domain",
"through",
"specialization",
"by",
"constraint"
] |
3fd010cbf2e156013e0ea9afa608ba9b44e7bc75
|
https://github.com/blambeau/domain/blob/3fd010cbf2e156013e0ea9afa608ba9b44e7bc75/lib/domain/factory.rb#L19-L21
|
9,039
|
chocolateboy/wireless
|
lib/wireless/synchronized_store.rb
|
Wireless.SynchronizedStore.get_or_create
|
def get_or_create(key)
@lock.synchronize do
if @store.include?(key)
@store[key]
elsif block_given?
@store[key] = yield
else
# XXX don't expose the receiver as this class is an internal
# implementation detail
raise Wireless::KeyError.new(
"#{@type} not found: #{key}",
key: key
)
end
end
end
|
ruby
|
def get_or_create(key)
@lock.synchronize do
if @store.include?(key)
@store[key]
elsif block_given?
@store[key] = yield
else
# XXX don't expose the receiver as this class is an internal
# implementation detail
raise Wireless::KeyError.new(
"#{@type} not found: #{key}",
key: key
)
end
end
end
|
[
"def",
"get_or_create",
"(",
"key",
")",
"@lock",
".",
"synchronize",
"do",
"if",
"@store",
".",
"include?",
"(",
"key",
")",
"@store",
"[",
"key",
"]",
"elsif",
"block_given?",
"@store",
"[",
"key",
"]",
"=",
"yield",
"else",
"# XXX don't expose the receiver as this class is an internal",
"# implementation detail",
"raise",
"Wireless",
"::",
"KeyError",
".",
"new",
"(",
"\"#{@type} not found: #{key}\"",
",",
"key",
":",
"key",
")",
"end",
"end",
"end"
] |
Retrieve a value from the store. If it doesn't exist and a block is
supplied, create and return it; otherwise, raise a KeyError.
A synchronized version of:
store[key] ||= value
|
[
"Retrieve",
"a",
"value",
"from",
"the",
"store",
".",
"If",
"it",
"doesn",
"t",
"exist",
"and",
"a",
"block",
"is",
"supplied",
"create",
"and",
"return",
"it",
";",
"otherwise",
"raise",
"a",
"KeyError",
"."
] |
d764691d39d64557693ac500e2b763ed4c5bf24d
|
https://github.com/chocolateboy/wireless/blob/d764691d39d64557693ac500e2b763ed4c5bf24d/lib/wireless/synchronized_store.rb#L51-L66
|
9,040
|
danielweinmann/unlock_gateway
|
lib/unlock_gateway/controller.rb
|
UnlockGateway.Controller.transition_state
|
def transition_state(state)
authorize @contribution
@initiative = @contribution.initiative
@user = @contribution.user
state = state.to_sym
transition = @contribution.transition_by_state(state)
initial_state = @contribution.state_name
resource_name = @contribution.class.model_name.human
if @contribution.send("can_#{transition}?")
begin
if @contribution.state_on_gateway != state
if @contribution.update_state_on_gateway!(state)
@contribution.send("#{transition}!")
else
flash[:alert] = t('flash.actions.update.alert', resource_name: resource_name)
end
else
@contribution.send("#{transition}!")
end
rescue
flash[:alert] = t('flash.actions.update.alert', resource_name: resource_name)
end
else
flash[:alert] = t('flash.actions.update.alert', resource_name: resource_name)
end
if flash[:alert].present?
render 'initiatives/contributions/show'
else
if initial_state == :pending
flash[:notice] = t('flash.actions.create.notice', resource_name: resource_name)
else
flash[:notice] = t('flash.actions.update.notice', resource_name: resource_name)
end
redirect_to initiative_contribution_path(@contribution.initiative.id, @contribution)
end
end
|
ruby
|
def transition_state(state)
authorize @contribution
@initiative = @contribution.initiative
@user = @contribution.user
state = state.to_sym
transition = @contribution.transition_by_state(state)
initial_state = @contribution.state_name
resource_name = @contribution.class.model_name.human
if @contribution.send("can_#{transition}?")
begin
if @contribution.state_on_gateway != state
if @contribution.update_state_on_gateway!(state)
@contribution.send("#{transition}!")
else
flash[:alert] = t('flash.actions.update.alert', resource_name: resource_name)
end
else
@contribution.send("#{transition}!")
end
rescue
flash[:alert] = t('flash.actions.update.alert', resource_name: resource_name)
end
else
flash[:alert] = t('flash.actions.update.alert', resource_name: resource_name)
end
if flash[:alert].present?
render 'initiatives/contributions/show'
else
if initial_state == :pending
flash[:notice] = t('flash.actions.create.notice', resource_name: resource_name)
else
flash[:notice] = t('flash.actions.update.notice', resource_name: resource_name)
end
redirect_to initiative_contribution_path(@contribution.initiative.id, @contribution)
end
end
|
[
"def",
"transition_state",
"(",
"state",
")",
"authorize",
"@contribution",
"@initiative",
"=",
"@contribution",
".",
"initiative",
"@user",
"=",
"@contribution",
".",
"user",
"state",
"=",
"state",
".",
"to_sym",
"transition",
"=",
"@contribution",
".",
"transition_by_state",
"(",
"state",
")",
"initial_state",
"=",
"@contribution",
".",
"state_name",
"resource_name",
"=",
"@contribution",
".",
"class",
".",
"model_name",
".",
"human",
"if",
"@contribution",
".",
"send",
"(",
"\"can_#{transition}?\"",
")",
"begin",
"if",
"@contribution",
".",
"state_on_gateway",
"!=",
"state",
"if",
"@contribution",
".",
"update_state_on_gateway!",
"(",
"state",
")",
"@contribution",
".",
"send",
"(",
"\"#{transition}!\"",
")",
"else",
"flash",
"[",
":alert",
"]",
"=",
"t",
"(",
"'flash.actions.update.alert'",
",",
"resource_name",
":",
"resource_name",
")",
"end",
"else",
"@contribution",
".",
"send",
"(",
"\"#{transition}!\"",
")",
"end",
"rescue",
"flash",
"[",
":alert",
"]",
"=",
"t",
"(",
"'flash.actions.update.alert'",
",",
"resource_name",
":",
"resource_name",
")",
"end",
"else",
"flash",
"[",
":alert",
"]",
"=",
"t",
"(",
"'flash.actions.update.alert'",
",",
"resource_name",
":",
"resource_name",
")",
"end",
"if",
"flash",
"[",
":alert",
"]",
".",
"present?",
"render",
"'initiatives/contributions/show'",
"else",
"if",
"initial_state",
"==",
":pending",
"flash",
"[",
":notice",
"]",
"=",
"t",
"(",
"'flash.actions.create.notice'",
",",
"resource_name",
":",
"resource_name",
")",
"else",
"flash",
"[",
":notice",
"]",
"=",
"t",
"(",
"'flash.actions.update.notice'",
",",
"resource_name",
":",
"resource_name",
")",
"end",
"redirect_to",
"initiative_contribution_path",
"(",
"@contribution",
".",
"initiative",
".",
"id",
",",
"@contribution",
")",
"end",
"end"
] |
This method authorizes @contribution, checks if the contribution can be transitioned to the desired state, calls Contribution#update_state_on_gateway!, transition the contribution's state, and return the proper JSON for Unlock's AJAX calls
|
[
"This",
"method",
"authorizes"
] |
50fe59d4d97874ce7372cb2830a87af5424ebdd3
|
https://github.com/danielweinmann/unlock_gateway/blob/50fe59d4d97874ce7372cb2830a87af5424ebdd3/lib/unlock_gateway/controller.rb#L67-L102
|
9,041
|
petebrowne/machined
|
lib/machined/cli.rb
|
Machined.CLI.rack_options
|
def rack_options # :nodoc:
symbolized_options(:port, :host, :server, :daemonize, :pid).tap do |rack_options|
rack_options[:environment] = environment
rack_options[:Port] = rack_options.delete :port
rack_options[:Host] = rack_options.delete :host
rack_options[:app] = machined
end
end
|
ruby
|
def rack_options # :nodoc:
symbolized_options(:port, :host, :server, :daemonize, :pid).tap do |rack_options|
rack_options[:environment] = environment
rack_options[:Port] = rack_options.delete :port
rack_options[:Host] = rack_options.delete :host
rack_options[:app] = machined
end
end
|
[
"def",
"rack_options",
"# :nodoc:",
"symbolized_options",
"(",
":port",
",",
":host",
",",
":server",
",",
":daemonize",
",",
":pid",
")",
".",
"tap",
"do",
"|",
"rack_options",
"|",
"rack_options",
"[",
":environment",
"]",
"=",
"environment",
"rack_options",
"[",
":Port",
"]",
"=",
"rack_options",
".",
"delete",
":port",
"rack_options",
"[",
":Host",
"]",
"=",
"rack_options",
".",
"delete",
":host",
"rack_options",
"[",
":app",
"]",
"=",
"machined",
"end",
"end"
] |
Returns the options needed for setting up the Rack server.
|
[
"Returns",
"the",
"options",
"needed",
"for",
"setting",
"up",
"the",
"Rack",
"server",
"."
] |
4f3921bc5098104096474300e933f009f1b4f7dd
|
https://github.com/petebrowne/machined/blob/4f3921bc5098104096474300e933f009f1b4f7dd/lib/machined/cli.rb#L87-L94
|
9,042
|
petebrowne/machined
|
lib/machined/cli.rb
|
Machined.CLI.symbolized_options
|
def symbolized_options(*keys) # :nodoc:
@symbolized_options ||= begin
opts = {}.merge(options)
opts.merge! saved_options if saved_options?
opts.symbolize_keys
end
@symbolized_options.slice(*keys)
end
|
ruby
|
def symbolized_options(*keys) # :nodoc:
@symbolized_options ||= begin
opts = {}.merge(options)
opts.merge! saved_options if saved_options?
opts.symbolize_keys
end
@symbolized_options.slice(*keys)
end
|
[
"def",
"symbolized_options",
"(",
"*",
"keys",
")",
"# :nodoc:",
"@symbolized_options",
"||=",
"begin",
"opts",
"=",
"{",
"}",
".",
"merge",
"(",
"options",
")",
"opts",
".",
"merge!",
"saved_options",
"if",
"saved_options?",
"opts",
".",
"symbolize_keys",
"end",
"@symbolized_options",
".",
"slice",
"(",
"keys",
")",
"end"
] |
Returns a mutable options hash with symbolized keys.
Optionally, returns only the keys given.
|
[
"Returns",
"a",
"mutable",
"options",
"hash",
"with",
"symbolized",
"keys",
".",
"Optionally",
"returns",
"only",
"the",
"keys",
"given",
"."
] |
4f3921bc5098104096474300e933f009f1b4f7dd
|
https://github.com/petebrowne/machined/blob/4f3921bc5098104096474300e933f009f1b4f7dd/lib/machined/cli.rb#L98-L105
|
9,043
|
Deradon/Rails-LookUpTable
|
lib/look_up_table/base.rb
|
LookUpTable.ClassMethods.look_up_table
|
def look_up_table(lut_key, options = {}, &block)
options = {
:batch_size => 10000,
:prefix => "#{self.name}/",
:read_on_init => false,
:use_cache => true,
:sql_mode => true,
:where => nil
}.merge(options)
self.lut_set_proc(lut_key, block)
self.lut_set_options(lut_key, options)
self.lut(lut_key) if options[:read_on_init]
end
|
ruby
|
def look_up_table(lut_key, options = {}, &block)
options = {
:batch_size => 10000,
:prefix => "#{self.name}/",
:read_on_init => false,
:use_cache => true,
:sql_mode => true,
:where => nil
}.merge(options)
self.lut_set_proc(lut_key, block)
self.lut_set_options(lut_key, options)
self.lut(lut_key) if options[:read_on_init]
end
|
[
"def",
"look_up_table",
"(",
"lut_key",
",",
"options",
"=",
"{",
"}",
",",
"&",
"block",
")",
"options",
"=",
"{",
":batch_size",
"=>",
"10000",
",",
":prefix",
"=>",
"\"#{self.name}/\"",
",",
":read_on_init",
"=>",
"false",
",",
":use_cache",
"=>",
"true",
",",
":sql_mode",
"=>",
"true",
",",
":where",
"=>",
"nil",
"}",
".",
"merge",
"(",
"options",
")",
"self",
".",
"lut_set_proc",
"(",
"lut_key",
",",
"block",
")",
"self",
".",
"lut_set_options",
"(",
"lut_key",
",",
"options",
")",
"self",
".",
"lut",
"(",
"lut_key",
")",
"if",
"options",
"[",
":read_on_init",
"]",
"end"
] |
== Defining LookUpTables
# Sample class:
Foobar(id: integer, foo: string, bar: integer)
=== Simplest way to define a LookUpTable:
look_up_table :id
look_up_table :foo
look_up_table :bar
=== Add some options to your LookUpTable:
look_up_table :foo, :batch_size => 5000, :where => "id > 10000"
=== Pass a block to define the LUT manually
look_up_table :foo do |lut, foobar|
lut[foobar.foo] = foobar.id
end
=== Turn off AutoFinder and completly define the whole LUT yourself:
look_up_table :foo, :sql_mode => false do |lut|
Foobar.where("id > 10000").each do |foobar|
lut[foobar.foo] = foobar.id
end
end
|
[
"==",
"Defining",
"LookUpTables"
] |
da873f48b039ef01ed3d3820d3a59d8886281be1
|
https://github.com/Deradon/Rails-LookUpTable/blob/da873f48b039ef01ed3d3820d3a59d8886281be1/lib/look_up_table/base.rb#L38-L52
|
9,044
|
Deradon/Rails-LookUpTable
|
lib/look_up_table/base.rb
|
LookUpTable.ClassMethods.lut
|
def lut(lut_key = nil, lut_item_key = nil)
@lut ||= {}
if lut_key.nil?
hash = {}
self.lut_keys.each { |key| hash[key] = self.lut(key) } # CHECK: use .inject?
return hash
end
@lut[lut_key.intern] ||= lut_read(lut_key) || {} if lut_key.respond_to?(:intern)
self.lut_deep_hash_call(:lut, @lut, lut_key, lut_item_key)
end
|
ruby
|
def lut(lut_key = nil, lut_item_key = nil)
@lut ||= {}
if lut_key.nil?
hash = {}
self.lut_keys.each { |key| hash[key] = self.lut(key) } # CHECK: use .inject?
return hash
end
@lut[lut_key.intern] ||= lut_read(lut_key) || {} if lut_key.respond_to?(:intern)
self.lut_deep_hash_call(:lut, @lut, lut_key, lut_item_key)
end
|
[
"def",
"lut",
"(",
"lut_key",
"=",
"nil",
",",
"lut_item_key",
"=",
"nil",
")",
"@lut",
"||=",
"{",
"}",
"if",
"lut_key",
".",
"nil?",
"hash",
"=",
"{",
"}",
"self",
".",
"lut_keys",
".",
"each",
"{",
"|",
"key",
"|",
"hash",
"[",
"key",
"]",
"=",
"self",
".",
"lut",
"(",
"key",
")",
"}",
"# CHECK: use .inject?",
"return",
"hash",
"end",
"@lut",
"[",
"lut_key",
".",
"intern",
"]",
"||=",
"lut_read",
"(",
"lut_key",
")",
"||",
"{",
"}",
"if",
"lut_key",
".",
"respond_to?",
"(",
":intern",
")",
"self",
".",
"lut_deep_hash_call",
"(",
":lut",
",",
"@lut",
",",
"lut_key",
",",
"lut_item_key",
")",
"end"
] |
== Calling LookUpTables
=== Call without any params
* Returns: All LUTs defined within Foobar
Foobar.lut
=>
{
:foo => { :a => 1 },
:bar => { :b => 2 },
:foobar => { :c => 3, :d => 4, :e => 5 }
}
=== Call with :lut_key:
* Returns: Hash representing LUT defined by :lut_key
Foobar.lut :foo
=> { :a => 1 }
=== Call with array of :lut_keys
* Returns: Hash representing LUT defined with :lut_key in given Array
Foobar.lut [:foo, :bar]
=>
{
:foo => { :a => 1 },
:bar => { :b => 2 }
}
=== Call with Call with :lut_key and :lut_item_key
* Returns: Value in LUT defined by :lut_key and :lut_item_key
Foobar.lut :foo, "foobar"
=> 1
# So we've got a Foobar with :foo => "foobar", its ID is '1'
=== Call with Call with :lut_key and :lut_item_key as Array
* Returns: Hash representing LUT defined by :lut_key with
:lut_item_keys in Array
Foobar.lut :foobar, ["foo", "bar", "oof"]
=>
{
"foo" => 3,
"bar" => 4,
"oof" => nil
}
# So we got Foobars with ID '3' and '4'
# and no Foobar defined by :foobar => :oof
=== Call with :lut_key as a Hash
* Returns: Hash representing LUTs given by keys of passed Hash.
- If given value of Hash-Item is nil, will get whole LUT.
- If given value is String or Symbol, will get value of LUT.
- If given value is Array, will get values of entries.
* Example:
Foobar.lut { :foo => :a, :bar => nil, :foobar => [:c, :d] }
=>
{
:foo => 1,
:bar => { :b => 2 },
:foobar => { :c => 3, :d => 4 }
}
|
[
"==",
"Calling",
"LookUpTables"
] |
da873f48b039ef01ed3d3820d3a59d8886281be1
|
https://github.com/Deradon/Rails-LookUpTable/blob/da873f48b039ef01ed3d3820d3a59d8886281be1/lib/look_up_table/base.rb#L112-L124
|
9,045
|
Deradon/Rails-LookUpTable
|
lib/look_up_table/base.rb
|
LookUpTable.ClassMethods.lut_reload
|
def lut_reload(lut_key = nil)
if lut_key
lut_reset(lut_key)
lut(lut_key)
else
lut_keys.each { |k| lut_reload(k) }
end
lut_keys
end
|
ruby
|
def lut_reload(lut_key = nil)
if lut_key
lut_reset(lut_key)
lut(lut_key)
else
lut_keys.each { |k| lut_reload(k) }
end
lut_keys
end
|
[
"def",
"lut_reload",
"(",
"lut_key",
"=",
"nil",
")",
"if",
"lut_key",
"lut_reset",
"(",
"lut_key",
")",
"lut",
"(",
"lut_key",
")",
"else",
"lut_keys",
".",
"each",
"{",
"|",
"k",
"|",
"lut_reload",
"(",
"k",
")",
"}",
"end",
"lut_keys",
"end"
] |
Reading LUT and writing cache again
|
[
"Reading",
"LUT",
"and",
"writing",
"cache",
"again"
] |
da873f48b039ef01ed3d3820d3a59d8886281be1
|
https://github.com/Deradon/Rails-LookUpTable/blob/da873f48b039ef01ed3d3820d3a59d8886281be1/lib/look_up_table/base.rb#L141-L150
|
9,046
|
Deradon/Rails-LookUpTable
|
lib/look_up_table/base.rb
|
LookUpTable.ClassMethods.lut_read
|
def lut_read(name)
return nil unless options = lut_options(name)# HACK
if options[:use_cache]
lut_read_from_cache(name)
else
lut_read_without_cache(name)
end
end
|
ruby
|
def lut_read(name)
return nil unless options = lut_options(name)# HACK
if options[:use_cache]
lut_read_from_cache(name)
else
lut_read_without_cache(name)
end
end
|
[
"def",
"lut_read",
"(",
"name",
")",
"return",
"nil",
"unless",
"options",
"=",
"lut_options",
"(",
"name",
")",
"# HACK",
"if",
"options",
"[",
":use_cache",
"]",
"lut_read_from_cache",
"(",
"name",
")",
"else",
"lut_read_without_cache",
"(",
"name",
")",
"end",
"end"
] |
Reads a single lut
|
[
"Reads",
"a",
"single",
"lut"
] |
da873f48b039ef01ed3d3820d3a59d8886281be1
|
https://github.com/Deradon/Rails-LookUpTable/blob/da873f48b039ef01ed3d3820d3a59d8886281be1/lib/look_up_table/base.rb#L210-L218
|
9,047
|
vojto/active_harmony
|
lib/active_harmony/synchronizer_configuration.rb
|
ActiveHarmony.SynchronizerConfiguration.synchronizable_for_types
|
def synchronizable_for_types(types)
@synchronizable_fields.select do |field_description|
types.include?(field_description[:type])
end.collect do |field_description|
field_description[:field]
end
end
|
ruby
|
def synchronizable_for_types(types)
@synchronizable_fields.select do |field_description|
types.include?(field_description[:type])
end.collect do |field_description|
field_description[:field]
end
end
|
[
"def",
"synchronizable_for_types",
"(",
"types",
")",
"@synchronizable_fields",
".",
"select",
"do",
"|",
"field_description",
"|",
"types",
".",
"include?",
"(",
"field_description",
"[",
":type",
"]",
")",
"end",
".",
"collect",
"do",
"|",
"field_description",
"|",
"field_description",
"[",
":field",
"]",
"end",
"end"
] |
Fields that should be synchronized on types specified
in argument
@param [Array<Symbol>] Types
@return [Array<Symbol>] Fields
|
[
"Fields",
"that",
"should",
"be",
"synchronized",
"on",
"types",
"specified",
"in",
"argument"
] |
03e5c67ea7a1f986c729001c4fec944bf116640f
|
https://github.com/vojto/active_harmony/blob/03e5c67ea7a1f986c729001c4fec944bf116640f/lib/active_harmony/synchronizer_configuration.rb#L63-L69
|
9,048
|
jemmyw/measurement
|
lib/measurement.rb
|
Measurement.Base.to_s
|
def to_s(unit = nil, precision = 0)
if unit.to_s =~ /_and_/
units = unit.to_s.split('_and_').map do |unit|
self.class.fetch_scale(unit)
end
UnitGroup.new(units).format(@amount, precision)
else
unit = self.class.fetch_scale(unit)
unit.format(@amount, precision)
end
end
|
ruby
|
def to_s(unit = nil, precision = 0)
if unit.to_s =~ /_and_/
units = unit.to_s.split('_and_').map do |unit|
self.class.fetch_scale(unit)
end
UnitGroup.new(units).format(@amount, precision)
else
unit = self.class.fetch_scale(unit)
unit.format(@amount, precision)
end
end
|
[
"def",
"to_s",
"(",
"unit",
"=",
"nil",
",",
"precision",
"=",
"0",
")",
"if",
"unit",
".",
"to_s",
"=~",
"/",
"/",
"units",
"=",
"unit",
".",
"to_s",
".",
"split",
"(",
"'_and_'",
")",
".",
"map",
"do",
"|",
"unit",
"|",
"self",
".",
"class",
".",
"fetch_scale",
"(",
"unit",
")",
"end",
"UnitGroup",
".",
"new",
"(",
"units",
")",
".",
"format",
"(",
"@amount",
",",
"precision",
")",
"else",
"unit",
"=",
"self",
".",
"class",
".",
"fetch_scale",
"(",
"unit",
")",
"unit",
".",
"format",
"(",
"@amount",
",",
"precision",
")",
"end",
"end"
] |
Format the measurement and return as a string.
This will format using the base unit if no unit
is specified.
Example:
Length.new(1.8034).to_s(:feet) => 6'
Multiple units can be specified allowing for a
more naturally formatted measurement. For example:
Length.new(1.8034).to_s(:feet_and_inches) => 5' 11"
Naturally formatted measurements can be returned using
shorthand functions:
Length.new(1.8034).in_feet_and_inches => 5' 11"
The unit group can also be specified to get a similar effect:
Length.new(1.8034).to_s(:metric) => '1m 80cm 3mm'
A precision can be specified, otherwise the measurement
is rounded to the nearest integer.
|
[
"Format",
"the",
"measurement",
"and",
"return",
"as",
"a",
"string",
".",
"This",
"will",
"format",
"using",
"the",
"base",
"unit",
"if",
"no",
"unit",
"is",
"specified",
"."
] |
dfa192875e014ed56acfd496bcc12b00da15b540
|
https://github.com/jemmyw/measurement/blob/dfa192875e014ed56acfd496bcc12b00da15b540/lib/measurement.rb#L284-L295
|
9,049
|
fauxparse/matchy_matchy
|
lib/matchy_matchy/match_list.rb
|
MatchyMatchy.MatchList.<<
|
def <<(match)
if include?(match)
match.reject!
else
@matches << match
@matches.sort!
@matches.pop.reject! if @matches.size > @capacity
end
self
end
|
ruby
|
def <<(match)
if include?(match)
match.reject!
else
@matches << match
@matches.sort!
@matches.pop.reject! if @matches.size > @capacity
end
self
end
|
[
"def",
"<<",
"(",
"match",
")",
"if",
"include?",
"(",
"match",
")",
"match",
".",
"reject!",
"else",
"@matches",
"<<",
"match",
"@matches",
".",
"sort!",
"@matches",
".",
"pop",
".",
"reject!",
"if",
"@matches",
".",
"size",
">",
"@capacity",
"end",
"self",
"end"
] |
Initializes the list.
@param capacity [Integer] The maximum number of matches this list can hold
Pushes a match into the list.
The list is re-sorted and any matches that don’t fit are rejected.
@param match [MatchyMatchy::Match]
@return [MatchyMatchy::MatchList] Self
|
[
"Initializes",
"the",
"list",
"."
] |
4e11ea438e08c0cc4d04836ffe0c61f196a70b94
|
https://github.com/fauxparse/matchy_matchy/blob/4e11ea438e08c0cc4d04836ffe0c61f196a70b94/lib/matchy_matchy/match_list.rb#L19-L28
|
9,050
|
tomtt/method_info
|
lib/method_info/ancestor_method_structure.rb
|
MethodInfo.AncestorMethodStructure.method_owner
|
def method_owner(method_symbol)
# Under normal circumstances just calling @object.method(method_symbol) would work,
# but this will go wrong if the object has redefined the method method.
method = Object.instance_method(:method).bind(@object).call(method_symbol)
method.owner
rescue NameError
poor_mans_method_owner(method, method_symbol.to_s)
end
|
ruby
|
def method_owner(method_symbol)
# Under normal circumstances just calling @object.method(method_symbol) would work,
# but this will go wrong if the object has redefined the method method.
method = Object.instance_method(:method).bind(@object).call(method_symbol)
method.owner
rescue NameError
poor_mans_method_owner(method, method_symbol.to_s)
end
|
[
"def",
"method_owner",
"(",
"method_symbol",
")",
"# Under normal circumstances just calling @object.method(method_symbol) would work,",
"# but this will go wrong if the object has redefined the method method.",
"method",
"=",
"Object",
".",
"instance_method",
"(",
":method",
")",
".",
"bind",
"(",
"@object",
")",
".",
"call",
"(",
"method_symbol",
")",
"method",
".",
"owner",
"rescue",
"NameError",
"poor_mans_method_owner",
"(",
"method",
",",
"method_symbol",
".",
"to_s",
")",
"end"
] |
Returns the class or module where method is defined
|
[
"Returns",
"the",
"class",
"or",
"module",
"where",
"method",
"is",
"defined"
] |
c9436535dc9d2314cb6d6914ba072554ac956c5c
|
https://github.com/tomtt/method_info/blob/c9436535dc9d2314cb6d6914ba072554ac956c5c/lib/method_info/ancestor_method_structure.rb#L163-L171
|
9,051
|
simonswine/php_fpm_docker
|
lib/php_fpm_docker/launcher.rb
|
PhpFpmDocker.Launcher.parse_config
|
def parse_config # rubocop:disable MethodLength
# Test for file usability
fail "Config file '#{@config_path}' not found"\
unless @config_path.file?
fail "Config file '#{@config_path}' not readable"\
unless @config_path.readable?
@ini_file = IniFile.load(@config_path)
begin
docker_image = @ini_file[:main]['docker_image']
@docker_image = Docker::Image.get(docker_image)
@logger.info(to_s) do
"Docker image id=#{@docker_image.id[0..11]} name=#{docker_image}"
end
rescue NoMethodError
raise 'No docker_image in section main in config found'
rescue Docker::Error::NotFoundError
raise "Docker_image '#{docker_image}' not found"
rescue Excon::Errors::SocketError => e
raise "Docker connection could not be established: #{e.message}"
end
end
|
ruby
|
def parse_config # rubocop:disable MethodLength
# Test for file usability
fail "Config file '#{@config_path}' not found"\
unless @config_path.file?
fail "Config file '#{@config_path}' not readable"\
unless @config_path.readable?
@ini_file = IniFile.load(@config_path)
begin
docker_image = @ini_file[:main]['docker_image']
@docker_image = Docker::Image.get(docker_image)
@logger.info(to_s) do
"Docker image id=#{@docker_image.id[0..11]} name=#{docker_image}"
end
rescue NoMethodError
raise 'No docker_image in section main in config found'
rescue Docker::Error::NotFoundError
raise "Docker_image '#{docker_image}' not found"
rescue Excon::Errors::SocketError => e
raise "Docker connection could not be established: #{e.message}"
end
end
|
[
"def",
"parse_config",
"# rubocop:disable MethodLength",
"# Test for file usability",
"fail",
"\"Config file '#{@config_path}' not found\"",
"unless",
"@config_path",
".",
"file?",
"fail",
"\"Config file '#{@config_path}' not readable\"",
"unless",
"@config_path",
".",
"readable?",
"@ini_file",
"=",
"IniFile",
".",
"load",
"(",
"@config_path",
")",
"begin",
"docker_image",
"=",
"@ini_file",
"[",
":main",
"]",
"[",
"'docker_image'",
"]",
"@docker_image",
"=",
"Docker",
"::",
"Image",
".",
"get",
"(",
"docker_image",
")",
"@logger",
".",
"info",
"(",
"to_s",
")",
"do",
"\"Docker image id=#{@docker_image.id[0..11]} name=#{docker_image}\"",
"end",
"rescue",
"NoMethodError",
"raise",
"'No docker_image in section main in config found'",
"rescue",
"Docker",
"::",
"Error",
"::",
"NotFoundError",
"raise",
"\"Docker_image '#{docker_image}' not found\"",
"rescue",
"Excon",
"::",
"Errors",
"::",
"SocketError",
"=>",
"e",
"raise",
"\"Docker connection could not be established: #{e.message}\"",
"end",
"end"
] |
Parse the config file for all pools
|
[
"Parse",
"the",
"config",
"file",
"for",
"all",
"pools"
] |
2d7ab79fb6394a6a3f90457f58fb584cd916ffcd
|
https://github.com/simonswine/php_fpm_docker/blob/2d7ab79fb6394a6a3f90457f58fb584cd916ffcd/lib/php_fpm_docker/launcher.rb#L174-L196
|
9,052
|
simonswine/php_fpm_docker
|
lib/php_fpm_docker/launcher.rb
|
PhpFpmDocker.Launcher.pools_config_content_from_file
|
def pools_config_content_from_file(config_path)
ini_file = IniFile.load(config_path)
ret_val = []
ini_file.each_section do |section|
ret_val << [section, ini_file[section]]
end
ret_val
end
|
ruby
|
def pools_config_content_from_file(config_path)
ini_file = IniFile.load(config_path)
ret_val = []
ini_file.each_section do |section|
ret_val << [section, ini_file[section]]
end
ret_val
end
|
[
"def",
"pools_config_content_from_file",
"(",
"config_path",
")",
"ini_file",
"=",
"IniFile",
".",
"load",
"(",
"config_path",
")",
"ret_val",
"=",
"[",
"]",
"ini_file",
".",
"each_section",
"do",
"|",
"section",
"|",
"ret_val",
"<<",
"[",
"section",
",",
"ini_file",
"[",
"section",
"]",
"]",
"end",
"ret_val",
"end"
] |
Reads config sections from a inifile
|
[
"Reads",
"config",
"sections",
"from",
"a",
"inifile"
] |
2d7ab79fb6394a6a3f90457f58fb584cd916ffcd
|
https://github.com/simonswine/php_fpm_docker/blob/2d7ab79fb6394a6a3f90457f58fb584cd916ffcd/lib/php_fpm_docker/launcher.rb#L205-L213
|
9,053
|
simonswine/php_fpm_docker
|
lib/php_fpm_docker/launcher.rb
|
PhpFpmDocker.Launcher.pools_config_contents
|
def pools_config_contents
ret_val = []
# Loop over
Dir[@pools_directory.join('*.conf').to_s].each do |config_path|
ret_val += pools_config_content_from_file(config_path)
end
ret_val
end
|
ruby
|
def pools_config_contents
ret_val = []
# Loop over
Dir[@pools_directory.join('*.conf').to_s].each do |config_path|
ret_val += pools_config_content_from_file(config_path)
end
ret_val
end
|
[
"def",
"pools_config_contents",
"ret_val",
"=",
"[",
"]",
"# Loop over",
"Dir",
"[",
"@pools_directory",
".",
"join",
"(",
"'*.conf'",
")",
".",
"to_s",
"]",
".",
"each",
"do",
"|",
"config_path",
"|",
"ret_val",
"+=",
"pools_config_content_from_file",
"(",
"config_path",
")",
"end",
"ret_val",
"end"
] |
Merges config sections form all inifiles
|
[
"Merges",
"config",
"sections",
"form",
"all",
"inifiles"
] |
2d7ab79fb6394a6a3f90457f58fb584cd916ffcd
|
https://github.com/simonswine/php_fpm_docker/blob/2d7ab79fb6394a6a3f90457f58fb584cd916ffcd/lib/php_fpm_docker/launcher.rb#L216-L224
|
9,054
|
simonswine/php_fpm_docker
|
lib/php_fpm_docker/launcher.rb
|
PhpFpmDocker.Launcher.pools_from_config
|
def pools_from_config
configs = {}
pools_config_contents.each do |section|
# Hash section name and content
d = Digest::SHA2.new(256)
hash = d.reset.update(section[0]).update(section[1].to_s).to_s
configs[hash] = {
name: section[0],
config: section[1]
}
end
configs
end
|
ruby
|
def pools_from_config
configs = {}
pools_config_contents.each do |section|
# Hash section name and content
d = Digest::SHA2.new(256)
hash = d.reset.update(section[0]).update(section[1].to_s).to_s
configs[hash] = {
name: section[0],
config: section[1]
}
end
configs
end
|
[
"def",
"pools_from_config",
"configs",
"=",
"{",
"}",
"pools_config_contents",
".",
"each",
"do",
"|",
"section",
"|",
"# Hash section name and content",
"d",
"=",
"Digest",
"::",
"SHA2",
".",
"new",
"(",
"256",
")",
"hash",
"=",
"d",
".",
"reset",
".",
"update",
"(",
"section",
"[",
"0",
"]",
")",
".",
"update",
"(",
"section",
"[",
"1",
"]",
".",
"to_s",
")",
".",
"to_s",
"configs",
"[",
"hash",
"]",
"=",
"{",
"name",
":",
"section",
"[",
"0",
"]",
",",
"config",
":",
"section",
"[",
"1",
"]",
"}",
"end",
"configs",
"end"
] |
Hashes configs to detect changes
|
[
"Hashes",
"configs",
"to",
"detect",
"changes"
] |
2d7ab79fb6394a6a3f90457f58fb584cd916ffcd
|
https://github.com/simonswine/php_fpm_docker/blob/2d7ab79fb6394a6a3f90457f58fb584cd916ffcd/lib/php_fpm_docker/launcher.rb#L227-L241
|
9,055
|
vjoel/tkar
|
lib/tkar/primitives.rb
|
Tkar.Primitives.polybox
|
def polybox args, key_args
dx, dy = args
# return a proc to make the info needed to instantiate/update
proc do |tkaroid, cos_r, sin_r|
x = tkaroid.x
y = tkaroid.y
params = tkaroid.params
ex = dx[params] rescue dx
ey = dy[params] rescue dy
points =
[ [ ex, ey],
[ ex, -ey],
[-ex, -ey],
[-ex, ey] ]
coords = []
points.each do |xv, yv|
coords << x + xv * cos_r - yv * sin_r
coords << y + xv * sin_r + yv * cos_r
end
## possible to skip below if no changes?
config = {}
handle_generic_config(config, params, key_args)
[TkcPolygon, coords, config]
end
end
|
ruby
|
def polybox args, key_args
dx, dy = args
# return a proc to make the info needed to instantiate/update
proc do |tkaroid, cos_r, sin_r|
x = tkaroid.x
y = tkaroid.y
params = tkaroid.params
ex = dx[params] rescue dx
ey = dy[params] rescue dy
points =
[ [ ex, ey],
[ ex, -ey],
[-ex, -ey],
[-ex, ey] ]
coords = []
points.each do |xv, yv|
coords << x + xv * cos_r - yv * sin_r
coords << y + xv * sin_r + yv * cos_r
end
## possible to skip below if no changes?
config = {}
handle_generic_config(config, params, key_args)
[TkcPolygon, coords, config]
end
end
|
[
"def",
"polybox",
"args",
",",
"key_args",
"dx",
",",
"dy",
"=",
"args",
"# return a proc to make the info needed to instantiate/update",
"proc",
"do",
"|",
"tkaroid",
",",
"cos_r",
",",
"sin_r",
"|",
"x",
"=",
"tkaroid",
".",
"x",
"y",
"=",
"tkaroid",
".",
"y",
"params",
"=",
"tkaroid",
".",
"params",
"ex",
"=",
"dx",
"[",
"params",
"]",
"rescue",
"dx",
"ey",
"=",
"dy",
"[",
"params",
"]",
"rescue",
"dy",
"points",
"=",
"[",
"[",
"ex",
",",
"ey",
"]",
",",
"[",
"ex",
",",
"-",
"ey",
"]",
",",
"[",
"-",
"ex",
",",
"-",
"ey",
"]",
",",
"[",
"-",
"ex",
",",
"ey",
"]",
"]",
"coords",
"=",
"[",
"]",
"points",
".",
"each",
"do",
"|",
"xv",
",",
"yv",
"|",
"coords",
"<<",
"x",
"+",
"xv",
"*",
"cos_r",
"-",
"yv",
"*",
"sin_r",
"coords",
"<<",
"y",
"+",
"xv",
"*",
"sin_r",
"+",
"yv",
"*",
"cos_r",
"end",
"## possible to skip below if no changes?",
"config",
"=",
"{",
"}",
"handle_generic_config",
"(",
"config",
",",
"params",
",",
"key_args",
")",
"[",
"TkcPolygon",
",",
"coords",
",",
"config",
"]",
"end",
"end"
] |
bitmap
anchor anchorPos
height pixels
width pixels
window pathName
def window args, key_args
x, y = args
end
An embedded window that shows a list of key-value pairs.
def proplist args, key_args
end
just a very simple example!
|
[
"bitmap",
"anchor",
"anchorPos",
"height",
"pixels",
"width",
"pixels",
"window",
"pathName",
"def",
"window",
"args",
"key_args",
"x",
"y",
"=",
"args"
] |
4c446bdcc028c0ec2fb858ea882717bd9908d9d0
|
https://github.com/vjoel/tkar/blob/4c446bdcc028c0ec2fb858ea882717bd9908d9d0/lib/tkar/primitives.rb#L344-L374
|
9,056
|
cordawyn/redlander
|
lib/redlander/model_proxy.rb
|
Redlander.ModelProxy.delete_all
|
def delete_all(pattern = {})
result = true
each(pattern) { |st| result &&= delete(st) }
result
end
|
ruby
|
def delete_all(pattern = {})
result = true
each(pattern) { |st| result &&= delete(st) }
result
end
|
[
"def",
"delete_all",
"(",
"pattern",
"=",
"{",
"}",
")",
"result",
"=",
"true",
"each",
"(",
"pattern",
")",
"{",
"|",
"st",
"|",
"result",
"&&=",
"delete",
"(",
"st",
")",
"}",
"result",
"end"
] |
Delete all statements from the model,
matching the given pattern
@param [Statement, Hash] pattern (see {#find})
@return [Boolean]
|
[
"Delete",
"all",
"statements",
"from",
"the",
"model",
"matching",
"the",
"given",
"pattern"
] |
a5c84e15a7602c674606e531bda6a616b1237c44
|
https://github.com/cordawyn/redlander/blob/a5c84e15a7602c674606e531bda6a616b1237c44/lib/redlander/model_proxy.rb#L52-L56
|
9,057
|
cordawyn/redlander
|
lib/redlander/model_proxy.rb
|
Redlander.ModelProxy.find
|
def find(scope, pattern = {})
case scope
when :first
each(pattern).first
when :all
each(pattern).to_a
else
raise RedlandError, "Invalid search scope '#{scope}' specified."
end
end
|
ruby
|
def find(scope, pattern = {})
case scope
when :first
each(pattern).first
when :all
each(pattern).to_a
else
raise RedlandError, "Invalid search scope '#{scope}' specified."
end
end
|
[
"def",
"find",
"(",
"scope",
",",
"pattern",
"=",
"{",
"}",
")",
"case",
"scope",
"when",
":first",
"each",
"(",
"pattern",
")",
".",
"first",
"when",
":all",
"each",
"(",
"pattern",
")",
".",
"to_a",
"else",
"raise",
"RedlandError",
",",
"\"Invalid search scope '#{scope}' specified.\"",
"end",
"end"
] |
Find statements satisfying the given criteria.
@param [:first, :all] scope find just one or all matches
@param [Hash, Statement] pattern matching pattern made of:
- Hash with :subject, :predicate or :object nodes, or
- "patternized" Statement (nil nodes are matching anything).
@return [Statement, Array, nil]
|
[
"Find",
"statements",
"satisfying",
"the",
"given",
"criteria",
"."
] |
a5c84e15a7602c674606e531bda6a616b1237c44
|
https://github.com/cordawyn/redlander/blob/a5c84e15a7602c674606e531bda6a616b1237c44/lib/redlander/model_proxy.rb#L127-L136
|
9,058
|
bbc/code_cache
|
lib/code_cache/repo.rb
|
CodeCache.Repo.location_in_cache
|
def location_in_cache( revision = nil )
begin
elements = [cache, repo_type, split_url, revision].flatten.compact.collect { |i| i.to_s }
File.join( elements )
rescue => e
raise CacheCalculationError.new(e.msg + e.backtrace.to_s)
end
end
|
ruby
|
def location_in_cache( revision = nil )
begin
elements = [cache, repo_type, split_url, revision].flatten.compact.collect { |i| i.to_s }
File.join( elements )
rescue => e
raise CacheCalculationError.new(e.msg + e.backtrace.to_s)
end
end
|
[
"def",
"location_in_cache",
"(",
"revision",
"=",
"nil",
")",
"begin",
"elements",
"=",
"[",
"cache",
",",
"repo_type",
",",
"split_url",
",",
"revision",
"]",
".",
"flatten",
".",
"compact",
".",
"collect",
"{",
"|",
"i",
"|",
"i",
".",
"to_s",
"}",
"File",
".",
"join",
"(",
"elements",
")",
"rescue",
"=>",
"e",
"raise",
"CacheCalculationError",
".",
"new",
"(",
"e",
".",
"msg",
"+",
"e",
".",
"backtrace",
".",
"to_s",
")",
"end",
"end"
] |
Calculates the location of a cached checkout
|
[
"Calculates",
"the",
"location",
"of",
"a",
"cached",
"checkout"
] |
69ab998898f9b0953da17117e8ee33e8e15dfc97
|
https://github.com/bbc/code_cache/blob/69ab998898f9b0953da17117e8ee33e8e15dfc97/lib/code_cache/repo.rb#L26-L33
|
9,059
|
ryansobol/mango
|
lib/mango/content_page.rb
|
Mango.ContentPage.method_missing
|
def method_missing(method_name, *args, &block)
key = method_name.to_s
attributes.has_key?(key) ? attributes[key] : super
end
|
ruby
|
def method_missing(method_name, *args, &block)
key = method_name.to_s
attributes.has_key?(key) ? attributes[key] : super
end
|
[
"def",
"method_missing",
"(",
"method_name",
",",
"*",
"args",
",",
"&",
"block",
")",
"key",
"=",
"method_name",
".",
"to_s",
"attributes",
".",
"has_key?",
"(",
"key",
")",
"?",
"attributes",
"[",
"key",
"]",
":",
"super",
"end"
] |
Adds syntactic suger for reading attributes.
@example
page.title == page.attributes["title"]
@param [Symbol] method_name
@param [Array] args
@param [Proc] block
@raise [NoMethodError] Raised when there is no method name key in attributes
@return [Object] Value of the method name attribute
|
[
"Adds",
"syntactic",
"suger",
"for",
"reading",
"attributes",
"."
] |
f28f1fb9ff2820f11e6b9f96cdd92576774da12f
|
https://github.com/ryansobol/mango/blob/f28f1fb9ff2820f11e6b9f96cdd92576774da12f/lib/mango/content_page.rb#L159-L162
|
9,060
|
eriksk/kawaii
|
lib/kawaii/content_manager.rb
|
Kawaii.ContentManager.load_image
|
def load_image(path, tileable = false)
if !@images[path]
@images[path] = Gosu::Image.new(@window, "#{@root}/#{path}", tileable)
end
@images[path]
end
|
ruby
|
def load_image(path, tileable = false)
if !@images[path]
@images[path] = Gosu::Image.new(@window, "#{@root}/#{path}", tileable)
end
@images[path]
end
|
[
"def",
"load_image",
"(",
"path",
",",
"tileable",
"=",
"false",
")",
"if",
"!",
"@images",
"[",
"path",
"]",
"@images",
"[",
"path",
"]",
"=",
"Gosu",
"::",
"Image",
".",
"new",
"(",
"@window",
",",
"\"#{@root}/#{path}\"",
",",
"tileable",
")",
"end",
"@images",
"[",
"path",
"]",
"end"
] |
loads an image and caches it for further use
if an image has been loaded it is just being returned
|
[
"loads",
"an",
"image",
"and",
"caches",
"it",
"for",
"further",
"use",
"if",
"an",
"image",
"has",
"been",
"loaded",
"it",
"is",
"just",
"being",
"returned"
] |
6779a50657a816f014d33b61314eaa3991982d13
|
https://github.com/eriksk/kawaii/blob/6779a50657a816f014d33b61314eaa3991982d13/lib/kawaii/content_manager.rb#L20-L25
|
9,061
|
xiuxian123/loyals
|
projects/mustache_render/lib/mustache_render/mustache.rb
|
MustacheRender.Mustache.partial
|
def partial(name)
name = self.class.generate_template_name name, config.file_template_extension
# return self.read_template_from_media name, media
@_cached_partials ||= {}
(@_cached_partials[media] ||= {})[name] ||= self.read_template_from_media name, media
end
|
ruby
|
def partial(name)
name = self.class.generate_template_name name, config.file_template_extension
# return self.read_template_from_media name, media
@_cached_partials ||= {}
(@_cached_partials[media] ||= {})[name] ||= self.read_template_from_media name, media
end
|
[
"def",
"partial",
"(",
"name",
")",
"name",
"=",
"self",
".",
"class",
".",
"generate_template_name",
"name",
",",
"config",
".",
"file_template_extension",
"# return self.read_template_from_media name, media",
"@_cached_partials",
"||=",
"{",
"}",
"(",
"@_cached_partials",
"[",
"media",
"]",
"||=",
"{",
"}",
")",
"[",
"name",
"]",
"||=",
"self",
".",
"read_template_from_media",
"name",
",",
"media",
"end"
] |
Override this in your subclass if you want to do fun things like
reading templates from a database. It will be rendered by the
context, so all you need to do is return a string.
|
[
"Override",
"this",
"in",
"your",
"subclass",
"if",
"you",
"want",
"to",
"do",
"fun",
"things",
"like",
"reading",
"templates",
"from",
"a",
"database",
".",
"It",
"will",
"be",
"rendered",
"by",
"the",
"context",
"so",
"all",
"you",
"need",
"to",
"do",
"is",
"return",
"a",
"string",
"."
] |
41f586ca1551f64e5375ad32a406d5fca0afae43
|
https://github.com/xiuxian123/loyals/blob/41f586ca1551f64e5375ad32a406d5fca0afae43/projects/mustache_render/lib/mustache_render/mustache.rb#L124-L130
|
9,062
|
maxim/has_price
|
lib/has_price/has_price.rb
|
HasPrice.HasPrice.has_price
|
def has_price(options = {}, &block)
attribute = options[:attribute] || :price
free = !block_given? && options[:free]
define_method attribute.to_sym do
builder = PriceBuilder.new self
builder.instance_eval &block unless free
builder.price
end
end
|
ruby
|
def has_price(options = {}, &block)
attribute = options[:attribute] || :price
free = !block_given? && options[:free]
define_method attribute.to_sym do
builder = PriceBuilder.new self
builder.instance_eval &block unless free
builder.price
end
end
|
[
"def",
"has_price",
"(",
"options",
"=",
"{",
"}",
",",
"&",
"block",
")",
"attribute",
"=",
"options",
"[",
":attribute",
"]",
"||",
":price",
"free",
"=",
"!",
"block_given?",
"&&",
"options",
"[",
":free",
"]",
"define_method",
"attribute",
".",
"to_sym",
"do",
"builder",
"=",
"PriceBuilder",
".",
"new",
"self",
"builder",
".",
"instance_eval",
"block",
"unless",
"free",
"builder",
".",
"price",
"end",
"end"
] |
Provides a simple DSL to defines price instance method on the receiver.
@param [Hash] options the options for creating price method.
@option options [Symbol] :attribute (:price) Name of the price method.
@option options [Boolean] :free (false) Set `:free => true` to use null object pattern.
@yield The yielded block provides method `item` for declaring price entries,
and method `group` for declaring price groups.
@example Normal usage
class Product < ActiveRecord::Base
has_price do
item base_price, "base"
item discount, "discount"
group "taxes" do
item federal_tax, "federal tax"
item state_tax, "state tax"
end
group "shipment" do
# Notice that delivery_method is an instance method.
# You can call instance methods anywhere in has_price block.
item delivery_price, delivery_method
end
end
end
@example Null object pattern
class Product < ActiveRecord::Base
# Creates method #price which returns empty Price.
has_price :free => true
end
@see PriceBuilder#item
@see PriceBuilder#group
|
[
"Provides",
"a",
"simple",
"DSL",
"to",
"defines",
"price",
"instance",
"method",
"on",
"the",
"receiver",
"."
] |
671c5c7463b0e6540cbb8ac3114da08b99c697bd
|
https://github.com/maxim/has_price/blob/671c5c7463b0e6540cbb8ac3114da08b99c697bd/lib/has_price/has_price.rb#L41-L50
|
9,063
|
octoai/gem-octocore-cassandra
|
lib/octocore-cassandra/scheduler.rb
|
Octo.Scheduler.schedule_counters
|
def schedule_counters
counter_classes = [
Octo::ProductHit,
Octo::CategoryHit,
Octo::TagHit,
Octo::ApiHit,
Octo::NewsfeedHit
]
counter_classes.each do |clazz|
clazz.send(:get_typecounters).each do |counter|
name = [clazz, counter].join('::')
config = {
class: clazz.to_s,
args: [counter],
cron: '* * * * *',
persist: true,
queue: 'high'
}
Resque.set_schedule name, config
end
end
# Schedules the processing of baselines
def schedule_baseline
baseline_classes = [
Octo::ProductBaseline,
Octo::CategoryBaseline,
Octo::TagBaseline
]
baseline_classes.each do |clazz|
clazz.send(:get_typecounters).each do |counter|
name = [clazz, counter].join('::')
config = {
class: clazz.to_s,
args: [counter],
cron: '* * * * *',
persists: true,
queue: 'baseline_processing'
}
Resque.set_schedule name, config
end
end
end
# Schedules the daily mail, to be sent at noon
def schedule_subscribermail
name = 'SubscriberDailyMailer'
config = {
class: Octo::Mailer::SubscriberMailer,
args: [],
cron: '0 0 * * *',
persist: true,
queue: 'subscriber_notifier'
}
Resque.set_schedule name, config
end
end
|
ruby
|
def schedule_counters
counter_classes = [
Octo::ProductHit,
Octo::CategoryHit,
Octo::TagHit,
Octo::ApiHit,
Octo::NewsfeedHit
]
counter_classes.each do |clazz|
clazz.send(:get_typecounters).each do |counter|
name = [clazz, counter].join('::')
config = {
class: clazz.to_s,
args: [counter],
cron: '* * * * *',
persist: true,
queue: 'high'
}
Resque.set_schedule name, config
end
end
# Schedules the processing of baselines
def schedule_baseline
baseline_classes = [
Octo::ProductBaseline,
Octo::CategoryBaseline,
Octo::TagBaseline
]
baseline_classes.each do |clazz|
clazz.send(:get_typecounters).each do |counter|
name = [clazz, counter].join('::')
config = {
class: clazz.to_s,
args: [counter],
cron: '* * * * *',
persists: true,
queue: 'baseline_processing'
}
Resque.set_schedule name, config
end
end
end
# Schedules the daily mail, to be sent at noon
def schedule_subscribermail
name = 'SubscriberDailyMailer'
config = {
class: Octo::Mailer::SubscriberMailer,
args: [],
cron: '0 0 * * *',
persist: true,
queue: 'subscriber_notifier'
}
Resque.set_schedule name, config
end
end
|
[
"def",
"schedule_counters",
"counter_classes",
"=",
"[",
"Octo",
"::",
"ProductHit",
",",
"Octo",
"::",
"CategoryHit",
",",
"Octo",
"::",
"TagHit",
",",
"Octo",
"::",
"ApiHit",
",",
"Octo",
"::",
"NewsfeedHit",
"]",
"counter_classes",
".",
"each",
"do",
"|",
"clazz",
"|",
"clazz",
".",
"send",
"(",
":get_typecounters",
")",
".",
"each",
"do",
"|",
"counter",
"|",
"name",
"=",
"[",
"clazz",
",",
"counter",
"]",
".",
"join",
"(",
"'::'",
")",
"config",
"=",
"{",
"class",
":",
"clazz",
".",
"to_s",
",",
"args",
":",
"[",
"counter",
"]",
",",
"cron",
":",
"'* * * * *'",
",",
"persist",
":",
"true",
",",
"queue",
":",
"'high'",
"}",
"Resque",
".",
"set_schedule",
"name",
",",
"config",
"end",
"end",
"# Schedules the processing of baselines",
"def",
"schedule_baseline",
"baseline_classes",
"=",
"[",
"Octo",
"::",
"ProductBaseline",
",",
"Octo",
"::",
"CategoryBaseline",
",",
"Octo",
"::",
"TagBaseline",
"]",
"baseline_classes",
".",
"each",
"do",
"|",
"clazz",
"|",
"clazz",
".",
"send",
"(",
":get_typecounters",
")",
".",
"each",
"do",
"|",
"counter",
"|",
"name",
"=",
"[",
"clazz",
",",
"counter",
"]",
".",
"join",
"(",
"'::'",
")",
"config",
"=",
"{",
"class",
":",
"clazz",
".",
"to_s",
",",
"args",
":",
"[",
"counter",
"]",
",",
"cron",
":",
"'* * * * *'",
",",
"persists",
":",
"true",
",",
"queue",
":",
"'baseline_processing'",
"}",
"Resque",
".",
"set_schedule",
"name",
",",
"config",
"end",
"end",
"end",
"# Schedules the daily mail, to be sent at noon",
"def",
"schedule_subscribermail",
"name",
"=",
"'SubscriberDailyMailer'",
"config",
"=",
"{",
"class",
":",
"Octo",
"::",
"Mailer",
"::",
"SubscriberMailer",
",",
"args",
":",
"[",
"]",
",",
"cron",
":",
"'0 0 * * *'",
",",
"persist",
":",
"true",
",",
"queue",
":",
"'subscriber_notifier'",
"}",
"Resque",
".",
"set_schedule",
"name",
",",
"config",
"end",
"end"
] |
Setup the schedules for counters.
|
[
"Setup",
"the",
"schedules",
"for",
"counters",
"."
] |
c0977dce5ba0eb174ff810f161aba151069935df
|
https://github.com/octoai/gem-octocore-cassandra/blob/c0977dce5ba0eb174ff810f161aba151069935df/lib/octocore-cassandra/scheduler.rb#L13-L70
|
9,064
|
influenza/hosties
|
lib/hosties/definitions.rb
|
Hosties.HasAttributes.have_attributes
|
def have_attributes(attr, *more)
sum = (more << attr)
sum.each do |name|
raise ArgumentError, "Reserved attribute name #{name}" if @verbotten.include?(name)
end
@attributes += sum
end
|
ruby
|
def have_attributes(attr, *more)
sum = (more << attr)
sum.each do |name|
raise ArgumentError, "Reserved attribute name #{name}" if @verbotten.include?(name)
end
@attributes += sum
end
|
[
"def",
"have_attributes",
"(",
"attr",
",",
"*",
"more",
")",
"sum",
"=",
"(",
"more",
"<<",
"attr",
")",
"sum",
".",
"each",
"do",
"|",
"name",
"|",
"raise",
"ArgumentError",
",",
"\"Reserved attribute name #{name}\"",
"if",
"@verbotten",
".",
"include?",
"(",
"name",
")",
"end",
"@attributes",
"+=",
"sum",
"end"
] |
Specify symbols that will later be reified into attributes
|
[
"Specify",
"symbols",
"that",
"will",
"later",
"be",
"reified",
"into",
"attributes"
] |
a3030cd4a23a23a0fcc2664c01a497b31e6e49fe
|
https://github.com/influenza/hosties/blob/a3030cd4a23a23a0fcc2664c01a497b31e6e49fe/lib/hosties/definitions.rb#L38-L44
|
9,065
|
influenza/hosties
|
lib/hosties/definitions.rb
|
Hosties.HasAttributes.where
|
def where(name)
# Must define the attributes before constraining them
raise ArgumentError, "Unknown attribute: #{name}" unless @attributes.include? name
@constraints[name] = AttributeConstraint.new(name)
end
|
ruby
|
def where(name)
# Must define the attributes before constraining them
raise ArgumentError, "Unknown attribute: #{name}" unless @attributes.include? name
@constraints[name] = AttributeConstraint.new(name)
end
|
[
"def",
"where",
"(",
"name",
")",
"# Must define the attributes before constraining them",
"raise",
"ArgumentError",
",",
"\"Unknown attribute: #{name}\"",
"unless",
"@attributes",
".",
"include?",
"name",
"@constraints",
"[",
"name",
"]",
"=",
"AttributeConstraint",
".",
"new",
"(",
"name",
")",
"end"
] |
Helpful method to define constraints
|
[
"Helpful",
"method",
"to",
"define",
"constraints"
] |
a3030cd4a23a23a0fcc2664c01a497b31e6e49fe
|
https://github.com/influenza/hosties/blob/a3030cd4a23a23a0fcc2664c01a497b31e6e49fe/lib/hosties/definitions.rb#L51-L55
|
9,066
|
influenza/hosties
|
lib/hosties/definitions.rb
|
Hosties.HasAttributes.valid?
|
def valid?(name, value)
if @constraints.include? name then
constraints[name].possible_vals.include? value
else true end
end
|
ruby
|
def valid?(name, value)
if @constraints.include? name then
constraints[name].possible_vals.include? value
else true end
end
|
[
"def",
"valid?",
"(",
"name",
",",
"value",
")",
"if",
"@constraints",
".",
"include?",
"name",
"then",
"constraints",
"[",
"name",
"]",
".",
"possible_vals",
".",
"include?",
"value",
"else",
"true",
"end",
"end"
] |
Check if a given name-value pair is valid given the constraints
|
[
"Check",
"if",
"a",
"given",
"name",
"-",
"value",
"pair",
"is",
"valid",
"given",
"the",
"constraints"
] |
a3030cd4a23a23a0fcc2664c01a497b31e6e49fe
|
https://github.com/influenza/hosties/blob/a3030cd4a23a23a0fcc2664c01a497b31e6e49fe/lib/hosties/definitions.rb#L58-L62
|
9,067
|
grappendorf/xbee-ruby
|
lib/xbee-ruby/xbee.rb
|
XBeeRuby.XBee.open
|
def open
@serial ||= SerialPort.new @port, @rate
@serial_input = Enumerator.new { |y| loop do
y.yield @serial.readbyte
end }
@connected = true
end
|
ruby
|
def open
@serial ||= SerialPort.new @port, @rate
@serial_input = Enumerator.new { |y| loop do
y.yield @serial.readbyte
end }
@connected = true
end
|
[
"def",
"open",
"@serial",
"||=",
"SerialPort",
".",
"new",
"@port",
",",
"@rate",
"@serial_input",
"=",
"Enumerator",
".",
"new",
"{",
"|",
"y",
"|",
"loop",
"do",
"y",
".",
"yield",
"@serial",
".",
"readbyte",
"end",
"}",
"@connected",
"=",
"true",
"end"
] |
Either specify the port and serial parameters
xbee = XBeeRuby::Xbee.new port: '/dev/ttyUSB0', rate: 9600
or pass in a SerialPort like object
xbee = XBeeRuby::XBee.new serial: some_serial_mockup_for_testing
|
[
"Either",
"specify",
"the",
"port",
"and",
"serial",
"parameters"
] |
dece2da12b7cd2973f82286c6659671b953030b8
|
https://github.com/grappendorf/xbee-ruby/blob/dece2da12b7cd2973f82286c6659671b953030b8/lib/xbee-ruby/xbee.rb#L33-L39
|
9,068
|
goncalvesjoao/usecasing_validations
|
lib/usecasing_validations.rb
|
UseCaseValidations.ClassMethods.inherited
|
def inherited(base)
dup = _validators.dup
base._validators = dup.each { |k, v| dup[k] = v.dup }
super
end
|
ruby
|
def inherited(base)
dup = _validators.dup
base._validators = dup.each { |k, v| dup[k] = v.dup }
super
end
|
[
"def",
"inherited",
"(",
"base",
")",
"dup",
"=",
"_validators",
".",
"dup",
"base",
".",
"_validators",
"=",
"dup",
".",
"each",
"{",
"|",
"k",
",",
"v",
"|",
"dup",
"[",
"k",
"]",
"=",
"v",
".",
"dup",
"}",
"super",
"end"
] |
Copy validators on inheritance.
|
[
"Copy",
"validators",
"on",
"inheritance",
"."
] |
97375b7ade94eaa7c138f4fd9e0cf24e56db343f
|
https://github.com/goncalvesjoao/usecasing_validations/blob/97375b7ade94eaa7c138f4fd9e0cf24e56db343f/lib/usecasing_validations.rb#L116-L120
|
9,069
|
michaeledgar/amp-front
|
lib/amp-front/third_party/maruku/toc.rb
|
MaRuKu.Section.numerate
|
def numerate(a=[])
self.section_number = a
section_children.each_with_index do |c,i|
c.numerate(a.clone.push(i+1))
end
if h = self.header_element
h.attributes[:section_number] = self.section_number
end
end
|
ruby
|
def numerate(a=[])
self.section_number = a
section_children.each_with_index do |c,i|
c.numerate(a.clone.push(i+1))
end
if h = self.header_element
h.attributes[:section_number] = self.section_number
end
end
|
[
"def",
"numerate",
"(",
"a",
"=",
"[",
"]",
")",
"self",
".",
"section_number",
"=",
"a",
"section_children",
".",
"each_with_index",
"do",
"|",
"c",
",",
"i",
"|",
"c",
".",
"numerate",
"(",
"a",
".",
"clone",
".",
"push",
"(",
"i",
"+",
"1",
")",
")",
"end",
"if",
"h",
"=",
"self",
".",
"header_element",
"h",
".",
"attributes",
"[",
":section_number",
"]",
"=",
"self",
".",
"section_number",
"end",
"end"
] |
Numerate this section and its children
|
[
"Numerate",
"this",
"section",
"and",
"its",
"children"
] |
d939b7ed9a7b0e5a3d26e536b95149f88b64e3a9
|
https://github.com/michaeledgar/amp-front/blob/d939b7ed9a7b0e5a3d26e536b95149f88b64e3a9/lib/amp-front/third_party/maruku/toc.rb#L70-L78
|
9,070
|
bclennox/acts_as_featured
|
lib/acts_as_featured.rb
|
ActsAsFeatured.ClassMethods.acts_as_featured
|
def acts_as_featured(attribute, options = {})
cattr_accessor :featured_attribute
cattr_accessor :featured_attribute_scope
self.featured_attribute = attribute
self.featured_attribute_scope = options[:scope] || false
if scope_name = options[:create_scope]
scope_name = attribute if scope_name == true
scope scope_name, -> { where(attribute => true).limit(1) }
end
before_save :remove_featured_from_other_records
after_save :add_featured_to_first_record
before_destroy :add_featured_to_first_record_if_featured
end
|
ruby
|
def acts_as_featured(attribute, options = {})
cattr_accessor :featured_attribute
cattr_accessor :featured_attribute_scope
self.featured_attribute = attribute
self.featured_attribute_scope = options[:scope] || false
if scope_name = options[:create_scope]
scope_name = attribute if scope_name == true
scope scope_name, -> { where(attribute => true).limit(1) }
end
before_save :remove_featured_from_other_records
after_save :add_featured_to_first_record
before_destroy :add_featured_to_first_record_if_featured
end
|
[
"def",
"acts_as_featured",
"(",
"attribute",
",",
"options",
"=",
"{",
"}",
")",
"cattr_accessor",
":featured_attribute",
"cattr_accessor",
":featured_attribute_scope",
"self",
".",
"featured_attribute",
"=",
"attribute",
"self",
".",
"featured_attribute_scope",
"=",
"options",
"[",
":scope",
"]",
"||",
"false",
"if",
"scope_name",
"=",
"options",
"[",
":create_scope",
"]",
"scope_name",
"=",
"attribute",
"if",
"scope_name",
"==",
"true",
"scope",
"scope_name",
",",
"->",
"{",
"where",
"(",
"attribute",
"=>",
"true",
")",
".",
"limit",
"(",
"1",
")",
"}",
"end",
"before_save",
":remove_featured_from_other_records",
"after_save",
":add_featured_to_first_record",
"before_destroy",
":add_featured_to_first_record_if_featured",
"end"
] |
Designates an attribute on this model to indicate "featuredness," where
only one record within a given scope may be featured at a time.
Pass in the name of the attribute and an options hash:
* <tt>:scope</tt> - If given, designates the scope in which this model is featured. This would typically be a <tt>belongs_to</tt> association.
* <tt>:create_scope</tt> - If <tt>true</tt>, creates a named scope using the name of the attribute given here. If it's a symbol, creates a named scope using that symbol.
class Project < ActiveRecord::Base
# no two Projects will ever have their @featured attributes set simultaneously
acts_as_featured :featured
end
class Photo < ActiveRecord::Base
# each account gets a favorite photo
belongs_to :account
acts_as_featured :favorite, :scope => :account
end
class Article < ActiveRecord::Base
# creates a named scope called Article.featured to return the featured article
acts_as_featured :main, :create_scope => :featured
end
|
[
"Designates",
"an",
"attribute",
"on",
"this",
"model",
"to",
"indicate",
"featuredness",
"where",
"only",
"one",
"record",
"within",
"a",
"given",
"scope",
"may",
"be",
"featured",
"at",
"a",
"time",
"."
] |
69f033dafa8a143f9cd90c90eaca39912f0a4ddc
|
https://github.com/bclennox/acts_as_featured/blob/69f033dafa8a143f9cd90c90eaca39912f0a4ddc/lib/acts_as_featured.rb#L31-L46
|
9,071
|
maxjacobson/todo_lint
|
lib/todo_lint/judge.rb
|
TodoLint.Judge.make_charge
|
def make_charge
if !todo.annotated?
"Missing due date annotation"
elsif todo.due_date.overdue? && todo.tag?
"Overdue due date #{todo.due_date.to_date} via tag"
elsif todo.due_date.overdue?
"Overdue due date"
end
end
|
ruby
|
def make_charge
if !todo.annotated?
"Missing due date annotation"
elsif todo.due_date.overdue? && todo.tag?
"Overdue due date #{todo.due_date.to_date} via tag"
elsif todo.due_date.overdue?
"Overdue due date"
end
end
|
[
"def",
"make_charge",
"if",
"!",
"todo",
".",
"annotated?",
"\"Missing due date annotation\"",
"elsif",
"todo",
".",
"due_date",
".",
"overdue?",
"&&",
"todo",
".",
"tag?",
"\"Overdue due date #{todo.due_date.to_date} via tag\"",
"elsif",
"todo",
".",
"due_date",
".",
"overdue?",
"\"Overdue due date\"",
"end",
"end"
] |
What is the problem with this todo?
@return [String] if there's a problem
@return [NilClass] if no charge needed
@api private
|
[
"What",
"is",
"the",
"problem",
"with",
"this",
"todo?"
] |
0d1061383ea205ef4c74edc64568e308ac1af990
|
https://github.com/maxjacobson/todo_lint/blob/0d1061383ea205ef4c74edc64568e308ac1af990/lib/todo_lint/judge.rb#L35-L43
|
9,072
|
jwtd/xively-rb-connector
|
lib/xively-rb-connector/datastream.rb
|
XivelyConnector.Datastream.<<
|
def <<(measurement)
# Make sure the value provided is a datapoint
datapoint = cast_to_datapoint(measurement)
# If only_save_changes is true, ignore datapoints whose value is the same as the current value
if only_save_changes and BigDecimal.new(datapoint.value) == BigDecimal.new(current_value)
@logger.debug "Ignoring datapoint from #{datapoint.at} because value did not change from #{current_value}"
else
@current_value = datapoint.value
datapoints << datapoint
@logger.debug "Queuing datapoint from #{datapoint.at} with value #{current_value}"
end
# See if the buffer is full
check_datapoints_buffer
end
|
ruby
|
def <<(measurement)
# Make sure the value provided is a datapoint
datapoint = cast_to_datapoint(measurement)
# If only_save_changes is true, ignore datapoints whose value is the same as the current value
if only_save_changes and BigDecimal.new(datapoint.value) == BigDecimal.new(current_value)
@logger.debug "Ignoring datapoint from #{datapoint.at} because value did not change from #{current_value}"
else
@current_value = datapoint.value
datapoints << datapoint
@logger.debug "Queuing datapoint from #{datapoint.at} with value #{current_value}"
end
# See if the buffer is full
check_datapoints_buffer
end
|
[
"def",
"<<",
"(",
"measurement",
")",
"# Make sure the value provided is a datapoint",
"datapoint",
"=",
"cast_to_datapoint",
"(",
"measurement",
")",
"# If only_save_changes is true, ignore datapoints whose value is the same as the current value",
"if",
"only_save_changes",
"and",
"BigDecimal",
".",
"new",
"(",
"datapoint",
".",
"value",
")",
"==",
"BigDecimal",
".",
"new",
"(",
"current_value",
")",
"@logger",
".",
"debug",
"\"Ignoring datapoint from #{datapoint.at} because value did not change from #{current_value}\"",
"else",
"@current_value",
"=",
"datapoint",
".",
"value",
"datapoints",
"<<",
"datapoint",
"@logger",
".",
"debug",
"\"Queuing datapoint from #{datapoint.at} with value #{current_value}\"",
"end",
"# See if the buffer is full",
"check_datapoints_buffer",
"end"
] |
Have shift operator load the datapoint into the datastream's datapoints array
|
[
"Have",
"shift",
"operator",
"load",
"the",
"datapoint",
"into",
"the",
"datastream",
"s",
"datapoints",
"array"
] |
014c2e08d2857e67d65103b84ba23a91569baecb
|
https://github.com/jwtd/xively-rb-connector/blob/014c2e08d2857e67d65103b84ba23a91569baecb/lib/xively-rb-connector/datastream.rb#L52-L67
|
9,073
|
jwtd/xively-rb-connector
|
lib/xively-rb-connector/datastream.rb
|
XivelyConnector.Datastream.cast_to_datapoint
|
def cast_to_datapoint(measurement, at=Time.now())
@logger.debug "cast_to_datapoint(#{measurement.inspect})"
if measurement.is_a?(Xively::Datapoint)
return measurement
elsif measurement.is_a?(Hash)
raise "The datapoint hash does not contain :at" unless measurement[:at]
raise "The datapoint hash does not contain :value" unless measurement[:value]
return Xively::Datapoint.new(measurement)
else
return Xively::Datapoint.new(:at => at, :value => measurement.to_s)
end
end
|
ruby
|
def cast_to_datapoint(measurement, at=Time.now())
@logger.debug "cast_to_datapoint(#{measurement.inspect})"
if measurement.is_a?(Xively::Datapoint)
return measurement
elsif measurement.is_a?(Hash)
raise "The datapoint hash does not contain :at" unless measurement[:at]
raise "The datapoint hash does not contain :value" unless measurement[:value]
return Xively::Datapoint.new(measurement)
else
return Xively::Datapoint.new(:at => at, :value => measurement.to_s)
end
end
|
[
"def",
"cast_to_datapoint",
"(",
"measurement",
",",
"at",
"=",
"Time",
".",
"now",
"(",
")",
")",
"@logger",
".",
"debug",
"\"cast_to_datapoint(#{measurement.inspect})\"",
"if",
"measurement",
".",
"is_a?",
"(",
"Xively",
"::",
"Datapoint",
")",
"return",
"measurement",
"elsif",
"measurement",
".",
"is_a?",
"(",
"Hash",
")",
"raise",
"\"The datapoint hash does not contain :at\"",
"unless",
"measurement",
"[",
":at",
"]",
"raise",
"\"The datapoint hash does not contain :value\"",
"unless",
"measurement",
"[",
":value",
"]",
"return",
"Xively",
"::",
"Datapoint",
".",
"new",
"(",
"measurement",
")",
"else",
"return",
"Xively",
"::",
"Datapoint",
".",
"new",
"(",
":at",
"=>",
"at",
",",
":value",
"=>",
"measurement",
".",
"to_s",
")",
"end",
"end"
] |
Converts a measurement to a Datapoint
|
[
"Converts",
"a",
"measurement",
"to",
"a",
"Datapoint"
] |
014c2e08d2857e67d65103b84ba23a91569baecb
|
https://github.com/jwtd/xively-rb-connector/blob/014c2e08d2857e67d65103b84ba23a91569baecb/lib/xively-rb-connector/datastream.rb#L70-L81
|
9,074
|
jwtd/xively-rb-connector
|
lib/xively-rb-connector/datastream.rb
|
XivelyConnector.Datastream.save_datapoints
|
def save_datapoints
@logger.debug "Saving #{datapoints.size} datapoints to the #{id} datastream"
response = XivelyConnector.connection.post("/v2/feeds/#{device.id}/datastreams/#{id}/datapoints",
:body => {:datapoints => datapoints}.to_json)
# If the response succeeded, clear the datapoint buffer and return the response object
if response.success?
clear_datapoints_buffer
response
else
logger.error response.response
raise response.response
end
end
|
ruby
|
def save_datapoints
@logger.debug "Saving #{datapoints.size} datapoints to the #{id} datastream"
response = XivelyConnector.connection.post("/v2/feeds/#{device.id}/datastreams/#{id}/datapoints",
:body => {:datapoints => datapoints}.to_json)
# If the response succeeded, clear the datapoint buffer and return the response object
if response.success?
clear_datapoints_buffer
response
else
logger.error response.response
raise response.response
end
end
|
[
"def",
"save_datapoints",
"@logger",
".",
"debug",
"\"Saving #{datapoints.size} datapoints to the #{id} datastream\"",
"response",
"=",
"XivelyConnector",
".",
"connection",
".",
"post",
"(",
"\"/v2/feeds/#{device.id}/datastreams/#{id}/datapoints\"",
",",
":body",
"=>",
"{",
":datapoints",
"=>",
"datapoints",
"}",
".",
"to_json",
")",
"# If the response succeeded, clear the datapoint buffer and return the response object",
"if",
"response",
".",
"success?",
"clear_datapoints_buffer",
"response",
"else",
"logger",
".",
"error",
"response",
".",
"response",
"raise",
"response",
".",
"response",
"end",
"end"
] |
Send the queued datapoints array to Xively
|
[
"Send",
"the",
"queued",
"datapoints",
"array",
"to",
"Xively"
] |
014c2e08d2857e67d65103b84ba23a91569baecb
|
https://github.com/jwtd/xively-rb-connector/blob/014c2e08d2857e67d65103b84ba23a91569baecb/lib/xively-rb-connector/datastream.rb#L84-L96
|
9,075
|
lexruee/coach4rb
|
lib/coach4rb/client.rb
|
Coach4rb.Client.put
|
def put(url, payload, options={}, &block)
http_options = options.merge(@basic_options)
if block_given?
RestClient.put(url, payload, http_options, &block)
else
RestClient.put(url, payload, http_options)
end
end
|
ruby
|
def put(url, payload, options={}, &block)
http_options = options.merge(@basic_options)
if block_given?
RestClient.put(url, payload, http_options, &block)
else
RestClient.put(url, payload, http_options)
end
end
|
[
"def",
"put",
"(",
"url",
",",
"payload",
",",
"options",
"=",
"{",
"}",
",",
"&",
"block",
")",
"http_options",
"=",
"options",
".",
"merge",
"(",
"@basic_options",
")",
"if",
"block_given?",
"RestClient",
".",
"put",
"(",
"url",
",",
"payload",
",",
"http_options",
",",
"block",
")",
"else",
"RestClient",
".",
"put",
"(",
"url",
",",
"payload",
",",
"http_options",
")",
"end",
"end"
] |
Performs a put request.
@param [String] url
@param [String] payload
@param [Block] block
@return [String] the payload of the response as string
|
[
"Performs",
"a",
"put",
"request",
"."
] |
59105bfe45a0717e655e0deff4d1540d511f6b02
|
https://github.com/lexruee/coach4rb/blob/59105bfe45a0717e655e0deff4d1540d511f6b02/lib/coach4rb/client.rb#L70-L78
|
9,076
|
lexruee/coach4rb
|
lib/coach4rb/client.rb
|
Coach4rb.Client.delete
|
def delete(url, options={}, &block)
http_options = options.merge(@basic_options)
if block_given?
RestClient.delete(url, http_options, &block)
else
RestClient.delete(url, http_options)
end
end
|
ruby
|
def delete(url, options={}, &block)
http_options = options.merge(@basic_options)
if block_given?
RestClient.delete(url, http_options, &block)
else
RestClient.delete(url, http_options)
end
end
|
[
"def",
"delete",
"(",
"url",
",",
"options",
"=",
"{",
"}",
",",
"&",
"block",
")",
"http_options",
"=",
"options",
".",
"merge",
"(",
"@basic_options",
")",
"if",
"block_given?",
"RestClient",
".",
"delete",
"(",
"url",
",",
"http_options",
",",
"block",
")",
"else",
"RestClient",
".",
"delete",
"(",
"url",
",",
"http_options",
")",
"end",
"end"
] |
Performs a delete request.
@param [String] url
@param [Hash] options
@param [Block] block
@return [String] the payload of the response as string
|
[
"Performs",
"a",
"delete",
"request",
"."
] |
59105bfe45a0717e655e0deff4d1540d511f6b02
|
https://github.com/lexruee/coach4rb/blob/59105bfe45a0717e655e0deff4d1540d511f6b02/lib/coach4rb/client.rb#L105-L112
|
9,077
|
goncalvesjoao/object_attorney
|
lib/object_attorney/class_methods.rb
|
ObjectAttorney.ClassMethods.inherited
|
def inherited(base)
base.allegations = allegations.clone
base.defendant_options = defendant_options.clone
super
end
|
ruby
|
def inherited(base)
base.allegations = allegations.clone
base.defendant_options = defendant_options.clone
super
end
|
[
"def",
"inherited",
"(",
"base",
")",
"base",
".",
"allegations",
"=",
"allegations",
".",
"clone",
"base",
".",
"defendant_options",
"=",
"defendant_options",
".",
"clone",
"super",
"end"
] |
Copy allegations on inheritance.
|
[
"Copy",
"allegations",
"on",
"inheritance",
"."
] |
d3e3f3916460010c793d7e3b4cb89eb974d4e88d
|
https://github.com/goncalvesjoao/object_attorney/blob/d3e3f3916460010c793d7e3b4cb89eb974d4e88d/lib/object_attorney/class_methods.rb#L39-L44
|
9,078
|
wwidea/rexport
|
lib/rexport/export_methods.rb
|
Rexport.ExportMethods.to_s
|
def to_s
String.new.tap do |result|
result << header * '|' << "\n"
records.each do |record|
result << record * '|' << "\n"
end
end
end
|
ruby
|
def to_s
String.new.tap do |result|
result << header * '|' << "\n"
records.each do |record|
result << record * '|' << "\n"
end
end
end
|
[
"def",
"to_s",
"String",
".",
"new",
".",
"tap",
"do",
"|",
"result",
"|",
"result",
"<<",
"header",
"*",
"'|'",
"<<",
"\"\\n\"",
"records",
".",
"each",
"do",
"|",
"record",
"|",
"result",
"<<",
"record",
"*",
"'|'",
"<<",
"\"\\n\"",
"end",
"end",
"end"
] |
Returns a string with the export data
|
[
"Returns",
"a",
"string",
"with",
"the",
"export",
"data"
] |
f4f978dd0327ddba3a4318dd24090fbc6d4e4e59
|
https://github.com/wwidea/rexport/blob/f4f978dd0327ddba3a4318dd24090fbc6d4e4e59/lib/rexport/export_methods.rb#L30-L37
|
9,079
|
wwidea/rexport
|
lib/rexport/export_methods.rb
|
Rexport.ExportMethods.to_csv
|
def to_csv(objects = nil)
seed_records(objects) unless objects.nil?
CSV.generate do |csv|
csv << header
records.each do |record|
csv << record
end
end
end
|
ruby
|
def to_csv(objects = nil)
seed_records(objects) unless objects.nil?
CSV.generate do |csv|
csv << header
records.each do |record|
csv << record
end
end
end
|
[
"def",
"to_csv",
"(",
"objects",
"=",
"nil",
")",
"seed_records",
"(",
"objects",
")",
"unless",
"objects",
".",
"nil?",
"CSV",
".",
"generate",
"do",
"|",
"csv",
"|",
"csv",
"<<",
"header",
"records",
".",
"each",
"do",
"|",
"record",
"|",
"csv",
"<<",
"record",
"end",
"end",
"end"
] |
Returns a csv string with the export data
|
[
"Returns",
"a",
"csv",
"string",
"with",
"the",
"export",
"data"
] |
f4f978dd0327ddba3a4318dd24090fbc6d4e4e59
|
https://github.com/wwidea/rexport/blob/f4f978dd0327ddba3a4318dd24090fbc6d4e4e59/lib/rexport/export_methods.rb#L40-L48
|
9,080
|
wwidea/rexport
|
lib/rexport/export_methods.rb
|
Rexport.ExportMethods.get_klass_from_path
|
def get_klass_from_path(path, klass = export_model)
return klass unless (association_name = path.shift)
get_klass_from_path(path, klass.reflect_on_association(association_name.to_sym).klass)
end
|
ruby
|
def get_klass_from_path(path, klass = export_model)
return klass unless (association_name = path.shift)
get_klass_from_path(path, klass.reflect_on_association(association_name.to_sym).klass)
end
|
[
"def",
"get_klass_from_path",
"(",
"path",
",",
"klass",
"=",
"export_model",
")",
"return",
"klass",
"unless",
"(",
"association_name",
"=",
"path",
".",
"shift",
")",
"get_klass_from_path",
"(",
"path",
",",
"klass",
".",
"reflect_on_association",
"(",
"association_name",
".",
"to_sym",
")",
".",
"klass",
")",
"end"
] |
Returns a class based on a path array
|
[
"Returns",
"a",
"class",
"based",
"on",
"a",
"path",
"array"
] |
f4f978dd0327ddba3a4318dd24090fbc6d4e4e59
|
https://github.com/wwidea/rexport/blob/f4f978dd0327ddba3a4318dd24090fbc6d4e4e59/lib/rexport/export_methods.rb#L76-L79
|
9,081
|
lizconlan/diffable
|
lib/diffable.rb
|
Diffable.InstanceMethods.diff
|
def diff(other)
check_class_compatibility(self, other)
self_attribs = self.get_attributes(self.class.excluded_fields)
other_attribs = other.get_attributes(other.class.excluded_fields)
change = compare_objects(self_attribs, other_attribs, self, other)
#the last bit - no change, no report; simples
if other.class.conditional_fields
other.class.conditional_fields.each do |key|
change[key.to_sym] = eval("other.#{key}") unless change.empty?
end
end
change
end
|
ruby
|
def diff(other)
check_class_compatibility(self, other)
self_attribs = self.get_attributes(self.class.excluded_fields)
other_attribs = other.get_attributes(other.class.excluded_fields)
change = compare_objects(self_attribs, other_attribs, self, other)
#the last bit - no change, no report; simples
if other.class.conditional_fields
other.class.conditional_fields.each do |key|
change[key.to_sym] = eval("other.#{key}") unless change.empty?
end
end
change
end
|
[
"def",
"diff",
"(",
"other",
")",
"check_class_compatibility",
"(",
"self",
",",
"other",
")",
"self_attribs",
"=",
"self",
".",
"get_attributes",
"(",
"self",
".",
"class",
".",
"excluded_fields",
")",
"other_attribs",
"=",
"other",
".",
"get_attributes",
"(",
"other",
".",
"class",
".",
"excluded_fields",
")",
"change",
"=",
"compare_objects",
"(",
"self_attribs",
",",
"other_attribs",
",",
"self",
",",
"other",
")",
"#the last bit - no change, no report; simples",
"if",
"other",
".",
"class",
".",
"conditional_fields",
"other",
".",
"class",
".",
"conditional_fields",
".",
"each",
"do",
"|",
"key",
"|",
"change",
"[",
"key",
".",
"to_sym",
"]",
"=",
"eval",
"(",
"\"other.#{key}\"",
")",
"unless",
"change",
".",
"empty?",
"end",
"end",
"change",
"end"
] |
Produces a Hash containing the differences between the calling object
and the object passed in as a parameter
|
[
"Produces",
"a",
"Hash",
"containing",
"the",
"differences",
"between",
"the",
"calling",
"object",
"and",
"the",
"object",
"passed",
"in",
"as",
"a",
"parameter"
] |
c9920a97841205b856c720777eb2bab43793a9ed
|
https://github.com/lizconlan/diffable/blob/c9920a97841205b856c720777eb2bab43793a9ed/lib/diffable.rb#L22-L37
|
9,082
|
lizconlan/diffable
|
lib/diffable.rb
|
Diffable.InstanceMethods.get_attributes
|
def get_attributes(excluded)
attribs = attributes.dup
attribs.delete_if { |key, value|
(!excluded.nil? and excluded.include?(key)) or key == "id" }
end
|
ruby
|
def get_attributes(excluded)
attribs = attributes.dup
attribs.delete_if { |key, value|
(!excluded.nil? and excluded.include?(key)) or key == "id" }
end
|
[
"def",
"get_attributes",
"(",
"excluded",
")",
"attribs",
"=",
"attributes",
".",
"dup",
"attribs",
".",
"delete_if",
"{",
"|",
"key",
",",
"value",
"|",
"(",
"!",
"excluded",
".",
"nil?",
"and",
"excluded",
".",
"include?",
"(",
"key",
")",
")",
"or",
"key",
"==",
"\"id\"",
"}",
"end"
] |
Fetches the attributes of the calling object, exluding the +id+ field
and any fields specified passed as an array of symbols via the +excluded+
parameter
|
[
"Fetches",
"the",
"attributes",
"of",
"the",
"calling",
"object",
"exluding",
"the",
"+",
"id",
"+",
"field",
"and",
"any",
"fields",
"specified",
"passed",
"as",
"an",
"array",
"of",
"symbols",
"via",
"the",
"+",
"excluded",
"+",
"parameter"
] |
c9920a97841205b856c720777eb2bab43793a9ed
|
https://github.com/lizconlan/diffable/blob/c9920a97841205b856c720777eb2bab43793a9ed/lib/diffable.rb#L43-L47
|
9,083
|
lizconlan/diffable
|
lib/diffable.rb
|
Diffable.InstanceMethods.reflected_names
|
def reflected_names(obj)
classes = obj.reflections
class_names = []
classes.each do |key, cl|
if eval(cl.class_name).respond_to?("diffable") \
and cl.association_class != ActiveRecord::Associations::BelongsToAssociation
class_names << key
end
end
class_names
end
|
ruby
|
def reflected_names(obj)
classes = obj.reflections
class_names = []
classes.each do |key, cl|
if eval(cl.class_name).respond_to?("diffable") \
and cl.association_class != ActiveRecord::Associations::BelongsToAssociation
class_names << key
end
end
class_names
end
|
[
"def",
"reflected_names",
"(",
"obj",
")",
"classes",
"=",
"obj",
".",
"reflections",
"class_names",
"=",
"[",
"]",
"classes",
".",
"each",
"do",
"|",
"key",
",",
"cl",
"|",
"if",
"eval",
"(",
"cl",
".",
"class_name",
")",
".",
"respond_to?",
"(",
"\"diffable\"",
")",
"and",
"cl",
".",
"association_class",
"!=",
"ActiveRecord",
"::",
"Associations",
"::",
"BelongsToAssociation",
"class_names",
"<<",
"key",
"end",
"end",
"class_names",
"end"
] |
Uses reflection to fetch the eligible associated objects for the current
object, excluding parent objects and child objects that do not include
the Diffable mixin
|
[
"Uses",
"reflection",
"to",
"fetch",
"the",
"eligible",
"associated",
"objects",
"for",
"the",
"current",
"object",
"excluding",
"parent",
"objects",
"and",
"child",
"objects",
"that",
"do",
"not",
"include",
"the",
"Diffable",
"mixin"
] |
c9920a97841205b856c720777eb2bab43793a9ed
|
https://github.com/lizconlan/diffable/blob/c9920a97841205b856c720777eb2bab43793a9ed/lib/diffable.rb#L53-L63
|
9,084
|
MakarovCode/EasyPayULatam
|
lib/easy_pay_u_latam/r_api/subscription_service.rb
|
PayuLatam.SubscriptionService.plan
|
def plan
# si el usuario no tiene plan_id en su modelo, se le asigna el plan_id seleccionado en el formulario
# recordar que ese plan_id llega en los params del contexto y por tanto tenemos acceso a el
# como variable de clase @plan_id
if @current_user.plan_id.nil?
if @plan_id.nil?
raise StandardError, 'Error creando plan, plan_id null'
end
# se almacena en el user
@current_user.update_attribute(:plan_id, @plan_id)
# despues de tenerlo almacenado en la bd, llamamos nuevamente este metodo plan
plan
else
# el usuario tiene un plan_id asignado, se le actualiza el plan_id en caso de que haya seleccionado uno
# diferente al que tiene actualmente
@current_user.update_attribute(:plan_id, @plan_id)
# obtener informacion del plan de la BD
plan_db = @current_user.plan
#
# NOTA: los planes deben tener un plan_code es OBLIGATORIO para el buen funcionamiento
#
if plan_db.plan_code.nil? || plan_db.plan_code.empty?
raise StandardError, 'Error creando plan, code null'
end
# con el plan_code lo buscamos en payu
plan_payu = PayuLatam::Plan.new(plan_db.plan_code)
# si existe?
if plan_payu.success?
# llenar la variable plan con la instancia de clase PayuLatam:Plan
@plan = plan_payu
else
# si no existe en pyu, crearlo con el metodo del modelo plan
plan_db.create_payu_plan
# llamado recursivo
plan
end
end
end
|
ruby
|
def plan
# si el usuario no tiene plan_id en su modelo, se le asigna el plan_id seleccionado en el formulario
# recordar que ese plan_id llega en los params del contexto y por tanto tenemos acceso a el
# como variable de clase @plan_id
if @current_user.plan_id.nil?
if @plan_id.nil?
raise StandardError, 'Error creando plan, plan_id null'
end
# se almacena en el user
@current_user.update_attribute(:plan_id, @plan_id)
# despues de tenerlo almacenado en la bd, llamamos nuevamente este metodo plan
plan
else
# el usuario tiene un plan_id asignado, se le actualiza el plan_id en caso de que haya seleccionado uno
# diferente al que tiene actualmente
@current_user.update_attribute(:plan_id, @plan_id)
# obtener informacion del plan de la BD
plan_db = @current_user.plan
#
# NOTA: los planes deben tener un plan_code es OBLIGATORIO para el buen funcionamiento
#
if plan_db.plan_code.nil? || plan_db.plan_code.empty?
raise StandardError, 'Error creando plan, code null'
end
# con el plan_code lo buscamos en payu
plan_payu = PayuLatam::Plan.new(plan_db.plan_code)
# si existe?
if plan_payu.success?
# llenar la variable plan con la instancia de clase PayuLatam:Plan
@plan = plan_payu
else
# si no existe en pyu, crearlo con el metodo del modelo plan
plan_db.create_payu_plan
# llamado recursivo
plan
end
end
end
|
[
"def",
"plan",
"# si el usuario no tiene plan_id en su modelo, se le asigna el plan_id seleccionado en el formulario",
"# recordar que ese plan_id llega en los params del contexto y por tanto tenemos acceso a el",
"# como variable de clase @plan_id",
"if",
"@current_user",
".",
"plan_id",
".",
"nil?",
"if",
"@plan_id",
".",
"nil?",
"raise",
"StandardError",
",",
"'Error creando plan, plan_id null'",
"end",
"# se almacena en el user",
"@current_user",
".",
"update_attribute",
"(",
":plan_id",
",",
"@plan_id",
")",
"# despues de tenerlo almacenado en la bd, llamamos nuevamente este metodo plan",
"plan",
"else",
"# el usuario tiene un plan_id asignado, se le actualiza el plan_id en caso de que haya seleccionado uno",
"# diferente al que tiene actualmente",
"@current_user",
".",
"update_attribute",
"(",
":plan_id",
",",
"@plan_id",
")",
"# obtener informacion del plan de la BD",
"plan_db",
"=",
"@current_user",
".",
"plan",
"#",
"# NOTA: los planes deben tener un plan_code es OBLIGATORIO para el buen funcionamiento",
"#",
"if",
"plan_db",
".",
"plan_code",
".",
"nil?",
"||",
"plan_db",
".",
"plan_code",
".",
"empty?",
"raise",
"StandardError",
",",
"'Error creando plan, code null'",
"end",
"# con el plan_code lo buscamos en payu",
"plan_payu",
"=",
"PayuLatam",
"::",
"Plan",
".",
"new",
"(",
"plan_db",
".",
"plan_code",
")",
"# si existe?",
"if",
"plan_payu",
".",
"success?",
"# llenar la variable plan con la instancia de clase PayuLatam:Plan",
"@plan",
"=",
"plan_payu",
"else",
"# si no existe en pyu, crearlo con el metodo del modelo plan",
"plan_db",
".",
"create_payu_plan",
"# llamado recursivo",
"plan",
"end",
"end",
"end"
] |
crea o carga un plan en un cliente de payu
se utiliza el current_user, el payu_id del cliente y el plan_code del plan
|
[
"crea",
"o",
"carga",
"un",
"plan",
"en",
"un",
"cliente",
"de",
"payu",
"se",
"utiliza",
"el",
"current_user",
"el",
"payu_id",
"del",
"cliente",
"y",
"el",
"plan_code",
"del",
"plan"
] |
c412b36fc316eabc338ce9cd152b8fea7316983d
|
https://github.com/MakarovCode/EasyPayULatam/blob/c412b36fc316eabc338ce9cd152b8fea7316983d/lib/easy_pay_u_latam/r_api/subscription_service.rb#L47-L85
|
9,085
|
MakarovCode/EasyPayULatam
|
lib/easy_pay_u_latam/r_api/subscription_service.rb
|
PayuLatam.SubscriptionService.create_card
|
def create_card
raise StandardError, 'Cliente null' if @client.nil?
# la instancia de card recibe como parametro el @client al que se le va asociar la tarjeta
card = PayuLatam::Card.new(@client)
# hay un metodo card_params que genera el objeto a enviar con los datos correctos
# se asignan los params correctos para la peticion
card.params.merge! card_params
# intento de creacion de tarjeta
card.create!
# si todo bien
if card.success?
# se llena la variable @card con la instancia de la clase PayuLatam::Card
@card = card
# no me acuerdo XD
@client.remove_cards
# se agrega la tarjeta al array de tarjetas del usuario. Ojo este array esta en memoria no necesariamente
# es el mismo array de payu
@client.add_card( card.response )
# la respuesta de creacion de payu solo incluye el token de la tarjeta, entonces
# volvemos a consultar la info almacenada en payu para recibier un poco mas de detalle y almacenarlo
_card = card.load(card.response['token'])
# se crea un registro de payu_card con la info publica de la tarjeta y el token de payu de la tarjeta
@current_user.payu_cards.create(token: @card.response['token'], last_4: _card['number'], brand: _card['type'])
else
raise StandardError, "Error generando token de tarjeta: #{card.error}"
end
end
|
ruby
|
def create_card
raise StandardError, 'Cliente null' if @client.nil?
# la instancia de card recibe como parametro el @client al que se le va asociar la tarjeta
card = PayuLatam::Card.new(@client)
# hay un metodo card_params que genera el objeto a enviar con los datos correctos
# se asignan los params correctos para la peticion
card.params.merge! card_params
# intento de creacion de tarjeta
card.create!
# si todo bien
if card.success?
# se llena la variable @card con la instancia de la clase PayuLatam::Card
@card = card
# no me acuerdo XD
@client.remove_cards
# se agrega la tarjeta al array de tarjetas del usuario. Ojo este array esta en memoria no necesariamente
# es el mismo array de payu
@client.add_card( card.response )
# la respuesta de creacion de payu solo incluye el token de la tarjeta, entonces
# volvemos a consultar la info almacenada en payu para recibier un poco mas de detalle y almacenarlo
_card = card.load(card.response['token'])
# se crea un registro de payu_card con la info publica de la tarjeta y el token de payu de la tarjeta
@current_user.payu_cards.create(token: @card.response['token'], last_4: _card['number'], brand: _card['type'])
else
raise StandardError, "Error generando token de tarjeta: #{card.error}"
end
end
|
[
"def",
"create_card",
"raise",
"StandardError",
",",
"'Cliente null'",
"if",
"@client",
".",
"nil?",
"# la instancia de card recibe como parametro el @client al que se le va asociar la tarjeta",
"card",
"=",
"PayuLatam",
"::",
"Card",
".",
"new",
"(",
"@client",
")",
"# hay un metodo card_params que genera el objeto a enviar con los datos correctos",
"# se asignan los params correctos para la peticion",
"card",
".",
"params",
".",
"merge!",
"card_params",
"# intento de creacion de tarjeta",
"card",
".",
"create!",
"# si todo bien",
"if",
"card",
".",
"success?",
"# se llena la variable @card con la instancia de la clase PayuLatam::Card",
"@card",
"=",
"card",
"# no me acuerdo XD",
"@client",
".",
"remove_cards",
"# se agrega la tarjeta al array de tarjetas del usuario. Ojo este array esta en memoria no necesariamente",
"# es el mismo array de payu",
"@client",
".",
"add_card",
"(",
"card",
".",
"response",
")",
"# la respuesta de creacion de payu solo incluye el token de la tarjeta, entonces",
"# volvemos a consultar la info almacenada en payu para recibier un poco mas de detalle y almacenarlo",
"_card",
"=",
"card",
".",
"load",
"(",
"card",
".",
"response",
"[",
"'token'",
"]",
")",
"# se crea un registro de payu_card con la info publica de la tarjeta y el token de payu de la tarjeta",
"@current_user",
".",
"payu_cards",
".",
"create",
"(",
"token",
":",
"@card",
".",
"response",
"[",
"'token'",
"]",
",",
"last_4",
":",
"_card",
"[",
"'number'",
"]",
",",
"brand",
":",
"_card",
"[",
"'type'",
"]",
")",
"else",
"raise",
"StandardError",
",",
"\"Error generando token de tarjeta: #{card.error}\"",
"end",
"end"
] |
crear tarjeta de credito en payu
utiliza los params recibidos
|
[
"crear",
"tarjeta",
"de",
"credito",
"en",
"payu",
"utiliza",
"los",
"params",
"recibidos"
] |
c412b36fc316eabc338ce9cd152b8fea7316983d
|
https://github.com/MakarovCode/EasyPayULatam/blob/c412b36fc316eabc338ce9cd152b8fea7316983d/lib/easy_pay_u_latam/r_api/subscription_service.rb#L94-L124
|
9,086
|
MakarovCode/EasyPayULatam
|
lib/easy_pay_u_latam/r_api/subscription_service.rb
|
PayuLatam.SubscriptionService.find_card
|
def find_card
@client.remove_cards
card = PayuLatam::Card.new(@client) # info de payu
card.load( PayuCard.find(@selected_card).token )
@client.add_card({token: card.resource['token']})
end
|
ruby
|
def find_card
@client.remove_cards
card = PayuLatam::Card.new(@client) # info de payu
card.load( PayuCard.find(@selected_card).token )
@client.add_card({token: card.resource['token']})
end
|
[
"def",
"find_card",
"@client",
".",
"remove_cards",
"card",
"=",
"PayuLatam",
"::",
"Card",
".",
"new",
"(",
"@client",
")",
"# info de payu",
"card",
".",
"load",
"(",
"PayuCard",
".",
"find",
"(",
"@selected_card",
")",
".",
"token",
")",
"@client",
".",
"add_card",
"(",
"{",
"token",
":",
"card",
".",
"resource",
"[",
"'token'",
"]",
"}",
")",
"end"
] |
busca la info de una tarjeta de payu
|
[
"busca",
"la",
"info",
"de",
"una",
"tarjeta",
"de",
"payu"
] |
c412b36fc316eabc338ce9cd152b8fea7316983d
|
https://github.com/MakarovCode/EasyPayULatam/blob/c412b36fc316eabc338ce9cd152b8fea7316983d/lib/easy_pay_u_latam/r_api/subscription_service.rb#L144-L149
|
9,087
|
nebiros/dm-paginator
|
lib/dm-paginator/paginator.rb
|
DataMapper.Paginator.limit
|
def limit options = {}
# Remove this key if we come from limit_page method.
page = options.delete :page
query = options.dup
collection = new_collection scoped_query( options = {
:limit => options[:limit],
:offset => options[:offset],
:order => [options[:order]]
}.merge( query ) )
options.merge! :count => calculate_total_records( query ), :page => page
collection.paginator = DataMapper::Paginator::Main.new options
collection
end
|
ruby
|
def limit options = {}
# Remove this key if we come from limit_page method.
page = options.delete :page
query = options.dup
collection = new_collection scoped_query( options = {
:limit => options[:limit],
:offset => options[:offset],
:order => [options[:order]]
}.merge( query ) )
options.merge! :count => calculate_total_records( query ), :page => page
collection.paginator = DataMapper::Paginator::Main.new options
collection
end
|
[
"def",
"limit",
"options",
"=",
"{",
"}",
"# Remove this key if we come from limit_page method.",
"page",
"=",
"options",
".",
"delete",
":page",
"query",
"=",
"options",
".",
"dup",
"collection",
"=",
"new_collection",
"scoped_query",
"(",
"options",
"=",
"{",
":limit",
"=>",
"options",
"[",
":limit",
"]",
",",
":offset",
"=>",
"options",
"[",
":offset",
"]",
",",
":order",
"=>",
"[",
"options",
"[",
":order",
"]",
"]",
"}",
".",
"merge",
"(",
"query",
")",
")",
"options",
".",
"merge!",
":count",
"=>",
"calculate_total_records",
"(",
"query",
")",
",",
":page",
"=>",
"page",
"collection",
".",
"paginator",
"=",
"DataMapper",
"::",
"Paginator",
"::",
"Main",
".",
"new",
"options",
"collection",
"end"
] |
Limit results.
@param [Hash] options
@return [Collection]
|
[
"Limit",
"results",
"."
] |
e7486cce5c3712227b7eeef3ff76c1025c70d146
|
https://github.com/nebiros/dm-paginator/blob/e7486cce5c3712227b7eeef3ff76c1025c70d146/lib/dm-paginator/paginator.rb#L10-L22
|
9,088
|
nebiros/dm-paginator
|
lib/dm-paginator/paginator.rb
|
DataMapper.Paginator.limit_page
|
def limit_page page = nil, options = {}
if page.is_a?( Hash )
options = page
else
options[:page] = page.to_i
end
options[:page] = options[:page].to_i > 0 ? options[:page] : DataMapper::Paginator.default[:page]
options[:limit] = options[:limit].to_i || DataMapper::Paginator.default[:limit]
options[:offset] = options[:limit] * ( options[:page] - 1 )
options[:order] = options[:order] || DataMapper::Paginator.default[:order]
limit options
end
|
ruby
|
def limit_page page = nil, options = {}
if page.is_a?( Hash )
options = page
else
options[:page] = page.to_i
end
options[:page] = options[:page].to_i > 0 ? options[:page] : DataMapper::Paginator.default[:page]
options[:limit] = options[:limit].to_i || DataMapper::Paginator.default[:limit]
options[:offset] = options[:limit] * ( options[:page] - 1 )
options[:order] = options[:order] || DataMapper::Paginator.default[:order]
limit options
end
|
[
"def",
"limit_page",
"page",
"=",
"nil",
",",
"options",
"=",
"{",
"}",
"if",
"page",
".",
"is_a?",
"(",
"Hash",
")",
"options",
"=",
"page",
"else",
"options",
"[",
":page",
"]",
"=",
"page",
".",
"to_i",
"end",
"options",
"[",
":page",
"]",
"=",
"options",
"[",
":page",
"]",
".",
"to_i",
">",
"0",
"?",
"options",
"[",
":page",
"]",
":",
"DataMapper",
"::",
"Paginator",
".",
"default",
"[",
":page",
"]",
"options",
"[",
":limit",
"]",
"=",
"options",
"[",
":limit",
"]",
".",
"to_i",
"||",
"DataMapper",
"::",
"Paginator",
".",
"default",
"[",
":limit",
"]",
"options",
"[",
":offset",
"]",
"=",
"options",
"[",
":limit",
"]",
"*",
"(",
"options",
"[",
":page",
"]",
"-",
"1",
")",
"options",
"[",
":order",
"]",
"=",
"options",
"[",
":order",
"]",
"||",
"DataMapper",
"::",
"Paginator",
".",
"default",
"[",
":order",
"]",
"limit",
"options",
"end"
] |
Limit results by page.
@param [Integer, Hash] page
@param [Hash] options
@return [Collection]
|
[
"Limit",
"results",
"by",
"page",
"."
] |
e7486cce5c3712227b7eeef3ff76c1025c70d146
|
https://github.com/nebiros/dm-paginator/blob/e7486cce5c3712227b7eeef3ff76c1025c70d146/lib/dm-paginator/paginator.rb#L30-L42
|
9,089
|
nebiros/dm-paginator
|
lib/dm-paginator/paginator.rb
|
DataMapper.Paginator.calculate_total_records
|
def calculate_total_records query
# Remove those keys from the query
query.delete :page
query.delete :limit
query.delete :offset
collection = new_collection scoped_query( query )
collection.count.to_i
end
|
ruby
|
def calculate_total_records query
# Remove those keys from the query
query.delete :page
query.delete :limit
query.delete :offset
collection = new_collection scoped_query( query )
collection.count.to_i
end
|
[
"def",
"calculate_total_records",
"query",
"# Remove those keys from the query",
"query",
".",
"delete",
":page",
"query",
".",
"delete",
":limit",
"query",
".",
"delete",
":offset",
"collection",
"=",
"new_collection",
"scoped_query",
"(",
"query",
")",
"collection",
".",
"count",
".",
"to_i",
"end"
] |
Calculate total records
@param [Hash] query
@return [Integer]
|
[
"Calculate",
"total",
"records"
] |
e7486cce5c3712227b7eeef3ff76c1025c70d146
|
https://github.com/nebiros/dm-paginator/blob/e7486cce5c3712227b7eeef3ff76c1025c70d146/lib/dm-paginator/paginator.rb#L51-L58
|
9,090
|
dlindahl/network_executive
|
lib/network_executive/scheduled_program.rb
|
NetworkExecutive.ScheduledProgram.+
|
def +( other_program )
raise ArgumentError if @program.class != other_program.class
additional_duration = other_program.duration + 1
program.duration += additional_duration
occurrence.duration += additional_duration
occurrence.end_time += additional_duration
self
end
|
ruby
|
def +( other_program )
raise ArgumentError if @program.class != other_program.class
additional_duration = other_program.duration + 1
program.duration += additional_duration
occurrence.duration += additional_duration
occurrence.end_time += additional_duration
self
end
|
[
"def",
"+",
"(",
"other_program",
")",
"raise",
"ArgumentError",
"if",
"@program",
".",
"class",
"!=",
"other_program",
".",
"class",
"additional_duration",
"=",
"other_program",
".",
"duration",
"+",
"1",
"program",
".",
"duration",
"+=",
"additional_duration",
"occurrence",
".",
"duration",
"+=",
"additional_duration",
"occurrence",
".",
"end_time",
"+=",
"additional_duration",
"self",
"end"
] |
Extends this scheduled program with another program of the same type.
|
[
"Extends",
"this",
"scheduled",
"program",
"with",
"another",
"program",
"of",
"the",
"same",
"type",
"."
] |
4802e8b20225d7058c82f5ded05bfa6c84918e3d
|
https://github.com/dlindahl/network_executive/blob/4802e8b20225d7058c82f5ded05bfa6c84918e3d/lib/network_executive/scheduled_program.rb#L14-L24
|
9,091
|
babausse/kharon
|
lib/kharon/processor.rb
|
Kharon.Processor.before_all
|
def before_all(key, options)
required(key) if (options.has_key?(:required) and options[:required] == true)
if options.has_key?(:dependencies)
dependencies(key, options[:dependencies])
elsif options.has_key?(:dependency)
dependency(key, options[:dependency])
end
end
|
ruby
|
def before_all(key, options)
required(key) if (options.has_key?(:required) and options[:required] == true)
if options.has_key?(:dependencies)
dependencies(key, options[:dependencies])
elsif options.has_key?(:dependency)
dependency(key, options[:dependency])
end
end
|
[
"def",
"before_all",
"(",
"key",
",",
"options",
")",
"required",
"(",
"key",
")",
"if",
"(",
"options",
".",
"has_key?",
"(",
":required",
")",
"and",
"options",
"[",
":required",
"]",
"==",
"true",
")",
"if",
"options",
".",
"has_key?",
"(",
":dependencies",
")",
"dependencies",
"(",
"key",
",",
"options",
"[",
":dependencies",
"]",
")",
"elsif",
"options",
".",
"has_key?",
"(",
":dependency",
")",
"dependency",
"(",
"key",
",",
"options",
"[",
":dependency",
"]",
")",
"end",
"end"
] |
This method is executed before any call to a public method.
@param [Object] key the key associated with the value currently filteres in the filtered datas.
@param [Hash] options the options applied to the initial value.
|
[
"This",
"method",
"is",
"executed",
"before",
"any",
"call",
"to",
"a",
"public",
"method",
"."
] |
bfd3d90cbc229db70f2ed1762f5f1743259154cd
|
https://github.com/babausse/kharon/blob/bfd3d90cbc229db70f2ed1762f5f1743259154cd/lib/kharon/processor.rb#L27-L34
|
9,092
|
babausse/kharon
|
lib/kharon/processor.rb
|
Kharon.Processor.store
|
def store(key, process, options = {})
unless (options.has_key?(:extract) and options[:extract] == false)
if validator.datas.has_key?(key)
value = ((options.has_key?(:cast) and options[:cast] == false) ? validator.datas[key] : process.call(validator.datas[key]))
if(options.has_key?(:in))
in_array?(key, options[:in])
elsif(options.has_key?(:equals))
equals_to?(key, options[:equals])
elsif(options.has_key?(:equals_key))
equals_key?(key, options[:equals_key])
end
options.has_key?(:rename) ? (validator.filtered[options[:rename]] = value) : (validator.filtered[key] = value)
end
end
end
|
ruby
|
def store(key, process, options = {})
unless (options.has_key?(:extract) and options[:extract] == false)
if validator.datas.has_key?(key)
value = ((options.has_key?(:cast) and options[:cast] == false) ? validator.datas[key] : process.call(validator.datas[key]))
if(options.has_key?(:in))
in_array?(key, options[:in])
elsif(options.has_key?(:equals))
equals_to?(key, options[:equals])
elsif(options.has_key?(:equals_key))
equals_key?(key, options[:equals_key])
end
options.has_key?(:rename) ? (validator.filtered[options[:rename]] = value) : (validator.filtered[key] = value)
end
end
end
|
[
"def",
"store",
"(",
"key",
",",
"process",
",",
"options",
"=",
"{",
"}",
")",
"unless",
"(",
"options",
".",
"has_key?",
"(",
":extract",
")",
"and",
"options",
"[",
":extract",
"]",
"==",
"false",
")",
"if",
"validator",
".",
"datas",
".",
"has_key?",
"(",
"key",
")",
"value",
"=",
"(",
"(",
"options",
".",
"has_key?",
"(",
":cast",
")",
"and",
"options",
"[",
":cast",
"]",
"==",
"false",
")",
"?",
"validator",
".",
"datas",
"[",
"key",
"]",
":",
"process",
".",
"call",
"(",
"validator",
".",
"datas",
"[",
"key",
"]",
")",
")",
"if",
"(",
"options",
".",
"has_key?",
"(",
":in",
")",
")",
"in_array?",
"(",
"key",
",",
"options",
"[",
":in",
"]",
")",
"elsif",
"(",
"options",
".",
"has_key?",
"(",
":equals",
")",
")",
"equals_to?",
"(",
"key",
",",
"options",
"[",
":equals",
"]",
")",
"elsif",
"(",
"options",
".",
"has_key?",
"(",
":equals_key",
")",
")",
"equals_key?",
"(",
"key",
",",
"options",
"[",
":equals_key",
"]",
")",
"end",
"options",
".",
"has_key?",
"(",
":rename",
")",
"?",
"(",
"validator",
".",
"filtered",
"[",
"options",
"[",
":rename",
"]",
"]",
"=",
"value",
")",
":",
"(",
"validator",
".",
"filtered",
"[",
"key",
"]",
"=",
"value",
")",
"end",
"end",
"end"
] |
Tries to store the associated key in the filtered key, transforming it with the given process.
@param [Object] key the key associated with the value to store in the filtered datas.
@param [Proc] process a process (lambda) to execute on the initial value. Must contain strictly one argument.
@param [Hash] options the options applied to the initial value.
|
[
"Tries",
"to",
"store",
"the",
"associated",
"key",
"in",
"the",
"filtered",
"key",
"transforming",
"it",
"with",
"the",
"given",
"process",
"."
] |
bfd3d90cbc229db70f2ed1762f5f1743259154cd
|
https://github.com/babausse/kharon/blob/bfd3d90cbc229db70f2ed1762f5f1743259154cd/lib/kharon/processor.rb#L40-L54
|
9,093
|
babausse/kharon
|
lib/kharon/processor.rb
|
Kharon.Processor.raise_type_error
|
def raise_type_error(key, type)
raise_error(type: "type", key: key, supposed: type, found: key.class)
end
|
ruby
|
def raise_type_error(key, type)
raise_error(type: "type", key: key, supposed: type, found: key.class)
end
|
[
"def",
"raise_type_error",
"(",
"key",
",",
"type",
")",
"raise_error",
"(",
"type",
":",
"\"type\"",
",",
"key",
":",
"key",
",",
"supposed",
":",
"type",
",",
"found",
":",
"key",
".",
"class",
")",
"end"
] |
Raises a type error with a generic message.
@param [Object] key the key associated from the value triggering the error.
@param [Class] type the expected type, not respected by the initial value.
@raise [ArgumentError] the chosen type error.
|
[
"Raises",
"a",
"type",
"error",
"with",
"a",
"generic",
"message",
"."
] |
bfd3d90cbc229db70f2ed1762f5f1743259154cd
|
https://github.com/babausse/kharon/blob/bfd3d90cbc229db70f2ed1762f5f1743259154cd/lib/kharon/processor.rb#L60-L62
|
9,094
|
babausse/kharon
|
lib/kharon/processor.rb
|
Kharon.Processor.required
|
def required(key)
raise_error(type: "required", key: key) unless validator.datas.has_key?(key)
end
|
ruby
|
def required(key)
raise_error(type: "required", key: key) unless validator.datas.has_key?(key)
end
|
[
"def",
"required",
"(",
"key",
")",
"raise_error",
"(",
"type",
":",
"\"required\"",
",",
"key",
":",
"key",
")",
"unless",
"validator",
".",
"datas",
".",
"has_key?",
"(",
"key",
")",
"end"
] |
Checks if a required key is present in provided datas.
@param [Object] key the key of which check the presence.
@raise [ArgumentError] if the key is not present.
|
[
"Checks",
"if",
"a",
"required",
"key",
"is",
"present",
"in",
"provided",
"datas",
"."
] |
bfd3d90cbc229db70f2ed1762f5f1743259154cd
|
https://github.com/babausse/kharon/blob/bfd3d90cbc229db70f2ed1762f5f1743259154cd/lib/kharon/processor.rb#L80-L82
|
9,095
|
babausse/kharon
|
lib/kharon/processor.rb
|
Kharon.Processor.dependency
|
def dependency(key, dependency)
raise_error(type: "dependency", key: "key", needed: dependency) unless validator.datas.has_key?(dependency)
end
|
ruby
|
def dependency(key, dependency)
raise_error(type: "dependency", key: "key", needed: dependency) unless validator.datas.has_key?(dependency)
end
|
[
"def",
"dependency",
"(",
"key",
",",
"dependency",
")",
"raise_error",
"(",
"type",
":",
"\"dependency\"",
",",
"key",
":",
"\"key\"",
",",
"needed",
":",
"dependency",
")",
"unless",
"validator",
".",
"datas",
".",
"has_key?",
"(",
"dependency",
")",
"end"
] |
Checks if a dependency is respected. A dependency is a key openly needed by another key.
@param [Object] key the key needing another key to properly work.
@param [Object] dependency the key needed by another key for it to properly work.
@raise [ArgumentError] if the required dependency is not present.
|
[
"Checks",
"if",
"a",
"dependency",
"is",
"respected",
".",
"A",
"dependency",
"is",
"a",
"key",
"openly",
"needed",
"by",
"another",
"key",
"."
] |
bfd3d90cbc229db70f2ed1762f5f1743259154cd
|
https://github.com/babausse/kharon/blob/bfd3d90cbc229db70f2ed1762f5f1743259154cd/lib/kharon/processor.rb#L97-L99
|
9,096
|
babausse/kharon
|
lib/kharon/processor.rb
|
Kharon.Processor.is_typed?
|
def is_typed?(key, type)
return (!validator.datas.has_key?(key) or validator.datas[key].kind_of?(type))
end
|
ruby
|
def is_typed?(key, type)
return (!validator.datas.has_key?(key) or validator.datas[key].kind_of?(type))
end
|
[
"def",
"is_typed?",
"(",
"key",
",",
"type",
")",
"return",
"(",
"!",
"validator",
".",
"datas",
".",
"has_key?",
"(",
"key",
")",
"or",
"validator",
".",
"datas",
"[",
"key",
"]",
".",
"kind_of?",
"(",
"type",
")",
")",
"end"
] |
Check if the value associated with the given key is typed with the given type, or with a type inheriting from it.
@param [Object] key the key of the value to check the type from.
@param [Class] type the type with which check the initial value.
@return [Boolean] true if the initial value is from the right type, false if not.
|
[
"Check",
"if",
"the",
"value",
"associated",
"with",
"the",
"given",
"key",
"is",
"typed",
"with",
"the",
"given",
"type",
"or",
"with",
"a",
"type",
"inheriting",
"from",
"it",
"."
] |
bfd3d90cbc229db70f2ed1762f5f1743259154cd
|
https://github.com/babausse/kharon/blob/bfd3d90cbc229db70f2ed1762f5f1743259154cd/lib/kharon/processor.rb#L105-L107
|
9,097
|
babausse/kharon
|
lib/kharon/processor.rb
|
Kharon.Processor.in_array?
|
def in_array?(key, values)
raise_error(type: "array.in", key: key, supposed: values, value: validator.datas[key]) unless (values.empty? or values.include?(validator.datas[key]))
end
|
ruby
|
def in_array?(key, values)
raise_error(type: "array.in", key: key, supposed: values, value: validator.datas[key]) unless (values.empty? or values.include?(validator.datas[key]))
end
|
[
"def",
"in_array?",
"(",
"key",
",",
"values",
")",
"raise_error",
"(",
"type",
":",
"\"array.in\"",
",",
"key",
":",
"key",
",",
"supposed",
":",
"values",
",",
"value",
":",
"validator",
".",
"datas",
"[",
"key",
"]",
")",
"unless",
"(",
"values",
".",
"empty?",
"or",
"values",
".",
"include?",
"(",
"validator",
".",
"datas",
"[",
"key",
"]",
")",
")",
"end"
] |
Checks if the value associated with the given key is included in the given array of values.
@param [Object] key the key associated with the value to check.
@param [Array] values the values in which the initial value should be contained.
@raise [ArgumentError] if the initial value is not included in the given possible values.
|
[
"Checks",
"if",
"the",
"value",
"associated",
"with",
"the",
"given",
"key",
"is",
"included",
"in",
"the",
"given",
"array",
"of",
"values",
"."
] |
bfd3d90cbc229db70f2ed1762f5f1743259154cd
|
https://github.com/babausse/kharon/blob/bfd3d90cbc229db70f2ed1762f5f1743259154cd/lib/kharon/processor.rb#L113-L115
|
9,098
|
babausse/kharon
|
lib/kharon/processor.rb
|
Kharon.Processor.equals_to?
|
def equals_to?(key, value)
raise_error(type: "equals", key: key, supposed: value, found: validator.datas[key]) unless validator.datas[key] == value
end
|
ruby
|
def equals_to?(key, value)
raise_error(type: "equals", key: key, supposed: value, found: validator.datas[key]) unless validator.datas[key] == value
end
|
[
"def",
"equals_to?",
"(",
"key",
",",
"value",
")",
"raise_error",
"(",
"type",
":",
"\"equals\"",
",",
"key",
":",
"key",
",",
"supposed",
":",
"value",
",",
"found",
":",
"validator",
".",
"datas",
"[",
"key",
"]",
")",
"unless",
"validator",
".",
"datas",
"[",
"key",
"]",
"==",
"value",
"end"
] |
Checks if the value associated with the given key is equal to the given value.
@param [Object] key the key associated with the value to check.
@param [Object] value the values with which the initial value should be compared.
@raise [ArgumentError] if the initial value is not equal to the given value.
|
[
"Checks",
"if",
"the",
"value",
"associated",
"with",
"the",
"given",
"key",
"is",
"equal",
"to",
"the",
"given",
"value",
"."
] |
bfd3d90cbc229db70f2ed1762f5f1743259154cd
|
https://github.com/babausse/kharon/blob/bfd3d90cbc229db70f2ed1762f5f1743259154cd/lib/kharon/processor.rb#L121-L123
|
9,099
|
babausse/kharon
|
lib/kharon/processor.rb
|
Kharon.Processor.match?
|
def match?(key, regex)
return (!validator.datas.has_key?(key) or validator.datas[key].to_s.match(regex))
end
|
ruby
|
def match?(key, regex)
return (!validator.datas.has_key?(key) or validator.datas[key].to_s.match(regex))
end
|
[
"def",
"match?",
"(",
"key",
",",
"regex",
")",
"return",
"(",
"!",
"validator",
".",
"datas",
".",
"has_key?",
"(",
"key",
")",
"or",
"validator",
".",
"datas",
"[",
"key",
"]",
".",
"to_s",
".",
"match",
"(",
"regex",
")",
")",
"end"
] |
Check if the value associated with the given key matches the given regular expression.
@param [Object] key the key of the value to compare with the given regexp.
@param [Regexp] regex the regex with which match the initial value.
@return [Boolean] true if the initial value matches the regex, false if not.
|
[
"Check",
"if",
"the",
"value",
"associated",
"with",
"the",
"given",
"key",
"matches",
"the",
"given",
"regular",
"expression",
"."
] |
bfd3d90cbc229db70f2ed1762f5f1743259154cd
|
https://github.com/babausse/kharon/blob/bfd3d90cbc229db70f2ed1762f5f1743259154cd/lib/kharon/processor.rb#L137-L139
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.