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
sequence | docstring
stringlengths 8
16k
| docstring_tokens
sequence | sha
stringlengths 40
40
| url
stringlengths 94
266
|
---|---|---|---|---|---|---|---|---|---|---|---|
1,900 | meineerde/rackstash | lib/rackstash/logger.rb | Rackstash.Logger.capture | def capture(buffer_args = {})
raise ArgumentError, 'block required' unless block_given?
buffer_stack.push(buffer_args)
begin
yield
ensure
buffer_stack.flush_and_pop
end
end | ruby | def capture(buffer_args = {})
raise ArgumentError, 'block required' unless block_given?
buffer_stack.push(buffer_args)
begin
yield
ensure
buffer_stack.flush_and_pop
end
end | [
"def",
"capture",
"(",
"buffer_args",
"=",
"{",
"}",
")",
"raise",
"ArgumentError",
",",
"'block required'",
"unless",
"block_given?",
"buffer_stack",
".",
"push",
"(",
"buffer_args",
")",
"begin",
"yield",
"ensure",
"buffer_stack",
".",
"flush_and_pop",
"end",
"end"
] | Capture all messages and fields logged for the duration of the provided
block in the current thread.
Create a new {Buffer} and put in on the {BufferStack} for the current
thread. For the duration of the block, all new logged messages and any
access to fields and tags will be sent to this new buffer. Previous
buffers created in the same thread will only be visible after the
execution left the block.
Note that the created {Buffer} is only valid for the current thread. In
other threads, it not visible and will thus not be used.
@param buffer_args [Hash<Symbol => Object>] optional arguments for the new
{Buffer}. See {Buffer#initialize} for allowed values.
@yield During the duration of the block, all logged messages, fields and
tags are set on the new buffer. After the block returns, the {Buffer} is
removed from the {BufferStack} again and is always flushed
automatically.
@return [Object] the return value of the block | [
"Capture",
"all",
"messages",
"and",
"fields",
"logged",
"for",
"the",
"duration",
"of",
"the",
"provided",
"block",
"in",
"the",
"current",
"thread",
"."
] | b610a2157187dd05ef8d500320aa846234487b01 | https://github.com/meineerde/rackstash/blob/b610a2157187dd05ef8d500320aa846234487b01/lib/rackstash/logger.rb#L454-L463 |
1,901 | seapagan/confoog | lib/confoog.rb | Confoog.Settings.load | def load
@config = YAML.load_file(config_path)
@status.set(errors: Status::INFO_FILE_LOADED)
if @config == false
@status.set(errors: Status::ERR_NOT_LOADING_EMPTY_FILE)
end
rescue
@status.set(errors: Status::ERR_CANT_LOAD)
end | ruby | def load
@config = YAML.load_file(config_path)
@status.set(errors: Status::INFO_FILE_LOADED)
if @config == false
@status.set(errors: Status::ERR_NOT_LOADING_EMPTY_FILE)
end
rescue
@status.set(errors: Status::ERR_CANT_LOAD)
end | [
"def",
"load",
"@config",
"=",
"YAML",
".",
"load_file",
"(",
"config_path",
")",
"@status",
".",
"set",
"(",
"errors",
":",
"Status",
"::",
"INFO_FILE_LOADED",
")",
"if",
"@config",
"==",
"false",
"@status",
".",
"set",
"(",
"errors",
":",
"Status",
"::",
"ERR_NOT_LOADING_EMPTY_FILE",
")",
"end",
"rescue",
"@status",
".",
"set",
"(",
"errors",
":",
"Status",
"::",
"ERR_CANT_LOAD",
")",
"end"
] | Populate the configuration (@config) from the YAML file.
@param [None]
@example
settings.load
@return Unspecified | [
"Populate",
"the",
"configuration",
"("
] | f5a00ff6db132a3f6d7ce880f360e9e5b74bf5b7 | https://github.com/seapagan/confoog/blob/f5a00ff6db132a3f6d7ce880f360e9e5b74bf5b7/lib/confoog.rb#L137-L145 |
1,902 | DocsWebApps/page_right | lib/page_right/css_helper.rb | PageRight.CssHelper.is_css_in_page? | def is_css_in_page?(css, flag=true)
if flag
assert page.has_css?("#{css}"), "Error: #{css} not found on page !"
else
assert !page.has_css?("#{css}"), "Error: #{css} found on page !"
end
end | ruby | def is_css_in_page?(css, flag=true)
if flag
assert page.has_css?("#{css}"), "Error: #{css} not found on page !"
else
assert !page.has_css?("#{css}"), "Error: #{css} found on page !"
end
end | [
"def",
"is_css_in_page?",
"(",
"css",
",",
"flag",
"=",
"true",
")",
"if",
"flag",
"assert",
"page",
".",
"has_css?",
"(",
"\"#{css}\"",
")",
",",
"\"Error: #{css} not found on page !\"",
"else",
"assert",
"!",
"page",
".",
"has_css?",
"(",
"\"#{css}\"",
")",
",",
"\"Error: #{css} found on page !\"",
"end",
"end"
] | Check that a css element is on the page, set flag to check that it isn't | [
"Check",
"that",
"a",
"css",
"element",
"is",
"on",
"the",
"page",
"set",
"flag",
"to",
"check",
"that",
"it",
"isn",
"t"
] | 54dacbb7197c0d4371c64ef18f7588843dcc0940 | https://github.com/DocsWebApps/page_right/blob/54dacbb7197c0d4371c64ef18f7588843dcc0940/lib/page_right/css_helper.rb#L4-L10 |
1,903 | DocsWebApps/page_right | lib/page_right/css_helper.rb | PageRight.CssHelper.is_css_in_section? | def is_css_in_section?(css1, css2, flag=true)
within("#{css1}") do
if flag
assert page.has_css?("#{css2}"), "Error: #{css2} not found in #{css1} !"
else
assert !page.has_css?("#{css2}"), "Error: #{css2} found in #{css1} !"
end
end
end | ruby | def is_css_in_section?(css1, css2, flag=true)
within("#{css1}") do
if flag
assert page.has_css?("#{css2}"), "Error: #{css2} not found in #{css1} !"
else
assert !page.has_css?("#{css2}"), "Error: #{css2} found in #{css1} !"
end
end
end | [
"def",
"is_css_in_section?",
"(",
"css1",
",",
"css2",
",",
"flag",
"=",
"true",
")",
"within",
"(",
"\"#{css1}\"",
")",
"do",
"if",
"flag",
"assert",
"page",
".",
"has_css?",
"(",
"\"#{css2}\"",
")",
",",
"\"Error: #{css2} not found in #{css1} !\"",
"else",
"assert",
"!",
"page",
".",
"has_css?",
"(",
"\"#{css2}\"",
")",
",",
"\"Error: #{css2} found in #{css1} !\"",
"end",
"end",
"end"
] | Check that a css element is nested within another css element, set flag to check that it isn't | [
"Check",
"that",
"a",
"css",
"element",
"is",
"nested",
"within",
"another",
"css",
"element",
"set",
"flag",
"to",
"check",
"that",
"it",
"isn",
"t"
] | 54dacbb7197c0d4371c64ef18f7588843dcc0940 | https://github.com/DocsWebApps/page_right/blob/54dacbb7197c0d4371c64ef18f7588843dcc0940/lib/page_right/css_helper.rb#L13-L21 |
1,904 | fixrb/fix-its | lib/fix/its.rb | Fix.On.its | def its(method, &spec)
i = It.new(described, (challenges + [Defi.send(method)]), helpers.dup)
result = i.verify(&spec)
if configuration.fetch(:verbose, true)
print result.to_char(configuration.fetch(:color, false))
end
results << result
end | ruby | def its(method, &spec)
i = It.new(described, (challenges + [Defi.send(method)]), helpers.dup)
result = i.verify(&spec)
if configuration.fetch(:verbose, true)
print result.to_char(configuration.fetch(:color, false))
end
results << result
end | [
"def",
"its",
"(",
"method",
",",
"&",
"spec",
")",
"i",
"=",
"It",
".",
"new",
"(",
"described",
",",
"(",
"challenges",
"+",
"[",
"Defi",
".",
"send",
"(",
"method",
")",
"]",
")",
",",
"helpers",
".",
"dup",
")",
"result",
"=",
"i",
".",
"verify",
"(",
"spec",
")",
"if",
"configuration",
".",
"fetch",
"(",
":verbose",
",",
"true",
")",
"print",
"result",
".",
"to_char",
"(",
"configuration",
".",
"fetch",
"(",
":color",
",",
"false",
")",
")",
"end",
"results",
"<<",
"result",
"end"
] | Add its method to the DSL.
@api public
@example Its absolute value must equal 42
its(:abs) { MUST equal 42 }
@param method [Symbol] The identifier of a method.
@param spec [Proc] A spec to compare against the computed value.
@return [Array] List of results.
rubocop:disable AbcSize | [
"Add",
"its",
"method",
"to",
"the",
"DSL",
"."
] | 9baf121b610b33ee48b63a7e378f419d4214a2d7 | https://github.com/fixrb/fix-its/blob/9baf121b610b33ee48b63a7e378f419d4214a2d7/lib/fix/its.rb#L28-L38 |
1,905 | bys-control/active_model_serializers_binary | lib/active_model_serializers_binary/base_type.rb | DataTypes.BaseType.before_dump | def before_dump(value)
self.value = value if !value.nil?
if [email protected]?
value = @parent.instance_exec( self, :dump, &@block )
end
self.value = value if !value.nil?
end | ruby | def before_dump(value)
self.value = value if !value.nil?
if [email protected]?
value = @parent.instance_exec( self, :dump, &@block )
end
self.value = value if !value.nil?
end | [
"def",
"before_dump",
"(",
"value",
")",
"self",
".",
"value",
"=",
"value",
"if",
"!",
"value",
".",
"nil?",
"if",
"!",
"@block",
".",
"nil?",
"value",
"=",
"@parent",
".",
"instance_exec",
"(",
"self",
",",
":dump",
",",
"@block",
")",
"end",
"self",
".",
"value",
"=",
"value",
"if",
"!",
"value",
".",
"nil?",
"end"
] | Se ejecuta antes de serializar los datos
@param [Object] value valor del objeto a serializar original
@return [Array] nuevo valor del objeto a serializar | [
"Se",
"ejecuta",
"antes",
"de",
"serializar",
"los",
"datos"
] | f5c77dcc57530a5dfa7b2e6bbe48e951e30412d1 | https://github.com/bys-control/active_model_serializers_binary/blob/f5c77dcc57530a5dfa7b2e6bbe48e951e30412d1/lib/active_model_serializers_binary/base_type.rb#L117-L123 |
1,906 | rapid7/daemon_runner | lib/daemon_runner/shell_out.rb | DaemonRunner.ShellOut.run_and_detach | def run_and_detach
log_r, log_w = IO.pipe
@pid = Process.spawn(command, pgroup: true, err: :out, out: log_w)
log_r.close
log_w.close
@pid
end | ruby | def run_and_detach
log_r, log_w = IO.pipe
@pid = Process.spawn(command, pgroup: true, err: :out, out: log_w)
log_r.close
log_w.close
@pid
end | [
"def",
"run_and_detach",
"log_r",
",",
"log_w",
"=",
"IO",
".",
"pipe",
"@pid",
"=",
"Process",
".",
"spawn",
"(",
"command",
",",
"pgroup",
":",
"true",
",",
"err",
":",
":out",
",",
"out",
":",
"log_w",
")",
"log_r",
".",
"close",
"log_w",
".",
"close",
"@pid",
"end"
] | Run a command in a new process group, thus ignoring any furthur
updates about the status of the process
@return [Fixnum] process id | [
"Run",
"a",
"command",
"in",
"a",
"new",
"process",
"group",
"thus",
"ignoring",
"any",
"furthur",
"updates",
"about",
"the",
"status",
"of",
"the",
"process"
] | dc840aeade0c802739e615718c58d7b243a9f13a | https://github.com/rapid7/daemon_runner/blob/dc840aeade0c802739e615718c58d7b243a9f13a/lib/daemon_runner/shell_out.rb#L66-L72 |
1,907 | meineerde/rackstash | lib/rackstash/message.rb | Rackstash.Message.gsub | def gsub(pattern, replacement = UNDEFINED, &block)
if UNDEFINED.equal? replacement
if block_given?
copy_with @message.gsub(pattern, &block).freeze
else
enum_for(__method__)
end
else
copy_with @message.gsub(pattern, replacement, &block).freeze
end
end | ruby | def gsub(pattern, replacement = UNDEFINED, &block)
if UNDEFINED.equal? replacement
if block_given?
copy_with @message.gsub(pattern, &block).freeze
else
enum_for(__method__)
end
else
copy_with @message.gsub(pattern, replacement, &block).freeze
end
end | [
"def",
"gsub",
"(",
"pattern",
",",
"replacement",
"=",
"UNDEFINED",
",",
"&",
"block",
")",
"if",
"UNDEFINED",
".",
"equal?",
"replacement",
"if",
"block_given?",
"copy_with",
"@message",
".",
"gsub",
"(",
"pattern",
",",
"block",
")",
".",
"freeze",
"else",
"enum_for",
"(",
"__method__",
")",
"end",
"else",
"copy_with",
"@message",
".",
"gsub",
"(",
"pattern",
",",
"replacement",
",",
"block",
")",
".",
"freeze",
"end",
"end"
] | Returns a copy of the Message with all occurances of `pattern` in the
`message` attribute substituted for the second argument.
This works very similar to
[`String#gsub`](https://ruby-doc.org/core/String.html#method-i-gsub). We
are returning a new Message object herre with the `message` attribute
being updated. Please see the documentation of the String method for how
to use this.
Note that when supplying a block for replacement, the current match string
is passed in as a parameter. Differing from `String#gsub`, the special
variables `$1`, `$2`, `$``, `$&`, and `$'` will *not* be set here.
@param pattern [String, Regexp] the search pattern
@param replacement [String, Hash] the replacement definition
@yield match If `replacement` is not given, we yield each match to the
supplied block and use its return value for the replacement
@return [Message, Enumerator] a new frozen Message object or an Enumerator
if neither a block nor a `replacement` were given. | [
"Returns",
"a",
"copy",
"of",
"the",
"Message",
"with",
"all",
"occurances",
"of",
"pattern",
"in",
"the",
"message",
"attribute",
"substituted",
"for",
"the",
"second",
"argument",
"."
] | b610a2157187dd05ef8d500320aa846234487b01 | https://github.com/meineerde/rackstash/blob/b610a2157187dd05ef8d500320aa846234487b01/lib/rackstash/message.rb#L94-L104 |
1,908 | meineerde/rackstash | lib/rackstash/message.rb | Rackstash.Message.sub | def sub(pattern, replacement = UNDEFINED, &block)
message =
if UNDEFINED.equal? replacement
@message.sub(pattern, &block)
else
@message.sub(pattern, replacement, &block)
end
copy_with(message.freeze)
end | ruby | def sub(pattern, replacement = UNDEFINED, &block)
message =
if UNDEFINED.equal? replacement
@message.sub(pattern, &block)
else
@message.sub(pattern, replacement, &block)
end
copy_with(message.freeze)
end | [
"def",
"sub",
"(",
"pattern",
",",
"replacement",
"=",
"UNDEFINED",
",",
"&",
"block",
")",
"message",
"=",
"if",
"UNDEFINED",
".",
"equal?",
"replacement",
"@message",
".",
"sub",
"(",
"pattern",
",",
"block",
")",
"else",
"@message",
".",
"sub",
"(",
"pattern",
",",
"replacement",
",",
"block",
")",
"end",
"copy_with",
"(",
"message",
".",
"freeze",
")",
"end"
] | Returns a copy of the Message with the first occurance of `pattern` in the
`message` attribute substituted for the second argument.
This works very similar to
[`String#sub`](https://ruby-doc.org/core/String.html#method-i-sub). We
are returning a new Message object herre with the `message` attribute
being updated. Please see the documentation of the String method for how
to use this.
Note that when supplying a block for replacement, the current match string
is passed in as a parameter. Differing from `String#gsub`, the special
variables `$1`, `$2`, `$``, `$&`, and `$'` will *not* be set here.
@param pattern [String, Regexp] the search pattern
@param replacement [String, Hash] the replacement definition
@yield match If `replacement` is not given, we yield the match (if any) to
the supplied block and use its return value for the replacement.
@return [Message, Enumerator] a new frozen Message object or an Enumerator
if neither a block nor a `replacement` were given. | [
"Returns",
"a",
"copy",
"of",
"the",
"Message",
"with",
"the",
"first",
"occurance",
"of",
"pattern",
"in",
"the",
"message",
"attribute",
"substituted",
"for",
"the",
"second",
"argument",
"."
] | b610a2157187dd05ef8d500320aa846234487b01 | https://github.com/meineerde/rackstash/blob/b610a2157187dd05ef8d500320aa846234487b01/lib/rackstash/message.rb#L125-L133 |
1,909 | erichmenge/signed_form | lib/signed_form/hmac.rb | SignedForm.HMAC.secure_compare | def secure_compare(a, b)
return false unless a.bytesize == b.bytesize
l = a.unpack("C*")
r, i = 0, -1
b.each_byte { |v| r |= v ^ l[i+=1] }
r == 0
end | ruby | def secure_compare(a, b)
return false unless a.bytesize == b.bytesize
l = a.unpack("C*")
r, i = 0, -1
b.each_byte { |v| r |= v ^ l[i+=1] }
r == 0
end | [
"def",
"secure_compare",
"(",
"a",
",",
"b",
")",
"return",
"false",
"unless",
"a",
".",
"bytesize",
"==",
"b",
".",
"bytesize",
"l",
"=",
"a",
".",
"unpack",
"(",
"\"C*\"",
")",
"r",
",",
"i",
"=",
"0",
",",
"-",
"1",
"b",
".",
"each_byte",
"{",
"|",
"v",
"|",
"r",
"|=",
"v",
"^",
"l",
"[",
"i",
"+=",
"1",
"]",
"}",
"r",
"==",
"0",
"end"
] | After the Rack implementation | [
"After",
"the",
"Rack",
"implementation"
] | ea3842888e78035b7da3fc28f7eaa220d4fc8640 | https://github.com/erichmenge/signed_form/blob/ea3842888e78035b7da3fc28f7eaa220d4fc8640/lib/signed_form/hmac.rb#L32-L40 |
1,910 | duck8823/danger-slack | lib/slack/plugin.rb | Danger.DangerSlack.notify | def notify(channel: '#general', text: nil, **opts)
attachments = text.nil? ? report : []
text ||= '<http://danger.systems/|Danger> reports'
@conn.post do |req|
req.url 'chat.postMessage'
req.params = {
token: @api_token,
channel: channel,
text: text,
attachments: attachments.to_json,
link_names: 1,
**opts
}
end
end | ruby | def notify(channel: '#general', text: nil, **opts)
attachments = text.nil? ? report : []
text ||= '<http://danger.systems/|Danger> reports'
@conn.post do |req|
req.url 'chat.postMessage'
req.params = {
token: @api_token,
channel: channel,
text: text,
attachments: attachments.to_json,
link_names: 1,
**opts
}
end
end | [
"def",
"notify",
"(",
"channel",
":",
"'#general'",
",",
"text",
":",
"nil",
",",
"**",
"opts",
")",
"attachments",
"=",
"text",
".",
"nil?",
"?",
"report",
":",
"[",
"]",
"text",
"||=",
"'<http://danger.systems/|Danger> reports'",
"@conn",
".",
"post",
"do",
"|",
"req",
"|",
"req",
".",
"url",
"'chat.postMessage'",
"req",
".",
"params",
"=",
"{",
"token",
":",
"@api_token",
",",
"channel",
":",
"channel",
",",
"text",
":",
"text",
",",
"attachments",
":",
"attachments",
".",
"to_json",
",",
"link_names",
":",
"1",
",",
"**",
"opts",
"}",
"end",
"end"
] | notify to Slack
@param [String] channel
It is channel to be notified, defaults to '#general'
@param [String] text
text message posted to slack, defaults to nil.
if nil, this method post danger reports to slack.
@param [Hash] **opts
@return [void] | [
"notify",
"to",
"Slack"
] | a5e7b7fa50fe4d7ee4d1e9f2e4d3afc9befafa18 | https://github.com/duck8823/danger-slack/blob/a5e7b7fa50fe4d7ee4d1e9f2e4d3afc9befafa18/lib/slack/plugin.rb#L78-L92 |
1,911 | duck8823/danger-slack | lib/slack/plugin.rb | Danger.DangerSlack.report | def report
attachment = status_report
.reject { |_, v| v.empty? }
.map do |k, v|
case k.to_s
when 'errors' then
{
text: v.join("\n"),
color: 'danger'
}
when 'warnings' then
{
text: v.join("\n"),
color: 'warning'
}
when 'messages' then
{
text: v.join("\n"),
color: 'good'
}
when 'markdowns' then
v.map do |val|
{
text: val.message,
fields: fields(val)
}
end
end
end
attachment.flatten
end | ruby | def report
attachment = status_report
.reject { |_, v| v.empty? }
.map do |k, v|
case k.to_s
when 'errors' then
{
text: v.join("\n"),
color: 'danger'
}
when 'warnings' then
{
text: v.join("\n"),
color: 'warning'
}
when 'messages' then
{
text: v.join("\n"),
color: 'good'
}
when 'markdowns' then
v.map do |val|
{
text: val.message,
fields: fields(val)
}
end
end
end
attachment.flatten
end | [
"def",
"report",
"attachment",
"=",
"status_report",
".",
"reject",
"{",
"|",
"_",
",",
"v",
"|",
"v",
".",
"empty?",
"}",
".",
"map",
"do",
"|",
"k",
",",
"v",
"|",
"case",
"k",
".",
"to_s",
"when",
"'errors'",
"then",
"{",
"text",
":",
"v",
".",
"join",
"(",
"\"\\n\"",
")",
",",
"color",
":",
"'danger'",
"}",
"when",
"'warnings'",
"then",
"{",
"text",
":",
"v",
".",
"join",
"(",
"\"\\n\"",
")",
",",
"color",
":",
"'warning'",
"}",
"when",
"'messages'",
"then",
"{",
"text",
":",
"v",
".",
"join",
"(",
"\"\\n\"",
")",
",",
"color",
":",
"'good'",
"}",
"when",
"'markdowns'",
"then",
"v",
".",
"map",
"do",
"|",
"val",
"|",
"{",
"text",
":",
"val",
".",
"message",
",",
"fields",
":",
"fields",
"(",
"val",
")",
"}",
"end",
"end",
"end",
"attachment",
".",
"flatten",
"end"
] | get status_report text
@return [[Hash]] | [
"get",
"status_report",
"text"
] | a5e7b7fa50fe4d7ee4d1e9f2e4d3afc9befafa18 | https://github.com/duck8823/danger-slack/blob/a5e7b7fa50fe4d7ee4d1e9f2e4d3afc9befafa18/lib/slack/plugin.rb#L98-L128 |
1,912 | duck8823/danger-slack | lib/slack/plugin.rb | Danger.DangerSlack.fields | def fields(markdown)
fields = []
if markdown.file
fields.push(title: 'file',
value: markdown.file,
short: true)
end
if markdown.line
fields.push(title: 'line',
value: markdown.line,
short: true)
end
fields
end | ruby | def fields(markdown)
fields = []
if markdown.file
fields.push(title: 'file',
value: markdown.file,
short: true)
end
if markdown.line
fields.push(title: 'line',
value: markdown.line,
short: true)
end
fields
end | [
"def",
"fields",
"(",
"markdown",
")",
"fields",
"=",
"[",
"]",
"if",
"markdown",
".",
"file",
"fields",
".",
"push",
"(",
"title",
":",
"'file'",
",",
"value",
":",
"markdown",
".",
"file",
",",
"short",
":",
"true",
")",
"end",
"if",
"markdown",
".",
"line",
"fields",
".",
"push",
"(",
"title",
":",
"'line'",
",",
"value",
":",
"markdown",
".",
"line",
",",
"short",
":",
"true",
")",
"end",
"fields",
"end"
] | get markdown fields
@return [[Hash]] | [
"get",
"markdown",
"fields"
] | a5e7b7fa50fe4d7ee4d1e9f2e4d3afc9befafa18 | https://github.com/duck8823/danger-slack/blob/a5e7b7fa50fe4d7ee4d1e9f2e4d3afc9befafa18/lib/slack/plugin.rb#L132-L145 |
1,913 | erichmenge/signed_form | lib/signed_form/form_builder.rb | SignedForm.FormBuilder.fields_for | def fields_for(record_name, record_object = nil, fields_options = {}, &block)
hash = {}
array = []
if nested_attributes_association?(record_name)
hash["#{record_name}_attributes"] = fields_options[:signed_attributes_context] = array
else
hash[record_name] = fields_options[:signed_attributes_context] = array
end
add_signed_fields hash
content = super
array.uniq!
content
end | ruby | def fields_for(record_name, record_object = nil, fields_options = {}, &block)
hash = {}
array = []
if nested_attributes_association?(record_name)
hash["#{record_name}_attributes"] = fields_options[:signed_attributes_context] = array
else
hash[record_name] = fields_options[:signed_attributes_context] = array
end
add_signed_fields hash
content = super
array.uniq!
content
end | [
"def",
"fields_for",
"(",
"record_name",
",",
"record_object",
"=",
"nil",
",",
"fields_options",
"=",
"{",
"}",
",",
"&",
"block",
")",
"hash",
"=",
"{",
"}",
"array",
"=",
"[",
"]",
"if",
"nested_attributes_association?",
"(",
"record_name",
")",
"hash",
"[",
"\"#{record_name}_attributes\"",
"]",
"=",
"fields_options",
"[",
":signed_attributes_context",
"]",
"=",
"array",
"else",
"hash",
"[",
"record_name",
"]",
"=",
"fields_options",
"[",
":signed_attributes_context",
"]",
"=",
"array",
"end",
"add_signed_fields",
"hash",
"content",
"=",
"super",
"array",
".",
"uniq!",
"content",
"end"
] | Wrapper for Rails fields_for
@see http://api.rubyonrails.org/classes/ActionView/Helpers/FormBuilder.html#method-i-fields_for | [
"Wrapper",
"for",
"Rails",
"fields_for"
] | ea3842888e78035b7da3fc28f7eaa220d4fc8640 | https://github.com/erichmenge/signed_form/blob/ea3842888e78035b7da3fc28f7eaa220d4fc8640/lib/signed_form/form_builder.rb#L65-L80 |
1,914 | datamapper/dm-migrations | lib/dm-migrations/migration.rb | DataMapper.Migration.say_with_time | def say_with_time(message, indent = 2)
say(message, indent)
result = nil
time = Benchmark.measure { result = yield }
say("-> %.4fs" % time.real, indent)
result
end | ruby | def say_with_time(message, indent = 2)
say(message, indent)
result = nil
time = Benchmark.measure { result = yield }
say("-> %.4fs" % time.real, indent)
result
end | [
"def",
"say_with_time",
"(",
"message",
",",
"indent",
"=",
"2",
")",
"say",
"(",
"message",
",",
"indent",
")",
"result",
"=",
"nil",
"time",
"=",
"Benchmark",
".",
"measure",
"{",
"result",
"=",
"yield",
"}",
"say",
"(",
"\"-> %.4fs\"",
"%",
"time",
".",
"real",
",",
"indent",
")",
"result",
"end"
] | Time how long the block takes to run, and output it with the message. | [
"Time",
"how",
"long",
"the",
"block",
"takes",
"to",
"run",
"and",
"output",
"it",
"with",
"the",
"message",
"."
] | ca96baac4072b7a4bf442c11da099c7f1461346d | https://github.com/datamapper/dm-migrations/blob/ca96baac4072b7a4bf442c11da099c7f1461346d/lib/dm-migrations/migration.rb#L207-L213 |
1,915 | datamapper/dm-migrations | lib/dm-migrations/migration.rb | DataMapper.Migration.update_migration_info | def update_migration_info(direction)
save, @verbose = @verbose, false
create_migration_info_table_if_needed
if direction.to_sym == :up
execute("INSERT INTO #{migration_info_table} (#{migration_name_column}) VALUES (#{quoted_name})")
elsif direction.to_sym == :down
execute("DELETE FROM #{migration_info_table} WHERE #{migration_name_column} = #{quoted_name}")
end
@verbose = save
end | ruby | def update_migration_info(direction)
save, @verbose = @verbose, false
create_migration_info_table_if_needed
if direction.to_sym == :up
execute("INSERT INTO #{migration_info_table} (#{migration_name_column}) VALUES (#{quoted_name})")
elsif direction.to_sym == :down
execute("DELETE FROM #{migration_info_table} WHERE #{migration_name_column} = #{quoted_name}")
end
@verbose = save
end | [
"def",
"update_migration_info",
"(",
"direction",
")",
"save",
",",
"@verbose",
"=",
"@verbose",
",",
"false",
"create_migration_info_table_if_needed",
"if",
"direction",
".",
"to_sym",
"==",
":up",
"execute",
"(",
"\"INSERT INTO #{migration_info_table} (#{migration_name_column}) VALUES (#{quoted_name})\"",
")",
"elsif",
"direction",
".",
"to_sym",
"==",
":down",
"execute",
"(",
"\"DELETE FROM #{migration_info_table} WHERE #{migration_name_column} = #{quoted_name}\"",
")",
"end",
"@verbose",
"=",
"save",
"end"
] | Inserts or removes a row into the `migration_info` table, so we can mark this migration as run, or un-done | [
"Inserts",
"or",
"removes",
"a",
"row",
"into",
"the",
"migration_info",
"table",
"so",
"we",
"can",
"mark",
"this",
"migration",
"as",
"run",
"or",
"un",
"-",
"done"
] | ca96baac4072b7a4bf442c11da099c7f1461346d | https://github.com/datamapper/dm-migrations/blob/ca96baac4072b7a4bf442c11da099c7f1461346d/lib/dm-migrations/migration.rb#L221-L232 |
1,916 | datamapper/dm-migrations | lib/dm-migrations/migration.rb | DataMapper.Migration.setup! | def setup!
@adapter = DataMapper.repository(@repository).adapter
case @adapter.class.name
when /Sqlite/ then @adapter.extend(SQL::Sqlite)
when /Mysql/ then @adapter.extend(SQL::Mysql)
when /Postgres/ then @adapter.extend(SQL::Postgres)
when /Sqlserver/ then @adapter.extend(SQL::Sqlserver)
when /Oracle/ then @adapter.extend(SQL::Oracle)
else
raise(RuntimeError,"Unsupported Migration Adapter #{@adapter.class}",caller)
end
end | ruby | def setup!
@adapter = DataMapper.repository(@repository).adapter
case @adapter.class.name
when /Sqlite/ then @adapter.extend(SQL::Sqlite)
when /Mysql/ then @adapter.extend(SQL::Mysql)
when /Postgres/ then @adapter.extend(SQL::Postgres)
when /Sqlserver/ then @adapter.extend(SQL::Sqlserver)
when /Oracle/ then @adapter.extend(SQL::Oracle)
else
raise(RuntimeError,"Unsupported Migration Adapter #{@adapter.class}",caller)
end
end | [
"def",
"setup!",
"@adapter",
"=",
"DataMapper",
".",
"repository",
"(",
"@repository",
")",
".",
"adapter",
"case",
"@adapter",
".",
"class",
".",
"name",
"when",
"/",
"/",
"then",
"@adapter",
".",
"extend",
"(",
"SQL",
"::",
"Sqlite",
")",
"when",
"/",
"/",
"then",
"@adapter",
".",
"extend",
"(",
"SQL",
"::",
"Mysql",
")",
"when",
"/",
"/",
"then",
"@adapter",
".",
"extend",
"(",
"SQL",
"::",
"Postgres",
")",
"when",
"/",
"/",
"then",
"@adapter",
".",
"extend",
"(",
"SQL",
"::",
"Sqlserver",
")",
"when",
"/",
"/",
"then",
"@adapter",
".",
"extend",
"(",
"SQL",
"::",
"Oracle",
")",
"else",
"raise",
"(",
"RuntimeError",
",",
"\"Unsupported Migration Adapter #{@adapter.class}\"",
",",
"caller",
")",
"end",
"end"
] | Sets up the migration.
@since 1.0.1 | [
"Sets",
"up",
"the",
"migration",
"."
] | ca96baac4072b7a4bf442c11da099c7f1461346d | https://github.com/datamapper/dm-migrations/blob/ca96baac4072b7a4bf442c11da099c7f1461346d/lib/dm-migrations/migration.rb#L308-L320 |
1,917 | datamapper/dm-migrations | lib/dm-migrations/migration_runner.rb | DataMapper.MigrationRunner.migration | def migration( number, name, opts = {}, &block )
raise "Migration name conflict: '#{name}'" if migrations.map { |m| m.name }.include?(name.to_s)
migrations << DataMapper::Migration.new( number, name.to_s, opts, &block )
end | ruby | def migration( number, name, opts = {}, &block )
raise "Migration name conflict: '#{name}'" if migrations.map { |m| m.name }.include?(name.to_s)
migrations << DataMapper::Migration.new( number, name.to_s, opts, &block )
end | [
"def",
"migration",
"(",
"number",
",",
"name",
",",
"opts",
"=",
"{",
"}",
",",
"&",
"block",
")",
"raise",
"\"Migration name conflict: '#{name}'\"",
"if",
"migrations",
".",
"map",
"{",
"|",
"m",
"|",
"m",
".",
"name",
"}",
".",
"include?",
"(",
"name",
".",
"to_s",
")",
"migrations",
"<<",
"DataMapper",
"::",
"Migration",
".",
"new",
"(",
"number",
",",
"name",
".",
"to_s",
",",
"opts",
",",
"block",
")",
"end"
] | Creates a new migration, and adds it to the list of migrations to be run.
Migrations can be defined in any order, they will be sorted and run in the
correct order.
The order that migrations are run in is set by the first argument. It is not
neccessary that this be unique; migrations with the same version number are
expected to be able to be run in any order.
The second argument is the name of the migration. This name is used internally
to track if the migration has been run. It is required that this name be unique
across all migrations.
Addtionally, it accepts a number of options:
* <tt>:database</tt> If you defined several DataMapper::database instances use this
to choose which one to run the migration gagainst. Defaults to <tt>:default</tt>.
Migrations are tracked individually per database.
* <tt>:verbose</tt> true/false, defaults to true. Determines if the migration should
output its status messages when it runs.
Example of a simple migration:
migration( 1, :create_people_table ) do
up do
create_table :people do
column :id, Integer, :serial => true
column :name, String, :size => 50
column :age, Integer
end
end
down do
drop_table :people
end
end
Its recommended that you stick with raw SQL for migrations that manipulate data. If
you write a migration using a model, then later change the model, there's a
possibility the migration will no longer work. Using SQL will always work. | [
"Creates",
"a",
"new",
"migration",
"and",
"adds",
"it",
"to",
"the",
"list",
"of",
"migrations",
"to",
"be",
"run",
".",
"Migrations",
"can",
"be",
"defined",
"in",
"any",
"order",
"they",
"will",
"be",
"sorted",
"and",
"run",
"in",
"the",
"correct",
"order",
"."
] | ca96baac4072b7a4bf442c11da099c7f1461346d | https://github.com/datamapper/dm-migrations/blob/ca96baac4072b7a4bf442c11da099c7f1461346d/lib/dm-migrations/migration_runner.rb#L42-L46 |
1,918 | datamapper/dm-migrations | lib/dm-migrations/migration_runner.rb | DataMapper.MigrationRunner.migrate_up! | def migrate_up!(level = nil)
migrations.sort.each do |migration|
if level.nil?
migration.perform_up()
else
migration.perform_up() if migration.position <= level.to_i
end
end
end | ruby | def migrate_up!(level = nil)
migrations.sort.each do |migration|
if level.nil?
migration.perform_up()
else
migration.perform_up() if migration.position <= level.to_i
end
end
end | [
"def",
"migrate_up!",
"(",
"level",
"=",
"nil",
")",
"migrations",
".",
"sort",
".",
"each",
"do",
"|",
"migration",
"|",
"if",
"level",
".",
"nil?",
"migration",
".",
"perform_up",
"(",
")",
"else",
"migration",
".",
"perform_up",
"(",
")",
"if",
"migration",
".",
"position",
"<=",
"level",
".",
"to_i",
"end",
"end",
"end"
] | Run all migrations that need to be run. In most cases, this would be called by a
rake task as part of a larger project, but this provides the ability to run them
in a script or test.
has an optional argument 'level' which if supplied, only performs the migrations
with a position less than or equal to the level. | [
"Run",
"all",
"migrations",
"that",
"need",
"to",
"be",
"run",
".",
"In",
"most",
"cases",
"this",
"would",
"be",
"called",
"by",
"a",
"rake",
"task",
"as",
"part",
"of",
"a",
"larger",
"project",
"but",
"this",
"provides",
"the",
"ability",
"to",
"run",
"them",
"in",
"a",
"script",
"or",
"test",
"."
] | ca96baac4072b7a4bf442c11da099c7f1461346d | https://github.com/datamapper/dm-migrations/blob/ca96baac4072b7a4bf442c11da099c7f1461346d/lib/dm-migrations/migration_runner.rb#L54-L62 |
1,919 | datamapper/dm-migrations | lib/dm-migrations/migration_runner.rb | DataMapper.MigrationRunner.migrate_down! | def migrate_down!(level = nil)
migrations.sort.reverse.each do |migration|
if level.nil?
migration.perform_down()
else
migration.perform_down() if migration.position > level.to_i
end
end
end | ruby | def migrate_down!(level = nil)
migrations.sort.reverse.each do |migration|
if level.nil?
migration.perform_down()
else
migration.perform_down() if migration.position > level.to_i
end
end
end | [
"def",
"migrate_down!",
"(",
"level",
"=",
"nil",
")",
"migrations",
".",
"sort",
".",
"reverse",
".",
"each",
"do",
"|",
"migration",
"|",
"if",
"level",
".",
"nil?",
"migration",
".",
"perform_down",
"(",
")",
"else",
"migration",
".",
"perform_down",
"(",
")",
"if",
"migration",
".",
"position",
">",
"level",
".",
"to_i",
"end",
"end",
"end"
] | Run all the down steps for the migrations that have already been run.
has an optional argument 'level' which, if supplied, only performs the
down migrations with a postion greater than the level. | [
"Run",
"all",
"the",
"down",
"steps",
"for",
"the",
"migrations",
"that",
"have",
"already",
"been",
"run",
"."
] | ca96baac4072b7a4bf442c11da099c7f1461346d | https://github.com/datamapper/dm-migrations/blob/ca96baac4072b7a4bf442c11da099c7f1461346d/lib/dm-migrations/migration_runner.rb#L68-L76 |
1,920 | waits/dropbox-sdk-ruby | lib/dropbox/client.rb | Dropbox.Client.copy | def copy(from_path, to_path)
resp = request('/files/copy', from_path: from_path, to_path: to_path)
parse_tagged_response(resp)
end | ruby | def copy(from_path, to_path)
resp = request('/files/copy', from_path: from_path, to_path: to_path)
parse_tagged_response(resp)
end | [
"def",
"copy",
"(",
"from_path",
",",
"to_path",
")",
"resp",
"=",
"request",
"(",
"'/files/copy'",
",",
"from_path",
":",
"from_path",
",",
"to_path",
":",
"to_path",
")",
"parse_tagged_response",
"(",
"resp",
")",
"end"
] | Copy a file or folder to a different location in the user's Dropbox.
@param [String] from_path
@param [String] to_path
@return [Dropbox::Metadata] | [
"Copy",
"a",
"file",
"or",
"folder",
"to",
"a",
"different",
"location",
"in",
"the",
"user",
"s",
"Dropbox",
"."
] | fb99660f8c2fdfcd6818f605a3cf3061bc21c189 | https://github.com/waits/dropbox-sdk-ruby/blob/fb99660f8c2fdfcd6818f605a3cf3061bc21c189/lib/dropbox/client.rb#L30-L33 |
1,921 | waits/dropbox-sdk-ruby | lib/dropbox/client.rb | Dropbox.Client.get_copy_reference | def get_copy_reference(path)
resp = request('/files/copy_reference/get', path: path)
metadata = parse_tagged_response(resp['metadata'])
return metadata, resp['copy_reference']
end | ruby | def get_copy_reference(path)
resp = request('/files/copy_reference/get', path: path)
metadata = parse_tagged_response(resp['metadata'])
return metadata, resp['copy_reference']
end | [
"def",
"get_copy_reference",
"(",
"path",
")",
"resp",
"=",
"request",
"(",
"'/files/copy_reference/get'",
",",
"path",
":",
"path",
")",
"metadata",
"=",
"parse_tagged_response",
"(",
"resp",
"[",
"'metadata'",
"]",
")",
"return",
"metadata",
",",
"resp",
"[",
"'copy_reference'",
"]",
"end"
] | Get a copy reference to a file or folder.
@param [String] path
@return [Dropbox::Metadata] metadata
@return [String] copy_reference | [
"Get",
"a",
"copy",
"reference",
"to",
"a",
"file",
"or",
"folder",
"."
] | fb99660f8c2fdfcd6818f605a3cf3061bc21c189 | https://github.com/waits/dropbox-sdk-ruby/blob/fb99660f8c2fdfcd6818f605a3cf3061bc21c189/lib/dropbox/client.rb#L40-L44 |
1,922 | waits/dropbox-sdk-ruby | lib/dropbox/client.rb | Dropbox.Client.save_copy_reference | def save_copy_reference(copy_reference, path)
resp = request('/files/copy_reference/save', copy_reference: copy_reference, path: path)
parse_tagged_response(resp['metadata'])
end | ruby | def save_copy_reference(copy_reference, path)
resp = request('/files/copy_reference/save', copy_reference: copy_reference, path: path)
parse_tagged_response(resp['metadata'])
end | [
"def",
"save_copy_reference",
"(",
"copy_reference",
",",
"path",
")",
"resp",
"=",
"request",
"(",
"'/files/copy_reference/save'",
",",
"copy_reference",
":",
"copy_reference",
",",
"path",
":",
"path",
")",
"parse_tagged_response",
"(",
"resp",
"[",
"'metadata'",
"]",
")",
"end"
] | Save a copy reference to the user's Dropbox.
@param [String] copy_reference
@param [String] path
@return [Dropbox::Metadata] metadata | [
"Save",
"a",
"copy",
"reference",
"to",
"the",
"user",
"s",
"Dropbox",
"."
] | fb99660f8c2fdfcd6818f605a3cf3061bc21c189 | https://github.com/waits/dropbox-sdk-ruby/blob/fb99660f8c2fdfcd6818f605a3cf3061bc21c189/lib/dropbox/client.rb#L51-L54 |
1,923 | waits/dropbox-sdk-ruby | lib/dropbox/client.rb | Dropbox.Client.download | def download(path)
resp, body = content_request('/files/download', path: path)
return FileMetadata.new(resp), body
end | ruby | def download(path)
resp, body = content_request('/files/download', path: path)
return FileMetadata.new(resp), body
end | [
"def",
"download",
"(",
"path",
")",
"resp",
",",
"body",
"=",
"content_request",
"(",
"'/files/download'",
",",
"path",
":",
"path",
")",
"return",
"FileMetadata",
".",
"new",
"(",
"resp",
")",
",",
"body",
"end"
] | Download a file from a user's Dropbox.
@param [String] path
@return [Dropbox::FileMetadata] metadata
@return [HTTP::Response::Body] body | [
"Download",
"a",
"file",
"from",
"a",
"user",
"s",
"Dropbox",
"."
] | fb99660f8c2fdfcd6818f605a3cf3061bc21c189 | https://github.com/waits/dropbox-sdk-ruby/blob/fb99660f8c2fdfcd6818f605a3cf3061bc21c189/lib/dropbox/client.rb#L79-L82 |
1,924 | waits/dropbox-sdk-ruby | lib/dropbox/client.rb | Dropbox.Client.get_preview | def get_preview(path)
resp, body = content_request('/files/get_preview', path: path)
return FileMetadata.new(resp), body
end | ruby | def get_preview(path)
resp, body = content_request('/files/get_preview', path: path)
return FileMetadata.new(resp), body
end | [
"def",
"get_preview",
"(",
"path",
")",
"resp",
",",
"body",
"=",
"content_request",
"(",
"'/files/get_preview'",
",",
"path",
":",
"path",
")",
"return",
"FileMetadata",
".",
"new",
"(",
"resp",
")",
",",
"body",
"end"
] | Get a preview for a file.
@param [String] path
@return [Dropbox::FileMetadata] metadata
@return [HTTP::Response::Body] body | [
"Get",
"a",
"preview",
"for",
"a",
"file",
"."
] | fb99660f8c2fdfcd6818f605a3cf3061bc21c189 | https://github.com/waits/dropbox-sdk-ruby/blob/fb99660f8c2fdfcd6818f605a3cf3061bc21c189/lib/dropbox/client.rb#L98-L101 |
1,925 | waits/dropbox-sdk-ruby | lib/dropbox/client.rb | Dropbox.Client.get_temporary_link | def get_temporary_link(path)
resp = request('/files/get_temporary_link', path: path)
return FileMetadata.new(resp['metadata']), resp['link']
end | ruby | def get_temporary_link(path)
resp = request('/files/get_temporary_link', path: path)
return FileMetadata.new(resp['metadata']), resp['link']
end | [
"def",
"get_temporary_link",
"(",
"path",
")",
"resp",
"=",
"request",
"(",
"'/files/get_temporary_link'",
",",
"path",
":",
"path",
")",
"return",
"FileMetadata",
".",
"new",
"(",
"resp",
"[",
"'metadata'",
"]",
")",
",",
"resp",
"[",
"'link'",
"]",
"end"
] | Get a temporary link to stream content of a file.
@param [String] path
@return [Dropbox::FileMetadata] metadata
@return [String] link | [
"Get",
"a",
"temporary",
"link",
"to",
"stream",
"content",
"of",
"a",
"file",
"."
] | fb99660f8c2fdfcd6818f605a3cf3061bc21c189 | https://github.com/waits/dropbox-sdk-ruby/blob/fb99660f8c2fdfcd6818f605a3cf3061bc21c189/lib/dropbox/client.rb#L108-L111 |
1,926 | waits/dropbox-sdk-ruby | lib/dropbox/client.rb | Dropbox.Client.get_thumbnail | def get_thumbnail(path, format='jpeg', size='w64h64')
resp, body = content_request('/files/get_thumbnail', path: path, format: format, size: size)
return FileMetadata.new(resp), body
end | ruby | def get_thumbnail(path, format='jpeg', size='w64h64')
resp, body = content_request('/files/get_thumbnail', path: path, format: format, size: size)
return FileMetadata.new(resp), body
end | [
"def",
"get_thumbnail",
"(",
"path",
",",
"format",
"=",
"'jpeg'",
",",
"size",
"=",
"'w64h64'",
")",
"resp",
",",
"body",
"=",
"content_request",
"(",
"'/files/get_thumbnail'",
",",
"path",
":",
"path",
",",
"format",
":",
"format",
",",
"size",
":",
"size",
")",
"return",
"FileMetadata",
".",
"new",
"(",
"resp",
")",
",",
"body",
"end"
] | Get a thumbnail for an image.
@param [String] path
@param [String] format
@param [String] size
@return [Dropbox::FileMetadata] metadata
@return [HTTP::Response::Body] body | [
"Get",
"a",
"thumbnail",
"for",
"an",
"image",
"."
] | fb99660f8c2fdfcd6818f605a3cf3061bc21c189 | https://github.com/waits/dropbox-sdk-ruby/blob/fb99660f8c2fdfcd6818f605a3cf3061bc21c189/lib/dropbox/client.rb#L120-L123 |
1,927 | waits/dropbox-sdk-ruby | lib/dropbox/client.rb | Dropbox.Client.list_folder | def list_folder(path)
resp = request('/files/list_folder', path: path)
resp['entries'].map { |e| parse_tagged_response(e) }
end | ruby | def list_folder(path)
resp = request('/files/list_folder', path: path)
resp['entries'].map { |e| parse_tagged_response(e) }
end | [
"def",
"list_folder",
"(",
"path",
")",
"resp",
"=",
"request",
"(",
"'/files/list_folder'",
",",
"path",
":",
"path",
")",
"resp",
"[",
"'entries'",
"]",
".",
"map",
"{",
"|",
"e",
"|",
"parse_tagged_response",
"(",
"e",
")",
"}",
"end"
] | Get the contents of a folder.
@param [String] path
@return [Array<Dropbox::Metadata>] | [
"Get",
"the",
"contents",
"of",
"a",
"folder",
"."
] | fb99660f8c2fdfcd6818f605a3cf3061bc21c189 | https://github.com/waits/dropbox-sdk-ruby/blob/fb99660f8c2fdfcd6818f605a3cf3061bc21c189/lib/dropbox/client.rb#L129-L132 |
1,928 | waits/dropbox-sdk-ruby | lib/dropbox/client.rb | Dropbox.Client.continue_list_folder | def continue_list_folder(cursor)
resp = request('/files/list_folder/continue', cursor: cursor)
resp['entries'].map { |e| parse_tagged_response(e) }
end | ruby | def continue_list_folder(cursor)
resp = request('/files/list_folder/continue', cursor: cursor)
resp['entries'].map { |e| parse_tagged_response(e) }
end | [
"def",
"continue_list_folder",
"(",
"cursor",
")",
"resp",
"=",
"request",
"(",
"'/files/list_folder/continue'",
",",
"cursor",
":",
"cursor",
")",
"resp",
"[",
"'entries'",
"]",
".",
"map",
"{",
"|",
"e",
"|",
"parse_tagged_response",
"(",
"e",
")",
"}",
"end"
] | Get the contents of a folder that are after a cursor.
@param [String] cursor
@return [Array<Dropbox::Metadata>] | [
"Get",
"the",
"contents",
"of",
"a",
"folder",
"that",
"are",
"after",
"a",
"cursor",
"."
] | fb99660f8c2fdfcd6818f605a3cf3061bc21c189 | https://github.com/waits/dropbox-sdk-ruby/blob/fb99660f8c2fdfcd6818f605a3cf3061bc21c189/lib/dropbox/client.rb#L138-L141 |
1,929 | waits/dropbox-sdk-ruby | lib/dropbox/client.rb | Dropbox.Client.list_revisions | def list_revisions(path)
resp = request('/files/list_revisions', path: path)
entries = resp['entries'].map { |e| FileMetadata.new(e) }
return entries, resp['is_deleted']
end | ruby | def list_revisions(path)
resp = request('/files/list_revisions', path: path)
entries = resp['entries'].map { |e| FileMetadata.new(e) }
return entries, resp['is_deleted']
end | [
"def",
"list_revisions",
"(",
"path",
")",
"resp",
"=",
"request",
"(",
"'/files/list_revisions'",
",",
"path",
":",
"path",
")",
"entries",
"=",
"resp",
"[",
"'entries'",
"]",
".",
"map",
"{",
"|",
"e",
"|",
"FileMetadata",
".",
"new",
"(",
"e",
")",
"}",
"return",
"entries",
",",
"resp",
"[",
"'is_deleted'",
"]",
"end"
] | Get the revisions of a file.
@param [String] path
@return [Array<Dropbox::FileMetadata>] entries
@return [Boolean] is_deleted | [
"Get",
"the",
"revisions",
"of",
"a",
"file",
"."
] | fb99660f8c2fdfcd6818f605a3cf3061bc21c189 | https://github.com/waits/dropbox-sdk-ruby/blob/fb99660f8c2fdfcd6818f605a3cf3061bc21c189/lib/dropbox/client.rb#L157-L161 |
1,930 | waits/dropbox-sdk-ruby | lib/dropbox/client.rb | Dropbox.Client.move | def move(from_path, to_path)
resp = request('/files/move', from_path: from_path, to_path: to_path)
parse_tagged_response(resp)
end | ruby | def move(from_path, to_path)
resp = request('/files/move', from_path: from_path, to_path: to_path)
parse_tagged_response(resp)
end | [
"def",
"move",
"(",
"from_path",
",",
"to_path",
")",
"resp",
"=",
"request",
"(",
"'/files/move'",
",",
"from_path",
":",
"from_path",
",",
"to_path",
":",
"to_path",
")",
"parse_tagged_response",
"(",
"resp",
")",
"end"
] | Move a file or folder to a different location in the user's Dropbox.
@param [String] from_path
@param [String] to_path
@return [Dropbox::Metadata] | [
"Move",
"a",
"file",
"or",
"folder",
"to",
"a",
"different",
"location",
"in",
"the",
"user",
"s",
"Dropbox",
"."
] | fb99660f8c2fdfcd6818f605a3cf3061bc21c189 | https://github.com/waits/dropbox-sdk-ruby/blob/fb99660f8c2fdfcd6818f605a3cf3061bc21c189/lib/dropbox/client.rb#L168-L171 |
1,931 | waits/dropbox-sdk-ruby | lib/dropbox/client.rb | Dropbox.Client.restore | def restore(path, rev)
resp = request('/files/restore', path: path, rev: rev)
FileMetadata.new(resp)
end | ruby | def restore(path, rev)
resp = request('/files/restore', path: path, rev: rev)
FileMetadata.new(resp)
end | [
"def",
"restore",
"(",
"path",
",",
"rev",
")",
"resp",
"=",
"request",
"(",
"'/files/restore'",
",",
"path",
":",
"path",
",",
"rev",
":",
"rev",
")",
"FileMetadata",
".",
"new",
"(",
"resp",
")",
"end"
] | Restore a file to a specific revision.
@param [String] path
@param [String] rev
@return [Dropbox::FileMetadata] | [
"Restore",
"a",
"file",
"to",
"a",
"specific",
"revision",
"."
] | fb99660f8c2fdfcd6818f605a3cf3061bc21c189 | https://github.com/waits/dropbox-sdk-ruby/blob/fb99660f8c2fdfcd6818f605a3cf3061bc21c189/lib/dropbox/client.rb#L187-L190 |
1,932 | waits/dropbox-sdk-ruby | lib/dropbox/client.rb | Dropbox.Client.save_url | def save_url(path, url)
resp = request('/files/save_url', path: path, url: url)
parse_tagged_response(resp)
end | ruby | def save_url(path, url)
resp = request('/files/save_url', path: path, url: url)
parse_tagged_response(resp)
end | [
"def",
"save_url",
"(",
"path",
",",
"url",
")",
"resp",
"=",
"request",
"(",
"'/files/save_url'",
",",
"path",
":",
"path",
",",
"url",
":",
"url",
")",
"parse_tagged_response",
"(",
"resp",
")",
"end"
] | Save a specified URL into a file in user's Dropbox.
@param [String] path
@param [String] url
@return [String] the job id, if the processing is asynchronous.
@return [Dropbox::FileMetadata] if the processing is synchronous. | [
"Save",
"a",
"specified",
"URL",
"into",
"a",
"file",
"in",
"user",
"s",
"Dropbox",
"."
] | fb99660f8c2fdfcd6818f605a3cf3061bc21c189 | https://github.com/waits/dropbox-sdk-ruby/blob/fb99660f8c2fdfcd6818f605a3cf3061bc21c189/lib/dropbox/client.rb#L198-L201 |
1,933 | waits/dropbox-sdk-ruby | lib/dropbox/client.rb | Dropbox.Client.search | def search(path, query, start=0, max_results=100, mode='filename')
resp = request('/files/search', path: path, query: query, start: start,
max_results: max_results, mode: mode)
matches = resp['matches'].map { |m| parse_tagged_response(m['metadata']) }
return matches
end | ruby | def search(path, query, start=0, max_results=100, mode='filename')
resp = request('/files/search', path: path, query: query, start: start,
max_results: max_results, mode: mode)
matches = resp['matches'].map { |m| parse_tagged_response(m['metadata']) }
return matches
end | [
"def",
"search",
"(",
"path",
",",
"query",
",",
"start",
"=",
"0",
",",
"max_results",
"=",
"100",
",",
"mode",
"=",
"'filename'",
")",
"resp",
"=",
"request",
"(",
"'/files/search'",
",",
"path",
":",
"path",
",",
"query",
":",
"query",
",",
"start",
":",
"start",
",",
"max_results",
":",
"max_results",
",",
"mode",
":",
"mode",
")",
"matches",
"=",
"resp",
"[",
"'matches'",
"]",
".",
"map",
"{",
"|",
"m",
"|",
"parse_tagged_response",
"(",
"m",
"[",
"'metadata'",
"]",
")",
"}",
"return",
"matches",
"end"
] | Search for files and folders.
@param [String] path
@param [String] query
@param [Integer] start
@param [Integer] max_results
@param [String] mode
@return [Array<Dropbox::Metadata>] matches | [
"Search",
"for",
"files",
"and",
"folders",
"."
] | fb99660f8c2fdfcd6818f605a3cf3061bc21c189 | https://github.com/waits/dropbox-sdk-ruby/blob/fb99660f8c2fdfcd6818f605a3cf3061bc21c189/lib/dropbox/client.rb#L222-L227 |
1,934 | waits/dropbox-sdk-ruby | lib/dropbox/client.rb | Dropbox.Client.upload | def upload(path, body, options={})
options[:client_modified] = Time.now.utc.iso8601
options[:path] = path
resp = upload_request('/files/upload', body, options.merge(path: path))
FileMetadata.new(resp)
end | ruby | def upload(path, body, options={})
options[:client_modified] = Time.now.utc.iso8601
options[:path] = path
resp = upload_request('/files/upload', body, options.merge(path: path))
FileMetadata.new(resp)
end | [
"def",
"upload",
"(",
"path",
",",
"body",
",",
"options",
"=",
"{",
"}",
")",
"options",
"[",
":client_modified",
"]",
"=",
"Time",
".",
"now",
".",
"utc",
".",
"iso8601",
"options",
"[",
":path",
"]",
"=",
"path",
"resp",
"=",
"upload_request",
"(",
"'/files/upload'",
",",
"body",
",",
"options",
".",
"merge",
"(",
"path",
":",
"path",
")",
")",
"FileMetadata",
".",
"new",
"(",
"resp",
")",
"end"
] | Create a new file.
@param [String] path
@param [String, Enumerable] body
@option options [String] :mode
@option options [Boolean] :autorename
@option options [Boolean] :mute
@return [Dropbox::FileMetadata] | [
"Create",
"a",
"new",
"file",
"."
] | fb99660f8c2fdfcd6818f605a3cf3061bc21c189 | https://github.com/waits/dropbox-sdk-ruby/blob/fb99660f8c2fdfcd6818f605a3cf3061bc21c189/lib/dropbox/client.rb#L237-L242 |
1,935 | waits/dropbox-sdk-ruby | lib/dropbox/client.rb | Dropbox.Client.start_upload_session | def start_upload_session(body, close=false)
resp = upload_request('/files/upload_session/start', body, close: close)
UploadSessionCursor.new(resp['session_id'], body.length)
end | ruby | def start_upload_session(body, close=false)
resp = upload_request('/files/upload_session/start', body, close: close)
UploadSessionCursor.new(resp['session_id'], body.length)
end | [
"def",
"start_upload_session",
"(",
"body",
",",
"close",
"=",
"false",
")",
"resp",
"=",
"upload_request",
"(",
"'/files/upload_session/start'",
",",
"body",
",",
"close",
":",
"close",
")",
"UploadSessionCursor",
".",
"new",
"(",
"resp",
"[",
"'session_id'",
"]",
",",
"body",
".",
"length",
")",
"end"
] | Start an upload session to upload a file using multiple requests.
@param [String, Enumerable] body
@param [Boolean] close
@return [Dropbox::UploadSessionCursor] cursor | [
"Start",
"an",
"upload",
"session",
"to",
"upload",
"a",
"file",
"using",
"multiple",
"requests",
"."
] | fb99660f8c2fdfcd6818f605a3cf3061bc21c189 | https://github.com/waits/dropbox-sdk-ruby/blob/fb99660f8c2fdfcd6818f605a3cf3061bc21c189/lib/dropbox/client.rb#L249-L252 |
1,936 | waits/dropbox-sdk-ruby | lib/dropbox/client.rb | Dropbox.Client.append_upload_session | def append_upload_session(cursor, body, close=false)
args = {cursor: cursor.to_h, close: close}
resp = upload_request('/files/upload_session/append_v2', body, args)
cursor.offset += body.length
cursor
end | ruby | def append_upload_session(cursor, body, close=false)
args = {cursor: cursor.to_h, close: close}
resp = upload_request('/files/upload_session/append_v2', body, args)
cursor.offset += body.length
cursor
end | [
"def",
"append_upload_session",
"(",
"cursor",
",",
"body",
",",
"close",
"=",
"false",
")",
"args",
"=",
"{",
"cursor",
":",
"cursor",
".",
"to_h",
",",
"close",
":",
"close",
"}",
"resp",
"=",
"upload_request",
"(",
"'/files/upload_session/append_v2'",
",",
"body",
",",
"args",
")",
"cursor",
".",
"offset",
"+=",
"body",
".",
"length",
"cursor",
"end"
] | Append more data to an upload session.
@param [Dropbox::UploadSessionCursor] cursor
@param [String, Enumerable] body
@param [Boolean] close
@return [Dropbox::UploadSessionCursor] cursor | [
"Append",
"more",
"data",
"to",
"an",
"upload",
"session",
"."
] | fb99660f8c2fdfcd6818f605a3cf3061bc21c189 | https://github.com/waits/dropbox-sdk-ruby/blob/fb99660f8c2fdfcd6818f605a3cf3061bc21c189/lib/dropbox/client.rb#L260-L265 |
1,937 | waits/dropbox-sdk-ruby | lib/dropbox/client.rb | Dropbox.Client.finish_upload_session | def finish_upload_session(cursor, path, body, options={})
options[:client_modified] = Time.now.utc.iso8601
options[:path] = path
args = {cursor: cursor.to_h, commit: options}
resp = upload_request('/files/upload_session/finish', body, args)
FileMetadata.new(resp)
end | ruby | def finish_upload_session(cursor, path, body, options={})
options[:client_modified] = Time.now.utc.iso8601
options[:path] = path
args = {cursor: cursor.to_h, commit: options}
resp = upload_request('/files/upload_session/finish', body, args)
FileMetadata.new(resp)
end | [
"def",
"finish_upload_session",
"(",
"cursor",
",",
"path",
",",
"body",
",",
"options",
"=",
"{",
"}",
")",
"options",
"[",
":client_modified",
"]",
"=",
"Time",
".",
"now",
".",
"utc",
".",
"iso8601",
"options",
"[",
":path",
"]",
"=",
"path",
"args",
"=",
"{",
"cursor",
":",
"cursor",
".",
"to_h",
",",
"commit",
":",
"options",
"}",
"resp",
"=",
"upload_request",
"(",
"'/files/upload_session/finish'",
",",
"body",
",",
"args",
")",
"FileMetadata",
".",
"new",
"(",
"resp",
")",
"end"
] | Finish an upload session and save the uploaded data to the given file path.
@param [Dropbox::UploadSessionCursor] cursor
@param [String] path
@param [String, Enumerable] body
@param [Hash] options
@option (see #upload)
@return [Dropbox::FileMetadata] | [
"Finish",
"an",
"upload",
"session",
"and",
"save",
"the",
"uploaded",
"data",
"to",
"the",
"given",
"file",
"path",
"."
] | fb99660f8c2fdfcd6818f605a3cf3061bc21c189 | https://github.com/waits/dropbox-sdk-ruby/blob/fb99660f8c2fdfcd6818f605a3cf3061bc21c189/lib/dropbox/client.rb#L275-L281 |
1,938 | waits/dropbox-sdk-ruby | lib/dropbox/client.rb | Dropbox.Client.get_account_batch | def get_account_batch(account_ids)
resp = request('/users/get_account_batch', account_ids: account_ids)
resp.map { |a| BasicAccount.new(a) }
end | ruby | def get_account_batch(account_ids)
resp = request('/users/get_account_batch', account_ids: account_ids)
resp.map { |a| BasicAccount.new(a) }
end | [
"def",
"get_account_batch",
"(",
"account_ids",
")",
"resp",
"=",
"request",
"(",
"'/users/get_account_batch'",
",",
"account_ids",
":",
"account_ids",
")",
"resp",
".",
"map",
"{",
"|",
"a",
"|",
"BasicAccount",
".",
"new",
"(",
"a",
")",
"}",
"end"
] | Get information about multiple user accounts.
@param [Array<String>] account_ids
@return [Array<Dropbox::BasicAccount>] | [
"Get",
"information",
"about",
"multiple",
"user",
"accounts",
"."
] | fb99660f8c2fdfcd6818f605a3cf3061bc21c189 | https://github.com/waits/dropbox-sdk-ruby/blob/fb99660f8c2fdfcd6818f605a3cf3061bc21c189/lib/dropbox/client.rb#L296-L299 |
1,939 | piotrmurach/tty-editor | lib/tty/editor.rb | TTY.Editor.tempfile_path | def tempfile_path(content)
tempfile = Tempfile.new('tty-editor')
tempfile << content
tempfile.flush
unless tempfile.nil?
tempfile.close
end
tempfile.path
end | ruby | def tempfile_path(content)
tempfile = Tempfile.new('tty-editor')
tempfile << content
tempfile.flush
unless tempfile.nil?
tempfile.close
end
tempfile.path
end | [
"def",
"tempfile_path",
"(",
"content",
")",
"tempfile",
"=",
"Tempfile",
".",
"new",
"(",
"'tty-editor'",
")",
"tempfile",
"<<",
"content",
"tempfile",
".",
"flush",
"unless",
"tempfile",
".",
"nil?",
"tempfile",
".",
"close",
"end",
"tempfile",
".",
"path",
"end"
] | Create tempfile with content
@param [String] content
@return [String]
@api private | [
"Create",
"tempfile",
"with",
"content"
] | e8a2082cbe5f160248c35a1baf6e891a017614e3 | https://github.com/piotrmurach/tty-editor/blob/e8a2082cbe5f160248c35a1baf6e891a017614e3/lib/tty/editor.rb#L187-L195 |
1,940 | piotrmurach/tty-editor | lib/tty/editor.rb | TTY.Editor.open | def open
status = system(env, *Shellwords.split(command_path))
return status if status
fail CommandInvocationError,
"`#{command_path}` failed with status: #{$? ? $?.exitstatus : nil}"
end | ruby | def open
status = system(env, *Shellwords.split(command_path))
return status if status
fail CommandInvocationError,
"`#{command_path}` failed with status: #{$? ? $?.exitstatus : nil}"
end | [
"def",
"open",
"status",
"=",
"system",
"(",
"env",
",",
"Shellwords",
".",
"split",
"(",
"command_path",
")",
")",
"return",
"status",
"if",
"status",
"fail",
"CommandInvocationError",
",",
"\"`#{command_path}` failed with status: #{$? ? $?.exitstatus : nil}\"",
"end"
] | Inovke editor command in a shell
@raise [TTY::CommandInvocationError]
@api private | [
"Inovke",
"editor",
"command",
"in",
"a",
"shell"
] | e8a2082cbe5f160248c35a1baf6e891a017614e3 | https://github.com/piotrmurach/tty-editor/blob/e8a2082cbe5f160248c35a1baf6e891a017614e3/lib/tty/editor.rb#L202-L207 |
1,941 | rvm/rvm-gem | lib/rvm/environment/gemset.rb | RVM.Environment.gemset_globalcache | def gemset_globalcache(enable = true)
case enable
when "enabled", :enabled
run(:__rvm_using_gemset_globalcache).successful?
when true, "enable", :enable
rvm(:gemset, :globalcache, :enable).successful?
when false, "disable", :disable
rvm(:gemset, :globalcache, :disable).successful?
else
false
end
end | ruby | def gemset_globalcache(enable = true)
case enable
when "enabled", :enabled
run(:__rvm_using_gemset_globalcache).successful?
when true, "enable", :enable
rvm(:gemset, :globalcache, :enable).successful?
when false, "disable", :disable
rvm(:gemset, :globalcache, :disable).successful?
else
false
end
end | [
"def",
"gemset_globalcache",
"(",
"enable",
"=",
"true",
")",
"case",
"enable",
"when",
"\"enabled\"",
",",
":enabled",
"run",
"(",
":__rvm_using_gemset_globalcache",
")",
".",
"successful?",
"when",
"true",
",",
"\"enable\"",
",",
":enable",
"rvm",
"(",
":gemset",
",",
":globalcache",
",",
":enable",
")",
".",
"successful?",
"when",
"false",
",",
"\"disable\"",
",",
":disable",
"rvm",
"(",
":gemset",
",",
":globalcache",
",",
":disable",
")",
".",
"successful?",
"else",
"false",
"end",
"end"
] | Enable or disable the rvm gem global cache. | [
"Enable",
"or",
"disable",
"the",
"rvm",
"gem",
"global",
"cache",
"."
] | 7ef58904108a1abf1dbabafc605ece1fc9c53668 | https://github.com/rvm/rvm-gem/blob/7ef58904108a1abf1dbabafc605ece1fc9c53668/lib/rvm/environment/gemset.rb#L66-L77 |
1,942 | take-five/acts_as_ordered_tree | lib/acts_as_ordered_tree/node.rb | ActsAsOrderedTree.Node.scope | def scope
if tree.columns.scope?
tree.base_class.where Hash[tree.columns.scope.map { |column| [column, record[column]] }]
else
tree.base_class.where(nil)
end
end | ruby | def scope
if tree.columns.scope?
tree.base_class.where Hash[tree.columns.scope.map { |column| [column, record[column]] }]
else
tree.base_class.where(nil)
end
end | [
"def",
"scope",
"if",
"tree",
".",
"columns",
".",
"scope?",
"tree",
".",
"base_class",
".",
"where",
"Hash",
"[",
"tree",
".",
"columns",
".",
"scope",
".",
"map",
"{",
"|",
"column",
"|",
"[",
"column",
",",
"record",
"[",
"column",
"]",
"]",
"}",
"]",
"else",
"tree",
".",
"base_class",
".",
"where",
"(",
"nil",
")",
"end",
"end"
] | Returns scope to which record should be applied | [
"Returns",
"scope",
"to",
"which",
"record",
"should",
"be",
"applied"
] | 082b08d7e5560256d09987bfb015d684f93b56ed | https://github.com/take-five/acts_as_ordered_tree/blob/082b08d7e5560256d09987bfb015d684f93b56ed/lib/acts_as_ordered_tree/node.rb#L31-L37 |
1,943 | take-five/acts_as_ordered_tree | lib/acts_as_ordered_tree/position.rb | ActsAsOrderedTree.Position.lower | def lower
position? ?
siblings.where(klass.arel_table[klass.ordered_tree.columns.position].gteq(position)) :
siblings
end | ruby | def lower
position? ?
siblings.where(klass.arel_table[klass.ordered_tree.columns.position].gteq(position)) :
siblings
end | [
"def",
"lower",
"position?",
"?",
"siblings",
".",
"where",
"(",
"klass",
".",
"arel_table",
"[",
"klass",
".",
"ordered_tree",
".",
"columns",
".",
"position",
"]",
".",
"gteq",
"(",
"position",
")",
")",
":",
"siblings",
"end"
] | Returns all nodes that are lower than current position | [
"Returns",
"all",
"nodes",
"that",
"are",
"lower",
"than",
"current",
"position"
] | 082b08d7e5560256d09987bfb015d684f93b56ed | https://github.com/take-five/acts_as_ordered_tree/blob/082b08d7e5560256d09987bfb015d684f93b56ed/lib/acts_as_ordered_tree/position.rb#L108-L112 |
1,944 | alloy/lowdown | lib/lowdown/client.rb | Lowdown.Client.disconnect | def disconnect
if @connection.respond_to?(:actors)
@connection.actors.each do |connection|
connection.async.disconnect if connection.alive?
end
else
@connection.async.disconnect if @connection.alive?
end
end | ruby | def disconnect
if @connection.respond_to?(:actors)
@connection.actors.each do |connection|
connection.async.disconnect if connection.alive?
end
else
@connection.async.disconnect if @connection.alive?
end
end | [
"def",
"disconnect",
"if",
"@connection",
".",
"respond_to?",
"(",
":actors",
")",
"@connection",
".",
"actors",
".",
"each",
"do",
"|",
"connection",
"|",
"connection",
".",
"async",
".",
"disconnect",
"if",
"connection",
".",
"alive?",
"end",
"else",
"@connection",
".",
"async",
".",
"disconnect",
"if",
"@connection",
".",
"alive?",
"end",
"end"
] | Closes the connection to the service.
@see Connection#disconnect
@return [void] | [
"Closes",
"the",
"connection",
"to",
"the",
"service",
"."
] | 7a75185d2b93015c18b6093f6784938d42c021f7 | https://github.com/alloy/lowdown/blob/7a75185d2b93015c18b6093f6784938d42c021f7/lib/lowdown/client.rb#L183-L191 |
1,945 | alloy/lowdown | lib/lowdown/client.rb | Lowdown.Client.group | def group(timeout: nil)
group = nil
monitor do |condition|
group = RequestGroup.new(self, condition)
yield group
if !group.empty? && exception = condition.wait(timeout || DEFAULT_GROUP_TIMEOUT)
raise exception
end
end
ensure
group.terminate
end | ruby | def group(timeout: nil)
group = nil
monitor do |condition|
group = RequestGroup.new(self, condition)
yield group
if !group.empty? && exception = condition.wait(timeout || DEFAULT_GROUP_TIMEOUT)
raise exception
end
end
ensure
group.terminate
end | [
"def",
"group",
"(",
"timeout",
":",
"nil",
")",
"group",
"=",
"nil",
"monitor",
"do",
"|",
"condition",
"|",
"group",
"=",
"RequestGroup",
".",
"new",
"(",
"self",
",",
"condition",
")",
"yield",
"group",
"if",
"!",
"group",
".",
"empty?",
"&&",
"exception",
"=",
"condition",
".",
"wait",
"(",
"timeout",
"||",
"DEFAULT_GROUP_TIMEOUT",
")",
"raise",
"exception",
"end",
"end",
"ensure",
"group",
".",
"terminate",
"end"
] | Use this to group a batch of requests and halt the caller thread until all of the requests in the group have been
performed.
It proxies {RequestGroup#send_notification} to {Client#send_notification}, but, unlike the latter, the request
callbacks are provided in the form of a block.
@note Do **not** share the yielded group across threads.
@see RequestGroup#send_notification
@see Connection::Monitor
@param [Numeric] timeout
the maximum amount of time to wait for a request group to halt the caller thread. Defaults to 1 hour.
@yieldparam [RequestGroup] group
the request group object.
@raise [Exception]
if a connection in the pool has died during the execution of this group, the reason for its death will be
raised.
@return [void] | [
"Use",
"this",
"to",
"group",
"a",
"batch",
"of",
"requests",
"and",
"halt",
"the",
"caller",
"thread",
"until",
"all",
"of",
"the",
"requests",
"in",
"the",
"group",
"have",
"been",
"performed",
"."
] | 7a75185d2b93015c18b6093f6784938d42c021f7 | https://github.com/alloy/lowdown/blob/7a75185d2b93015c18b6093f6784938d42c021f7/lib/lowdown/client.rb#L216-L227 |
1,946 | alloy/lowdown | lib/lowdown/client.rb | Lowdown.Client.monitor | def monitor
condition = Connection::Monitor::Condition.new
if defined?(Mock::Connection) && @connection.class == Mock::Connection
yield condition
else
begin
@connection.__register_lowdown_crash_condition__(condition)
yield condition
ensure
@connection.__deregister_lowdown_crash_condition__(condition)
end
end
end | ruby | def monitor
condition = Connection::Monitor::Condition.new
if defined?(Mock::Connection) && @connection.class == Mock::Connection
yield condition
else
begin
@connection.__register_lowdown_crash_condition__(condition)
yield condition
ensure
@connection.__deregister_lowdown_crash_condition__(condition)
end
end
end | [
"def",
"monitor",
"condition",
"=",
"Connection",
"::",
"Monitor",
"::",
"Condition",
".",
"new",
"if",
"defined?",
"(",
"Mock",
"::",
"Connection",
")",
"&&",
"@connection",
".",
"class",
"==",
"Mock",
"::",
"Connection",
"yield",
"condition",
"else",
"begin",
"@connection",
".",
"__register_lowdown_crash_condition__",
"(",
"condition",
")",
"yield",
"condition",
"ensure",
"@connection",
".",
"__deregister_lowdown_crash_condition__",
"(",
"condition",
")",
"end",
"end",
"end"
] | Registers a condition object with the connection pool, for the duration of the given block. It either returns an
exception that caused a connection to die, or whatever value you signal to it.
This is automatically used by {#group}.
@yieldparam [Connection::Monitor::Condition] condition
the monitor condition object.
@return [void] | [
"Registers",
"a",
"condition",
"object",
"with",
"the",
"connection",
"pool",
"for",
"the",
"duration",
"of",
"the",
"given",
"block",
".",
"It",
"either",
"returns",
"an",
"exception",
"that",
"caused",
"a",
"connection",
"to",
"die",
"or",
"whatever",
"value",
"you",
"signal",
"to",
"it",
"."
] | 7a75185d2b93015c18b6093f6784938d42c021f7 | https://github.com/alloy/lowdown/blob/7a75185d2b93015c18b6093f6784938d42c021f7/lib/lowdown/client.rb#L239-L251 |
1,947 | alloy/lowdown | lib/lowdown/client.rb | Lowdown.Client.send_notification | def send_notification(notification, delegate:, context: nil)
raise ArgumentError, "Invalid notification: #{notification.inspect}" unless notification.valid?
topic = notification.topic || @default_topic
headers = {}
headers["apns-expiration"] = (notification.expiration || 0).to_i
headers["apns-id"] = notification.formatted_id
headers["apns-priority"] = notification.priority if notification.priority
headers["apns-topic"] = topic if topic
body = notification.formatted_payload.to_json
@connection.async.post(path: "/3/device/#{notification.token}",
headers: headers,
body: body,
delegate: delegate,
context: context)
end | ruby | def send_notification(notification, delegate:, context: nil)
raise ArgumentError, "Invalid notification: #{notification.inspect}" unless notification.valid?
topic = notification.topic || @default_topic
headers = {}
headers["apns-expiration"] = (notification.expiration || 0).to_i
headers["apns-id"] = notification.formatted_id
headers["apns-priority"] = notification.priority if notification.priority
headers["apns-topic"] = topic if topic
body = notification.formatted_payload.to_json
@connection.async.post(path: "/3/device/#{notification.token}",
headers: headers,
body: body,
delegate: delegate,
context: context)
end | [
"def",
"send_notification",
"(",
"notification",
",",
"delegate",
":",
",",
"context",
":",
"nil",
")",
"raise",
"ArgumentError",
",",
"\"Invalid notification: #{notification.inspect}\"",
"unless",
"notification",
".",
"valid?",
"topic",
"=",
"notification",
".",
"topic",
"||",
"@default_topic",
"headers",
"=",
"{",
"}",
"headers",
"[",
"\"apns-expiration\"",
"]",
"=",
"(",
"notification",
".",
"expiration",
"||",
"0",
")",
".",
"to_i",
"headers",
"[",
"\"apns-id\"",
"]",
"=",
"notification",
".",
"formatted_id",
"headers",
"[",
"\"apns-priority\"",
"]",
"=",
"notification",
".",
"priority",
"if",
"notification",
".",
"priority",
"headers",
"[",
"\"apns-topic\"",
"]",
"=",
"topic",
"if",
"topic",
"body",
"=",
"notification",
".",
"formatted_payload",
".",
"to_json",
"@connection",
".",
"async",
".",
"post",
"(",
"path",
":",
"\"/3/device/#{notification.token}\"",
",",
"headers",
":",
"headers",
",",
"body",
":",
"body",
",",
"delegate",
":",
"delegate",
",",
"context",
":",
"context",
")",
"end"
] | Verifies the `notification` is valid and then sends it to the remote service. Response feedback is provided via
a delegate mechanism.
@note In general, you will probably want to use {#group} to be able to use {RequestGroup#send_notification},
which takes a traditional blocks-based callback approach.
@see Connection#post
@param [Notification] notification
the notification object whose data to send to the service.
@param [Connection::DelegateProtocol] delegate
an object that implements the connection delegate protocol.
@param [Object, nil] context
any object that you want to be passed to the delegate once the response is back.
@raise [ArgumentError]
raised if the Notification is not {Notification#valid?}.
@return [void] | [
"Verifies",
"the",
"notification",
"is",
"valid",
"and",
"then",
"sends",
"it",
"to",
"the",
"remote",
"service",
".",
"Response",
"feedback",
"is",
"provided",
"via",
"a",
"delegate",
"mechanism",
"."
] | 7a75185d2b93015c18b6093f6784938d42c021f7 | https://github.com/alloy/lowdown/blob/7a75185d2b93015c18b6093f6784938d42c021f7/lib/lowdown/client.rb#L275-L292 |
1,948 | xiewenwei/sneakers_packer | lib/sneakers_packer/rpc_client.rb | SneakersPacker.RpcClient.call | def call(request, options = {})
add_request(request)
@publisher.publish(request.message,
routing_key: request.name,
correlation_id: request.call_id,
reply_to: @subscriber.reply_queue_name)
timeout = (options[:timeout] || SneakersPacker.conf.rpc_timeout).to_i
client_lock.synchronize { request.condition.wait(client_lock, timeout) }
remove_request(request)
if request.processed?
request.response_data
else
raise RemoteCallTimeoutError, "Remote call timeouts.Exceed #{timeout} seconds."
end
end | ruby | def call(request, options = {})
add_request(request)
@publisher.publish(request.message,
routing_key: request.name,
correlation_id: request.call_id,
reply_to: @subscriber.reply_queue_name)
timeout = (options[:timeout] || SneakersPacker.conf.rpc_timeout).to_i
client_lock.synchronize { request.condition.wait(client_lock, timeout) }
remove_request(request)
if request.processed?
request.response_data
else
raise RemoteCallTimeoutError, "Remote call timeouts.Exceed #{timeout} seconds."
end
end | [
"def",
"call",
"(",
"request",
",",
"options",
"=",
"{",
"}",
")",
"add_request",
"(",
"request",
")",
"@publisher",
".",
"publish",
"(",
"request",
".",
"message",
",",
"routing_key",
":",
"request",
".",
"name",
",",
"correlation_id",
":",
"request",
".",
"call_id",
",",
"reply_to",
":",
"@subscriber",
".",
"reply_queue_name",
")",
"timeout",
"=",
"(",
"options",
"[",
":timeout",
"]",
"||",
"SneakersPacker",
".",
"conf",
".",
"rpc_timeout",
")",
".",
"to_i",
"client_lock",
".",
"synchronize",
"{",
"request",
".",
"condition",
".",
"wait",
"(",
"client_lock",
",",
"timeout",
")",
"}",
"remove_request",
"(",
"request",
")",
"if",
"request",
".",
"processed?",
"request",
".",
"response_data",
"else",
"raise",
"RemoteCallTimeoutError",
",",
"\"Remote call timeouts.Exceed #{timeout} seconds.\"",
"end",
"end"
] | call remote service via rabbitmq rpc
@param name route_key for service
@param message
@param options{timeout} [int] timeout. seconds. optional
@return result of service
@raise RemoteCallTimeoutError if timeout | [
"call",
"remote",
"service",
"via",
"rabbitmq",
"rpc"
] | 938286c2a275a63db89d14fec2deb9b8b8e61fbf | https://github.com/xiewenwei/sneakers_packer/blob/938286c2a275a63db89d14fec2deb9b8b8e61fbf/lib/sneakers_packer/rpc_client.rb#L20-L39 |
1,949 | Squeegy/fleximage | lib/fleximage/helper.rb | Fleximage.Helper.embedded_image_tag | def embedded_image_tag(model, options = {})
model.load_image
format = options[:format] || :jpg
mime = Mime::Type.lookup_by_extension(format.to_s).to_s
image = model.output_image(:format => format)
data = Base64.encode64(image)
options = { :alt => model.class.to_s }.merge(options)
result = image_tag("data:#{mime};base64,#{data}", options)
result.gsub(%r{src=".*/images/data:}, 'src="data:')
rescue Fleximage::Model::MasterImageNotFound => e
nil
end | ruby | def embedded_image_tag(model, options = {})
model.load_image
format = options[:format] || :jpg
mime = Mime::Type.lookup_by_extension(format.to_s).to_s
image = model.output_image(:format => format)
data = Base64.encode64(image)
options = { :alt => model.class.to_s }.merge(options)
result = image_tag("data:#{mime};base64,#{data}", options)
result.gsub(%r{src=".*/images/data:}, 'src="data:')
rescue Fleximage::Model::MasterImageNotFound => e
nil
end | [
"def",
"embedded_image_tag",
"(",
"model",
",",
"options",
"=",
"{",
"}",
")",
"model",
".",
"load_image",
"format",
"=",
"options",
"[",
":format",
"]",
"||",
":jpg",
"mime",
"=",
"Mime",
"::",
"Type",
".",
"lookup_by_extension",
"(",
"format",
".",
"to_s",
")",
".",
"to_s",
"image",
"=",
"model",
".",
"output_image",
"(",
":format",
"=>",
"format",
")",
"data",
"=",
"Base64",
".",
"encode64",
"(",
"image",
")",
"options",
"=",
"{",
":alt",
"=>",
"model",
".",
"class",
".",
"to_s",
"}",
".",
"merge",
"(",
"options",
")",
"result",
"=",
"image_tag",
"(",
"\"data:#{mime};base64,#{data}\"",
",",
"options",
")",
"result",
".",
"gsub",
"(",
"%r{",
"}",
",",
"'src=\"data:'",
")",
"rescue",
"Fleximage",
"::",
"Model",
"::",
"MasterImageNotFound",
"=>",
"e",
"nil",
"end"
] | Creates an image tag that links directly to image data. Recommended for displays of a
temporary upload that is not saved to a record in the databse yet. | [
"Creates",
"an",
"image",
"tag",
"that",
"links",
"directly",
"to",
"image",
"data",
".",
"Recommended",
"for",
"displays",
"of",
"a",
"temporary",
"upload",
"that",
"is",
"not",
"saved",
"to",
"a",
"record",
"in",
"the",
"databse",
"yet",
"."
] | dd6a486c29df3f56c0347dc9a70273f9aaf432fd | https://github.com/Squeegy/fleximage/blob/dd6a486c29df3f56c0347dc9a70273f9aaf432fd/lib/fleximage/helper.rb#L6-L20 |
1,950 | Squeegy/fleximage | lib/fleximage/helper.rb | Fleximage.Helper.link_to_edit_in_aviary | def link_to_edit_in_aviary(text, model, options = {})
key = aviary_image_hash(model)
image_url = options.delete(:image_url) || url_for(:action => 'aviary_image', :id => model, :only_path => false, :key => key)
post_url = options.delete(:image_update_url) || url_for(:action => 'aviary_image_update', :id => model, :only_path => false, :key => key)
api_key = Fleximage::AviaryController.api_key
url = "http://aviary.com/flash/aviary/index.aspx?tid=1&phoenix&apil=#{api_key}&loadurl=#{CGI.escape image_url}&posturl=#{CGI.escape post_url}"
link_to text, url, { :target => 'aviary' }.merge(options)
end | ruby | def link_to_edit_in_aviary(text, model, options = {})
key = aviary_image_hash(model)
image_url = options.delete(:image_url) || url_for(:action => 'aviary_image', :id => model, :only_path => false, :key => key)
post_url = options.delete(:image_update_url) || url_for(:action => 'aviary_image_update', :id => model, :only_path => false, :key => key)
api_key = Fleximage::AviaryController.api_key
url = "http://aviary.com/flash/aviary/index.aspx?tid=1&phoenix&apil=#{api_key}&loadurl=#{CGI.escape image_url}&posturl=#{CGI.escape post_url}"
link_to text, url, { :target => 'aviary' }.merge(options)
end | [
"def",
"link_to_edit_in_aviary",
"(",
"text",
",",
"model",
",",
"options",
"=",
"{",
"}",
")",
"key",
"=",
"aviary_image_hash",
"(",
"model",
")",
"image_url",
"=",
"options",
".",
"delete",
"(",
":image_url",
")",
"||",
"url_for",
"(",
":action",
"=>",
"'aviary_image'",
",",
":id",
"=>",
"model",
",",
":only_path",
"=>",
"false",
",",
":key",
"=>",
"key",
")",
"post_url",
"=",
"options",
".",
"delete",
"(",
":image_update_url",
")",
"||",
"url_for",
"(",
":action",
"=>",
"'aviary_image_update'",
",",
":id",
"=>",
"model",
",",
":only_path",
"=>",
"false",
",",
":key",
"=>",
"key",
")",
"api_key",
"=",
"Fleximage",
"::",
"AviaryController",
".",
"api_key",
"url",
"=",
"\"http://aviary.com/flash/aviary/index.aspx?tid=1&phoenix&apil=#{api_key}&loadurl=#{CGI.escape image_url}&posturl=#{CGI.escape post_url}\"",
"link_to",
"text",
",",
"url",
",",
"{",
":target",
"=>",
"'aviary'",
"}",
".",
"merge",
"(",
"options",
")",
"end"
] | Creates a link that opens an image for editing in Aviary.
Options:
* image_url: url to the master image used by Aviary for editing. Defauls to <tt>url_for(:action => 'aviary_image', :id => model, :only_path => false)</tt>
* post_url: url where Aviary will post the updated image. Defauls to <tt>url_for(:action => 'aviary_image_update', :id => model, :only_path => false)</tt>
All other options are passed directly to the @link_to@ helper. | [
"Creates",
"a",
"link",
"that",
"opens",
"an",
"image",
"for",
"editing",
"in",
"Aviary",
"."
] | dd6a486c29df3f56c0347dc9a70273f9aaf432fd | https://github.com/Squeegy/fleximage/blob/dd6a486c29df3f56c0347dc9a70273f9aaf432fd/lib/fleximage/helper.rb#L30-L38 |
1,951 | rvm/rvm-gem | lib/rvm/environment/alias.rb | RVM.Environment.alias_list | def alias_list
lines = normalize_array(rvm(:alias, :list).stdout)
lines.inject({}) do |acc, current|
alias_name, ruby_string = current.to_s.split(" => ")
unless alias_name.empty? || ruby_string.empty?
acc[alias_name] = ruby_string
end
acc
end
end | ruby | def alias_list
lines = normalize_array(rvm(:alias, :list).stdout)
lines.inject({}) do |acc, current|
alias_name, ruby_string = current.to_s.split(" => ")
unless alias_name.empty? || ruby_string.empty?
acc[alias_name] = ruby_string
end
acc
end
end | [
"def",
"alias_list",
"lines",
"=",
"normalize_array",
"(",
"rvm",
"(",
":alias",
",",
":list",
")",
".",
"stdout",
")",
"lines",
".",
"inject",
"(",
"{",
"}",
")",
"do",
"|",
"acc",
",",
"current",
"|",
"alias_name",
",",
"ruby_string",
"=",
"current",
".",
"to_s",
".",
"split",
"(",
"\" => \"",
")",
"unless",
"alias_name",
".",
"empty?",
"||",
"ruby_string",
".",
"empty?",
"acc",
"[",
"alias_name",
"]",
"=",
"ruby_string",
"end",
"acc",
"end",
"end"
] | Returns a hash of aliases. | [
"Returns",
"a",
"hash",
"of",
"aliases",
"."
] | 7ef58904108a1abf1dbabafc605ece1fc9c53668 | https://github.com/rvm/rvm-gem/blob/7ef58904108a1abf1dbabafc605ece1fc9c53668/lib/rvm/environment/alias.rb#L5-L14 |
1,952 | alloy/lowdown | lib/lowdown/connection.rb | Lowdown.Connection.post | def post(path:, headers:, body:, delegate:, context: nil)
request("POST", path, headers, body, delegate, context)
end | ruby | def post(path:, headers:, body:, delegate:, context: nil)
request("POST", path, headers, body, delegate, context)
end | [
"def",
"post",
"(",
"path",
":",
",",
"headers",
":",
",",
"body",
":",
",",
"delegate",
":",
",",
"context",
":",
"nil",
")",
"request",
"(",
"\"POST\"",
",",
"path",
",",
"headers",
",",
"body",
",",
"delegate",
",",
"context",
")",
"end"
] | Sends the provided data as a `POST` request to the service.
@note It is strongly advised that the delegate object is a Celluloid actor and that you pass in an async proxy
of that object, but that is not required. If you do not pass in an actor, then be advised that the
callback will run on this connection’s private thread and thus you should not perform long blocking
operations.
@param [String] path
the request path, which should be `/3/device/<device-token>`.
@param [Hash] headers
the additional headers for the request. By default it sends `:method`, `:path`, and `content-length`.
@param [String] body
the (JSON) encoded payload data to send to the service.
@param [DelegateProtocol] delegate
an object that implements the delegate protocol.
@param [Object, nil] context
any object that you want to be passed to the delegate once the response is back.
@return [void] | [
"Sends",
"the",
"provided",
"data",
"as",
"a",
"POST",
"request",
"to",
"the",
"service",
"."
] | 7a75185d2b93015c18b6093f6784938d42c021f7 | https://github.com/alloy/lowdown/blob/7a75185d2b93015c18b6093f6784938d42c021f7/lib/lowdown/connection.rb#L334-L336 |
1,953 | rvm/rvm-gem | lib/rvm/environment/sets.rb | RVM.Environment.ruby | def ruby(runnable, options = {})
if runnable.respond_to?(:path)
# Call the path
ruby_run runnable.path, options
elsif runnable.respond_to?(:to_str)
runnable = runnable.to_str
File.exist?(runnable) ? ruby_run(runnable, options) : ruby_eval(runnable, options)
elsif runnable.respond_to?(:read)
ruby_run runnable.read
end
end | ruby | def ruby(runnable, options = {})
if runnable.respond_to?(:path)
# Call the path
ruby_run runnable.path, options
elsif runnable.respond_to?(:to_str)
runnable = runnable.to_str
File.exist?(runnable) ? ruby_run(runnable, options) : ruby_eval(runnable, options)
elsif runnable.respond_to?(:read)
ruby_run runnable.read
end
end | [
"def",
"ruby",
"(",
"runnable",
",",
"options",
"=",
"{",
"}",
")",
"if",
"runnable",
".",
"respond_to?",
"(",
":path",
")",
"# Call the path",
"ruby_run",
"runnable",
".",
"path",
",",
"options",
"elsif",
"runnable",
".",
"respond_to?",
"(",
":to_str",
")",
"runnable",
"=",
"runnable",
".",
"to_str",
"File",
".",
"exist?",
"(",
"runnable",
")",
"?",
"ruby_run",
"(",
"runnable",
",",
"options",
")",
":",
"ruby_eval",
"(",
"runnable",
",",
"options",
")",
"elsif",
"runnable",
".",
"respond_to?",
"(",
":read",
")",
"ruby_run",
"runnable",
".",
"read",
"end",
"end"
] | Passed either something containing ruby code or
a path to a ruby file, will attempt to exectute
it in the current environment. | [
"Passed",
"either",
"something",
"containing",
"ruby",
"code",
"or",
"a",
"path",
"to",
"a",
"ruby",
"file",
"will",
"attempt",
"to",
"exectute",
"it",
"in",
"the",
"current",
"environment",
"."
] | 7ef58904108a1abf1dbabafc605ece1fc9c53668 | https://github.com/rvm/rvm-gem/blob/7ef58904108a1abf1dbabafc605ece1fc9c53668/lib/rvm/environment/sets.rb#L7-L17 |
1,954 | rvm/rvm-gem | lib/rvm/environment/sets.rb | RVM.Environment.system | def system(command, *args)
identifier = extract_identifier!(args)
args = [identifier, :exec, command, *args].compact
rvm(*args).successful?
end | ruby | def system(command, *args)
identifier = extract_identifier!(args)
args = [identifier, :exec, command, *args].compact
rvm(*args).successful?
end | [
"def",
"system",
"(",
"command",
",",
"*",
"args",
")",
"identifier",
"=",
"extract_identifier!",
"(",
"args",
")",
"args",
"=",
"[",
"identifier",
",",
":exec",
",",
"command",
",",
"args",
"]",
".",
"compact",
"rvm",
"(",
"args",
")",
".",
"successful?",
"end"
] | Like Kernel.system, but evaluates it within the environment.
Also note that it doesn't support redirection etc. | [
"Like",
"Kernel",
".",
"system",
"but",
"evaluates",
"it",
"within",
"the",
"environment",
".",
"Also",
"note",
"that",
"it",
"doesn",
"t",
"support",
"redirection",
"etc",
"."
] | 7ef58904108a1abf1dbabafc605ece1fc9c53668 | https://github.com/rvm/rvm-gem/blob/7ef58904108a1abf1dbabafc605ece1fc9c53668/lib/rvm/environment/sets.rb#L54-L58 |
1,955 | rvm/rvm-gem | lib/rvm/environment/sets.rb | RVM.Environment.extract_environment! | def extract_environment!(options)
values = []
[:environment, :env, :rubies, :ruby].each do |k|
values << options.delete(k)
end
values.compact.first
end | ruby | def extract_environment!(options)
values = []
[:environment, :env, :rubies, :ruby].each do |k|
values << options.delete(k)
end
values.compact.first
end | [
"def",
"extract_environment!",
"(",
"options",
")",
"values",
"=",
"[",
"]",
"[",
":environment",
",",
":env",
",",
":rubies",
",",
":ruby",
"]",
".",
"each",
"do",
"|",
"k",
"|",
"values",
"<<",
"options",
".",
"delete",
"(",
"k",
")",
"end",
"values",
".",
"compact",
".",
"first",
"end"
] | From an options hash, extract the environment identifier. | [
"From",
"an",
"options",
"hash",
"extract",
"the",
"environment",
"identifier",
"."
] | 7ef58904108a1abf1dbabafc605ece1fc9c53668 | https://github.com/rvm/rvm-gem/blob/7ef58904108a1abf1dbabafc605ece1fc9c53668/lib/rvm/environment/sets.rb#L89-L95 |
1,956 | rvm/rvm-gem | lib/rvm/environment/sets.rb | RVM.Environment.extract_identifier! | def extract_identifier!(args)
options = extract_options!(args)
identifier = normalize_set_identifier(extract_environment!(options))
args << options
identifier
end | ruby | def extract_identifier!(args)
options = extract_options!(args)
identifier = normalize_set_identifier(extract_environment!(options))
args << options
identifier
end | [
"def",
"extract_identifier!",
"(",
"args",
")",
"options",
"=",
"extract_options!",
"(",
"args",
")",
"identifier",
"=",
"normalize_set_identifier",
"(",
"extract_environment!",
"(",
"options",
")",
")",
"args",
"<<",
"options",
"identifier",
"end"
] | Shorthand to extra an identifier from args.
Since we | [
"Shorthand",
"to",
"extra",
"an",
"identifier",
"from",
"args",
".",
"Since",
"we"
] | 7ef58904108a1abf1dbabafc605ece1fc9c53668 | https://github.com/rvm/rvm-gem/blob/7ef58904108a1abf1dbabafc605ece1fc9c53668/lib/rvm/environment/sets.rb#L99-L104 |
1,957 | rvm/rvm-gem | lib/rvm/environment/utility.rb | RVM.Environment.chdir | def chdir(dir)
run_silently :pushd, dir.to_s
result = Dir.chdir(dir) { yield }
run_silently :popd
result
end | ruby | def chdir(dir)
run_silently :pushd, dir.to_s
result = Dir.chdir(dir) { yield }
run_silently :popd
result
end | [
"def",
"chdir",
"(",
"dir",
")",
"run_silently",
":pushd",
",",
"dir",
".",
"to_s",
"result",
"=",
"Dir",
".",
"chdir",
"(",
"dir",
")",
"{",
"yield",
"}",
"run_silently",
":popd",
"result",
"end"
] | Run commands inside the given directory. | [
"Run",
"commands",
"inside",
"the",
"given",
"directory",
"."
] | 7ef58904108a1abf1dbabafc605ece1fc9c53668 | https://github.com/rvm/rvm-gem/blob/7ef58904108a1abf1dbabafc605ece1fc9c53668/lib/rvm/environment/utility.rb#L81-L86 |
1,958 | rvm/rvm-gem | lib/rvm/environment/utility.rb | RVM.Environment.normalize_array | def normalize_array(value)
value.split("\n").map { |line| line.strip }.reject { |line| line.empty? }
end | ruby | def normalize_array(value)
value.split("\n").map { |line| line.strip }.reject { |line| line.empty? }
end | [
"def",
"normalize_array",
"(",
"value",
")",
"value",
".",
"split",
"(",
"\"\\n\"",
")",
".",
"map",
"{",
"|",
"line",
"|",
"line",
".",
"strip",
"}",
".",
"reject",
"{",
"|",
"line",
"|",
"line",
".",
"empty?",
"}",
"end"
] | Normalizes an array, removing blank lines. | [
"Normalizes",
"an",
"array",
"removing",
"blank",
"lines",
"."
] | 7ef58904108a1abf1dbabafc605ece1fc9c53668 | https://github.com/rvm/rvm-gem/blob/7ef58904108a1abf1dbabafc605ece1fc9c53668/lib/rvm/environment/utility.rb#L133-L135 |
1,959 | rvm/rvm-gem | lib/rvm/environment/utility.rb | RVM.Environment.hash_to_options | def hash_to_options(options)
result = []
options.each_pair do |key, value|
real_key = "--#{key.to_s.gsub("_", "-")}"
if value == true
result << real_key
elsif value != false
result << real_key
result << value.to_s
end
end
result
end | ruby | def hash_to_options(options)
result = []
options.each_pair do |key, value|
real_key = "--#{key.to_s.gsub("_", "-")}"
if value == true
result << real_key
elsif value != false
result << real_key
result << value.to_s
end
end
result
end | [
"def",
"hash_to_options",
"(",
"options",
")",
"result",
"=",
"[",
"]",
"options",
".",
"each_pair",
"do",
"|",
"key",
",",
"value",
"|",
"real_key",
"=",
"\"--#{key.to_s.gsub(\"_\", \"-\")}\"",
"if",
"value",
"==",
"true",
"result",
"<<",
"real_key",
"elsif",
"value",
"!=",
"false",
"result",
"<<",
"real_key",
"result",
"<<",
"value",
".",
"to_s",
"end",
"end",
"result",
"end"
] | Converts a hash of options to an array of command line argumets.
If the value is false, it wont be added but if it is true only the
key will be added. Lastly, when the value is neither true or false,
to_s will becalled on it and it shall be added to the array. | [
"Converts",
"a",
"hash",
"of",
"options",
"to",
"an",
"array",
"of",
"command",
"line",
"argumets",
".",
"If",
"the",
"value",
"is",
"false",
"it",
"wont",
"be",
"added",
"but",
"if",
"it",
"is",
"true",
"only",
"the",
"key",
"will",
"be",
"added",
".",
"Lastly",
"when",
"the",
"value",
"is",
"neither",
"true",
"or",
"false",
"to_s",
"will",
"becalled",
"on",
"it",
"and",
"it",
"shall",
"be",
"added",
"to",
"the",
"array",
"."
] | 7ef58904108a1abf1dbabafc605ece1fc9c53668 | https://github.com/rvm/rvm-gem/blob/7ef58904108a1abf1dbabafc605ece1fc9c53668/lib/rvm/environment/utility.rb#L146-L158 |
1,960 | rvm/rvm-gem | lib/rvm/environment/utility.rb | RVM.Environment.normalize_option_value | def normalize_option_value(value)
case value
when Array
value.map { |option| normalize_option_value(option) }.join(",")
else
value.to_s
end
end | ruby | def normalize_option_value(value)
case value
when Array
value.map { |option| normalize_option_value(option) }.join(",")
else
value.to_s
end
end | [
"def",
"normalize_option_value",
"(",
"value",
")",
"case",
"value",
"when",
"Array",
"value",
".",
"map",
"{",
"|",
"option",
"|",
"normalize_option_value",
"(",
"option",
")",
"}",
".",
"join",
"(",
"\",\"",
")",
"else",
"value",
".",
"to_s",
"end",
"end"
] | Recursively normalize options. | [
"Recursively",
"normalize",
"options",
"."
] | 7ef58904108a1abf1dbabafc605ece1fc9c53668 | https://github.com/rvm/rvm-gem/blob/7ef58904108a1abf1dbabafc605ece1fc9c53668/lib/rvm/environment/utility.rb#L161-L168 |
1,961 | rvm/rvm-gem | lib/rvm/environment/tools.rb | RVM.Environment.tools_path_identifier | def tools_path_identifier(path)
path_identifier = rvm(:tools, "path-identifier", path.to_s)
if path_identifier.exit_status == 2
error_message = "The rvmrc located in '#{path}' could not be loaded, likely due to trust mechanisms."
error_message << " Please run 'rvm rvmrc {trust,untrust} \"#{path}\"' to continue, or set rvm_trust_rvmrcs_flag to 1."
raise ErrorLoadingRVMRC, error_message
end
return normalize(path_identifier.stdout)
end | ruby | def tools_path_identifier(path)
path_identifier = rvm(:tools, "path-identifier", path.to_s)
if path_identifier.exit_status == 2
error_message = "The rvmrc located in '#{path}' could not be loaded, likely due to trust mechanisms."
error_message << " Please run 'rvm rvmrc {trust,untrust} \"#{path}\"' to continue, or set rvm_trust_rvmrcs_flag to 1."
raise ErrorLoadingRVMRC, error_message
end
return normalize(path_identifier.stdout)
end | [
"def",
"tools_path_identifier",
"(",
"path",
")",
"path_identifier",
"=",
"rvm",
"(",
":tools",
",",
"\"path-identifier\"",
",",
"path",
".",
"to_s",
")",
"if",
"path_identifier",
".",
"exit_status",
"==",
"2",
"error_message",
"=",
"\"The rvmrc located in '#{path}' could not be loaded, likely due to trust mechanisms.\"",
"error_message",
"<<",
"\" Please run 'rvm rvmrc {trust,untrust} \\\"#{path}\\\"' to continue, or set rvm_trust_rvmrcs_flag to 1.\"",
"raise",
"ErrorLoadingRVMRC",
",",
"error_message",
"end",
"return",
"normalize",
"(",
"path_identifier",
".",
"stdout",
")",
"end"
] | Gets the identifier after cd'ing to a path, no destructive. | [
"Gets",
"the",
"identifier",
"after",
"cd",
"ing",
"to",
"a",
"path",
"no",
"destructive",
"."
] | 7ef58904108a1abf1dbabafc605ece1fc9c53668 | https://github.com/rvm/rvm-gem/blob/7ef58904108a1abf1dbabafc605ece1fc9c53668/lib/rvm/environment/tools.rb#L10-L18 |
1,962 | rvm/rvm-gem | lib/rvm/environment/rubies.rb | RVM.Environment.use | def use(ruby_string, opts = {})
ruby_string = ruby_string.to_s
result = rvm(:use, ruby_string)
successful = result.successful?
if successful
@environment_name = ruby_string
@expanded_name = nil
use_env_from_result! result if opts[:replace_env]
end
successful
end | ruby | def use(ruby_string, opts = {})
ruby_string = ruby_string.to_s
result = rvm(:use, ruby_string)
successful = result.successful?
if successful
@environment_name = ruby_string
@expanded_name = nil
use_env_from_result! result if opts[:replace_env]
end
successful
end | [
"def",
"use",
"(",
"ruby_string",
",",
"opts",
"=",
"{",
"}",
")",
"ruby_string",
"=",
"ruby_string",
".",
"to_s",
"result",
"=",
"rvm",
"(",
":use",
",",
"ruby_string",
")",
"successful",
"=",
"result",
".",
"successful?",
"if",
"successful",
"@environment_name",
"=",
"ruby_string",
"@expanded_name",
"=",
"nil",
"use_env_from_result!",
"result",
"if",
"opts",
"[",
":replace_env",
"]",
"end",
"successful",
"end"
] | Changes the ruby string for the current environment.
env.use '1.9.2' # => true
env.use 'ree' # => true
env.use 'foo' # => false | [
"Changes",
"the",
"ruby",
"string",
"for",
"the",
"current",
"environment",
"."
] | 7ef58904108a1abf1dbabafc605ece1fc9c53668 | https://github.com/rvm/rvm-gem/blob/7ef58904108a1abf1dbabafc605ece1fc9c53668/lib/rvm/environment/rubies.rb#L25-L35 |
1,963 | rvm/rvm-gem | lib/rvm/environment.rb | RVM.Environment.source_rvm_environment | def source_rvm_environment
rvm_path = config_value_for(:rvm_path, self.class.default_rvm_path, false)
actual_config = defined_config.merge('rvm_path' => rvm_path)
config = []
actual_config.each_pair do |k, v|
config << "#{k}=#{escape_argument(v.to_s)}"
end
run_silently "export #{config.join(" ")}"
run_silently :source, File.join(rvm_path, "scripts", "rvm")
end | ruby | def source_rvm_environment
rvm_path = config_value_for(:rvm_path, self.class.default_rvm_path, false)
actual_config = defined_config.merge('rvm_path' => rvm_path)
config = []
actual_config.each_pair do |k, v|
config << "#{k}=#{escape_argument(v.to_s)}"
end
run_silently "export #{config.join(" ")}"
run_silently :source, File.join(rvm_path, "scripts", "rvm")
end | [
"def",
"source_rvm_environment",
"rvm_path",
"=",
"config_value_for",
"(",
":rvm_path",
",",
"self",
".",
"class",
".",
"default_rvm_path",
",",
"false",
")",
"actual_config",
"=",
"defined_config",
".",
"merge",
"(",
"'rvm_path'",
"=>",
"rvm_path",
")",
"config",
"=",
"[",
"]",
"actual_config",
".",
"each_pair",
"do",
"|",
"k",
",",
"v",
"|",
"config",
"<<",
"\"#{k}=#{escape_argument(v.to_s)}\"",
"end",
"run_silently",
"\"export #{config.join(\" \")}\"",
"run_silently",
":source",
",",
"File",
".",
"join",
"(",
"rvm_path",
",",
"\"scripts\"",
",",
"\"rvm\"",
")",
"end"
] | Automatically load rvm config from the multiple sources. | [
"Automatically",
"load",
"rvm",
"config",
"from",
"the",
"multiple",
"sources",
"."
] | 7ef58904108a1abf1dbabafc605ece1fc9c53668 | https://github.com/rvm/rvm-gem/blob/7ef58904108a1abf1dbabafc605ece1fc9c53668/lib/rvm/environment.rb#L53-L62 |
1,964 | alloy/lowdown | lib/lowdown/notification.rb | Lowdown.Notification.formatted_payload | def formatted_payload
if @payload.key?("aps")
@payload
else
payload = {}
payload["aps"] = aps = {}
@payload.each do |key, value|
next if value.nil?
key = key.to_s
if APS_KEYS.include?(key)
aps[key] = value
else
payload[key] = value
end
end
payload
end
end | ruby | def formatted_payload
if @payload.key?("aps")
@payload
else
payload = {}
payload["aps"] = aps = {}
@payload.each do |key, value|
next if value.nil?
key = key.to_s
if APS_KEYS.include?(key)
aps[key] = value
else
payload[key] = value
end
end
payload
end
end | [
"def",
"formatted_payload",
"if",
"@payload",
".",
"key?",
"(",
"\"aps\"",
")",
"@payload",
"else",
"payload",
"=",
"{",
"}",
"payload",
"[",
"\"aps\"",
"]",
"=",
"aps",
"=",
"{",
"}",
"@payload",
".",
"each",
"do",
"|",
"key",
",",
"value",
"|",
"next",
"if",
"value",
".",
"nil?",
"key",
"=",
"key",
".",
"to_s",
"if",
"APS_KEYS",
".",
"include?",
"(",
"key",
")",
"aps",
"[",
"key",
"]",
"=",
"value",
"else",
"payload",
"[",
"key",
"]",
"=",
"value",
"end",
"end",
"payload",
"end",
"end"
] | Unless the payload contains an `aps` entry, the payload is assumed to be a mix of APN defined attributes and
custom attributes and re-organized according to the specifications.
@see https://developer.apple.com/library/ios/documentation/NetworkingInternet/Conceptual/RemoteNotificationsPG/Chapters/TheNotificationPayload.html#//apple_ref/doc/uid/TP40008194-CH107-SW1
@return [Hash]
the payload organized according to the APN specification. | [
"Unless",
"the",
"payload",
"contains",
"an",
"aps",
"entry",
"the",
"payload",
"is",
"assumed",
"to",
"be",
"a",
"mix",
"of",
"APN",
"defined",
"attributes",
"and",
"custom",
"attributes",
"and",
"re",
"-",
"organized",
"according",
"to",
"the",
"specifications",
"."
] | 7a75185d2b93015c18b6093f6784938d42c021f7 | https://github.com/alloy/lowdown/blob/7a75185d2b93015c18b6093f6784938d42c021f7/lib/lowdown/notification.rb#L94-L111 |
1,965 | take-five/acts_as_ordered_tree | lib/acts_as_ordered_tree/persevering_transaction.rb | ActsAsOrderedTree.PerseveringTransaction.start | def start(&block)
@attempts += 1
with_transaction_state(&block)
rescue ActiveRecord::StatementInvalid => error
raise unless connection.open_transactions.zero?
raise unless error.message =~ DEADLOCK_MESSAGES
raise if attempts >= RETRY_COUNT
logger.info "Deadlock detected on attempt #{attempts}, restarting transaction"
pause and retry
end | ruby | def start(&block)
@attempts += 1
with_transaction_state(&block)
rescue ActiveRecord::StatementInvalid => error
raise unless connection.open_transactions.zero?
raise unless error.message =~ DEADLOCK_MESSAGES
raise if attempts >= RETRY_COUNT
logger.info "Deadlock detected on attempt #{attempts}, restarting transaction"
pause and retry
end | [
"def",
"start",
"(",
"&",
"block",
")",
"@attempts",
"+=",
"1",
"with_transaction_state",
"(",
"block",
")",
"rescue",
"ActiveRecord",
"::",
"StatementInvalid",
"=>",
"error",
"raise",
"unless",
"connection",
".",
"open_transactions",
".",
"zero?",
"raise",
"unless",
"error",
".",
"message",
"=~",
"DEADLOCK_MESSAGES",
"raise",
"if",
"attempts",
">=",
"RETRY_COUNT",
"logger",
".",
"info",
"\"Deadlock detected on attempt #{attempts}, restarting transaction\"",
"pause",
"and",
"retry",
"end"
] | Starts persevering transaction | [
"Starts",
"persevering",
"transaction"
] | 082b08d7e5560256d09987bfb015d684f93b56ed | https://github.com/take-five/acts_as_ordered_tree/blob/082b08d7e5560256d09987bfb015d684f93b56ed/lib/acts_as_ordered_tree/persevering_transaction.rb#L46-L58 |
1,966 | jdtornow/challah | lib/challah/encrypter.rb | Challah.Encrypter.compare | def compare(crypted_string, plain_string)
BCrypt::Password.new(crypted_string).is_password?(plain_string)
rescue BCrypt::Errors::InvalidHash
false
end | ruby | def compare(crypted_string, plain_string)
BCrypt::Password.new(crypted_string).is_password?(plain_string)
rescue BCrypt::Errors::InvalidHash
false
end | [
"def",
"compare",
"(",
"crypted_string",
",",
"plain_string",
")",
"BCrypt",
"::",
"Password",
".",
"new",
"(",
"crypted_string",
")",
".",
"is_password?",
"(",
"plain_string",
")",
"rescue",
"BCrypt",
"::",
"Errors",
"::",
"InvalidHash",
"false",
"end"
] | Returns true if the the bcrypted value of a is equal to b | [
"Returns",
"true",
"if",
"the",
"the",
"bcrypted",
"value",
"of",
"a",
"is",
"equal",
"to",
"b"
] | 251328f3762bb33c85c873ac8b1268fc0ba32f52 | https://github.com/jdtornow/challah/blob/251328f3762bb33c85c873ac8b1268fc0ba32f52/lib/challah/encrypter.rb#L36-L40 |
1,967 | jdtornow/challah | lib/challah/audit.rb | Challah.Audit.clear_audit_attributes | def clear_audit_attributes
all_audit_attributes.each do |attribute_name|
if respond_to?(attribute_name) && respond_to?("#{ attribute_name }=")
write_attribute(attribute_name, nil)
end
end
@changed_attributes = changed_attributes.reduce(ActiveSupport::HashWithIndifferentAccess.new) do |result, (key, value)|
unless all_audit_attributes.include?(key.to_sym)
result[key] = value
end
result
end
end | ruby | def clear_audit_attributes
all_audit_attributes.each do |attribute_name|
if respond_to?(attribute_name) && respond_to?("#{ attribute_name }=")
write_attribute(attribute_name, nil)
end
end
@changed_attributes = changed_attributes.reduce(ActiveSupport::HashWithIndifferentAccess.new) do |result, (key, value)|
unless all_audit_attributes.include?(key.to_sym)
result[key] = value
end
result
end
end | [
"def",
"clear_audit_attributes",
"all_audit_attributes",
".",
"each",
"do",
"|",
"attribute_name",
"|",
"if",
"respond_to?",
"(",
"attribute_name",
")",
"&&",
"respond_to?",
"(",
"\"#{ attribute_name }=\"",
")",
"write_attribute",
"(",
"attribute_name",
",",
"nil",
")",
"end",
"end",
"@changed_attributes",
"=",
"changed_attributes",
".",
"reduce",
"(",
"ActiveSupport",
"::",
"HashWithIndifferentAccess",
".",
"new",
")",
"do",
"|",
"result",
",",
"(",
"key",
",",
"value",
")",
"|",
"unless",
"all_audit_attributes",
".",
"include?",
"(",
"key",
".",
"to_sym",
")",
"result",
"[",
"key",
"]",
"=",
"value",
"end",
"result",
"end",
"end"
] | Clear attributes and changed_attributes | [
"Clear",
"attributes",
"and",
"changed_attributes"
] | 251328f3762bb33c85c873ac8b1268fc0ba32f52 | https://github.com/jdtornow/challah/blob/251328f3762bb33c85c873ac8b1268fc0ba32f52/lib/challah/audit.rb#L94-L108 |
1,968 | jonahb/bing-search | lib/bing-search/client.rb | BingSearch.Client.image | def image(query, opts = {})
invoke 'Image',
query,
opts,
param_name_replacements: {filters: 'ImageFilters'},
params: {filters: image_filters_from_opts(opts)}
end | ruby | def image(query, opts = {})
invoke 'Image',
query,
opts,
param_name_replacements: {filters: 'ImageFilters'},
params: {filters: image_filters_from_opts(opts)}
end | [
"def",
"image",
"(",
"query",
",",
"opts",
"=",
"{",
"}",
")",
"invoke",
"'Image'",
",",
"query",
",",
"opts",
",",
"param_name_replacements",
":",
"{",
"filters",
":",
"'ImageFilters'",
"}",
",",
"params",
":",
"{",
"filters",
":",
"image_filters_from_opts",
"(",
"opts",
")",
"}",
"end"
] | Searches for images
@!macro general
@option opts [Integer] :minimum_height
In pixels; ANDed with other filters
@option opts [Integer] :minimum_width
In pixels; ANDed with other filters
@option opts [Array<ImageFilter>] :filters
Multiple filters are ANDed
@return [Array<ImageResult>] | [
"Searches",
"for",
"images"
] | c0c1a6f51f42fbf41e1c5901a9158a4b9682898f | https://github.com/jonahb/bing-search/blob/c0c1a6f51f42fbf41e1c5901a9158a4b9682898f/lib/bing-search/client.rb#L169-L175 |
1,969 | jonahb/bing-search | lib/bing-search/client.rb | BingSearch.Client.video | def video(query, opts = {})
invoke 'Video',
query,
opts,
passthrough_opts: %i(filters sort),
enum_opt_to_module: {filters: VideoFilter, sort: VideoSort},
param_name_replacements: {filters: 'VideoFilters', sort: 'VideoSortBy'}
end | ruby | def video(query, opts = {})
invoke 'Video',
query,
opts,
passthrough_opts: %i(filters sort),
enum_opt_to_module: {filters: VideoFilter, sort: VideoSort},
param_name_replacements: {filters: 'VideoFilters', sort: 'VideoSortBy'}
end | [
"def",
"video",
"(",
"query",
",",
"opts",
"=",
"{",
"}",
")",
"invoke",
"'Video'",
",",
"query",
",",
"opts",
",",
"passthrough_opts",
":",
"%i(",
"filters",
"sort",
")",
",",
"enum_opt_to_module",
":",
"{",
"filters",
":",
"VideoFilter",
",",
"sort",
":",
"VideoSort",
"}",
",",
"param_name_replacements",
":",
"{",
"filters",
":",
"'VideoFilters'",
",",
"sort",
":",
"'VideoSortBy'",
"}",
"end"
] | Searches for videos
@!macro general
@option opts [Array<VideoFilter>] :filters
Multiple filters are ANDed. At most one duration is allowed.
@option opts [VideoSort] :sort
@return [Array<VideoResult>] | [
"Searches",
"for",
"videos"
] | c0c1a6f51f42fbf41e1c5901a9158a4b9682898f | https://github.com/jonahb/bing-search/blob/c0c1a6f51f42fbf41e1c5901a9158a4b9682898f/lib/bing-search/client.rb#L184-L191 |
1,970 | jonahb/bing-search | lib/bing-search/client.rb | BingSearch.Client.news | def news(query, opts = {})
invoke 'News',
query,
opts,
passthrough_opts: %i(category location_override sort),
enum_opt_to_module: {category: NewsCategory, sort: NewsSort},
param_name_replacements: {category: 'NewsCategory', location_override: 'NewsLocationOverride', sort: 'NewsSortBy'}
end | ruby | def news(query, opts = {})
invoke 'News',
query,
opts,
passthrough_opts: %i(category location_override sort),
enum_opt_to_module: {category: NewsCategory, sort: NewsSort},
param_name_replacements: {category: 'NewsCategory', location_override: 'NewsLocationOverride', sort: 'NewsSortBy'}
end | [
"def",
"news",
"(",
"query",
",",
"opts",
"=",
"{",
"}",
")",
"invoke",
"'News'",
",",
"query",
",",
"opts",
",",
"passthrough_opts",
":",
"%i(",
"category",
"location_override",
"sort",
")",
",",
"enum_opt_to_module",
":",
"{",
"category",
":",
"NewsCategory",
",",
"sort",
":",
"NewsSort",
"}",
",",
"param_name_replacements",
":",
"{",
"category",
":",
"'NewsCategory'",
",",
"location_override",
":",
"'NewsLocationOverride'",
",",
"sort",
":",
"'NewsSortBy'",
"}",
"end"
] | Searches for news
@!macro general
@option opts [Boolean] :highlighting (false)
Whether to surround query terms in {NewsResult#description} with the
delimiter {BingSearch::HIGHLIGHT_DELIMITER}.
@option opts [NewsCategory] :category
Only applies in the en-US market. If no news matches the category, Bing
returns results from a mix of categories.
@option opts [String] :location_override
Overrides Bing's location detection. Example: +US.WA+
@option opts [NewsSort] :sort
@return [Array<NewsResult>] | [
"Searches",
"for",
"news"
] | c0c1a6f51f42fbf41e1c5901a9158a4b9682898f | https://github.com/jonahb/bing-search/blob/c0c1a6f51f42fbf41e1c5901a9158a4b9682898f/lib/bing-search/client.rb#L206-L213 |
1,971 | jdtornow/challah | lib/challah/validators/password_validator.rb | Challah.PasswordValidator.validate | def validate(record)
if record.password_provider? or options[:force]
if record.new_record? and record.password.to_s.blank? and !record.password_changed?
record.errors.add :password, :blank
elsif record.password_changed?
if record.password.to_s.size < 4
record.errors.add :password, :invalid_password
elsif record.password.to_s != record.password_confirmation.to_s
record.errors.add :password, :no_match_password
end
end
end
end | ruby | def validate(record)
if record.password_provider? or options[:force]
if record.new_record? and record.password.to_s.blank? and !record.password_changed?
record.errors.add :password, :blank
elsif record.password_changed?
if record.password.to_s.size < 4
record.errors.add :password, :invalid_password
elsif record.password.to_s != record.password_confirmation.to_s
record.errors.add :password, :no_match_password
end
end
end
end | [
"def",
"validate",
"(",
"record",
")",
"if",
"record",
".",
"password_provider?",
"or",
"options",
"[",
":force",
"]",
"if",
"record",
".",
"new_record?",
"and",
"record",
".",
"password",
".",
"to_s",
".",
"blank?",
"and",
"!",
"record",
".",
"password_changed?",
"record",
".",
"errors",
".",
"add",
":password",
",",
":blank",
"elsif",
"record",
".",
"password_changed?",
"if",
"record",
".",
"password",
".",
"to_s",
".",
"size",
"<",
"4",
"record",
".",
"errors",
".",
"add",
":password",
",",
":invalid_password",
"elsif",
"record",
".",
"password",
".",
"to_s",
"!=",
"record",
".",
"password_confirmation",
".",
"to_s",
"record",
".",
"errors",
".",
"add",
":password",
",",
":no_match_password",
"end",
"end",
"end",
"end"
] | Check to make sure a valid password and confirmation were set | [
"Check",
"to",
"make",
"sure",
"a",
"valid",
"password",
"and",
"confirmation",
"were",
"set"
] | 251328f3762bb33c85c873ac8b1268fc0ba32f52 | https://github.com/jdtornow/challah/blob/251328f3762bb33c85c873ac8b1268fc0ba32f52/lib/challah/validators/password_validator.rb#L4-L16 |
1,972 | moiristo/settler | lib/settler/abstract_setting.rb | Settler.AbstractSetting.valid_values | def valid_values
if validators['inclusion']
return case
when validators['inclusion'].is_a?(Array) then validators['inclusion']
when validators['inclusion'].is_a?(String) then validators['inclusion'].to_s.split(',').map{|v| v.to_s.strip }
else nil
end
end
nil
end | ruby | def valid_values
if validators['inclusion']
return case
when validators['inclusion'].is_a?(Array) then validators['inclusion']
when validators['inclusion'].is_a?(String) then validators['inclusion'].to_s.split(',').map{|v| v.to_s.strip }
else nil
end
end
nil
end | [
"def",
"valid_values",
"if",
"validators",
"[",
"'inclusion'",
"]",
"return",
"case",
"when",
"validators",
"[",
"'inclusion'",
"]",
".",
"is_a?",
"(",
"Array",
")",
"then",
"validators",
"[",
"'inclusion'",
"]",
"when",
"validators",
"[",
"'inclusion'",
"]",
".",
"is_a?",
"(",
"String",
")",
"then",
"validators",
"[",
"'inclusion'",
"]",
".",
"to_s",
".",
"split",
"(",
"','",
")",
".",
"map",
"{",
"|",
"v",
"|",
"v",
".",
"to_s",
".",
"strip",
"}",
"else",
"nil",
"end",
"end",
"nil",
"end"
] | Returns all valid values for this setting, which is based on the presence of an inclusion validator.
Will return nil if no valid values could be determined. | [
"Returns",
"all",
"valid",
"values",
"for",
"this",
"setting",
"which",
"is",
"based",
"on",
"the",
"presence",
"of",
"an",
"inclusion",
"validator",
".",
"Will",
"return",
"nil",
"if",
"no",
"valid",
"values",
"could",
"be",
"determined",
"."
] | c56bf98b6c5c03b05119dbe53042b89e47d8bf21 | https://github.com/moiristo/settler/blob/c56bf98b6c5c03b05119dbe53042b89e47d8bf21/lib/settler/abstract_setting.rb#L49-L58 |
1,973 | sstephenson/hike | lib/hike/cached_trail.rb | Hike.CachedTrail.find_in_paths | def find_in_paths(logical_path, &block)
dirname, basename = File.split(logical_path)
@paths.each do |base_path|
match(File.expand_path(dirname, base_path), basename, &block)
end
end | ruby | def find_in_paths(logical_path, &block)
dirname, basename = File.split(logical_path)
@paths.each do |base_path|
match(File.expand_path(dirname, base_path), basename, &block)
end
end | [
"def",
"find_in_paths",
"(",
"logical_path",
",",
"&",
"block",
")",
"dirname",
",",
"basename",
"=",
"File",
".",
"split",
"(",
"logical_path",
")",
"@paths",
".",
"each",
"do",
"|",
"base_path",
"|",
"match",
"(",
"File",
".",
"expand_path",
"(",
"dirname",
",",
"base_path",
")",
",",
"basename",
",",
"block",
")",
"end",
"end"
] | Finds logical path across all `paths` | [
"Finds",
"logical",
"path",
"across",
"all",
"paths"
] | 3abf0b3feb47c26911f8cedf2cd409471fd26da1 | https://github.com/sstephenson/hike/blob/3abf0b3feb47c26911f8cedf2cd409471fd26da1/lib/hike/cached_trail.rb#L105-L110 |
1,974 | sstephenson/hike | lib/hike/cached_trail.rb | Hike.CachedTrail.match | def match(dirname, basename)
# Potential `entries` syscall
matches = @entries[dirname]
pattern = @patterns[basename]
matches = matches.select { |m| m =~ pattern }
sort_matches(matches, basename).each do |path|
filename = File.join(dirname, path)
# Potential `stat` syscall
stat = @stats[filename]
# Exclude directories
if stat && stat.file?
yield filename
end
end
end | ruby | def match(dirname, basename)
# Potential `entries` syscall
matches = @entries[dirname]
pattern = @patterns[basename]
matches = matches.select { |m| m =~ pattern }
sort_matches(matches, basename).each do |path|
filename = File.join(dirname, path)
# Potential `stat` syscall
stat = @stats[filename]
# Exclude directories
if stat && stat.file?
yield filename
end
end
end | [
"def",
"match",
"(",
"dirname",
",",
"basename",
")",
"# Potential `entries` syscall",
"matches",
"=",
"@entries",
"[",
"dirname",
"]",
"pattern",
"=",
"@patterns",
"[",
"basename",
"]",
"matches",
"=",
"matches",
".",
"select",
"{",
"|",
"m",
"|",
"m",
"=~",
"pattern",
"}",
"sort_matches",
"(",
"matches",
",",
"basename",
")",
".",
"each",
"do",
"|",
"path",
"|",
"filename",
"=",
"File",
".",
"join",
"(",
"dirname",
",",
"path",
")",
"# Potential `stat` syscall",
"stat",
"=",
"@stats",
"[",
"filename",
"]",
"# Exclude directories",
"if",
"stat",
"&&",
"stat",
".",
"file?",
"yield",
"filename",
"end",
"end",
"end"
] | Checks if the path is actually on the file system and performs
any syscalls if necessary. | [
"Checks",
"if",
"the",
"path",
"is",
"actually",
"on",
"the",
"file",
"system",
"and",
"performs",
"any",
"syscalls",
"if",
"necessary",
"."
] | 3abf0b3feb47c26911f8cedf2cd409471fd26da1 | https://github.com/sstephenson/hike/blob/3abf0b3feb47c26911f8cedf2cd409471fd26da1/lib/hike/cached_trail.rb#L122-L140 |
1,975 | sstephenson/hike | lib/hike/cached_trail.rb | Hike.CachedTrail.sort_matches | def sort_matches(matches, basename)
extname = File.extname(basename)
aliases = @reverse_aliases[extname] || []
matches.sort_by do |match|
extnames = match.sub(basename, '').scan(/\.[^.]+/)
extnames.inject(0) do |sum, ext|
if i = extensions.index(ext)
sum + i + 1
elsif i = aliases.index(ext)
sum + i + 11
else
sum
end
end
end
end | ruby | def sort_matches(matches, basename)
extname = File.extname(basename)
aliases = @reverse_aliases[extname] || []
matches.sort_by do |match|
extnames = match.sub(basename, '').scan(/\.[^.]+/)
extnames.inject(0) do |sum, ext|
if i = extensions.index(ext)
sum + i + 1
elsif i = aliases.index(ext)
sum + i + 11
else
sum
end
end
end
end | [
"def",
"sort_matches",
"(",
"matches",
",",
"basename",
")",
"extname",
"=",
"File",
".",
"extname",
"(",
"basename",
")",
"aliases",
"=",
"@reverse_aliases",
"[",
"extname",
"]",
"||",
"[",
"]",
"matches",
".",
"sort_by",
"do",
"|",
"match",
"|",
"extnames",
"=",
"match",
".",
"sub",
"(",
"basename",
",",
"''",
")",
".",
"scan",
"(",
"/",
"\\.",
"/",
")",
"extnames",
".",
"inject",
"(",
"0",
")",
"do",
"|",
"sum",
",",
"ext",
"|",
"if",
"i",
"=",
"extensions",
".",
"index",
"(",
"ext",
")",
"sum",
"+",
"i",
"+",
"1",
"elsif",
"i",
"=",
"aliases",
".",
"index",
"(",
"ext",
")",
"sum",
"+",
"i",
"+",
"11",
"else",
"sum",
"end",
"end",
"end",
"end"
] | Sorts candidate matches by their extension
priority. Extensions in the front of the `extensions` carry
more weight. | [
"Sorts",
"candidate",
"matches",
"by",
"their",
"extension",
"priority",
".",
"Extensions",
"in",
"the",
"front",
"of",
"the",
"extensions",
"carry",
"more",
"weight",
"."
] | 3abf0b3feb47c26911f8cedf2cd409471fd26da1 | https://github.com/sstephenson/hike/blob/3abf0b3feb47c26911f8cedf2cd409471fd26da1/lib/hike/cached_trail.rb#L170-L186 |
1,976 | jdtornow/challah | lib/challah/concerns/user/provideable.rb | Challah.UserProvideable.update_modified_providers_after_save | def update_modified_providers_after_save
# Save password provider
if @password_updated or @username_updated
Challah.providers[:password].save(self)
@password_updated = false
@username_updated = false
@password = nil
end
# Save any other providers
Challah.custom_providers.each do |name, klass|
custom_provider_attributes = provider_attributes[name]
if custom_provider_attributes.respond_to?(:fetch)
if klass.valid?(self)
klass.save(self)
end
end
end
end | ruby | def update_modified_providers_after_save
# Save password provider
if @password_updated or @username_updated
Challah.providers[:password].save(self)
@password_updated = false
@username_updated = false
@password = nil
end
# Save any other providers
Challah.custom_providers.each do |name, klass|
custom_provider_attributes = provider_attributes[name]
if custom_provider_attributes.respond_to?(:fetch)
if klass.valid?(self)
klass.save(self)
end
end
end
end | [
"def",
"update_modified_providers_after_save",
"# Save password provider",
"if",
"@password_updated",
"or",
"@username_updated",
"Challah",
".",
"providers",
"[",
":password",
"]",
".",
"save",
"(",
"self",
")",
"@password_updated",
"=",
"false",
"@username_updated",
"=",
"false",
"@password",
"=",
"nil",
"end",
"# Save any other providers",
"Challah",
".",
"custom_providers",
".",
"each",
"do",
"|",
"name",
",",
"klass",
"|",
"custom_provider_attributes",
"=",
"provider_attributes",
"[",
"name",
"]",
"if",
"custom_provider_attributes",
".",
"respond_to?",
"(",
":fetch",
")",
"if",
"klass",
".",
"valid?",
"(",
"self",
")",
"klass",
".",
"save",
"(",
"self",
")",
"end",
"end",
"end",
"end"
] | If password or username was changed, update the authorization record | [
"If",
"password",
"or",
"username",
"was",
"changed",
"update",
"the",
"authorization",
"record"
] | 251328f3762bb33c85c873ac8b1268fc0ba32f52 | https://github.com/jdtornow/challah/blob/251328f3762bb33c85c873ac8b1268fc0ba32f52/lib/challah/concerns/user/provideable.rb#L84-L103 |
1,977 | jdtornow/challah | lib/challah/session.rb | Challah.Session.method_missing | def method_missing(sym, *args, &block)
if @params.has_key?(sym)
return @params[sym]
elsif sym.to_s =~ /^[a-z0-9_]*=$/
return @params[sym.to_s.sub(/^(.*?)=$/, '\1').to_sym] = args.shift
elsif sym.to_s =~ /^[a-z0-9_]*\?$/
return !!@params[sym.to_s.sub(/^(.*?)\?$/, '\1').to_sym]
end
super(sym, *args, &block)
end | ruby | def method_missing(sym, *args, &block)
if @params.has_key?(sym)
return @params[sym]
elsif sym.to_s =~ /^[a-z0-9_]*=$/
return @params[sym.to_s.sub(/^(.*?)=$/, '\1').to_sym] = args.shift
elsif sym.to_s =~ /^[a-z0-9_]*\?$/
return !!@params[sym.to_s.sub(/^(.*?)\?$/, '\1').to_sym]
end
super(sym, *args, &block)
end | [
"def",
"method_missing",
"(",
"sym",
",",
"*",
"args",
",",
"&",
"block",
")",
"if",
"@params",
".",
"has_key?",
"(",
"sym",
")",
"return",
"@params",
"[",
"sym",
"]",
"elsif",
"sym",
".",
"to_s",
"=~",
"/",
"/",
"return",
"@params",
"[",
"sym",
".",
"to_s",
".",
"sub",
"(",
"/",
"/",
",",
"'\\1'",
")",
".",
"to_sym",
"]",
"=",
"args",
".",
"shift",
"elsif",
"sym",
".",
"to_s",
"=~",
"/",
"\\?",
"/",
"return",
"!",
"!",
"@params",
"[",
"sym",
".",
"to_s",
".",
"sub",
"(",
"/",
"\\?",
"/",
",",
"'\\1'",
")",
".",
"to_sym",
"]",
"end",
"super",
"(",
"sym",
",",
"args",
",",
"block",
")",
"end"
] | Allow for dynamic setting of instance variables.
also allows for variable? to see if it was provided | [
"Allow",
"for",
"dynamic",
"setting",
"of",
"instance",
"variables",
".",
"also",
"allows",
"for",
"variable?",
"to",
"see",
"if",
"it",
"was",
"provided"
] | 251328f3762bb33c85c873ac8b1268fc0ba32f52 | https://github.com/jdtornow/challah/blob/251328f3762bb33c85c873ac8b1268fc0ba32f52/lib/challah/session.rb#L99-L109 |
1,978 | jdtornow/challah | lib/challah/session.rb | Challah.Session.authenticate! | def authenticate!
Challah.techniques.values.each do |klass|
technique = klass.new(self)
technique.user_model = user_model if technique.respond_to?(:"user_model=")
@user = technique.authenticate
if @user
@persist = technique.respond_to?(:persist?) ? technique.persist? : false
break
end
end
if @user
# Only update user record if persistence is on for the technique.
# Otherwise this builds up quick (one session for each API call)
if @persist
@user.successful_authentication!(ip)
end
return @valid = true
end
@valid = false
end | ruby | def authenticate!
Challah.techniques.values.each do |klass|
technique = klass.new(self)
technique.user_model = user_model if technique.respond_to?(:"user_model=")
@user = technique.authenticate
if @user
@persist = technique.respond_to?(:persist?) ? technique.persist? : false
break
end
end
if @user
# Only update user record if persistence is on for the technique.
# Otherwise this builds up quick (one session for each API call)
if @persist
@user.successful_authentication!(ip)
end
return @valid = true
end
@valid = false
end | [
"def",
"authenticate!",
"Challah",
".",
"techniques",
".",
"values",
".",
"each",
"do",
"|",
"klass",
"|",
"technique",
"=",
"klass",
".",
"new",
"(",
"self",
")",
"technique",
".",
"user_model",
"=",
"user_model",
"if",
"technique",
".",
"respond_to?",
"(",
":\"",
"\"",
")",
"@user",
"=",
"technique",
".",
"authenticate",
"if",
"@user",
"@persist",
"=",
"technique",
".",
"respond_to?",
"(",
":persist?",
")",
"?",
"technique",
".",
"persist?",
":",
"false",
"break",
"end",
"end",
"if",
"@user",
"# Only update user record if persistence is on for the technique.",
"# Otherwise this builds up quick (one session for each API call)",
"if",
"@persist",
"@user",
".",
"successful_authentication!",
"(",
"ip",
")",
"end",
"return",
"@valid",
"=",
"true",
"end",
"@valid",
"=",
"false",
"end"
] | Try and authenticate against the various auth techniques. If one
technique works, then just exit and make the session active. | [
"Try",
"and",
"authenticate",
"against",
"the",
"various",
"auth",
"techniques",
".",
"If",
"one",
"technique",
"works",
"then",
"just",
"exit",
"and",
"make",
"the",
"session",
"active",
"."
] | 251328f3762bb33c85c873ac8b1268fc0ba32f52 | https://github.com/jdtornow/challah/blob/251328f3762bb33c85c873ac8b1268fc0ba32f52/lib/challah/session.rb#L162-L186 |
1,979 | jimeh/redistat | lib/redistat/buffer.rb | Redistat.Buffer.buffer_key | def buffer_key(key, opts)
# covert keys to strings, as sorting a Hash with Symbol keys fails on
# Ruby 1.8.x.
opts = opts.inject({}) do |result, (k, v)|
result[k.to_s] = v
result
end
"#{key.to_s}:#{opts.sort.flatten.join(':')}"
end | ruby | def buffer_key(key, opts)
# covert keys to strings, as sorting a Hash with Symbol keys fails on
# Ruby 1.8.x.
opts = opts.inject({}) do |result, (k, v)|
result[k.to_s] = v
result
end
"#{key.to_s}:#{opts.sort.flatten.join(':')}"
end | [
"def",
"buffer_key",
"(",
"key",
",",
"opts",
")",
"# covert keys to strings, as sorting a Hash with Symbol keys fails on",
"# Ruby 1.8.x.",
"opts",
"=",
"opts",
".",
"inject",
"(",
"{",
"}",
")",
"do",
"|",
"result",
",",
"(",
"k",
",",
"v",
")",
"|",
"result",
"[",
"k",
".",
"to_s",
"]",
"=",
"v",
"result",
"end",
"\"#{key.to_s}:#{opts.sort.flatten.join(':')}\"",
"end"
] | depth_limit is not needed as it's evident in key.to_s | [
"depth_limit",
"is",
"not",
"needed",
"as",
"it",
"s",
"evident",
"in",
"key",
".",
"to_s"
] | 4c6a6732bfb4d48266b54cc5f4e695be5ebc0122 | https://github.com/jimeh/redistat/blob/4c6a6732bfb4d48266b54cc5f4e695be5ebc0122/lib/redistat/buffer.rb#L99-L107 |
1,980 | jdtornow/challah | lib/challah/plugins.rb | Challah.Plugins.register_plugin | def register_plugin(name, &block)
plugin = Plugin.new
plugin.instance_eval(&block)
@plugins[name] = plugin
end | ruby | def register_plugin(name, &block)
plugin = Plugin.new
plugin.instance_eval(&block)
@plugins[name] = plugin
end | [
"def",
"register_plugin",
"(",
"name",
",",
"&",
"block",
")",
"plugin",
"=",
"Plugin",
".",
"new",
"plugin",
".",
"instance_eval",
"(",
"block",
")",
"@plugins",
"[",
"name",
"]",
"=",
"plugin",
"end"
] | Register a new plugin. | [
"Register",
"a",
"new",
"plugin",
"."
] | 251328f3762bb33c85c873ac8b1268fc0ba32f52 | https://github.com/jdtornow/challah/blob/251328f3762bb33c85c873ac8b1268fc0ba32f52/lib/challah/plugins.rb#L30-L34 |
1,981 | NullVoxPopuli/drawers | lib/drawers/active_support/dependency_extensions.rb | Drawers.DependencyExtensions.resource_path_from_qualified_name | def resource_path_from_qualified_name(qualified_name)
path_options = path_options_for_qualified_name(qualified_name)
file_path = ''
path_options.uniq.each do |path_option|
file_path = search_for_file(path_option)
break if file_path.present?
end
return file_path if file_path
# Note that sometimes, the resource_type path may only be defined in a
# resource type folder
# So, look for the first file within the resource type folder
# because of ruby namespacing conventions if there is a file in the folder,
# it MUST define the namespace
path_for_first_file_in(path_options.last) || path_for_first_file_in(path_options[-2])
end | ruby | def resource_path_from_qualified_name(qualified_name)
path_options = path_options_for_qualified_name(qualified_name)
file_path = ''
path_options.uniq.each do |path_option|
file_path = search_for_file(path_option)
break if file_path.present?
end
return file_path if file_path
# Note that sometimes, the resource_type path may only be defined in a
# resource type folder
# So, look for the first file within the resource type folder
# because of ruby namespacing conventions if there is a file in the folder,
# it MUST define the namespace
path_for_first_file_in(path_options.last) || path_for_first_file_in(path_options[-2])
end | [
"def",
"resource_path_from_qualified_name",
"(",
"qualified_name",
")",
"path_options",
"=",
"path_options_for_qualified_name",
"(",
"qualified_name",
")",
"file_path",
"=",
"''",
"path_options",
".",
"uniq",
".",
"each",
"do",
"|",
"path_option",
"|",
"file_path",
"=",
"search_for_file",
"(",
"path_option",
")",
"break",
"if",
"file_path",
".",
"present?",
"end",
"return",
"file_path",
"if",
"file_path",
"# Note that sometimes, the resource_type path may only be defined in a",
"# resource type folder",
"# So, look for the first file within the resource type folder",
"# because of ruby namespacing conventions if there is a file in the folder,",
"# it MUST define the namespace",
"path_for_first_file_in",
"(",
"path_options",
".",
"last",
")",
"||",
"path_for_first_file_in",
"(",
"path_options",
"[",
"-",
"2",
"]",
")",
"end"
] | A look for the possible places that various qualified names could be
@note The Lookup Rules:
- all resources are plural
- file_names can either be named after the type or traditional ruby/rails nameing
i.e.: posts_controller.rb vs controller.rb
- regular namespacing still applies.
i.e: Api::V2::CategoriesController should be in
api/v2/categories/controller.rb
@note The Pattern:
- namespace_a - api
- namespace_b - v2
- resource_name (plural) - posts
- file_type.rb - controller.rb (or posts_controller.rb)
- operations.rb (or post_operations.rb)
- folder_type - operations/ (or post_operations/)
- related namespaced classes - create.rb
All examples assume default resource directory ("resources")
and show the order of lookup
@example Api::PostsController
Possible Locations
- api/posts/controller.rb
- api/posts/posts_controller.rb
@example Api::PostSerializer
Possible Locations
- api/posts/serializer.rb
- api/posts/post_serializer.rb
@example Api::PostOperations::Create
Possible Locations
- api/posts/operations/create.rb
- api/posts/post_operations/create.rb
@example Api::V2::CategoriesController
Possible Locations
- api/v2/categories/controller.rb
- api/v2/categories/categories_controller.rb
@param [String] qualified_name fully qualified class/module name to find the file location for | [
"A",
"look",
"for",
"the",
"possible",
"places",
"that",
"various",
"qualified",
"names",
"could",
"be"
] | 75936a180b6b9c670144338584b1296af264f377 | https://github.com/NullVoxPopuli/drawers/blob/75936a180b6b9c670144338584b1296af264f377/lib/drawers/active_support/dependency_extensions.rb#L63-L81 |
1,982 | jdtornow/challah | lib/challah/simple_cookie_store.rb | Challah.SimpleCookieStore.existing? | def existing?
exists = false
if session_cookie and validation_cookie
session_tmp = session_cookie.to_s
validation_tmp = validation_cookie.to_s
if validation_tmp == validation_cookie_value(session_tmp)
exists = true
end
end
exists
end | ruby | def existing?
exists = false
if session_cookie and validation_cookie
session_tmp = session_cookie.to_s
validation_tmp = validation_cookie.to_s
if validation_tmp == validation_cookie_value(session_tmp)
exists = true
end
end
exists
end | [
"def",
"existing?",
"exists",
"=",
"false",
"if",
"session_cookie",
"and",
"validation_cookie",
"session_tmp",
"=",
"session_cookie",
".",
"to_s",
"validation_tmp",
"=",
"validation_cookie",
".",
"to_s",
"if",
"validation_tmp",
"==",
"validation_cookie_value",
"(",
"session_tmp",
")",
"exists",
"=",
"true",
"end",
"end",
"exists",
"end"
] | Do the cookies exist, and are they valid? | [
"Do",
"the",
"cookies",
"exist",
"and",
"are",
"they",
"valid?"
] | 251328f3762bb33c85c873ac8b1268fc0ba32f52 | https://github.com/jdtornow/challah/blob/251328f3762bb33c85c873ac8b1268fc0ba32f52/lib/challah/simple_cookie_store.rb#L54-L67 |
1,983 | jdtornow/challah | lib/challah/techniques/password_technique.rb | Challah.PasswordTechnique.authenticate | def authenticate
if username? and password?
user = user_model.find_for_session(username)
if user
if user.valid_session?
if user.authenticate(@password)
return user
end
end
user.failed_authentication!
user = nil
end
end
nil
end | ruby | def authenticate
if username? and password?
user = user_model.find_for_session(username)
if user
if user.valid_session?
if user.authenticate(@password)
return user
end
end
user.failed_authentication!
user = nil
end
end
nil
end | [
"def",
"authenticate",
"if",
"username?",
"and",
"password?",
"user",
"=",
"user_model",
".",
"find_for_session",
"(",
"username",
")",
"if",
"user",
"if",
"user",
".",
"valid_session?",
"if",
"user",
".",
"authenticate",
"(",
"@password",
")",
"return",
"user",
"end",
"end",
"user",
".",
"failed_authentication!",
"user",
"=",
"nil",
"end",
"end",
"nil",
"end"
] | grab the params we want from this request
if we can successfully authenticate, return a User instance, otherwise nil | [
"grab",
"the",
"params",
"we",
"want",
"from",
"this",
"request",
"if",
"we",
"can",
"successfully",
"authenticate",
"return",
"a",
"User",
"instance",
"otherwise",
"nil"
] | 251328f3762bb33c85c873ac8b1268fc0ba32f52 | https://github.com/jdtornow/challah/blob/251328f3762bb33c85c873ac8b1268fc0ba32f52/lib/challah/techniques/password_technique.rb#L14-L31 |
1,984 | sstephenson/hike | lib/hike/fileutils.rb | Hike.FileUtils.entries | def entries(path)
if File.directory?(path)
Dir.entries(path).reject { |entry| entry =~ /^\.|~$|^\#.*\#$/ }.sort
else
[]
end
end | ruby | def entries(path)
if File.directory?(path)
Dir.entries(path).reject { |entry| entry =~ /^\.|~$|^\#.*\#$/ }.sort
else
[]
end
end | [
"def",
"entries",
"(",
"path",
")",
"if",
"File",
".",
"directory?",
"(",
"path",
")",
"Dir",
".",
"entries",
"(",
"path",
")",
".",
"reject",
"{",
"|",
"entry",
"|",
"entry",
"=~",
"/",
"\\.",
"\\#",
"\\#",
"/",
"}",
".",
"sort",
"else",
"[",
"]",
"end",
"end"
] | A version of `Dir.entries` that filters out `.` files and `~` swap files.
Returns an empty `Array` if the directory does not exist. | [
"A",
"version",
"of",
"Dir",
".",
"entries",
"that",
"filters",
"out",
".",
"files",
"and",
"~",
"swap",
"files",
".",
"Returns",
"an",
"empty",
"Array",
"if",
"the",
"directory",
"does",
"not",
"exist",
"."
] | 3abf0b3feb47c26911f8cedf2cd409471fd26da1 | https://github.com/sstephenson/hike/blob/3abf0b3feb47c26911f8cedf2cd409471fd26da1/lib/hike/fileutils.rb#L16-L22 |
1,985 | jdtornow/challah | lib/challah/validators/email_validator.rb | Challah.EmailValidator.validate_each | def validate_each(record, attribute, value)
unless value =~ EmailValidator.pattern
record.errors.add(attribute, options[:message] || :invalid_email)
end
end | ruby | def validate_each(record, attribute, value)
unless value =~ EmailValidator.pattern
record.errors.add(attribute, options[:message] || :invalid_email)
end
end | [
"def",
"validate_each",
"(",
"record",
",",
"attribute",
",",
"value",
")",
"unless",
"value",
"=~",
"EmailValidator",
".",
"pattern",
"record",
".",
"errors",
".",
"add",
"(",
"attribute",
",",
"options",
"[",
":message",
"]",
"||",
":invalid_email",
")",
"end",
"end"
] | Called automatically by ActiveModel validation.. | [
"Called",
"automatically",
"by",
"ActiveModel",
"validation",
".."
] | 251328f3762bb33c85c873ac8b1268fc0ba32f52 | https://github.com/jdtornow/challah/blob/251328f3762bb33c85c873ac8b1268fc0ba32f52/lib/challah/validators/email_validator.rb#L10-L14 |
1,986 | jdtornow/challah | lib/challah/concerns/user/authenticateable.rb | Challah.UserAuthenticateable.authenticate | def authenticate(*args)
return false unless active?
if args.length > 1
method = args.shift
if Challah.authenticators[method]
return Challah.authenticators[method].match?(self, providers[method], *args)
end
false
else
self.authenticate(:password, args[0])
end
end | ruby | def authenticate(*args)
return false unless active?
if args.length > 1
method = args.shift
if Challah.authenticators[method]
return Challah.authenticators[method].match?(self, providers[method], *args)
end
false
else
self.authenticate(:password, args[0])
end
end | [
"def",
"authenticate",
"(",
"*",
"args",
")",
"return",
"false",
"unless",
"active?",
"if",
"args",
".",
"length",
">",
"1",
"method",
"=",
"args",
".",
"shift",
"if",
"Challah",
".",
"authenticators",
"[",
"method",
"]",
"return",
"Challah",
".",
"authenticators",
"[",
"method",
"]",
".",
"match?",
"(",
"self",
",",
"providers",
"[",
"method",
"]",
",",
"args",
")",
"end",
"false",
"else",
"self",
".",
"authenticate",
"(",
":password",
",",
"args",
"[",
"0",
"]",
")",
"end",
"end"
] | Generic authentication method. By default, this just checks to see if the password
given matches this user. You can also pass in the first parameter as the method
to use for a different type of authentication. | [
"Generic",
"authentication",
"method",
".",
"By",
"default",
"this",
"just",
"checks",
"to",
"see",
"if",
"the",
"password",
"given",
"matches",
"this",
"user",
".",
"You",
"can",
"also",
"pass",
"in",
"the",
"first",
"parameter",
"as",
"the",
"method",
"to",
"use",
"for",
"a",
"different",
"type",
"of",
"authentication",
"."
] | 251328f3762bb33c85c873ac8b1268fc0ba32f52 | https://github.com/jdtornow/challah/blob/251328f3762bb33c85c873ac8b1268fc0ba32f52/lib/challah/concerns/user/authenticateable.rb#L6-L20 |
1,987 | jdtornow/challah | lib/challah/concerns/user/authenticateable.rb | Challah.UserAuthenticateable.successful_authentication! | def successful_authentication!(ip_address = nil)
self.last_session_at = Time.now
self.last_session_ip = ip_address if respond_to?(:last_session_ip=)
self.save
self.increment!(:session_count, 1)
end | ruby | def successful_authentication!(ip_address = nil)
self.last_session_at = Time.now
self.last_session_ip = ip_address if respond_to?(:last_session_ip=)
self.save
self.increment!(:session_count, 1)
end | [
"def",
"successful_authentication!",
"(",
"ip_address",
"=",
"nil",
")",
"self",
".",
"last_session_at",
"=",
"Time",
".",
"now",
"self",
".",
"last_session_ip",
"=",
"ip_address",
"if",
"respond_to?",
"(",
":last_session_ip=",
")",
"self",
".",
"save",
"self",
".",
"increment!",
"(",
":session_count",
",",
"1",
")",
"end"
] | Called when a +Session+ validation is successful, and this user has
been authenticated. | [
"Called",
"when",
"a",
"+",
"Session",
"+",
"validation",
"is",
"successful",
"and",
"this",
"user",
"has",
"been",
"authenticated",
"."
] | 251328f3762bb33c85c873ac8b1268fc0ba32f52 | https://github.com/jdtornow/challah/blob/251328f3762bb33c85c873ac8b1268fc0ba32f52/lib/challah/concerns/user/authenticateable.rb#L36-L41 |
1,988 | dicom/rtp-connect | lib/rtp-connect/control_point.rb | RTP.ControlPoint.dcm_mlc_positions | def dcm_mlc_positions(scale=nil)
coeff = (scale == :elekta ? -1 : 1)
# As with the collimators, the first side (1/a) may need scale invertion:
pos_a = @mlc_lp_a.collect{|p| (p.to_f * 10 * coeff).round(1) unless p.empty?}.compact
pos_b = @mlc_lp_b.collect{|p| (p.to_f * 10).round(1) unless p.empty?}.compact
(pos_a + pos_b).join("\\")
end | ruby | def dcm_mlc_positions(scale=nil)
coeff = (scale == :elekta ? -1 : 1)
# As with the collimators, the first side (1/a) may need scale invertion:
pos_a = @mlc_lp_a.collect{|p| (p.to_f * 10 * coeff).round(1) unless p.empty?}.compact
pos_b = @mlc_lp_b.collect{|p| (p.to_f * 10).round(1) unless p.empty?}.compact
(pos_a + pos_b).join("\\")
end | [
"def",
"dcm_mlc_positions",
"(",
"scale",
"=",
"nil",
")",
"coeff",
"=",
"(",
"scale",
"==",
":elekta",
"?",
"-",
"1",
":",
"1",
")",
"# As with the collimators, the first side (1/a) may need scale invertion:",
"pos_a",
"=",
"@mlc_lp_a",
".",
"collect",
"{",
"|",
"p",
"|",
"(",
"p",
".",
"to_f",
"*",
"10",
"*",
"coeff",
")",
".",
"round",
"(",
"1",
")",
"unless",
"p",
".",
"empty?",
"}",
".",
"compact",
"pos_b",
"=",
"@mlc_lp_b",
".",
"collect",
"{",
"|",
"p",
"|",
"(",
"p",
".",
"to_f",
"*",
"10",
")",
".",
"round",
"(",
"1",
")",
"unless",
"p",
".",
"empty?",
"}",
".",
"compact",
"(",
"pos_a",
"+",
"pos_b",
")",
".",
"join",
"(",
"\"\\\\\"",
")",
"end"
] | Converts the mlc_lp_a & mlc_lp_b attributes to a proper DICOM formatted string.
@param [Symbol] scale if set, relevant device parameters are converted from native readout format to IEC1217 (supported values are :elekta & :varian)
@return [String] the DICOM-formatted leaf pair positions | [
"Converts",
"the",
"mlc_lp_a",
"&",
"mlc_lp_b",
"attributes",
"to",
"a",
"proper",
"DICOM",
"formatted",
"string",
"."
] | e23791970218a7087a0d798aa430acf36f79d758 | https://github.com/dicom/rtp-connect/blob/e23791970218a7087a0d798aa430acf36f79d758/lib/rtp-connect/control_point.rb#L193-L199 |
1,989 | dicom/rtp-connect | lib/rtp-connect/control_point.rb | RTP.ControlPoint.dcm_collimator_1 | def dcm_collimator_1(scale=nil, axis)
coeff = 1
if scale == :elekta
axis = (axis == :x ? :y : :x)
coeff = -1
elsif scale == :varian
coeff = -1
end
dcm_collimator(axis, coeff, side=1)
end | ruby | def dcm_collimator_1(scale=nil, axis)
coeff = 1
if scale == :elekta
axis = (axis == :x ? :y : :x)
coeff = -1
elsif scale == :varian
coeff = -1
end
dcm_collimator(axis, coeff, side=1)
end | [
"def",
"dcm_collimator_1",
"(",
"scale",
"=",
"nil",
",",
"axis",
")",
"coeff",
"=",
"1",
"if",
"scale",
"==",
":elekta",
"axis",
"=",
"(",
"axis",
"==",
":x",
"?",
":y",
":",
":x",
")",
"coeff",
"=",
"-",
"1",
"elsif",
"scale",
"==",
":varian",
"coeff",
"=",
"-",
"1",
"end",
"dcm_collimator",
"(",
"axis",
",",
"coeff",
",",
"side",
"=",
"1",
")",
"end"
] | Converts the collimator1 attribute to proper DICOM format.
@param [Symbol] scale if set, relevant device parameters are converted from a native readout format to IEC1217 (supported values are :elekta & :varian)
@return [Float] the DICOM-formatted collimator_x1 attribute | [
"Converts",
"the",
"collimator1",
"attribute",
"to",
"proper",
"DICOM",
"format",
"."
] | e23791970218a7087a0d798aa430acf36f79d758 | https://github.com/dicom/rtp-connect/blob/e23791970218a7087a0d798aa430acf36f79d758/lib/rtp-connect/control_point.rb#L600-L609 |
1,990 | SCPR/secretary-rails | lib/secretary/versioned_attributes.rb | Secretary.VersionedAttributes.versioned_changes | def versioned_changes
modified_changes = {}
raw_changes = self.changes.select {|k,_| versioned_attribute?(k)}.to_hash
raw_changes.each do |key, (previous, current)|
if reflection = self.class.reflect_on_association(key.to_sym)
if reflection.collection?
previous = previous.map(&:versioned_attributes)
current = current.map(&:versioned_attributes)
else
previous = previous ? previous.versioned_attributes : {}
current = if current && !current.marked_for_destruction?
current.versioned_attributes
else
{}
end
end
end
# This really shouldn't need to be here,
# but there is some confusion if we're destroying
# an associated object in a save callback on the
# parent object. We can't know that the callback
# is going to destroy this object on save,
# so we just have to add the association normally
# and then filter it out here.
if previous != current
modified_changes[key] = [previous, current]
end
end
modified_changes
end | ruby | def versioned_changes
modified_changes = {}
raw_changes = self.changes.select {|k,_| versioned_attribute?(k)}.to_hash
raw_changes.each do |key, (previous, current)|
if reflection = self.class.reflect_on_association(key.to_sym)
if reflection.collection?
previous = previous.map(&:versioned_attributes)
current = current.map(&:versioned_attributes)
else
previous = previous ? previous.versioned_attributes : {}
current = if current && !current.marked_for_destruction?
current.versioned_attributes
else
{}
end
end
end
# This really shouldn't need to be here,
# but there is some confusion if we're destroying
# an associated object in a save callback on the
# parent object. We can't know that the callback
# is going to destroy this object on save,
# so we just have to add the association normally
# and then filter it out here.
if previous != current
modified_changes[key] = [previous, current]
end
end
modified_changes
end | [
"def",
"versioned_changes",
"modified_changes",
"=",
"{",
"}",
"raw_changes",
"=",
"self",
".",
"changes",
".",
"select",
"{",
"|",
"k",
",",
"_",
"|",
"versioned_attribute?",
"(",
"k",
")",
"}",
".",
"to_hash",
"raw_changes",
".",
"each",
"do",
"|",
"key",
",",
"(",
"previous",
",",
"current",
")",
"|",
"if",
"reflection",
"=",
"self",
".",
"class",
".",
"reflect_on_association",
"(",
"key",
".",
"to_sym",
")",
"if",
"reflection",
".",
"collection?",
"previous",
"=",
"previous",
".",
"map",
"(",
":versioned_attributes",
")",
"current",
"=",
"current",
".",
"map",
"(",
":versioned_attributes",
")",
"else",
"previous",
"=",
"previous",
"?",
"previous",
".",
"versioned_attributes",
":",
"{",
"}",
"current",
"=",
"if",
"current",
"&&",
"!",
"current",
".",
"marked_for_destruction?",
"current",
".",
"versioned_attributes",
"else",
"{",
"}",
"end",
"end",
"end",
"# This really shouldn't need to be here,",
"# but there is some confusion if we're destroying",
"# an associated object in a save callback on the",
"# parent object. We can't know that the callback",
"# is going to destroy this object on save,",
"# so we just have to add the association normally",
"# and then filter it out here.",
"if",
"previous",
"!=",
"current",
"modified_changes",
"[",
"key",
"]",
"=",
"[",
"previous",
",",
"current",
"]",
"end",
"end",
"modified_changes",
"end"
] | The hash that gets serialized into the `object_changes` column.
This takes the `changes` hash and processes the associations to be
human-readable objects. | [
"The",
"hash",
"that",
"gets",
"serialized",
"into",
"the",
"object_changes",
"column",
"."
] | f831a2e9b7fa4fe7b1d50f6f060ddc77ee857945 | https://github.com/SCPR/secretary-rails/blob/f831a2e9b7fa4fe7b1d50f6f060ddc77ee857945/lib/secretary/versioned_attributes.rb#L78-L111 |
1,991 | SCPR/secretary-rails | lib/secretary/versioned_attributes.rb | Secretary.VersionedAttributes.versioned_attributes | def versioned_attributes
json = self.as_json(:root => false).select do |k,_|
versioned_attribute?(k)
end
json.to_hash
end | ruby | def versioned_attributes
json = self.as_json(:root => false).select do |k,_|
versioned_attribute?(k)
end
json.to_hash
end | [
"def",
"versioned_attributes",
"json",
"=",
"self",
".",
"as_json",
"(",
":root",
"=>",
"false",
")",
".",
"select",
"do",
"|",
"k",
",",
"_",
"|",
"versioned_attribute?",
"(",
"k",
")",
"end",
"json",
".",
"to_hash",
"end"
] | The object's versioned attributes as a hash. | [
"The",
"object",
"s",
"versioned",
"attributes",
"as",
"a",
"hash",
"."
] | f831a2e9b7fa4fe7b1d50f6f060ddc77ee857945 | https://github.com/SCPR/secretary-rails/blob/f831a2e9b7fa4fe7b1d50f6f060ddc77ee857945/lib/secretary/versioned_attributes.rb#L114-L120 |
1,992 | norman/disqus | lib/disqus/forum.rb | Disqus.Forum.get_thread_by_url | def get_thread_by_url(url)
response = Disqus::Api::get_thread_by_url(:url => url, :forum_api_key => key)
if response["succeeded"]
t = response["message"]
Thread.new(t["id"], self, t["slug"], t["title"], t["created_at"], t["allow_comments"], t["url"], t["identifier"])
else
raise_api_error(response)
end
end | ruby | def get_thread_by_url(url)
response = Disqus::Api::get_thread_by_url(:url => url, :forum_api_key => key)
if response["succeeded"]
t = response["message"]
Thread.new(t["id"], self, t["slug"], t["title"], t["created_at"], t["allow_comments"], t["url"], t["identifier"])
else
raise_api_error(response)
end
end | [
"def",
"get_thread_by_url",
"(",
"url",
")",
"response",
"=",
"Disqus",
"::",
"Api",
"::",
"get_thread_by_url",
"(",
":url",
"=>",
"url",
",",
":forum_api_key",
"=>",
"key",
")",
"if",
"response",
"[",
"\"succeeded\"",
"]",
"t",
"=",
"response",
"[",
"\"message\"",
"]",
"Thread",
".",
"new",
"(",
"t",
"[",
"\"id\"",
"]",
",",
"self",
",",
"t",
"[",
"\"slug\"",
"]",
",",
"t",
"[",
"\"title\"",
"]",
",",
"t",
"[",
"\"created_at\"",
"]",
",",
"t",
"[",
"\"allow_comments\"",
"]",
",",
"t",
"[",
"\"url\"",
"]",
",",
"t",
"[",
"\"identifier\"",
"]",
")",
"else",
"raise_api_error",
"(",
"response",
")",
"end",
"end"
] | Returns a thread associated with the given URL.
A thread will only have an associated URL if it was automatically
created by Disqus javascript embedded on that page. | [
"Returns",
"a",
"thread",
"associated",
"with",
"the",
"given",
"URL",
"."
] | 6a5fa19d2be2ff67909e988356533a4d7ac2b51b | https://github.com/norman/disqus/blob/6a5fa19d2be2ff67909e988356533a4d7ac2b51b/lib/disqus/forum.rb#L55-L63 |
1,993 | SCPR/secretary-rails | app/models/secretary/version.rb | Secretary.Version.attribute_diffs | def attribute_diffs
@attribute_diffs ||= begin
changes = self.object_changes.dup
attribute_diffs = {}
# Compare each of object_b's attributes to object_a's attributes
# And if there is a difference, add it to the Diff
changes.each do |attribute, values|
# values is [previous_value, new_value]
diff = Diffy::Diff.new(values[0].to_s, values[1].to_s)
attribute_diffs[attribute] = diff
end
attribute_diffs
end
end | ruby | def attribute_diffs
@attribute_diffs ||= begin
changes = self.object_changes.dup
attribute_diffs = {}
# Compare each of object_b's attributes to object_a's attributes
# And if there is a difference, add it to the Diff
changes.each do |attribute, values|
# values is [previous_value, new_value]
diff = Diffy::Diff.new(values[0].to_s, values[1].to_s)
attribute_diffs[attribute] = diff
end
attribute_diffs
end
end | [
"def",
"attribute_diffs",
"@attribute_diffs",
"||=",
"begin",
"changes",
"=",
"self",
".",
"object_changes",
".",
"dup",
"attribute_diffs",
"=",
"{",
"}",
"# Compare each of object_b's attributes to object_a's attributes",
"# And if there is a difference, add it to the Diff",
"changes",
".",
"each",
"do",
"|",
"attribute",
",",
"values",
"|",
"# values is [previous_value, new_value]",
"diff",
"=",
"Diffy",
"::",
"Diff",
".",
"new",
"(",
"values",
"[",
"0",
"]",
".",
"to_s",
",",
"values",
"[",
"1",
"]",
".",
"to_s",
")",
"attribute_diffs",
"[",
"attribute",
"]",
"=",
"diff",
"end",
"attribute_diffs",
"end",
"end"
] | The attribute diffs for this version | [
"The",
"attribute",
"diffs",
"for",
"this",
"version"
] | f831a2e9b7fa4fe7b1d50f6f060ddc77ee857945 | https://github.com/SCPR/secretary-rails/blob/f831a2e9b7fa4fe7b1d50f6f060ddc77ee857945/app/models/secretary/version.rb#L61-L76 |
1,994 | SCPR/secretary-rails | lib/secretary/dirty_associations.rb | Secretary.DirtyAssociations.__compat_set_attribute_was | def __compat_set_attribute_was(name, previous)
if respond_to?(:set_attribute_was, true)
# Rails 4.2+
set_attribute_was(name, previous)
else
# Rails < 4.2
changed_attributes[name] = previous
end
end | ruby | def __compat_set_attribute_was(name, previous)
if respond_to?(:set_attribute_was, true)
# Rails 4.2+
set_attribute_was(name, previous)
else
# Rails < 4.2
changed_attributes[name] = previous
end
end | [
"def",
"__compat_set_attribute_was",
"(",
"name",
",",
"previous",
")",
"if",
"respond_to?",
"(",
":set_attribute_was",
",",
"true",
")",
"# Rails 4.2+",
"set_attribute_was",
"(",
"name",
",",
"previous",
")",
"else",
"# Rails < 4.2",
"changed_attributes",
"[",
"name",
"]",
"=",
"previous",
"end",
"end"
] | Rails 4.2 adds "set_attribute_was" which must be used, so we'll
check for it. | [
"Rails",
"4",
".",
"2",
"adds",
"set_attribute_was",
"which",
"must",
"be",
"used",
"so",
"we",
"ll",
"check",
"for",
"it",
"."
] | f831a2e9b7fa4fe7b1d50f6f060ddc77ee857945 | https://github.com/SCPR/secretary-rails/blob/f831a2e9b7fa4fe7b1d50f6f060ddc77ee857945/lib/secretary/dirty_associations.rb#L125-L133 |
1,995 | dicom/rtp-connect | lib/rtp-connect/record.rb | RTP.Record.encode | def encode(options={})
encoded_values = values.collect {|v| v && v.encode('ISO8859-1')}
encoded_values = discard_unsupported_attributes(encoded_values, options) if options[:version]
content = CSV.generate_line(encoded_values, force_quotes: true, row_sep: '') + ","
checksum = content.checksum
# Complete string is content + checksum (in double quotes) + carriage return + line feed
return (content + checksum.to_s.wrap + "\r\n").encode('ISO8859-1')
end | ruby | def encode(options={})
encoded_values = values.collect {|v| v && v.encode('ISO8859-1')}
encoded_values = discard_unsupported_attributes(encoded_values, options) if options[:version]
content = CSV.generate_line(encoded_values, force_quotes: true, row_sep: '') + ","
checksum = content.checksum
# Complete string is content + checksum (in double quotes) + carriage return + line feed
return (content + checksum.to_s.wrap + "\r\n").encode('ISO8859-1')
end | [
"def",
"encode",
"(",
"options",
"=",
"{",
"}",
")",
"encoded_values",
"=",
"values",
".",
"collect",
"{",
"|",
"v",
"|",
"v",
"&&",
"v",
".",
"encode",
"(",
"'ISO8859-1'",
")",
"}",
"encoded_values",
"=",
"discard_unsupported_attributes",
"(",
"encoded_values",
",",
"options",
")",
"if",
"options",
"[",
":version",
"]",
"content",
"=",
"CSV",
".",
"generate_line",
"(",
"encoded_values",
",",
"force_quotes",
":",
"true",
",",
"row_sep",
":",
"''",
")",
"+",
"\",\"",
"checksum",
"=",
"content",
".",
"checksum",
"# Complete string is content + checksum (in double quotes) + carriage return + line feed",
"return",
"(",
"content",
"+",
"checksum",
".",
"to_s",
".",
"wrap",
"+",
"\"\\r\\n\"",
")",
".",
"encode",
"(",
"'ISO8859-1'",
")",
"end"
] | Encodes a string from the contents of this instance.
This produces the full record string line, including a computed CRC checksum.
@param [Hash] options an optional hash parameter
@option options [Float] :version the Mosaiq compatibility version number (e.g. 2.4) used for the output
@return [String] a proper RTPConnect type CSV string | [
"Encodes",
"a",
"string",
"from",
"the",
"contents",
"of",
"this",
"instance",
"."
] | e23791970218a7087a0d798aa430acf36f79d758 | https://github.com/dicom/rtp-connect/blob/e23791970218a7087a0d798aa430acf36f79d758/lib/rtp-connect/record.rb#L47-L54 |
1,996 | dicom/rtp-connect | lib/rtp-connect/record.rb | RTP.Record.get_parent | def get_parent(last_parent, klass)
if last_parent.is_a?(klass)
return last_parent
else
return last_parent.get_parent(last_parent.parent, klass)
end
end | ruby | def get_parent(last_parent, klass)
if last_parent.is_a?(klass)
return last_parent
else
return last_parent.get_parent(last_parent.parent, klass)
end
end | [
"def",
"get_parent",
"(",
"last_parent",
",",
"klass",
")",
"if",
"last_parent",
".",
"is_a?",
"(",
"klass",
")",
"return",
"last_parent",
"else",
"return",
"last_parent",
".",
"get_parent",
"(",
"last_parent",
".",
"parent",
",",
"klass",
")",
"end",
"end"
] | Follows the tree of parents until the appropriate parent of the requesting record is found.
@param [Record] last_parent the previous parent (the record from the previous line in the RTP file)
@param [Record] klass the expected parent record class of this record (e.g. Plan, Field) | [
"Follows",
"the",
"tree",
"of",
"parents",
"until",
"the",
"appropriate",
"parent",
"of",
"the",
"requesting",
"record",
"is",
"found",
"."
] | e23791970218a7087a0d798aa430acf36f79d758 | https://github.com/dicom/rtp-connect/blob/e23791970218a7087a0d798aa430acf36f79d758/lib/rtp-connect/record.rb#L61-L67 |
1,997 | dicom/rtp-connect | lib/rtp-connect/record.rb | RTP.Record.load | def load(string, options={})
# Extract processed values:
values = string.to_s.values(options[:repair])
raise ArgumentError, "Invalid argument 'string': Expected at least #{@min_elements} elements for #{@keyword}, got #{values.length}." if values.length < @min_elements
RTP.logger.warn "The number of given elements (#{values.length}) exceeds the known number of data elements for this record (#{@max_elements}). This may indicate an invalid string record or that the RTP format has recently been expanded with new elements." if values.length > @max_elements
self.send(:set_attributes, values)
self
end | ruby | def load(string, options={})
# Extract processed values:
values = string.to_s.values(options[:repair])
raise ArgumentError, "Invalid argument 'string': Expected at least #{@min_elements} elements for #{@keyword}, got #{values.length}." if values.length < @min_elements
RTP.logger.warn "The number of given elements (#{values.length}) exceeds the known number of data elements for this record (#{@max_elements}). This may indicate an invalid string record or that the RTP format has recently been expanded with new elements." if values.length > @max_elements
self.send(:set_attributes, values)
self
end | [
"def",
"load",
"(",
"string",
",",
"options",
"=",
"{",
"}",
")",
"# Extract processed values:",
"values",
"=",
"string",
".",
"to_s",
".",
"values",
"(",
"options",
"[",
":repair",
"]",
")",
"raise",
"ArgumentError",
",",
"\"Invalid argument 'string': Expected at least #{@min_elements} elements for #{@keyword}, got #{values.length}.\"",
"if",
"values",
".",
"length",
"<",
"@min_elements",
"RTP",
".",
"logger",
".",
"warn",
"\"The number of given elements (#{values.length}) exceeds the known number of data elements for this record (#{@max_elements}). This may indicate an invalid string record or that the RTP format has recently been expanded with new elements.\"",
"if",
"values",
".",
"length",
">",
"@max_elements",
"self",
".",
"send",
"(",
":set_attributes",
",",
"values",
")",
"self",
"end"
] | Sets up a record by parsing a RTPConnect string line.
@param [#to_s] string the extended treatment field definition record string line
@return [Record] the updated Record instance
@raise [ArgumentError] if given a string containing an invalid number of elements | [
"Sets",
"up",
"a",
"record",
"by",
"parsing",
"a",
"RTPConnect",
"string",
"line",
"."
] | e23791970218a7087a0d798aa430acf36f79d758 | https://github.com/dicom/rtp-connect/blob/e23791970218a7087a0d798aa430acf36f79d758/lib/rtp-connect/record.rb#L86-L93 |
1,998 | dicom/rtp-connect | lib/rtp-connect/record.rb | RTP.Record.to_s | def to_s(options={})
str = encode(options)
children.each do |child|
# Note that the extended plan record was introduced in Mosaiq 2.5.
str += child.to_s(options) unless child.class == ExtendedPlan && options[:version].to_f < 2.5
end
str
end | ruby | def to_s(options={})
str = encode(options)
children.each do |child|
# Note that the extended plan record was introduced in Mosaiq 2.5.
str += child.to_s(options) unless child.class == ExtendedPlan && options[:version].to_f < 2.5
end
str
end | [
"def",
"to_s",
"(",
"options",
"=",
"{",
"}",
")",
"str",
"=",
"encode",
"(",
"options",
")",
"children",
".",
"each",
"do",
"|",
"child",
"|",
"# Note that the extended plan record was introduced in Mosaiq 2.5.",
"str",
"+=",
"child",
".",
"to_s",
"(",
"options",
")",
"unless",
"child",
".",
"class",
"==",
"ExtendedPlan",
"&&",
"options",
"[",
":version",
"]",
".",
"to_f",
"<",
"2.5",
"end",
"str",
"end"
] | Encodes the record + any hiearchy of child objects,
to a properly formatted RTPConnect ascii string.
@param [Hash] options an optional hash parameter
@option options [Float] :version the Mosaiq compatibility version number (e.g. 2.4) used for the output
@return [String] an RTP string with a single or multiple lines/records | [
"Encodes",
"the",
"record",
"+",
"any",
"hiearchy",
"of",
"child",
"objects",
"to",
"a",
"properly",
"formatted",
"RTPConnect",
"ascii",
"string",
"."
] | e23791970218a7087a0d798aa430acf36f79d758 | https://github.com/dicom/rtp-connect/blob/e23791970218a7087a0d798aa430acf36f79d758/lib/rtp-connect/record.rb#L110-L117 |
1,999 | dicom/rtp-connect | lib/rtp-connect/record.rb | RTP.Record.delete_child | def delete_child(attribute, instance=nil)
if self.send(attribute).is_a?(Array)
deleted = self.send(attribute).delete(instance)
deleted.parent = nil if deleted
else
self.send(attribute).parent = nil if self.send(attribute)
self.instance_variable_set("@#{attribute}", nil)
end
end | ruby | def delete_child(attribute, instance=nil)
if self.send(attribute).is_a?(Array)
deleted = self.send(attribute).delete(instance)
deleted.parent = nil if deleted
else
self.send(attribute).parent = nil if self.send(attribute)
self.instance_variable_set("@#{attribute}", nil)
end
end | [
"def",
"delete_child",
"(",
"attribute",
",",
"instance",
"=",
"nil",
")",
"if",
"self",
".",
"send",
"(",
"attribute",
")",
".",
"is_a?",
"(",
"Array",
")",
"deleted",
"=",
"self",
".",
"send",
"(",
"attribute",
")",
".",
"delete",
"(",
"instance",
")",
"deleted",
".",
"parent",
"=",
"nil",
"if",
"deleted",
"else",
"self",
".",
"send",
"(",
"attribute",
")",
".",
"parent",
"=",
"nil",
"if",
"self",
".",
"send",
"(",
"attribute",
")",
"self",
".",
"instance_variable_set",
"(",
"\"@#{attribute}\"",
",",
"nil",
")",
"end",
"end"
] | Removes the reference of the given instance from the attribute of this record.
@param [Symbol] attribute the name of the child attribute from which to remove a child
@param [Record] instance a child record to be removed from this instance | [
"Removes",
"the",
"reference",
"of",
"the",
"given",
"instance",
"from",
"the",
"attribute",
"of",
"this",
"record",
"."
] | e23791970218a7087a0d798aa430acf36f79d758 | https://github.com/dicom/rtp-connect/blob/e23791970218a7087a0d798aa430acf36f79d758/lib/rtp-connect/record.rb#L139-L147 |
Subsets and Splits