repo
stringlengths 5
58
| path
stringlengths 9
168
| func_name
stringlengths 9
130
| original_string
stringlengths 66
10.5k
| language
stringclasses 1
value | code
stringlengths 66
10.5k
| code_tokens
sequence | docstring
stringlengths 8
16k
| docstring_tokens
sequence | sha
stringlengths 40
40
| url
stringlengths 94
266
| partition
stringclasses 1
value |
---|---|---|---|---|---|---|---|---|---|---|---|
sumoheavy/jira-ruby | lib/jira/base.rb | JIRA.Base.set_attrs | def set_attrs(hash, clobber = true, target = nil)
target ||= @attrs
if clobber
target.merge!(hash)
hash
else
hash.each do |k, v|
if v.is_a?(Hash)
set_attrs(v, clobber, target[k])
else
target[k] = v
end
end
end
end | ruby | def set_attrs(hash, clobber = true, target = nil)
target ||= @attrs
if clobber
target.merge!(hash)
hash
else
hash.each do |k, v|
if v.is_a?(Hash)
set_attrs(v, clobber, target[k])
else
target[k] = v
end
end
end
end | [
"def",
"set_attrs",
"(",
"hash",
",",
"clobber",
"=",
"true",
",",
"target",
"=",
"nil",
")",
"target",
"||=",
"@attrs",
"if",
"clobber",
"target",
".",
"merge!",
"(",
"hash",
")",
"hash",
"else",
"hash",
".",
"each",
"do",
"|",
"k",
",",
"v",
"|",
"if",
"v",
".",
"is_a?",
"(",
"Hash",
")",
"set_attrs",
"(",
"v",
",",
"clobber",
",",
"target",
"[",
"k",
"]",
")",
"else",
"target",
"[",
"k",
"]",
"=",
"v",
"end",
"end",
"end",
"end"
] | Set the current attributes from a hash. If clobber is true, any existing
hash values will be clobbered by the new hash, otherwise the hash will
be deeply merged into attrs. The target paramater is for internal use only
and should not be used. | [
"Set",
"the",
"current",
"attributes",
"from",
"a",
"hash",
".",
"If",
"clobber",
"is",
"true",
"any",
"existing",
"hash",
"values",
"will",
"be",
"clobbered",
"by",
"the",
"new",
"hash",
"otherwise",
"the",
"hash",
"will",
"be",
"deeply",
"merged",
"into",
"attrs",
".",
"The",
"target",
"paramater",
"is",
"for",
"internal",
"use",
"only",
"and",
"should",
"not",
"be",
"used",
"."
] | 25e896f227ab81c528e9678708cb546d2f62f018 | https://github.com/sumoheavy/jira-ruby/blob/25e896f227ab81c528e9678708cb546d2f62f018/lib/jira/base.rb#L391-L405 | train |
chanks/que | lib/que/job_methods.rb | Que.JobMethods._run | def _run(args: nil, reraise_errors: false)
if args.nil? && que_target
args = que_target.que_attrs.fetch(:args)
end
run(*args)
default_resolve_action if que_target && !que_target.que_resolved
rescue => error
raise error unless que_target
que_target.que_error = error
run_error_notifier =
begin
handle_error(error)
rescue => error_2
Que.notify_error(error_2, que_target.que_attrs)
true
end
Que.notify_error(error, que_target.que_attrs) if run_error_notifier
retry_in_default_interval unless que_target.que_resolved
raise error if reraise_errors
end | ruby | def _run(args: nil, reraise_errors: false)
if args.nil? && que_target
args = que_target.que_attrs.fetch(:args)
end
run(*args)
default_resolve_action if que_target && !que_target.que_resolved
rescue => error
raise error unless que_target
que_target.que_error = error
run_error_notifier =
begin
handle_error(error)
rescue => error_2
Que.notify_error(error_2, que_target.que_attrs)
true
end
Que.notify_error(error, que_target.que_attrs) if run_error_notifier
retry_in_default_interval unless que_target.que_resolved
raise error if reraise_errors
end | [
"def",
"_run",
"(",
"args",
":",
"nil",
",",
"reraise_errors",
":",
"false",
")",
"if",
"args",
".",
"nil?",
"&&",
"que_target",
"args",
"=",
"que_target",
".",
"que_attrs",
".",
"fetch",
"(",
":args",
")",
"end",
"run",
"(",
"args",
")",
"default_resolve_action",
"if",
"que_target",
"&&",
"!",
"que_target",
".",
"que_resolved",
"rescue",
"=>",
"error",
"raise",
"error",
"unless",
"que_target",
"que_target",
".",
"que_error",
"=",
"error",
"run_error_notifier",
"=",
"begin",
"handle_error",
"(",
"error",
")",
"rescue",
"=>",
"error_2",
"Que",
".",
"notify_error",
"(",
"error_2",
",",
"que_target",
".",
"que_attrs",
")",
"true",
"end",
"Que",
".",
"notify_error",
"(",
"error",
",",
"que_target",
".",
"que_attrs",
")",
"if",
"run_error_notifier",
"retry_in_default_interval",
"unless",
"que_target",
".",
"que_resolved",
"raise",
"error",
"if",
"reraise_errors",
"end"
] | Note that we delegate almost all methods to the result of the que_target
method, which could be one of a few things, depending on the circumstance.
Run the job with error handling and cleanup logic. Optionally support
overriding the args, because it's necessary when jobs are invoked from
ActiveJob. | [
"Note",
"that",
"we",
"delegate",
"almost",
"all",
"methods",
"to",
"the",
"result",
"of",
"the",
"que_target",
"method",
"which",
"could",
"be",
"one",
"of",
"a",
"few",
"things",
"depending",
"on",
"the",
"circumstance",
".",
"Run",
"the",
"job",
"with",
"error",
"handling",
"and",
"cleanup",
"logic",
".",
"Optionally",
"support",
"overriding",
"the",
"args",
"because",
"it",
"s",
"necessary",
"when",
"jobs",
"are",
"invoked",
"from",
"ActiveJob",
"."
] | c7ae049db0ca13056a28c71ae610f8900f21feb4 | https://github.com/chanks/que/blob/c7ae049db0ca13056a28c71ae610f8900f21feb4/lib/que/job_methods.rb#L42-L66 | train |
chanks/que | lib/que/job_methods.rb | Que.JobMethods.handle_error | def handle_error(error)
return unless que_target
max = resolve_que_setting(:maximum_retry_count)
if max && error_count > max
expire
else
retry_in_default_interval
end
end | ruby | def handle_error(error)
return unless que_target
max = resolve_que_setting(:maximum_retry_count)
if max && error_count > max
expire
else
retry_in_default_interval
end
end | [
"def",
"handle_error",
"(",
"error",
")",
"return",
"unless",
"que_target",
"max",
"=",
"resolve_que_setting",
"(",
":maximum_retry_count",
")",
"if",
"max",
"&&",
"error_count",
">",
"max",
"expire",
"else",
"retry_in_default_interval",
"end",
"end"
] | To be overridden in subclasses. | [
"To",
"be",
"overridden",
"in",
"subclasses",
"."
] | c7ae049db0ca13056a28c71ae610f8900f21feb4 | https://github.com/chanks/que/blob/c7ae049db0ca13056a28c71ae610f8900f21feb4/lib/que/job_methods.rb#L124-L134 | train |
chanks/que | lib/que/job_methods.rb | Que.JobMethods.retry_in | def retry_in(period)
return unless que_target
if id = que_target.que_attrs[:id]
values = [period]
if e = que_target.que_error
values << "#{e.class}: #{e.message}".slice(0, 500) << e.backtrace.join("\n").slice(0, 10000)
else
values << nil << nil
end
Que.execute :set_error, values << id
end
que_target.que_resolved = true
end | ruby | def retry_in(period)
return unless que_target
if id = que_target.que_attrs[:id]
values = [period]
if e = que_target.que_error
values << "#{e.class}: #{e.message}".slice(0, 500) << e.backtrace.join("\n").slice(0, 10000)
else
values << nil << nil
end
Que.execute :set_error, values << id
end
que_target.que_resolved = true
end | [
"def",
"retry_in",
"(",
"period",
")",
"return",
"unless",
"que_target",
"if",
"id",
"=",
"que_target",
".",
"que_attrs",
"[",
":id",
"]",
"values",
"=",
"[",
"period",
"]",
"if",
"e",
"=",
"que_target",
".",
"que_error",
"values",
"<<",
"\"#{e.class}: #{e.message}\"",
".",
"slice",
"(",
"0",
",",
"500",
")",
"<<",
"e",
".",
"backtrace",
".",
"join",
"(",
"\"\\n\"",
")",
".",
"slice",
"(",
"0",
",",
"10000",
")",
"else",
"values",
"<<",
"nil",
"<<",
"nil",
"end",
"Que",
".",
"execute",
":set_error",
",",
"values",
"<<",
"id",
"end",
"que_target",
".",
"que_resolved",
"=",
"true",
"end"
] | Explicitly check for the job id in these helpers, because it won't exist
if we're running synchronously. | [
"Explicitly",
"check",
"for",
"the",
"job",
"id",
"in",
"these",
"helpers",
"because",
"it",
"won",
"t",
"exist",
"if",
"we",
"re",
"running",
"synchronously",
"."
] | c7ae049db0ca13056a28c71ae610f8900f21feb4 | https://github.com/chanks/que/blob/c7ae049db0ca13056a28c71ae610f8900f21feb4/lib/que/job_methods.rb#L144-L160 | train |
chanks/que | lib/que/job_buffer.rb | Que.JobBuffer.push | def push(*metajobs)
Que.internal_log(:job_buffer_push, self) do
{
maximum_size: maximum_size,
ids: metajobs.map(&:id),
current_queue: to_a,
}
end
sync do
return metajobs if _stopping?
@array.concat(metajobs).sort!
# Relying on the hash's contents being sorted, here.
priority_queues.reverse_each do |_, pq|
pq.waiting_count.times do
job = _shift_job(pq.priority)
break if job.nil? # False would mean we're stopping.
pq.push(job)
end
end
# If we passed the maximum buffer size, drop the lowest sort keys and
# return their ids to be unlocked.
overage = -_buffer_space
pop(overage) if overage > 0
end
end | ruby | def push(*metajobs)
Que.internal_log(:job_buffer_push, self) do
{
maximum_size: maximum_size,
ids: metajobs.map(&:id),
current_queue: to_a,
}
end
sync do
return metajobs if _stopping?
@array.concat(metajobs).sort!
# Relying on the hash's contents being sorted, here.
priority_queues.reverse_each do |_, pq|
pq.waiting_count.times do
job = _shift_job(pq.priority)
break if job.nil? # False would mean we're stopping.
pq.push(job)
end
end
# If we passed the maximum buffer size, drop the lowest sort keys and
# return their ids to be unlocked.
overage = -_buffer_space
pop(overage) if overage > 0
end
end | [
"def",
"push",
"(",
"*",
"metajobs",
")",
"Que",
".",
"internal_log",
"(",
":job_buffer_push",
",",
"self",
")",
"do",
"{",
"maximum_size",
":",
"maximum_size",
",",
"ids",
":",
"metajobs",
".",
"map",
"(",
":id",
")",
",",
"current_queue",
":",
"to_a",
",",
"}",
"end",
"sync",
"do",
"return",
"metajobs",
"if",
"_stopping?",
"@array",
".",
"concat",
"(",
"metajobs",
")",
".",
"sort!",
"# Relying on the hash's contents being sorted, here.",
"priority_queues",
".",
"reverse_each",
"do",
"|",
"_",
",",
"pq",
"|",
"pq",
".",
"waiting_count",
".",
"times",
"do",
"job",
"=",
"_shift_job",
"(",
"pq",
".",
"priority",
")",
"break",
"if",
"job",
".",
"nil?",
"# False would mean we're stopping.",
"pq",
".",
"push",
"(",
"job",
")",
"end",
"end",
"# If we passed the maximum buffer size, drop the lowest sort keys and",
"# return their ids to be unlocked.",
"overage",
"=",
"-",
"_buffer_space",
"pop",
"(",
"overage",
")",
"if",
"overage",
">",
"0",
"end",
"end"
] | Since we use a mutex, which is not reentrant, we have to be a little
careful to not call a method that locks the mutex when we've already
locked it. So, as a general rule, public methods handle locking the mutex
when necessary, while private methods handle the actual underlying data
changes. This lets us reuse those private methods without running into
locking issues. | [
"Since",
"we",
"use",
"a",
"mutex",
"which",
"is",
"not",
"reentrant",
"we",
"have",
"to",
"be",
"a",
"little",
"careful",
"to",
"not",
"call",
"a",
"method",
"that",
"locks",
"the",
"mutex",
"when",
"we",
"ve",
"already",
"locked",
"it",
".",
"So",
"as",
"a",
"general",
"rule",
"public",
"methods",
"handle",
"locking",
"the",
"mutex",
"when",
"necessary",
"while",
"private",
"methods",
"handle",
"the",
"actual",
"underlying",
"data",
"changes",
".",
"This",
"lets",
"us",
"reuse",
"those",
"private",
"methods",
"without",
"running",
"into",
"locking",
"issues",
"."
] | c7ae049db0ca13056a28c71ae610f8900f21feb4 | https://github.com/chanks/que/blob/c7ae049db0ca13056a28c71ae610f8900f21feb4/lib/que/job_buffer.rb#L46-L74 | train |
middleman/middleman | middleman-core/lib/middleman-core/dns_resolver.rb | Middleman.DnsResolver.ips_for | def ips_for(name)
resolvers.each do |r|
ips = r.getaddresses(name)
return ips unless ips.nil? || ips.empty?
end
[]
end | ruby | def ips_for(name)
resolvers.each do |r|
ips = r.getaddresses(name)
return ips unless ips.nil? || ips.empty?
end
[]
end | [
"def",
"ips_for",
"(",
"name",
")",
"resolvers",
".",
"each",
"do",
"|",
"r",
"|",
"ips",
"=",
"r",
".",
"getaddresses",
"(",
"name",
")",
"return",
"ips",
"unless",
"ips",
".",
"nil?",
"||",
"ips",
".",
"empty?",
"end",
"[",
"]",
"end"
] | Get ips for given name
First the local resolver is used. On POSIX-systems /etc/hosts is used. On
Windows C:\Windows\System32\drivers\etc\hosts is used.
@param [String] name
The name which should be resolved. | [
"Get",
"ips",
"for",
"given",
"name"
] | a0dd9f78094813162895511e8516e0c5507cee50 | https://github.com/middleman/middleman/blob/a0dd9f78094813162895511e8516e0c5507cee50/middleman-core/lib/middleman-core/dns_resolver.rb#L63-L71 | train |
middleman/middleman | middleman-core/lib/middleman-core/config_context.rb | Middleman.ConfigContext.mime_type | def mime_type(type, value)
type = ".#{type}" unless type.to_s[0] == '.'
::Rack::Mime::MIME_TYPES[type] = value
end | ruby | def mime_type(type, value)
type = ".#{type}" unless type.to_s[0] == '.'
::Rack::Mime::MIME_TYPES[type] = value
end | [
"def",
"mime_type",
"(",
"type",
",",
"value",
")",
"type",
"=",
"\".#{type}\"",
"unless",
"type",
".",
"to_s",
"[",
"0",
"]",
"==",
"'.'",
"::",
"Rack",
"::",
"Mime",
"::",
"MIME_TYPES",
"[",
"type",
"]",
"=",
"value",
"end"
] | Add a new mime-type for a specific extension
@param [Symbol] type File extension
@param [String] value Mime type
@return [void] | [
"Add",
"a",
"new",
"mime",
"-",
"type",
"for",
"a",
"specific",
"extension"
] | a0dd9f78094813162895511e8516e0c5507cee50 | https://github.com/middleman/middleman/blob/a0dd9f78094813162895511e8516e0c5507cee50/middleman-core/lib/middleman-core/config_context.rb#L62-L65 | train |
middleman/middleman | middleman-core/lib/middleman-core/extension_manager.rb | Middleman.ExtensionManager.activate | def activate(ext_name, options_hash = ::Middleman::EMPTY_HASH, &block)
begin
extension = ::Middleman::Extensions.load(ext_name)
rescue LoadError => e
logger.debug "== Failed Activation `#{ext_name}` : #{e.message}"
return
end
logger.debug "== Activating: #{ext_name}"
if extension.supports_multiple_instances?
@activated[ext_name] ||= {}
key = "instance_#{@activated[ext_name].keys.length}"
@activated[ext_name][key] = extension.new(@app, options_hash, &block)
elsif active?(ext_name)
raise "#{ext_name} has already been activated and cannot be re-activated."
else
@activated[ext_name] = extension.new(@app, options_hash, &block)
end
end | ruby | def activate(ext_name, options_hash = ::Middleman::EMPTY_HASH, &block)
begin
extension = ::Middleman::Extensions.load(ext_name)
rescue LoadError => e
logger.debug "== Failed Activation `#{ext_name}` : #{e.message}"
return
end
logger.debug "== Activating: #{ext_name}"
if extension.supports_multiple_instances?
@activated[ext_name] ||= {}
key = "instance_#{@activated[ext_name].keys.length}"
@activated[ext_name][key] = extension.new(@app, options_hash, &block)
elsif active?(ext_name)
raise "#{ext_name} has already been activated and cannot be re-activated."
else
@activated[ext_name] = extension.new(@app, options_hash, &block)
end
end | [
"def",
"activate",
"(",
"ext_name",
",",
"options_hash",
"=",
"::",
"Middleman",
"::",
"EMPTY_HASH",
",",
"&",
"block",
")",
"begin",
"extension",
"=",
"::",
"Middleman",
"::",
"Extensions",
".",
"load",
"(",
"ext_name",
")",
"rescue",
"LoadError",
"=>",
"e",
"logger",
".",
"debug",
"\"== Failed Activation `#{ext_name}` : #{e.message}\"",
"return",
"end",
"logger",
".",
"debug",
"\"== Activating: #{ext_name}\"",
"if",
"extension",
".",
"supports_multiple_instances?",
"@activated",
"[",
"ext_name",
"]",
"||=",
"{",
"}",
"key",
"=",
"\"instance_#{@activated[ext_name].keys.length}\"",
"@activated",
"[",
"ext_name",
"]",
"[",
"key",
"]",
"=",
"extension",
".",
"new",
"(",
"@app",
",",
"options_hash",
",",
"block",
")",
"elsif",
"active?",
"(",
"ext_name",
")",
"raise",
"\"#{ext_name} has already been activated and cannot be re-activated.\"",
"else",
"@activated",
"[",
"ext_name",
"]",
"=",
"extension",
".",
"new",
"(",
"@app",
",",
"options_hash",
",",
"block",
")",
"end",
"end"
] | Activate an extension, optionally passing in options.
This method is typically used from a project's `config.rb`.
@example Activate an extension with no options
activate :lorem
@example Activate an extension, with options
activate :minify_javascript, inline: true
@example Use a block to configure extension options
activate :minify_javascript do |opts|
opts.ignore += ['*-test.js']
end
@param [Symbol] ext_name The name of thed extension to activate
@param [Hash] options Options to pass to the extension
@yield [Middleman::Configuration::ConfigurationManager] Extension options that can be modified before the extension is initialized.
@return [void] | [
"Activate",
"an",
"extension",
"optionally",
"passing",
"in",
"options",
".",
"This",
"method",
"is",
"typically",
"used",
"from",
"a",
"project",
"s",
"config",
".",
"rb",
"."
] | a0dd9f78094813162895511e8516e0c5507cee50 | https://github.com/middleman/middleman/blob/a0dd9f78094813162895511e8516e0c5507cee50/middleman-core/lib/middleman-core/extension_manager.rb#L53-L72 | train |
middleman/middleman | middleman-core/lib/middleman-core/application.rb | Middleman.Application.apply_cli_options | def apply_cli_options
config[:cli_options].each do |k, v|
setting = config.setting(k.to_sym)
next unless setting
v = setting.options[:import].call(v) if setting.options[:import]
config[k.to_sym] = v
end
end | ruby | def apply_cli_options
config[:cli_options].each do |k, v|
setting = config.setting(k.to_sym)
next unless setting
v = setting.options[:import].call(v) if setting.options[:import]
config[k.to_sym] = v
end
end | [
"def",
"apply_cli_options",
"config",
"[",
":cli_options",
"]",
".",
"each",
"do",
"|",
"k",
",",
"v",
"|",
"setting",
"=",
"config",
".",
"setting",
"(",
"k",
".",
"to_sym",
")",
"next",
"unless",
"setting",
"v",
"=",
"setting",
".",
"options",
"[",
":import",
"]",
".",
"call",
"(",
"v",
")",
"if",
"setting",
".",
"options",
"[",
":import",
"]",
"config",
"[",
"k",
".",
"to_sym",
"]",
"=",
"v",
"end",
"end"
] | Initialize the Middleman project | [
"Initialize",
"the",
"Middleman",
"project"
] | a0dd9f78094813162895511e8516e0c5507cee50 | https://github.com/middleman/middleman/blob/a0dd9f78094813162895511e8516e0c5507cee50/middleman-core/lib/middleman-core/application.rb#L309-L318 | train |
middleman/middleman | middleman-core/lib/middleman-core/application.rb | Middleman.Application.prune_tilt_templates! | def prune_tilt_templates!
mapping = ::Tilt.default_mapping
mapping.lazy_map.each_key do |key|
begin
mapping[key]
rescue LoadError, NameError
end
end
mapping.lazy_map.clear
end | ruby | def prune_tilt_templates!
mapping = ::Tilt.default_mapping
mapping.lazy_map.each_key do |key|
begin
mapping[key]
rescue LoadError, NameError
end
end
mapping.lazy_map.clear
end | [
"def",
"prune_tilt_templates!",
"mapping",
"=",
"::",
"Tilt",
".",
"default_mapping",
"mapping",
".",
"lazy_map",
".",
"each_key",
"do",
"|",
"key",
"|",
"begin",
"mapping",
"[",
"key",
"]",
"rescue",
"LoadError",
",",
"NameError",
"end",
"end",
"mapping",
".",
"lazy_map",
".",
"clear",
"end"
] | Clean up missing Tilt exts | [
"Clean",
"up",
"missing",
"Tilt",
"exts"
] | a0dd9f78094813162895511e8516e0c5507cee50 | https://github.com/middleman/middleman/blob/a0dd9f78094813162895511e8516e0c5507cee50/middleman-core/lib/middleman-core/application.rb#L344-L353 | train |
middleman/middleman | middleman-cli/lib/middleman-cli/extension.rb | Middleman::Cli.Extension.extension | def extension
copy_file 'extension/gitignore', File.join(name, '.gitignore') unless options[:'skip-git']
template 'extension/Rakefile', File.join(name, 'Rakefile')
template 'extension/gemspec', File.join(name, "#{name}.gemspec")
template 'extension/Gemfile', File.join(name, 'Gemfile')
template 'extension/lib/lib.rb', File.join(name, 'lib', "#{name}.rb")
template 'extension/lib/lib/extension.rb', File.join(name, 'lib', name, 'extension.rb')
template 'extension/features/support/env.rb', File.join(name, 'features', 'support', 'env.rb')
empty_directory File.join(name, 'fixtures')
end | ruby | def extension
copy_file 'extension/gitignore', File.join(name, '.gitignore') unless options[:'skip-git']
template 'extension/Rakefile', File.join(name, 'Rakefile')
template 'extension/gemspec', File.join(name, "#{name}.gemspec")
template 'extension/Gemfile', File.join(name, 'Gemfile')
template 'extension/lib/lib.rb', File.join(name, 'lib', "#{name}.rb")
template 'extension/lib/lib/extension.rb', File.join(name, 'lib', name, 'extension.rb')
template 'extension/features/support/env.rb', File.join(name, 'features', 'support', 'env.rb')
empty_directory File.join(name, 'fixtures')
end | [
"def",
"extension",
"copy_file",
"'extension/gitignore'",
",",
"File",
".",
"join",
"(",
"name",
",",
"'.gitignore'",
")",
"unless",
"options",
"[",
":'",
"'",
"]",
"template",
"'extension/Rakefile'",
",",
"File",
".",
"join",
"(",
"name",
",",
"'Rakefile'",
")",
"template",
"'extension/gemspec'",
",",
"File",
".",
"join",
"(",
"name",
",",
"\"#{name}.gemspec\"",
")",
"template",
"'extension/Gemfile'",
",",
"File",
".",
"join",
"(",
"name",
",",
"'Gemfile'",
")",
"template",
"'extension/lib/lib.rb'",
",",
"File",
".",
"join",
"(",
"name",
",",
"'lib'",
",",
"\"#{name}.rb\"",
")",
"template",
"'extension/lib/lib/extension.rb'",
",",
"File",
".",
"join",
"(",
"name",
",",
"'lib'",
",",
"name",
",",
"'extension.rb'",
")",
"template",
"'extension/features/support/env.rb'",
",",
"File",
".",
"join",
"(",
"name",
",",
"'features'",
",",
"'support'",
",",
"'env.rb'",
")",
"empty_directory",
"File",
".",
"join",
"(",
"name",
",",
"'fixtures'",
")",
"end"
] | The extension task | [
"The",
"extension",
"task"
] | a0dd9f78094813162895511e8516e0c5507cee50 | https://github.com/middleman/middleman/blob/a0dd9f78094813162895511e8516e0c5507cee50/middleman-cli/lib/middleman-cli/extension.rb#L27-L36 | train |
middleman/middleman | middleman-core/lib/middleman-core/extension.rb | Middleman.Extension.add_exposed_to_context | def add_exposed_to_context(context)
(self.class.exposed_to_template || {}).each do |k, v|
context.define_singleton_method(k, &method(v))
end
end | ruby | def add_exposed_to_context(context)
(self.class.exposed_to_template || {}).each do |k, v|
context.define_singleton_method(k, &method(v))
end
end | [
"def",
"add_exposed_to_context",
"(",
"context",
")",
"(",
"self",
".",
"class",
".",
"exposed_to_template",
"||",
"{",
"}",
")",
".",
"each",
"do",
"|",
"k",
",",
"v",
"|",
"context",
".",
"define_singleton_method",
"(",
"k",
",",
"method",
"(",
"v",
")",
")",
"end",
"end"
] | Extensions are instantiated when they are activated.
@param [Middleman::Application] app The Middleman::Application instance
@param [Hash] options_hash The raw options hash. Subclasses should not manipulate this directly - it will be turned into {#options}.
@yield An optional block that can be used to customize options before the extension is activated.
@yieldparam [Middleman::Configuration::ConfigurationManager] options Extension options
@!method before_configuration
Respond to the `before_configuration` event.
If a `before_configuration` method is implemented, that method will be run before `config.rb` is run.
@note Because most extensions are activated from within `config.rb`, they *will not run* any `before_configuration` hook.
@!method after_configuration
Respond to the `after_configuration` event.
If an `after_configuration` method is implemented, that method will be run before `config.rb` is run.
@!method before_build
Respond to the `before_build` event.
If an `before_build` method is implemented, that method will be run before the builder runs.
@!method after_build
Respond to the `after_build` event.
If an `after_build` method is implemented, that method will be run after the builder runs.
@!method ready
Respond to the `ready` event.
If an `ready` method is implemented, that method will be run after the app has finished booting up.
@!method manipulate_resource_list(resources)
Manipulate the resource list by transforming or adding {Sitemap::Resource}s.
Sitemap manipulation is a powerful way of interacting with a project, since it can modify each {Sitemap::Resource} or generate new {Sitemap::Resources}. This method is used in a pipeline where each sitemap manipulator is run in turn, with each one being fed the output of the previous manipulator. See the source of built-in Middleman extensions like {Middleman::Extensions::DirectoryIndexes} and {Middleman::Extensions::AssetHash} for examples of how to use this.
@note This method *must* return the full set of resources, because its return value will be used as the new sitemap.
@see http://middlemanapp.com/advanced/sitemap/ Sitemap Documentation
@see Sitemap::Store
@see Sitemap::Resource
@param [Array<Sitemap::Resource>] resources A list of all the resources known to the sitemap.
@return [Array<Sitemap::Resource>] The transformed list of resources. | [
"Extensions",
"are",
"instantiated",
"when",
"they",
"are",
"activated",
"."
] | a0dd9f78094813162895511e8516e0c5507cee50 | https://github.com/middleman/middleman/blob/a0dd9f78094813162895511e8516e0c5507cee50/middleman-core/lib/middleman-core/extension.rb#L355-L359 | train |
middleman/middleman | middleman-cli/lib/middleman-cli/init.rb | Middleman::Cli.Init.init | def init
require 'fileutils'
require 'tmpdir'
unless git_present?
msg = 'You need to install the git command line tool to initialize a new project. '
msg << "For help installing git, please refer to GitHub's tutorial at https://help.github.com/articles/set-up-git"
say msg, :red
exit 1
end
repo_path, repo_branch = if shortname?(options[:template])
require 'open-uri'
require 'json'
api = 'https://directory.middlemanapp.com/api'
uri = ::URI.parse("#{api}/#{options[:template]}.json")
begin
data = ::JSON.parse(uri.read)
is_local_dir = false
data['links']['github'].split('#')
rescue ::OpenURI::HTTPError
say "Template `#{options[:template]}` not found in Middleman Directory."
say 'Did you mean to use a full `user/repo` path?'
exit 1
end
else
repo_name, repo_branch = options[:template].split('#')
repo_path, is_local_dir = repository_path(repo_name)
[repo_path, repo_branch]
end
begin
dir = is_local_dir ? repo_path : clone_repository(repo_path, repo_branch)
inside(target) do
thorfile = File.join(dir, 'Thorfile')
if File.exist?(thorfile)
::Thor::Util.load_thorfile(thorfile)
invoke 'middleman:generator'
else
source_paths << dir
directory dir, '.', exclude_pattern: /\.git\/|\.gitignore$/
end
bundle_args = options[:'bundle-path'] ? " --path=#{options[:'bundle-path']}" : ''
run("bundle install#{bundle_args}") unless ENV['TEST'] || options[:'skip-bundle']
end
ensure
FileUtils.remove_entry(dir) if !is_local_dir && File.directory?(dir)
end
end | ruby | def init
require 'fileutils'
require 'tmpdir'
unless git_present?
msg = 'You need to install the git command line tool to initialize a new project. '
msg << "For help installing git, please refer to GitHub's tutorial at https://help.github.com/articles/set-up-git"
say msg, :red
exit 1
end
repo_path, repo_branch = if shortname?(options[:template])
require 'open-uri'
require 'json'
api = 'https://directory.middlemanapp.com/api'
uri = ::URI.parse("#{api}/#{options[:template]}.json")
begin
data = ::JSON.parse(uri.read)
is_local_dir = false
data['links']['github'].split('#')
rescue ::OpenURI::HTTPError
say "Template `#{options[:template]}` not found in Middleman Directory."
say 'Did you mean to use a full `user/repo` path?'
exit 1
end
else
repo_name, repo_branch = options[:template].split('#')
repo_path, is_local_dir = repository_path(repo_name)
[repo_path, repo_branch]
end
begin
dir = is_local_dir ? repo_path : clone_repository(repo_path, repo_branch)
inside(target) do
thorfile = File.join(dir, 'Thorfile')
if File.exist?(thorfile)
::Thor::Util.load_thorfile(thorfile)
invoke 'middleman:generator'
else
source_paths << dir
directory dir, '.', exclude_pattern: /\.git\/|\.gitignore$/
end
bundle_args = options[:'bundle-path'] ? " --path=#{options[:'bundle-path']}" : ''
run("bundle install#{bundle_args}") unless ENV['TEST'] || options[:'skip-bundle']
end
ensure
FileUtils.remove_entry(dir) if !is_local_dir && File.directory?(dir)
end
end | [
"def",
"init",
"require",
"'fileutils'",
"require",
"'tmpdir'",
"unless",
"git_present?",
"msg",
"=",
"'You need to install the git command line tool to initialize a new project. '",
"msg",
"<<",
"\"For help installing git, please refer to GitHub's tutorial at https://help.github.com/articles/set-up-git\"",
"say",
"msg",
",",
":red",
"exit",
"1",
"end",
"repo_path",
",",
"repo_branch",
"=",
"if",
"shortname?",
"(",
"options",
"[",
":template",
"]",
")",
"require",
"'open-uri'",
"require",
"'json'",
"api",
"=",
"'https://directory.middlemanapp.com/api'",
"uri",
"=",
"::",
"URI",
".",
"parse",
"(",
"\"#{api}/#{options[:template]}.json\"",
")",
"begin",
"data",
"=",
"::",
"JSON",
".",
"parse",
"(",
"uri",
".",
"read",
")",
"is_local_dir",
"=",
"false",
"data",
"[",
"'links'",
"]",
"[",
"'github'",
"]",
".",
"split",
"(",
"'#'",
")",
"rescue",
"::",
"OpenURI",
"::",
"HTTPError",
"say",
"\"Template `#{options[:template]}` not found in Middleman Directory.\"",
"say",
"'Did you mean to use a full `user/repo` path?'",
"exit",
"1",
"end",
"else",
"repo_name",
",",
"repo_branch",
"=",
"options",
"[",
":template",
"]",
".",
"split",
"(",
"'#'",
")",
"repo_path",
",",
"is_local_dir",
"=",
"repository_path",
"(",
"repo_name",
")",
"[",
"repo_path",
",",
"repo_branch",
"]",
"end",
"begin",
"dir",
"=",
"is_local_dir",
"?",
"repo_path",
":",
"clone_repository",
"(",
"repo_path",
",",
"repo_branch",
")",
"inside",
"(",
"target",
")",
"do",
"thorfile",
"=",
"File",
".",
"join",
"(",
"dir",
",",
"'Thorfile'",
")",
"if",
"File",
".",
"exist?",
"(",
"thorfile",
")",
"::",
"Thor",
"::",
"Util",
".",
"load_thorfile",
"(",
"thorfile",
")",
"invoke",
"'middleman:generator'",
"else",
"source_paths",
"<<",
"dir",
"directory",
"dir",
",",
"'.'",
",",
"exclude_pattern",
":",
"/",
"\\.",
"\\/",
"\\.",
"/",
"end",
"bundle_args",
"=",
"options",
"[",
":'",
"'",
"]",
"?",
"\" --path=#{options[:'bundle-path']}\"",
":",
"''",
"run",
"(",
"\"bundle install#{bundle_args}\"",
")",
"unless",
"ENV",
"[",
"'TEST'",
"]",
"||",
"options",
"[",
":'",
"'",
"]",
"end",
"ensure",
"FileUtils",
".",
"remove_entry",
"(",
"dir",
")",
"if",
"!",
"is_local_dir",
"&&",
"File",
".",
"directory?",
"(",
"dir",
")",
"end",
"end"
] | The init task | [
"The",
"init",
"task"
] | a0dd9f78094813162895511e8516e0c5507cee50 | https://github.com/middleman/middleman/blob/a0dd9f78094813162895511e8516e0c5507cee50/middleman-cli/lib/middleman-cli/init.rb#L30-L84 | train |
middleman/middleman | middleman-cli/lib/middleman-cli/init.rb | Middleman::Cli.Init.which | def which(executable)
if File.file?(executable) && File.executable?(executable)
executable
elsif ENV['PATH']
path = ENV['PATH'].split(File::PATH_SEPARATOR).find do |p|
abs_path = File.join(p, executable)
File.file?(abs_path) && File.executable?(abs_path)
end
path && File.expand_path(executable, path)
end
end | ruby | def which(executable)
if File.file?(executable) && File.executable?(executable)
executable
elsif ENV['PATH']
path = ENV['PATH'].split(File::PATH_SEPARATOR).find do |p|
abs_path = File.join(p, executable)
File.file?(abs_path) && File.executable?(abs_path)
end
path && File.expand_path(executable, path)
end
end | [
"def",
"which",
"(",
"executable",
")",
"if",
"File",
".",
"file?",
"(",
"executable",
")",
"&&",
"File",
".",
"executable?",
"(",
"executable",
")",
"executable",
"elsif",
"ENV",
"[",
"'PATH'",
"]",
"path",
"=",
"ENV",
"[",
"'PATH'",
"]",
".",
"split",
"(",
"File",
"::",
"PATH_SEPARATOR",
")",
".",
"find",
"do",
"|",
"p",
"|",
"abs_path",
"=",
"File",
".",
"join",
"(",
"p",
",",
"executable",
")",
"File",
".",
"file?",
"(",
"abs_path",
")",
"&&",
"File",
".",
"executable?",
"(",
"abs_path",
")",
"end",
"path",
"&&",
"File",
".",
"expand_path",
"(",
"executable",
",",
"path",
")",
"end",
"end"
] | Copied from Bundler | [
"Copied",
"from",
"Bundler"
] | a0dd9f78094813162895511e8516e0c5507cee50 | https://github.com/middleman/middleman/blob/a0dd9f78094813162895511e8516e0c5507cee50/middleman-cli/lib/middleman-cli/init.rb#L96-L106 | train |
middleman/middleman | middleman-cli/lib/middleman-cli/build.rb | Middleman::Cli.Build.build | def build
root = ENV['MM_ROOT'] || Dir.pwd
raise Thor::Error, 'Error: Could not find a Middleman project config, perhaps you are in the wrong folder?' unless File.exist?(File.join(root, 'config.rb'))
require 'middleman-core'
require 'middleman-core/logger'
require 'middleman-core/builder'
require 'fileutils'
verbose = options['verbose'] ? 0 : 1
instrument = options['instrument']
builder = nil
cli_options = options
::Middleman::Logger.singleton(verbose, instrument)
::Middleman::Util.instrument 'builder.setup' do
missing_and_changed = !options['only_changed'] && options['missing_and_changed']
should_track_dependencies = options['only_changed'] || missing_and_changed || options['track_dependencies']
data_collection_depth = options['data_collection_depth']
@app = ::Middleman::Application.new do
config[:mode] = :build
config[:show_exceptions] = false
config[:cli_options] = cli_options.each_with_object({}) do |(k, v), sum|
sum[k] = v
end
config[:track_data_access] = should_track_dependencies
config[:data_collection_depth] = data_collection_depth
end
builder = Middleman::Builder.new(@app,
glob: options['glob'],
dry_run: options['dry_run'],
clean: options['clean'],
parallel: options['parallel'],
only_changed: options['only_changed'],
missing_and_changed: missing_and_changed,
track_dependencies: should_track_dependencies,
visualize_graph: options['visualize_graph'])
builder.thor = self
builder.on_build_event(&method(:on_event))
end
::Middleman::Util.instrument 'builder.run' do
if builder.run!
clean_directories! if options['clean']
puts 'Project built successfully.'
else
msg = 'There were errors during this build'
msg << ', re-run with `middleman build --verbose` to see the full exception.' unless options['verbose']
shell.say msg, :red
exit(1)
end
end
end | ruby | def build
root = ENV['MM_ROOT'] || Dir.pwd
raise Thor::Error, 'Error: Could not find a Middleman project config, perhaps you are in the wrong folder?' unless File.exist?(File.join(root, 'config.rb'))
require 'middleman-core'
require 'middleman-core/logger'
require 'middleman-core/builder'
require 'fileutils'
verbose = options['verbose'] ? 0 : 1
instrument = options['instrument']
builder = nil
cli_options = options
::Middleman::Logger.singleton(verbose, instrument)
::Middleman::Util.instrument 'builder.setup' do
missing_and_changed = !options['only_changed'] && options['missing_and_changed']
should_track_dependencies = options['only_changed'] || missing_and_changed || options['track_dependencies']
data_collection_depth = options['data_collection_depth']
@app = ::Middleman::Application.new do
config[:mode] = :build
config[:show_exceptions] = false
config[:cli_options] = cli_options.each_with_object({}) do |(k, v), sum|
sum[k] = v
end
config[:track_data_access] = should_track_dependencies
config[:data_collection_depth] = data_collection_depth
end
builder = Middleman::Builder.new(@app,
glob: options['glob'],
dry_run: options['dry_run'],
clean: options['clean'],
parallel: options['parallel'],
only_changed: options['only_changed'],
missing_and_changed: missing_and_changed,
track_dependencies: should_track_dependencies,
visualize_graph: options['visualize_graph'])
builder.thor = self
builder.on_build_event(&method(:on_event))
end
::Middleman::Util.instrument 'builder.run' do
if builder.run!
clean_directories! if options['clean']
puts 'Project built successfully.'
else
msg = 'There were errors during this build'
msg << ', re-run with `middleman build --verbose` to see the full exception.' unless options['verbose']
shell.say msg, :red
exit(1)
end
end
end | [
"def",
"build",
"root",
"=",
"ENV",
"[",
"'MM_ROOT'",
"]",
"||",
"Dir",
".",
"pwd",
"raise",
"Thor",
"::",
"Error",
",",
"'Error: Could not find a Middleman project config, perhaps you are in the wrong folder?'",
"unless",
"File",
".",
"exist?",
"(",
"File",
".",
"join",
"(",
"root",
",",
"'config.rb'",
")",
")",
"require",
"'middleman-core'",
"require",
"'middleman-core/logger'",
"require",
"'middleman-core/builder'",
"require",
"'fileutils'",
"verbose",
"=",
"options",
"[",
"'verbose'",
"]",
"?",
"0",
":",
"1",
"instrument",
"=",
"options",
"[",
"'instrument'",
"]",
"builder",
"=",
"nil",
"cli_options",
"=",
"options",
"::",
"Middleman",
"::",
"Logger",
".",
"singleton",
"(",
"verbose",
",",
"instrument",
")",
"::",
"Middleman",
"::",
"Util",
".",
"instrument",
"'builder.setup'",
"do",
"missing_and_changed",
"=",
"!",
"options",
"[",
"'only_changed'",
"]",
"&&",
"options",
"[",
"'missing_and_changed'",
"]",
"should_track_dependencies",
"=",
"options",
"[",
"'only_changed'",
"]",
"||",
"missing_and_changed",
"||",
"options",
"[",
"'track_dependencies'",
"]",
"data_collection_depth",
"=",
"options",
"[",
"'data_collection_depth'",
"]",
"@app",
"=",
"::",
"Middleman",
"::",
"Application",
".",
"new",
"do",
"config",
"[",
":mode",
"]",
"=",
":build",
"config",
"[",
":show_exceptions",
"]",
"=",
"false",
"config",
"[",
":cli_options",
"]",
"=",
"cli_options",
".",
"each_with_object",
"(",
"{",
"}",
")",
"do",
"|",
"(",
"k",
",",
"v",
")",
",",
"sum",
"|",
"sum",
"[",
"k",
"]",
"=",
"v",
"end",
"config",
"[",
":track_data_access",
"]",
"=",
"should_track_dependencies",
"config",
"[",
":data_collection_depth",
"]",
"=",
"data_collection_depth",
"end",
"builder",
"=",
"Middleman",
"::",
"Builder",
".",
"new",
"(",
"@app",
",",
"glob",
":",
"options",
"[",
"'glob'",
"]",
",",
"dry_run",
":",
"options",
"[",
"'dry_run'",
"]",
",",
"clean",
":",
"options",
"[",
"'clean'",
"]",
",",
"parallel",
":",
"options",
"[",
"'parallel'",
"]",
",",
"only_changed",
":",
"options",
"[",
"'only_changed'",
"]",
",",
"missing_and_changed",
":",
"missing_and_changed",
",",
"track_dependencies",
":",
"should_track_dependencies",
",",
"visualize_graph",
":",
"options",
"[",
"'visualize_graph'",
"]",
")",
"builder",
".",
"thor",
"=",
"self",
"builder",
".",
"on_build_event",
"(",
"method",
"(",
":on_event",
")",
")",
"end",
"::",
"Middleman",
"::",
"Util",
".",
"instrument",
"'builder.run'",
"do",
"if",
"builder",
".",
"run!",
"clean_directories!",
"if",
"options",
"[",
"'clean'",
"]",
"puts",
"'Project built successfully.'",
"else",
"msg",
"=",
"'There were errors during this build'",
"msg",
"<<",
"', re-run with `middleman build --verbose` to see the full exception.'",
"unless",
"options",
"[",
"'verbose'",
"]",
"shell",
".",
"say",
"msg",
",",
":red",
"exit",
"(",
"1",
")",
"end",
"end",
"end"
] | Core build Thor command
@return [void] | [
"Core",
"build",
"Thor",
"command"
] | a0dd9f78094813162895511e8516e0c5507cee50 | https://github.com/middleman/middleman/blob/a0dd9f78094813162895511e8516e0c5507cee50/middleman-cli/lib/middleman-cli/build.rb#L72-L130 | train |
middleman/middleman | middleman-cli/lib/middleman-cli/build.rb | Middleman::Cli.Build.on_event | def on_event(event_type, target, extra = nil)
case event_type
when :error
say_status :error, target, :red
shell.say extra, :red if options['verbose'] || options['bail']
raise 'Build error' if options['bail']
when :deleted
say_status :remove, target, :green
when :created
say_status :create, target, :green
when :identical
say_status :identical, target, :blue
when :skipped
say_status :skipped, target, :blue
when :updated
say_status :updated, target, :yellow
else
say_status event_type, extra, :blue
end
end | ruby | def on_event(event_type, target, extra = nil)
case event_type
when :error
say_status :error, target, :red
shell.say extra, :red if options['verbose'] || options['bail']
raise 'Build error' if options['bail']
when :deleted
say_status :remove, target, :green
when :created
say_status :create, target, :green
when :identical
say_status :identical, target, :blue
when :skipped
say_status :skipped, target, :blue
when :updated
say_status :updated, target, :yellow
else
say_status event_type, extra, :blue
end
end | [
"def",
"on_event",
"(",
"event_type",
",",
"target",
",",
"extra",
"=",
"nil",
")",
"case",
"event_type",
"when",
":error",
"say_status",
":error",
",",
"target",
",",
":red",
"shell",
".",
"say",
"extra",
",",
":red",
"if",
"options",
"[",
"'verbose'",
"]",
"||",
"options",
"[",
"'bail'",
"]",
"raise",
"'Build error'",
"if",
"options",
"[",
"'bail'",
"]",
"when",
":deleted",
"say_status",
":remove",
",",
"target",
",",
":green",
"when",
":created",
"say_status",
":create",
",",
"target",
",",
":green",
"when",
":identical",
"say_status",
":identical",
",",
"target",
",",
":blue",
"when",
":skipped",
"say_status",
":skipped",
",",
"target",
",",
":blue",
"when",
":updated",
"say_status",
":updated",
",",
"target",
",",
":yellow",
"else",
"say_status",
"event_type",
",",
"extra",
",",
":blue",
"end",
"end"
] | Handles incoming events from the builder.
@param [Symbol] event_type The type of event.
@param [String] target The event contents.
@param [String] extra The extra information.
@return [void] | [
"Handles",
"incoming",
"events",
"from",
"the",
"builder",
"."
] | a0dd9f78094813162895511e8516e0c5507cee50 | https://github.com/middleman/middleman/blob/a0dd9f78094813162895511e8516e0c5507cee50/middleman-cli/lib/middleman-cli/build.rb#L139-L159 | train |
middleman/middleman | middleman-cli/lib/middleman-cli/build.rb | Middleman::Cli.Build.clean_directories! | def clean_directories!
all_build_files = File.join(@app.config[:build_dir], '**', '*')
empty_directories = Dir[all_build_files].select do |d|
File.directory?(d)
end
empty_directories.each do |d|
remove_file d, force: true if Pathname(d).children.empty?
end
end | ruby | def clean_directories!
all_build_files = File.join(@app.config[:build_dir], '**', '*')
empty_directories = Dir[all_build_files].select do |d|
File.directory?(d)
end
empty_directories.each do |d|
remove_file d, force: true if Pathname(d).children.empty?
end
end | [
"def",
"clean_directories!",
"all_build_files",
"=",
"File",
".",
"join",
"(",
"@app",
".",
"config",
"[",
":build_dir",
"]",
",",
"'**'",
",",
"'*'",
")",
"empty_directories",
"=",
"Dir",
"[",
"all_build_files",
"]",
".",
"select",
"do",
"|",
"d",
"|",
"File",
".",
"directory?",
"(",
"d",
")",
"end",
"empty_directories",
".",
"each",
"do",
"|",
"d",
"|",
"remove_file",
"d",
",",
"force",
":",
"true",
"if",
"Pathname",
"(",
"d",
")",
".",
"children",
".",
"empty?",
"end",
"end"
] | Find empty directories in the build folder and remove them.
@return [Boolean] | [
"Find",
"empty",
"directories",
"in",
"the",
"build",
"folder",
"and",
"remove",
"them",
"."
] | a0dd9f78094813162895511e8516e0c5507cee50 | https://github.com/middleman/middleman/blob/a0dd9f78094813162895511e8516e0c5507cee50/middleman-cli/lib/middleman-cli/build.rb#L163-L173 | train |
middleman/middleman | middleman-core/lib/middleman-core/rack.rb | Middleman.Rack.process_request | def process_request(env, req, res)
start_time = Time.now
request_path = URI.decode(env['PATH_INFO'].dup)
request_path.force_encoding('UTF-8') if request_path.respond_to? :force_encoding
request_path = ::Middleman::Util.full_path(request_path, @middleman)
full_request_path = File.join(env['SCRIPT_NAME'], request_path) # Path including rack mount
# Get the resource object for this path
resource = @middleman.sitemap.by_destination_path(request_path.gsub(' ', '%20'))
# Return 404 if not in sitemap
return not_found(res, full_request_path) unless resource && !resource.ignored?
# If this path is a binary file, send it immediately
return send_file(resource, env) if resource.binary? || resource.static_file?
res['Content-Type'] = resource.content_type || 'text/plain'
begin
# Write out the contents of the page
res.write resource.render({}, rack: { request: req })
# Valid content is a 200 status
res.status = 200
rescue Middleman::TemplateRenderer::TemplateNotFound => e
res.write "Error: #{e.message}"
res.status = 500
end
# End the request
logger.debug "== Finishing Request: #{resource.destination_path} (#{(Time.now - start_time).round(2)}s)"
halt res.finish
end | ruby | def process_request(env, req, res)
start_time = Time.now
request_path = URI.decode(env['PATH_INFO'].dup)
request_path.force_encoding('UTF-8') if request_path.respond_to? :force_encoding
request_path = ::Middleman::Util.full_path(request_path, @middleman)
full_request_path = File.join(env['SCRIPT_NAME'], request_path) # Path including rack mount
# Get the resource object for this path
resource = @middleman.sitemap.by_destination_path(request_path.gsub(' ', '%20'))
# Return 404 if not in sitemap
return not_found(res, full_request_path) unless resource && !resource.ignored?
# If this path is a binary file, send it immediately
return send_file(resource, env) if resource.binary? || resource.static_file?
res['Content-Type'] = resource.content_type || 'text/plain'
begin
# Write out the contents of the page
res.write resource.render({}, rack: { request: req })
# Valid content is a 200 status
res.status = 200
rescue Middleman::TemplateRenderer::TemplateNotFound => e
res.write "Error: #{e.message}"
res.status = 500
end
# End the request
logger.debug "== Finishing Request: #{resource.destination_path} (#{(Time.now - start_time).round(2)}s)"
halt res.finish
end | [
"def",
"process_request",
"(",
"env",
",",
"req",
",",
"res",
")",
"start_time",
"=",
"Time",
".",
"now",
"request_path",
"=",
"URI",
".",
"decode",
"(",
"env",
"[",
"'PATH_INFO'",
"]",
".",
"dup",
")",
"request_path",
".",
"force_encoding",
"(",
"'UTF-8'",
")",
"if",
"request_path",
".",
"respond_to?",
":force_encoding",
"request_path",
"=",
"::",
"Middleman",
"::",
"Util",
".",
"full_path",
"(",
"request_path",
",",
"@middleman",
")",
"full_request_path",
"=",
"File",
".",
"join",
"(",
"env",
"[",
"'SCRIPT_NAME'",
"]",
",",
"request_path",
")",
"# Path including rack mount",
"# Get the resource object for this path",
"resource",
"=",
"@middleman",
".",
"sitemap",
".",
"by_destination_path",
"(",
"request_path",
".",
"gsub",
"(",
"' '",
",",
"'%20'",
")",
")",
"# Return 404 if not in sitemap",
"return",
"not_found",
"(",
"res",
",",
"full_request_path",
")",
"unless",
"resource",
"&&",
"!",
"resource",
".",
"ignored?",
"# If this path is a binary file, send it immediately",
"return",
"send_file",
"(",
"resource",
",",
"env",
")",
"if",
"resource",
".",
"binary?",
"||",
"resource",
".",
"static_file?",
"res",
"[",
"'Content-Type'",
"]",
"=",
"resource",
".",
"content_type",
"||",
"'text/plain'",
"begin",
"# Write out the contents of the page",
"res",
".",
"write",
"resource",
".",
"render",
"(",
"{",
"}",
",",
"rack",
":",
"{",
"request",
":",
"req",
"}",
")",
"# Valid content is a 200 status",
"res",
".",
"status",
"=",
"200",
"rescue",
"Middleman",
"::",
"TemplateRenderer",
"::",
"TemplateNotFound",
"=>",
"e",
"res",
".",
"write",
"\"Error: #{e.message}\"",
"res",
".",
"status",
"=",
"500",
"end",
"# End the request",
"logger",
".",
"debug",
"\"== Finishing Request: #{resource.destination_path} (#{(Time.now - start_time).round(2)}s)\"",
"halt",
"res",
".",
"finish",
"end"
] | Core response method. We process the request, check with
the sitemap, and return the correct file, response or status
message.
@param env
@param [Rack::Request] req
@param [Rack::Response] res | [
"Core",
"response",
"method",
".",
"We",
"process",
"the",
"request",
"check",
"with",
"the",
"sitemap",
"and",
"return",
"the",
"correct",
"file",
"response",
"or",
"status",
"message",
"."
] | a0dd9f78094813162895511e8516e0c5507cee50 | https://github.com/middleman/middleman/blob/a0dd9f78094813162895511e8516e0c5507cee50/middleman-core/lib/middleman-core/rack.rb#L86-L119 | train |
middleman/middleman | middleman-core/lib/middleman-core/rack.rb | Middleman.Rack.not_found | def not_found(res, path)
path = ::Rack::Utils.escape_html(path)
res.status = 404
res.write "<html><head></head><body><h1>File Not Found</h1><p>#{path}</p></body></html>"
res.finish
end | ruby | def not_found(res, path)
path = ::Rack::Utils.escape_html(path)
res.status = 404
res.write "<html><head></head><body><h1>File Not Found</h1><p>#{path}</p></body></html>"
res.finish
end | [
"def",
"not_found",
"(",
"res",
",",
"path",
")",
"path",
"=",
"::",
"Rack",
"::",
"Utils",
".",
"escape_html",
"(",
"path",
")",
"res",
".",
"status",
"=",
"404",
"res",
".",
"write",
"\"<html><head></head><body><h1>File Not Found</h1><p>#{path}</p></body></html>\"",
"res",
".",
"finish",
"end"
] | Halt request and return 404 | [
"Halt",
"request",
"and",
"return",
"404"
] | a0dd9f78094813162895511e8516e0c5507cee50 | https://github.com/middleman/middleman/blob/a0dd9f78094813162895511e8516e0c5507cee50/middleman-core/lib/middleman-core/rack.rb#L122-L127 | train |
middleman/middleman | middleman-core/lib/middleman-core/rack.rb | Middleman.Rack.send_file | def send_file(resource, env)
file = ::Rack::File.new nil
path = resource.file_descriptor[:full_path]
if !file.respond_to?(:path=)
request = ::Rack::Request.new(env)
response = file.serving(request, path)
else
file.path = path
response = file.serving(env)
end
status = response[0]
response[1]['Content-Encoding'] = 'gzip' if %w[.svgz .gz].include?(resource.ext)
# Do not set Content-Type if status is 1xx, 204, 205 or 304, otherwise
# Rack will throw an error (500)
if !(100..199).cover?(status) && ![204, 205, 304].include?(status)
response[1]['Content-Type'] = resource.content_type || (resource.binary? ? 'application/octet-stream' : 'text/plain')
end
halt response
end | ruby | def send_file(resource, env)
file = ::Rack::File.new nil
path = resource.file_descriptor[:full_path]
if !file.respond_to?(:path=)
request = ::Rack::Request.new(env)
response = file.serving(request, path)
else
file.path = path
response = file.serving(env)
end
status = response[0]
response[1]['Content-Encoding'] = 'gzip' if %w[.svgz .gz].include?(resource.ext)
# Do not set Content-Type if status is 1xx, 204, 205 or 304, otherwise
# Rack will throw an error (500)
if !(100..199).cover?(status) && ![204, 205, 304].include?(status)
response[1]['Content-Type'] = resource.content_type || (resource.binary? ? 'application/octet-stream' : 'text/plain')
end
halt response
end | [
"def",
"send_file",
"(",
"resource",
",",
"env",
")",
"file",
"=",
"::",
"Rack",
"::",
"File",
".",
"new",
"nil",
"path",
"=",
"resource",
".",
"file_descriptor",
"[",
":full_path",
"]",
"if",
"!",
"file",
".",
"respond_to?",
"(",
":path=",
")",
"request",
"=",
"::",
"Rack",
"::",
"Request",
".",
"new",
"(",
"env",
")",
"response",
"=",
"file",
".",
"serving",
"(",
"request",
",",
"path",
")",
"else",
"file",
".",
"path",
"=",
"path",
"response",
"=",
"file",
".",
"serving",
"(",
"env",
")",
"end",
"status",
"=",
"response",
"[",
"0",
"]",
"response",
"[",
"1",
"]",
"[",
"'Content-Encoding'",
"]",
"=",
"'gzip'",
"if",
"%w[",
".svgz",
".gz",
"]",
".",
"include?",
"(",
"resource",
".",
"ext",
")",
"# Do not set Content-Type if status is 1xx, 204, 205 or 304, otherwise",
"# Rack will throw an error (500)",
"if",
"!",
"(",
"100",
"..",
"199",
")",
".",
"cover?",
"(",
"status",
")",
"&&",
"!",
"[",
"204",
",",
"205",
",",
"304",
"]",
".",
"include?",
"(",
"status",
")",
"response",
"[",
"1",
"]",
"[",
"'Content-Type'",
"]",
"=",
"resource",
".",
"content_type",
"||",
"(",
"resource",
".",
"binary?",
"?",
"'application/octet-stream'",
":",
"'text/plain'",
")",
"end",
"halt",
"response",
"end"
] | Immediately send static file | [
"Immediately",
"send",
"static",
"file"
] | a0dd9f78094813162895511e8516e0c5507cee50 | https://github.com/middleman/middleman/blob/a0dd9f78094813162895511e8516e0c5507cee50/middleman-core/lib/middleman-core/rack.rb#L130-L149 | train |
middleman/middleman | middleman-cli/lib/middleman-cli/server.rb | Middleman::Cli.Server.server | def server
require 'middleman-core'
require 'middleman-core/preview_server'
unless ENV['MM_ROOT']
puts '== Could not find a Middleman project config.rb'
exit
end
params = {
debug: options['verbose'],
instrumenting: options['instrument'],
reload_paths: options['reload_paths'],
daemon: options['daemon']
}
puts '== The Middleman is loading'
::Middleman::PreviewServer.start(params, options)
end | ruby | def server
require 'middleman-core'
require 'middleman-core/preview_server'
unless ENV['MM_ROOT']
puts '== Could not find a Middleman project config.rb'
exit
end
params = {
debug: options['verbose'],
instrumenting: options['instrument'],
reload_paths: options['reload_paths'],
daemon: options['daemon']
}
puts '== The Middleman is loading'
::Middleman::PreviewServer.start(params, options)
end | [
"def",
"server",
"require",
"'middleman-core'",
"require",
"'middleman-core/preview_server'",
"unless",
"ENV",
"[",
"'MM_ROOT'",
"]",
"puts",
"'== Could not find a Middleman project config.rb'",
"exit",
"end",
"params",
"=",
"{",
"debug",
":",
"options",
"[",
"'verbose'",
"]",
",",
"instrumenting",
":",
"options",
"[",
"'instrument'",
"]",
",",
"reload_paths",
":",
"options",
"[",
"'reload_paths'",
"]",
",",
"daemon",
":",
"options",
"[",
"'daemon'",
"]",
"}",
"puts",
"'== The Middleman is loading'",
"::",
"Middleman",
"::",
"PreviewServer",
".",
"start",
"(",
"params",
",",
"options",
")",
"end"
] | Start the server | [
"Start",
"the",
"server"
] | a0dd9f78094813162895511e8516e0c5507cee50 | https://github.com/middleman/middleman/blob/a0dd9f78094813162895511e8516e0c5507cee50/middleman-cli/lib/middleman-cli/server.rb#L36-L54 | train |
middleman/middleman | middleman-core/lib/middleman-core/template_context.rb | Middleman.TemplateContext.wrap_layout | def wrap_layout(layout_name, &block)
# Save current buffer for later
buf_was = save_buffer
# Find a layout for this file
layout_file = ::Middleman::TemplateRenderer.locate_layout(@app, layout_name, current_engine)
# Get the layout engine
extension = File.extname(layout_file[:relative_path])
engine = extension[1..-1].to_sym
# Store last engine for later (could be inside nested renders)
self.current_engine = engine
engine_was = current_engine
# By default, no content is captured
content = ''
# Attempt to capture HTML from block
begin
content = capture_html(&block) if block_given?
ensure
# Reset stored buffer, regardless of success
restore_buffer(buf_was)
end
@vertices <<= ::Middleman::Dependencies::FileVertex.from_source_file(@app, layout_file)
# Render the layout, with the contents of the block inside.
concat_safe_content render_file(layout_file, @locs, @opts) { content }
ensure
# Reset engine back to template's value, regardless of success
self.current_engine = engine_was
end | ruby | def wrap_layout(layout_name, &block)
# Save current buffer for later
buf_was = save_buffer
# Find a layout for this file
layout_file = ::Middleman::TemplateRenderer.locate_layout(@app, layout_name, current_engine)
# Get the layout engine
extension = File.extname(layout_file[:relative_path])
engine = extension[1..-1].to_sym
# Store last engine for later (could be inside nested renders)
self.current_engine = engine
engine_was = current_engine
# By default, no content is captured
content = ''
# Attempt to capture HTML from block
begin
content = capture_html(&block) if block_given?
ensure
# Reset stored buffer, regardless of success
restore_buffer(buf_was)
end
@vertices <<= ::Middleman::Dependencies::FileVertex.from_source_file(@app, layout_file)
# Render the layout, with the contents of the block inside.
concat_safe_content render_file(layout_file, @locs, @opts) { content }
ensure
# Reset engine back to template's value, regardless of success
self.current_engine = engine_was
end | [
"def",
"wrap_layout",
"(",
"layout_name",
",",
"&",
"block",
")",
"# Save current buffer for later",
"buf_was",
"=",
"save_buffer",
"# Find a layout for this file",
"layout_file",
"=",
"::",
"Middleman",
"::",
"TemplateRenderer",
".",
"locate_layout",
"(",
"@app",
",",
"layout_name",
",",
"current_engine",
")",
"# Get the layout engine",
"extension",
"=",
"File",
".",
"extname",
"(",
"layout_file",
"[",
":relative_path",
"]",
")",
"engine",
"=",
"extension",
"[",
"1",
"..",
"-",
"1",
"]",
".",
"to_sym",
"# Store last engine for later (could be inside nested renders)",
"self",
".",
"current_engine",
"=",
"engine",
"engine_was",
"=",
"current_engine",
"# By default, no content is captured",
"content",
"=",
"''",
"# Attempt to capture HTML from block",
"begin",
"content",
"=",
"capture_html",
"(",
"block",
")",
"if",
"block_given?",
"ensure",
"# Reset stored buffer, regardless of success",
"restore_buffer",
"(",
"buf_was",
")",
"end",
"@vertices",
"<<=",
"::",
"Middleman",
"::",
"Dependencies",
"::",
"FileVertex",
".",
"from_source_file",
"(",
"@app",
",",
"layout_file",
")",
"# Render the layout, with the contents of the block inside.",
"concat_safe_content",
"render_file",
"(",
"layout_file",
",",
"@locs",
",",
"@opts",
")",
"{",
"content",
"}",
"ensure",
"# Reset engine back to template's value, regardless of success",
"self",
".",
"current_engine",
"=",
"engine_was",
"end"
] | Allow layouts to be wrapped in the contents of other layouts.
@param [String, Symbol] layout_name
@return [void] | [
"Allow",
"layouts",
"to",
"be",
"wrapped",
"in",
"the",
"contents",
"of",
"other",
"layouts",
"."
] | a0dd9f78094813162895511e8516e0c5507cee50 | https://github.com/middleman/middleman/blob/a0dd9f78094813162895511e8516e0c5507cee50/middleman-core/lib/middleman-core/template_context.rb#L81-L114 | train |
middleman/middleman | middleman-core/lib/middleman-core/template_context.rb | Middleman.TemplateContext.render_file | def render_file(file, locs, opts, &block)
_render_with_all_renderers(file[:relative_path].to_s, locs, self, opts, &block)
end | ruby | def render_file(file, locs, opts, &block)
_render_with_all_renderers(file[:relative_path].to_s, locs, self, opts, &block)
end | [
"def",
"render_file",
"(",
"file",
",",
"locs",
",",
"opts",
",",
"&",
"block",
")",
"_render_with_all_renderers",
"(",
"file",
"[",
":relative_path",
"]",
".",
"to_s",
",",
"locs",
",",
"self",
",",
"opts",
",",
"block",
")",
"end"
] | Render a path with locs, opts and contents block.
@api private
@param [Middleman::SourceFile] file The file.
@param [Hash] locs Template locals.
@param [Hash] opts Template options.
@param [Proc] block A block will be evaluated to return internal contents.
@return [String] The resulting content string.
Contract IsA['Middleman::SourceFile'], Hash, Hash, Maybe[Proc] => String | [
"Render",
"a",
"path",
"with",
"locs",
"opts",
"and",
"contents",
"block",
"."
] | a0dd9f78094813162895511e8516e0c5507cee50 | https://github.com/middleman/middleman/blob/a0dd9f78094813162895511e8516e0c5507cee50/middleman-core/lib/middleman-core/template_context.rb#L218-L220 | train |
middleman/middleman | middleman-core/lib/middleman-core/util/files.rb | Middleman.Util.glob_directory | def glob_directory(path)
results = ::Dir[path]
return results unless RUBY_PLATFORM =~ /darwin/
results.map { |r| r.encode('UTF-8', 'UTF-8-MAC') }
end | ruby | def glob_directory(path)
results = ::Dir[path]
return results unless RUBY_PLATFORM =~ /darwin/
results.map { |r| r.encode('UTF-8', 'UTF-8-MAC') }
end | [
"def",
"glob_directory",
"(",
"path",
")",
"results",
"=",
"::",
"Dir",
"[",
"path",
"]",
"return",
"results",
"unless",
"RUBY_PLATFORM",
"=~",
"/",
"/",
"results",
".",
"map",
"{",
"|",
"r",
"|",
"r",
".",
"encode",
"(",
"'UTF-8'",
",",
"'UTF-8-MAC'",
")",
"}",
"end"
] | Glob a directory and try to keep path encoding consistent.
@param [String] path The glob path.
@return [Array<String>] | [
"Glob",
"a",
"directory",
"and",
"try",
"to",
"keep",
"path",
"encoding",
"consistent",
"."
] | a0dd9f78094813162895511e8516e0c5507cee50 | https://github.com/middleman/middleman/blob/a0dd9f78094813162895511e8516e0c5507cee50/middleman-core/lib/middleman-core/util/files.rb#L40-L46 | train |
razorpay/razorpay-ruby | lib/razorpay/request.rb | Razorpay.Request.create_instance | def create_instance(res)
response = res.parsed_response
# if there was an error, throw it
raise_error(response['error'], res.code) if response.nil? || response.key?('error')
# There must be a top level entity
# This is either one of payment, refund, or collection at present
begin
class_name = response['entity'].split('_').collect(&:capitalize).join
klass = Razorpay.const_get class_name
rescue NameError
# Use Entity class if we don't find any
klass = Razorpay::Entity
end
klass.new(response)
end | ruby | def create_instance(res)
response = res.parsed_response
# if there was an error, throw it
raise_error(response['error'], res.code) if response.nil? || response.key?('error')
# There must be a top level entity
# This is either one of payment, refund, or collection at present
begin
class_name = response['entity'].split('_').collect(&:capitalize).join
klass = Razorpay.const_get class_name
rescue NameError
# Use Entity class if we don't find any
klass = Razorpay::Entity
end
klass.new(response)
end | [
"def",
"create_instance",
"(",
"res",
")",
"response",
"=",
"res",
".",
"parsed_response",
"# if there was an error, throw it",
"raise_error",
"(",
"response",
"[",
"'error'",
"]",
",",
"res",
".",
"code",
")",
"if",
"response",
".",
"nil?",
"||",
"response",
".",
"key?",
"(",
"'error'",
")",
"# There must be a top level entity",
"# This is either one of payment, refund, or collection at present",
"begin",
"class_name",
"=",
"response",
"[",
"'entity'",
"]",
".",
"split",
"(",
"'_'",
")",
".",
"collect",
"(",
":capitalize",
")",
".",
"join",
"klass",
"=",
"Razorpay",
".",
"const_get",
"class_name",
"rescue",
"NameError",
"# Use Entity class if we don't find any",
"klass",
"=",
"Razorpay",
"::",
"Entity",
"end",
"klass",
".",
"new",
"(",
"response",
")",
"end"
] | Recursively builds entity instances
out of all hashes in the response object | [
"Recursively",
"builds",
"entity",
"instances",
"out",
"of",
"all",
"hashes",
"in",
"the",
"response",
"object"
] | 2ef2a200e70fb7034c212673569cbba378a2ced6 | https://github.com/razorpay/razorpay-ruby/blob/2ef2a200e70fb7034c212673569cbba378a2ced6/lib/razorpay/request.rb#L80-L97 | train |
attr-encrypted/attr_encrypted | lib/attr_encrypted.rb | AttrEncrypted.InstanceMethods.decrypt | def decrypt(attribute, encrypted_value)
encrypted_attributes[attribute.to_sym][:operation] = :decrypting
encrypted_attributes[attribute.to_sym][:value_present] = self.class.not_empty?(encrypted_value)
self.class.decrypt(attribute, encrypted_value, evaluated_attr_encrypted_options_for(attribute))
end | ruby | def decrypt(attribute, encrypted_value)
encrypted_attributes[attribute.to_sym][:operation] = :decrypting
encrypted_attributes[attribute.to_sym][:value_present] = self.class.not_empty?(encrypted_value)
self.class.decrypt(attribute, encrypted_value, evaluated_attr_encrypted_options_for(attribute))
end | [
"def",
"decrypt",
"(",
"attribute",
",",
"encrypted_value",
")",
"encrypted_attributes",
"[",
"attribute",
".",
"to_sym",
"]",
"[",
":operation",
"]",
"=",
":decrypting",
"encrypted_attributes",
"[",
"attribute",
".",
"to_sym",
"]",
"[",
":value_present",
"]",
"=",
"self",
".",
"class",
".",
"not_empty?",
"(",
"encrypted_value",
")",
"self",
".",
"class",
".",
"decrypt",
"(",
"attribute",
",",
"encrypted_value",
",",
"evaluated_attr_encrypted_options_for",
"(",
"attribute",
")",
")",
"end"
] | Decrypts a value for the attribute specified using options evaluated in the current object's scope
Example
class User
attr_accessor :secret_key
attr_encrypted :email, key: :secret_key
def initialize(secret_key)
self.secret_key = secret_key
end
end
@user = User.new('some-secret-key')
@user.decrypt(:email, 'SOME_ENCRYPTED_EMAIL_STRING') | [
"Decrypts",
"a",
"value",
"for",
"the",
"attribute",
"specified",
"using",
"options",
"evaluated",
"in",
"the",
"current",
"object",
"s",
"scope"
] | 11df93aef14c661dd0c03169d382a0412f93124e | https://github.com/attr-encrypted/attr_encrypted/blob/11df93aef14c661dd0c03169d382a0412f93124e/lib/attr_encrypted.rb#L328-L332 | train |
attr-encrypted/attr_encrypted | lib/attr_encrypted.rb | AttrEncrypted.InstanceMethods.encrypt | def encrypt(attribute, value)
encrypted_attributes[attribute.to_sym][:operation] = :encrypting
encrypted_attributes[attribute.to_sym][:value_present] = self.class.not_empty?(value)
self.class.encrypt(attribute, value, evaluated_attr_encrypted_options_for(attribute))
end | ruby | def encrypt(attribute, value)
encrypted_attributes[attribute.to_sym][:operation] = :encrypting
encrypted_attributes[attribute.to_sym][:value_present] = self.class.not_empty?(value)
self.class.encrypt(attribute, value, evaluated_attr_encrypted_options_for(attribute))
end | [
"def",
"encrypt",
"(",
"attribute",
",",
"value",
")",
"encrypted_attributes",
"[",
"attribute",
".",
"to_sym",
"]",
"[",
":operation",
"]",
"=",
":encrypting",
"encrypted_attributes",
"[",
"attribute",
".",
"to_sym",
"]",
"[",
":value_present",
"]",
"=",
"self",
".",
"class",
".",
"not_empty?",
"(",
"value",
")",
"self",
".",
"class",
".",
"encrypt",
"(",
"attribute",
",",
"value",
",",
"evaluated_attr_encrypted_options_for",
"(",
"attribute",
")",
")",
"end"
] | Encrypts a value for the attribute specified using options evaluated in the current object's scope
Example
class User
attr_accessor :secret_key
attr_encrypted :email, key: :secret_key
def initialize(secret_key)
self.secret_key = secret_key
end
end
@user = User.new('some-secret-key')
@user.encrypt(:email, '[email protected]') | [
"Encrypts",
"a",
"value",
"for",
"the",
"attribute",
"specified",
"using",
"options",
"evaluated",
"in",
"the",
"current",
"object",
"s",
"scope"
] | 11df93aef14c661dd0c03169d382a0412f93124e | https://github.com/attr-encrypted/attr_encrypted/blob/11df93aef14c661dd0c03169d382a0412f93124e/lib/attr_encrypted.rb#L349-L353 | train |
attr-encrypted/attr_encrypted | lib/attr_encrypted.rb | AttrEncrypted.InstanceMethods.encrypted_attributes | def encrypted_attributes
@encrypted_attributes ||= begin
duplicated= {}
self.class.encrypted_attributes.map { |key, value| duplicated[key] = value.dup }
duplicated
end
end | ruby | def encrypted_attributes
@encrypted_attributes ||= begin
duplicated= {}
self.class.encrypted_attributes.map { |key, value| duplicated[key] = value.dup }
duplicated
end
end | [
"def",
"encrypted_attributes",
"@encrypted_attributes",
"||=",
"begin",
"duplicated",
"=",
"{",
"}",
"self",
".",
"class",
".",
"encrypted_attributes",
".",
"map",
"{",
"|",
"key",
",",
"value",
"|",
"duplicated",
"[",
"key",
"]",
"=",
"value",
".",
"dup",
"}",
"duplicated",
"end",
"end"
] | Copies the class level hash of encrypted attributes with virtual attribute names as keys
and their corresponding options as values to the instance | [
"Copies",
"the",
"class",
"level",
"hash",
"of",
"encrypted",
"attributes",
"with",
"virtual",
"attribute",
"names",
"as",
"keys",
"and",
"their",
"corresponding",
"options",
"as",
"values",
"to",
"the",
"instance"
] | 11df93aef14c661dd0c03169d382a0412f93124e | https://github.com/attr-encrypted/attr_encrypted/blob/11df93aef14c661dd0c03169d382a0412f93124e/lib/attr_encrypted.rb#L358-L364 | train |
fazibear/colorize | lib/colorize/instance_methods.rb | Colorize.InstanceMethods.colorize | def colorize(params)
return self if self.class.disable_colorization
require_windows_libs
scan_for_colors.inject(self.class.new) do |str, match|
colors_from_params(match, params)
defaults_colors(match)
str << "\033[#{match[0]};#{match[1]};#{match[2]}m#{match[3]}\033[0m"
end
end | ruby | def colorize(params)
return self if self.class.disable_colorization
require_windows_libs
scan_for_colors.inject(self.class.new) do |str, match|
colors_from_params(match, params)
defaults_colors(match)
str << "\033[#{match[0]};#{match[1]};#{match[2]}m#{match[3]}\033[0m"
end
end | [
"def",
"colorize",
"(",
"params",
")",
"return",
"self",
"if",
"self",
".",
"class",
".",
"disable_colorization",
"require_windows_libs",
"scan_for_colors",
".",
"inject",
"(",
"self",
".",
"class",
".",
"new",
")",
"do",
"|",
"str",
",",
"match",
"|",
"colors_from_params",
"(",
"match",
",",
"params",
")",
"defaults_colors",
"(",
"match",
")",
"str",
"<<",
"\"\\033[#{match[0]};#{match[1]};#{match[2]}m#{match[3]}\\033[0m\"",
"end",
"end"
] | Change color of string
Examples:
puts "This is blue".colorize(:blue)
puts "This is light blue".colorize(:light_blue)
puts "This is also blue".colorize(:color => :blue)
puts "This is light blue with red background".colorize(:color => :light_blue, :background => :red)
puts "This is light blue with red background".colorize(:light_blue ).colorize( :background => :red)
puts "This is blue text on red".blue.on_red
puts "This is red on blue".colorize(:red).on_blue
puts "This is red on blue and underline".colorize(:red).on_blue.underline
puts "This is blue text on red".blue.on_red.blink
puts "This is uncolorized".blue.on_red.uncolorize | [
"Change",
"color",
"of",
"string"
] | 526654c6d7dfc5483b70184d06b994eba8359514 | https://github.com/fazibear/colorize/blob/526654c6d7dfc5483b70184d06b994eba8359514/lib/colorize/instance_methods.rb#L19-L27 | train |
fazibear/colorize | lib/colorize/instance_methods.rb | Colorize.InstanceMethods.colorized? | def colorized?
scan_for_colors.inject([]) do |colors, match|
colors << match.tap(&:pop)
end.flatten.compact.any?
end | ruby | def colorized?
scan_for_colors.inject([]) do |colors, match|
colors << match.tap(&:pop)
end.flatten.compact.any?
end | [
"def",
"colorized?",
"scan_for_colors",
".",
"inject",
"(",
"[",
"]",
")",
"do",
"|",
"colors",
",",
"match",
"|",
"colors",
"<<",
"match",
".",
"tap",
"(",
":pop",
")",
"end",
".",
"flatten",
".",
"compact",
".",
"any?",
"end"
] | Return true if string is colorized | [
"Return",
"true",
"if",
"string",
"is",
"colorized"
] | 526654c6d7dfc5483b70184d06b994eba8359514 | https://github.com/fazibear/colorize/blob/526654c6d7dfc5483b70184d06b994eba8359514/lib/colorize/instance_methods.rb#L41-L45 | train |
fazibear/colorize | lib/colorize/instance_methods.rb | Colorize.InstanceMethods.colors_from_params | def colors_from_params(match, params)
case params
when Hash then colors_from_hash(match, params)
when Symbol then color_from_symbol(match, params)
end
end | ruby | def colors_from_params(match, params)
case params
when Hash then colors_from_hash(match, params)
when Symbol then color_from_symbol(match, params)
end
end | [
"def",
"colors_from_params",
"(",
"match",
",",
"params",
")",
"case",
"params",
"when",
"Hash",
"then",
"colors_from_hash",
"(",
"match",
",",
"params",
")",
"when",
"Symbol",
"then",
"color_from_symbol",
"(",
"match",
",",
"params",
")",
"end",
"end"
] | Set color from params | [
"Set",
"color",
"from",
"params"
] | 526654c6d7dfc5483b70184d06b994eba8359514 | https://github.com/fazibear/colorize/blob/526654c6d7dfc5483b70184d06b994eba8359514/lib/colorize/instance_methods.rb#L61-L66 | train |
fazibear/colorize | lib/colorize/instance_methods.rb | Colorize.InstanceMethods.colors_from_hash | def colors_from_hash(match, hash)
match[0] = mode(hash[:mode]) if mode(hash[:mode])
match[1] = color(hash[:color]) if color(hash[:color])
match[2] = background_color(hash[:background]) if background_color(hash[:background])
end | ruby | def colors_from_hash(match, hash)
match[0] = mode(hash[:mode]) if mode(hash[:mode])
match[1] = color(hash[:color]) if color(hash[:color])
match[2] = background_color(hash[:background]) if background_color(hash[:background])
end | [
"def",
"colors_from_hash",
"(",
"match",
",",
"hash",
")",
"match",
"[",
"0",
"]",
"=",
"mode",
"(",
"hash",
"[",
":mode",
"]",
")",
"if",
"mode",
"(",
"hash",
"[",
":mode",
"]",
")",
"match",
"[",
"1",
"]",
"=",
"color",
"(",
"hash",
"[",
":color",
"]",
")",
"if",
"color",
"(",
"hash",
"[",
":color",
"]",
")",
"match",
"[",
"2",
"]",
"=",
"background_color",
"(",
"hash",
"[",
":background",
"]",
")",
"if",
"background_color",
"(",
"hash",
"[",
":background",
"]",
")",
"end"
] | Set colors from params hash | [
"Set",
"colors",
"from",
"params",
"hash"
] | 526654c6d7dfc5483b70184d06b994eba8359514 | https://github.com/fazibear/colorize/blob/526654c6d7dfc5483b70184d06b994eba8359514/lib/colorize/instance_methods.rb#L71-L75 | train |
fazibear/colorize | lib/colorize/class_methods.rb | Colorize.ClassMethods.color_methods | def color_methods
colors.each do |key|
next if key == :default
define_method key do
colorize(:color => key)
end
define_method "on_#{key}" do
colorize(:background => key)
end
end
end | ruby | def color_methods
colors.each do |key|
next if key == :default
define_method key do
colorize(:color => key)
end
define_method "on_#{key}" do
colorize(:background => key)
end
end
end | [
"def",
"color_methods",
"colors",
".",
"each",
"do",
"|",
"key",
"|",
"next",
"if",
"key",
"==",
":default",
"define_method",
"key",
"do",
"colorize",
"(",
":color",
"=>",
"key",
")",
"end",
"define_method",
"\"on_#{key}\"",
"do",
"colorize",
"(",
":background",
"=>",
"key",
")",
"end",
"end",
"end"
] | Generate color and on_color methods | [
"Generate",
"color",
"and",
"on_color",
"methods"
] | 526654c6d7dfc5483b70184d06b994eba8359514 | https://github.com/fazibear/colorize/blob/526654c6d7dfc5483b70184d06b994eba8359514/lib/colorize/class_methods.rb#L93-L105 | train |
ruby/racc | lib/racc/grammar_file_parser.rb | Racc.GrammarFileParser.parse_user_code | def parse_user_code
epilogue = @scanner.epilogue
return unless epilogue.text
epilogue.text.scan(/^----([^\n\r]*)(?:\n|\r\n|\r)(.*?)(?=^----|\Z)/m) do
label = canonical_label($~[1])
range = epilogue.slice($~.begin(2), $~.end(2))
add_user_code(label, range)
end
end | ruby | def parse_user_code
epilogue = @scanner.epilogue
return unless epilogue.text
epilogue.text.scan(/^----([^\n\r]*)(?:\n|\r\n|\r)(.*?)(?=^----|\Z)/m) do
label = canonical_label($~[1])
range = epilogue.slice($~.begin(2), $~.end(2))
add_user_code(label, range)
end
end | [
"def",
"parse_user_code",
"epilogue",
"=",
"@scanner",
".",
"epilogue",
"return",
"unless",
"epilogue",
".",
"text",
"epilogue",
".",
"text",
".",
"scan",
"(",
"/",
"\\n",
"\\r",
"\\n",
"\\r",
"\\n",
"\\r",
"\\Z",
"/m",
")",
"do",
"label",
"=",
"canonical_label",
"(",
"$~",
"[",
"1",
"]",
")",
"range",
"=",
"epilogue",
".",
"slice",
"(",
"$~",
".",
"begin",
"(",
"2",
")",
",",
"$~",
".",
"end",
"(",
"2",
")",
")",
"add_user_code",
"(",
"label",
",",
"range",
")",
"end",
"end"
] | User Code Block | [
"User",
"Code",
"Block"
] | d3244edfa11dd6e86e43f570c6444d41c7e3552a | https://github.com/ruby/racc/blob/d3244edfa11dd6e86e43f570c6444d41c7e3552a/lib/racc/grammar_file_parser.rb#L255-L263 | train |
ruby/racc | lib/racc/simulated_automaton.rb | Racc.SimulatedAutomaton.consume! | def consume!(token)
return self if @error
action = @state.action[token] || @state.defact
case action
when Shift
@sstack.push(@state)
@state = action.goto_state
shifted(token)
when Reduce
reduce_by!(action.rule)
consume!(token)
when Accept
done
when Error
@error = true
error
else
raise "Illegal action type: #{action.class}"
end
self
end | ruby | def consume!(token)
return self if @error
action = @state.action[token] || @state.defact
case action
when Shift
@sstack.push(@state)
@state = action.goto_state
shifted(token)
when Reduce
reduce_by!(action.rule)
consume!(token)
when Accept
done
when Error
@error = true
error
else
raise "Illegal action type: #{action.class}"
end
self
end | [
"def",
"consume!",
"(",
"token",
")",
"return",
"self",
"if",
"@error",
"action",
"=",
"@state",
".",
"action",
"[",
"token",
"]",
"||",
"@state",
".",
"defact",
"case",
"action",
"when",
"Shift",
"@sstack",
".",
"push",
"(",
"@state",
")",
"@state",
"=",
"action",
".",
"goto_state",
"shifted",
"(",
"token",
")",
"when",
"Reduce",
"reduce_by!",
"(",
"action",
".",
"rule",
")",
"consume!",
"(",
"token",
")",
"when",
"Accept",
"done",
"when",
"Error",
"@error",
"=",
"true",
"error",
"else",
"raise",
"\"Illegal action type: #{action.class}\"",
"end",
"self",
"end"
] | consuming a terminal may set off a series of reduces before the terminal
is shifted | [
"consuming",
"a",
"terminal",
"may",
"set",
"off",
"a",
"series",
"of",
"reduces",
"before",
"the",
"terminal",
"is",
"shifted"
] | d3244edfa11dd6e86e43f570c6444d41c7e3552a | https://github.com/ruby/racc/blob/d3244edfa11dd6e86e43f570c6444d41c7e3552a/lib/racc/simulated_automaton.rb#L36-L58 | train |
ruby/racc | lib/racc/state.rb | Racc.States.path | def path(state, rule)
rule.symbols.each_with_object([]) do |tok, path|
goto = state.gotos[tok]
path << goto
state = goto.to_state
end
end | ruby | def path(state, rule)
rule.symbols.each_with_object([]) do |tok, path|
goto = state.gotos[tok]
path << goto
state = goto.to_state
end
end | [
"def",
"path",
"(",
"state",
",",
"rule",
")",
"rule",
".",
"symbols",
".",
"each_with_object",
"(",
"[",
"]",
")",
"do",
"|",
"tok",
",",
"path",
"|",
"goto",
"=",
"state",
".",
"gotos",
"[",
"tok",
"]",
"path",
"<<",
"goto",
"state",
"=",
"goto",
".",
"to_state",
"end",
"end"
] | Sequence of state transitions which would be taken when starting
from 'state', then following the RHS of 'rule' right to the end | [
"Sequence",
"of",
"state",
"transitions",
"which",
"would",
"be",
"taken",
"when",
"starting",
"from",
"state",
"then",
"following",
"the",
"RHS",
"of",
"rule",
"right",
"to",
"the",
"end"
] | d3244edfa11dd6e86e43f570c6444d41c7e3552a | https://github.com/ruby/racc/blob/d3244edfa11dd6e86e43f570c6444d41c7e3552a/lib/racc/state.rb#L208-L214 | train |
ruby/racc | lib/racc/state.rb | Racc.States.walk_graph | def walk_graph(bitmap, graph)
index = Array.new(graph.size, nil)
traversed = Set.new
graph.nodes do |node|
next if traversed.include?(node)
traverse(node, traversed, index, [], bitmap, graph)
end
end | ruby | def walk_graph(bitmap, graph)
index = Array.new(graph.size, nil)
traversed = Set.new
graph.nodes do |node|
next if traversed.include?(node)
traverse(node, traversed, index, [], bitmap, graph)
end
end | [
"def",
"walk_graph",
"(",
"bitmap",
",",
"graph",
")",
"index",
"=",
"Array",
".",
"new",
"(",
"graph",
".",
"size",
",",
"nil",
")",
"traversed",
"=",
"Set",
".",
"new",
"graph",
".",
"nodes",
"do",
"|",
"node",
"|",
"next",
"if",
"traversed",
".",
"include?",
"(",
"node",
")",
"traverse",
"(",
"node",
",",
"traversed",
",",
"index",
",",
"[",
"]",
",",
"bitmap",
",",
"graph",
")",
"end",
"end"
] | traverse a directed graph
each entry in 'bitmap' corresponds to a graph node
after the traversal, the bitmap for each node will be the union of its
original value, and ALL the values for all the nodes which are reachable
from it | [
"traverse",
"a",
"directed",
"graph",
"each",
"entry",
"in",
"bitmap",
"corresponds",
"to",
"a",
"graph",
"node",
"after",
"the",
"traversal",
"the",
"bitmap",
"for",
"each",
"node",
"will",
"be",
"the",
"union",
"of",
"its",
"original",
"value",
"and",
"ALL",
"the",
"values",
"for",
"all",
"the",
"nodes",
"which",
"are",
"reachable",
"from",
"it"
] | d3244edfa11dd6e86e43f570c6444d41c7e3552a | https://github.com/ruby/racc/blob/d3244edfa11dd6e86e43f570c6444d41c7e3552a/lib/racc/state.rb#L221-L229 | train |
ruby/racc | lib/racc/state.rb | Racc.States.detailed_transition_graph | def detailed_transition_graph
@dtgraph ||= each_with_object(Graph::Labeled.new(size)) do |s, graph|
s.gotos.each do |tok, goto|
path = if tok.terminal?
[tok]
else
actions_to_reach_reduce(s.ident, tok)
end
graph.add_vector(s.ident, goto.to_state.ident, path)
end
end.tap { |graph| graph.start = 0 }.freeze
end | ruby | def detailed_transition_graph
@dtgraph ||= each_with_object(Graph::Labeled.new(size)) do |s, graph|
s.gotos.each do |tok, goto|
path = if tok.terminal?
[tok]
else
actions_to_reach_reduce(s.ident, tok)
end
graph.add_vector(s.ident, goto.to_state.ident, path)
end
end.tap { |graph| graph.start = 0 }.freeze
end | [
"def",
"detailed_transition_graph",
"@dtgraph",
"||=",
"each_with_object",
"(",
"Graph",
"::",
"Labeled",
".",
"new",
"(",
"size",
")",
")",
"do",
"|",
"s",
",",
"graph",
"|",
"s",
".",
"gotos",
".",
"each",
"do",
"|",
"tok",
",",
"goto",
"|",
"path",
"=",
"if",
"tok",
".",
"terminal?",
"[",
"tok",
"]",
"else",
"actions_to_reach_reduce",
"(",
"s",
".",
"ident",
",",
"tok",
")",
"end",
"graph",
".",
"add_vector",
"(",
"s",
".",
"ident",
",",
"goto",
".",
"to_state",
".",
"ident",
",",
"path",
")",
"end",
"end",
".",
"tap",
"{",
"|",
"graph",
"|",
"graph",
".",
"start",
"=",
"0",
"}",
".",
"freeze",
"end"
] | Like `transition_graph`, but rather than vectors labeled with NTs, we
have vectors labeled with the shortest series of terminals and reduce
operations which could take us through the same transition | [
"Like",
"transition_graph",
"but",
"rather",
"than",
"vectors",
"labeled",
"with",
"NTs",
"we",
"have",
"vectors",
"labeled",
"with",
"the",
"shortest",
"series",
"of",
"terminals",
"and",
"reduce",
"operations",
"which",
"could",
"take",
"us",
"through",
"the",
"same",
"transition"
] | d3244edfa11dd6e86e43f570c6444d41c7e3552a | https://github.com/ruby/racc/blob/d3244edfa11dd6e86e43f570c6444d41c7e3552a/lib/racc/state.rb#L430-L441 | train |
ruby/racc | lib/racc/grammar.rb | Racc.Rule.replace | def replace(placeholder, actual)
raise 'wrong placeholder' if placeholder != @target
@target.heads.delete(ptrs[0]) if @target
@target = actual
@target.heads << @ptrs[0]
@symbols.map! { |s| s == placeholder ? actual : s }
end | ruby | def replace(placeholder, actual)
raise 'wrong placeholder' if placeholder != @target
@target.heads.delete(ptrs[0]) if @target
@target = actual
@target.heads << @ptrs[0]
@symbols.map! { |s| s == placeholder ? actual : s }
end | [
"def",
"replace",
"(",
"placeholder",
",",
"actual",
")",
"raise",
"'wrong placeholder'",
"if",
"placeholder",
"!=",
"@target",
"@target",
".",
"heads",
".",
"delete",
"(",
"ptrs",
"[",
"0",
"]",
")",
"if",
"@target",
"@target",
"=",
"actual",
"@target",
".",
"heads",
"<<",
"@ptrs",
"[",
"0",
"]",
"@symbols",
".",
"map!",
"{",
"|",
"s",
"|",
"s",
"==",
"placeholder",
"?",
"actual",
":",
"s",
"}",
"end"
] | sometimes a Rule is instantiated before the target is actually known
it may be given a "placeholder" target first, which is later replaced
with the real one | [
"sometimes",
"a",
"Rule",
"is",
"instantiated",
"before",
"the",
"target",
"is",
"actually",
"known",
"it",
"may",
"be",
"given",
"a",
"placeholder",
"target",
"first",
"which",
"is",
"later",
"replaced",
"with",
"the",
"real",
"one"
] | d3244edfa11dd6e86e43f570c6444d41c7e3552a | https://github.com/ruby/racc/blob/d3244edfa11dd6e86e43f570c6444d41c7e3552a/lib/racc/grammar.rb#L470-L476 | train |
ruby/racc | lib/racc/grammar.rb | Racc.Sym.expand | def expand
@expand ||= Racc.set_closure(@heads.dup) do |ptr|
if (sym = ptr.symbol) && sym.nonterminal?
sym.heads
end
end.freeze
end | ruby | def expand
@expand ||= Racc.set_closure(@heads.dup) do |ptr|
if (sym = ptr.symbol) && sym.nonterminal?
sym.heads
end
end.freeze
end | [
"def",
"expand",
"@expand",
"||=",
"Racc",
".",
"set_closure",
"(",
"@heads",
".",
"dup",
")",
"do",
"|",
"ptr",
"|",
"if",
"(",
"sym",
"=",
"ptr",
".",
"symbol",
")",
"&&",
"sym",
".",
"nonterminal?",
"sym",
".",
"heads",
"end",
"end",
".",
"freeze",
"end"
] | If an instance of this NT comes next, then what rules could we be
starting? | [
"If",
"an",
"instance",
"of",
"this",
"NT",
"comes",
"next",
"then",
"what",
"rules",
"could",
"we",
"be",
"starting?"
] | d3244edfa11dd6e86e43f570c6444d41c7e3552a | https://github.com/ruby/racc/blob/d3244edfa11dd6e86e43f570c6444d41c7e3552a/lib/racc/grammar.rb#L738-L744 | train |
refile/refile | lib/refile/rails/attachment_helper.rb | Refile.AttachmentHelper.attachment_image_tag | def attachment_image_tag(record, name, *args, fallback: nil, host: nil, prefix: nil, format: nil, **options)
file = record && record.public_send(name)
classes = ["attachment", (record.class.model_name.singular if record), name, *options[:class]]
if file
image_tag(attachment_url(record, name, *args, host: host, prefix: prefix, format: format), options.merge(class: classes))
elsif fallback
classes << "fallback"
image_tag(fallback, options.merge(class: classes))
end
end | ruby | def attachment_image_tag(record, name, *args, fallback: nil, host: nil, prefix: nil, format: nil, **options)
file = record && record.public_send(name)
classes = ["attachment", (record.class.model_name.singular if record), name, *options[:class]]
if file
image_tag(attachment_url(record, name, *args, host: host, prefix: prefix, format: format), options.merge(class: classes))
elsif fallback
classes << "fallback"
image_tag(fallback, options.merge(class: classes))
end
end | [
"def",
"attachment_image_tag",
"(",
"record",
",",
"name",
",",
"*",
"args",
",",
"fallback",
":",
"nil",
",",
"host",
":",
"nil",
",",
"prefix",
":",
"nil",
",",
"format",
":",
"nil",
",",
"**",
"options",
")",
"file",
"=",
"record",
"&&",
"record",
".",
"public_send",
"(",
"name",
")",
"classes",
"=",
"[",
"\"attachment\"",
",",
"(",
"record",
".",
"class",
".",
"model_name",
".",
"singular",
"if",
"record",
")",
",",
"name",
",",
"options",
"[",
":class",
"]",
"]",
"if",
"file",
"image_tag",
"(",
"attachment_url",
"(",
"record",
",",
"name",
",",
"args",
",",
"host",
":",
"host",
",",
"prefix",
":",
"prefix",
",",
"format",
":",
"format",
")",
",",
"options",
".",
"merge",
"(",
"class",
":",
"classes",
")",
")",
"elsif",
"fallback",
"classes",
"<<",
"\"fallback\"",
"image_tag",
"(",
"fallback",
",",
"options",
".",
"merge",
"(",
"class",
":",
"classes",
")",
")",
"end",
"end"
] | Generates an image tag for the given attachment, adding appropriate
classes and optionally falling back to the given fallback image if there
is no file attached.
Returns `nil` if there is no file attached and no fallback specified.
@param [String] fallback The path to an image asset to be used as a fallback
@param [Hash] options Additional options for the image tag
@see #attachment_url
@return [ActiveSupport::SafeBuffer, nil] The generated image tag | [
"Generates",
"an",
"image",
"tag",
"for",
"the",
"given",
"attachment",
"adding",
"appropriate",
"classes",
"and",
"optionally",
"falling",
"back",
"to",
"the",
"given",
"fallback",
"image",
"if",
"there",
"is",
"no",
"file",
"attached",
"."
] | e910f5ca5a9060c307bd0a5e813f1fec73219ed5 | https://github.com/refile/refile/blob/e910f5ca5a9060c307bd0a5e813f1fec73219ed5/lib/refile/rails/attachment_helper.rb#L51-L61 | train |
refile/refile | lib/refile/rails/attachment_helper.rb | Refile.AttachmentHelper.attachment_cache_field | def attachment_cache_field(object_name, method, object:, **options)
options[:data] ||= {}
options[:data][:reference] ||= SecureRandom.hex
attacher_value = object.send("#{method}_data")
hidden_options = {
multiple: options[:multiple],
value: attacher_value.try(:to_json),
object: object,
disabled: attacher_value.blank?,
id: nil,
data: { reference: options[:data][:reference] }
}
hidden_options.merge!(index: options[:index]) if options.key?(:index)
hidden_field(object_name, method, hidden_options)
end | ruby | def attachment_cache_field(object_name, method, object:, **options)
options[:data] ||= {}
options[:data][:reference] ||= SecureRandom.hex
attacher_value = object.send("#{method}_data")
hidden_options = {
multiple: options[:multiple],
value: attacher_value.try(:to_json),
object: object,
disabled: attacher_value.blank?,
id: nil,
data: { reference: options[:data][:reference] }
}
hidden_options.merge!(index: options[:index]) if options.key?(:index)
hidden_field(object_name, method, hidden_options)
end | [
"def",
"attachment_cache_field",
"(",
"object_name",
",",
"method",
",",
"object",
":",
",",
"**",
"options",
")",
"options",
"[",
":data",
"]",
"||=",
"{",
"}",
"options",
"[",
":data",
"]",
"[",
":reference",
"]",
"||=",
"SecureRandom",
".",
"hex",
"attacher_value",
"=",
"object",
".",
"send",
"(",
"\"#{method}_data\"",
")",
"hidden_options",
"=",
"{",
"multiple",
":",
"options",
"[",
":multiple",
"]",
",",
"value",
":",
"attacher_value",
".",
"try",
"(",
":to_json",
")",
",",
"object",
":",
"object",
",",
"disabled",
":",
"attacher_value",
".",
"blank?",
",",
"id",
":",
"nil",
",",
"data",
":",
"{",
"reference",
":",
"options",
"[",
":data",
"]",
"[",
":reference",
"]",
"}",
"}",
"hidden_options",
".",
"merge!",
"(",
"index",
":",
"options",
"[",
":index",
"]",
")",
"if",
"options",
".",
"key?",
"(",
":index",
")",
"hidden_field",
"(",
"object_name",
",",
"method",
",",
"hidden_options",
")",
"end"
] | Generates a hidden form field which tracks the id of the file in the cache
before it is permanently stored.
@param object_name The name of the object to generate a field for
@param method The name of the field
@param [Hash] options
@option options [Object] object Set by the form builder
@return [ActiveSupport::SafeBuffer] The generated hidden form field | [
"Generates",
"a",
"hidden",
"form",
"field",
"which",
"tracks",
"the",
"id",
"of",
"the",
"file",
"in",
"the",
"cache",
"before",
"it",
"is",
"permanently",
"stored",
"."
] | e910f5ca5a9060c307bd0a5e813f1fec73219ed5 | https://github.com/refile/refile/blob/e910f5ca5a9060c307bd0a5e813f1fec73219ed5/lib/refile/rails/attachment_helper.rb#L105-L122 | train |
refile/refile | lib/refile/attachment.rb | Refile.Attachment.accepts_attachments_for | def accepts_attachments_for(collection_name, collection_class:, accessor_prefix:, attachment: :file, append: false)
include MultipleAttachments.new(
collection_name,
collection_class: collection_class,
name: accessor_prefix,
attachment: attachment,
append: append
)
end | ruby | def accepts_attachments_for(collection_name, collection_class:, accessor_prefix:, attachment: :file, append: false)
include MultipleAttachments.new(
collection_name,
collection_class: collection_class,
name: accessor_prefix,
attachment: attachment,
append: append
)
end | [
"def",
"accepts_attachments_for",
"(",
"collection_name",
",",
"collection_class",
":",
",",
"accessor_prefix",
":",
",",
"attachment",
":",
":file",
",",
"append",
":",
"false",
")",
"include",
"MultipleAttachments",
".",
"new",
"(",
"collection_name",
",",
"collection_class",
":",
"collection_class",
",",
"name",
":",
"accessor_prefix",
",",
"attachment",
":",
"attachment",
",",
"append",
":",
"append",
")",
"end"
] | Macro which generates accessors in pure Ruby classes for assigning
multiple attachments at once. This is primarily useful together with
multiple file uploads. There is also an Active Record version of
this macro.
The name of the generated accessors will be the name of the association
(represented by an attribute accessor) and the name of the attachment in
the associated class. So if a `Post` accepts attachments for `images`, and
the attachment in the `Image` class is named `file`, then the accessors will
be named `images_files`.
@example in associated class
class Document
extend Refile::Attachment
attr_accessor :file_id
attachment :file
def initialize(attributes = {})
self.file = attributes[:file]
end
end
@example in class
class Post
extend Refile::Attachment
include ActiveModel::Model
attr_accessor :documents
accepts_attachments_for :documents, accessor_prefix: 'documents_files', collection_class: Document
def initialize(attributes = {})
@documents = attributes[:documents] || []
end
end
@example in form
<%= form_for @post do |form| %>
<%= form.attachment_field :documents_files, multiple: true %>
<% end %>
@param [Symbol] collection_name Name of the association
@param [Class] collection_class Associated class
@param [String] accessor_prefix Name of the generated accessors
@param [Symbol] attachment Name of the attachment in the associated class
@param [Boolean] append If true, new files are appended instead of replacing the entire list of associated classes.
@return [void] | [
"Macro",
"which",
"generates",
"accessors",
"in",
"pure",
"Ruby",
"classes",
"for",
"assigning",
"multiple",
"attachments",
"at",
"once",
".",
"This",
"is",
"primarily",
"useful",
"together",
"with",
"multiple",
"file",
"uploads",
".",
"There",
"is",
"also",
"an",
"Active",
"Record",
"version",
"of",
"this",
"macro",
"."
] | e910f5ca5a9060c307bd0a5e813f1fec73219ed5 | https://github.com/refile/refile/blob/e910f5ca5a9060c307bd0a5e813f1fec73219ed5/lib/refile/attachment.rb#L156-L164 | train |
refile/refile | lib/refile/file.rb | Refile.File.download | def download
return io if io.is_a?(Tempfile)
Tempfile.new(id, binmode: true).tap do |tempfile|
IO.copy_stream(io, tempfile)
tempfile.rewind
tempfile.fsync
end
end | ruby | def download
return io if io.is_a?(Tempfile)
Tempfile.new(id, binmode: true).tap do |tempfile|
IO.copy_stream(io, tempfile)
tempfile.rewind
tempfile.fsync
end
end | [
"def",
"download",
"return",
"io",
"if",
"io",
".",
"is_a?",
"(",
"Tempfile",
")",
"Tempfile",
".",
"new",
"(",
"id",
",",
"binmode",
":",
"true",
")",
".",
"tap",
"do",
"|",
"tempfile",
"|",
"IO",
".",
"copy_stream",
"(",
"io",
",",
"tempfile",
")",
"tempfile",
".",
"rewind",
"tempfile",
".",
"fsync",
"end",
"end"
] | Downloads the file to a Tempfile on disk and returns this tempfile.
@example
file = backend.upload(StringIO.new("hello"))
tempfile = file.download
File.read(tempfile.path) # => "hello"
@return [Tempfile] a tempfile with the file's content | [
"Downloads",
"the",
"file",
"to",
"a",
"Tempfile",
"on",
"disk",
"and",
"returns",
"this",
"tempfile",
"."
] | e910f5ca5a9060c307bd0a5e813f1fec73219ed5 | https://github.com/refile/refile/blob/e910f5ca5a9060c307bd0a5e813f1fec73219ed5/lib/refile/file.rb#L69-L77 | train |
vcr/vcr | lib/vcr/structs.rb | VCR.Response.to_hash | def to_hash
{
'status' => status.to_hash,
'headers' => headers,
'body' => serializable_body,
'http_version' => http_version
}.tap do |hash|
hash['adapter_metadata'] = adapter_metadata unless adapter_metadata.empty?
end
end | ruby | def to_hash
{
'status' => status.to_hash,
'headers' => headers,
'body' => serializable_body,
'http_version' => http_version
}.tap do |hash|
hash['adapter_metadata'] = adapter_metadata unless adapter_metadata.empty?
end
end | [
"def",
"to_hash",
"{",
"'status'",
"=>",
"status",
".",
"to_hash",
",",
"'headers'",
"=>",
"headers",
",",
"'body'",
"=>",
"serializable_body",
",",
"'http_version'",
"=>",
"http_version",
"}",
".",
"tap",
"do",
"|",
"hash",
"|",
"hash",
"[",
"'adapter_metadata'",
"]",
"=",
"adapter_metadata",
"unless",
"adapter_metadata",
".",
"empty?",
"end",
"end"
] | Builds a serializable hash from the response data.
@return [Hash] hash that represents this response
and can be easily serialized.
@see Response.from_hash | [
"Builds",
"a",
"serializable",
"hash",
"from",
"the",
"response",
"data",
"."
] | 945ca793a4b25c7ffc406b9fd7da1e94cbbb8141 | https://github.com/vcr/vcr/blob/945ca793a4b25c7ffc406b9fd7da1e94cbbb8141/lib/vcr/structs.rb#L345-L354 | train |
vcr/vcr | lib/vcr/configuration.rb | VCR.Configuration.around_http_request | def around_http_request(*filters, &block)
unless VCR.fibers_available?
raise Errors::NotSupportedError.new \
"VCR::Configuration#around_http_request requires fibers, " +
"which are not available on your ruby intepreter."
end
fibers = {}
fiber_errors = {}
hook_allowed, hook_declaration = false, caller.first
before_http_request(*filters) do |request|
hook_allowed = true
start_new_fiber_for(request, fibers, fiber_errors, hook_declaration, block)
end
after_http_request(lambda { hook_allowed }) do |request, response|
fiber = fibers.delete(Thread.current)
resume_fiber(fiber, fiber_errors, response, hook_declaration)
end
end | ruby | def around_http_request(*filters, &block)
unless VCR.fibers_available?
raise Errors::NotSupportedError.new \
"VCR::Configuration#around_http_request requires fibers, " +
"which are not available on your ruby intepreter."
end
fibers = {}
fiber_errors = {}
hook_allowed, hook_declaration = false, caller.first
before_http_request(*filters) do |request|
hook_allowed = true
start_new_fiber_for(request, fibers, fiber_errors, hook_declaration, block)
end
after_http_request(lambda { hook_allowed }) do |request, response|
fiber = fibers.delete(Thread.current)
resume_fiber(fiber, fiber_errors, response, hook_declaration)
end
end | [
"def",
"around_http_request",
"(",
"*",
"filters",
",",
"&",
"block",
")",
"unless",
"VCR",
".",
"fibers_available?",
"raise",
"Errors",
"::",
"NotSupportedError",
".",
"new",
"\"VCR::Configuration#around_http_request requires fibers, \"",
"+",
"\"which are not available on your ruby intepreter.\"",
"end",
"fibers",
"=",
"{",
"}",
"fiber_errors",
"=",
"{",
"}",
"hook_allowed",
",",
"hook_declaration",
"=",
"false",
",",
"caller",
".",
"first",
"before_http_request",
"(",
"filters",
")",
"do",
"|",
"request",
"|",
"hook_allowed",
"=",
"true",
"start_new_fiber_for",
"(",
"request",
",",
"fibers",
",",
"fiber_errors",
",",
"hook_declaration",
",",
"block",
")",
"end",
"after_http_request",
"(",
"lambda",
"{",
"hook_allowed",
"}",
")",
"do",
"|",
"request",
",",
"response",
"|",
"fiber",
"=",
"fibers",
".",
"delete",
"(",
"Thread",
".",
"current",
")",
"resume_fiber",
"(",
"fiber",
",",
"fiber_errors",
",",
"response",
",",
"hook_declaration",
")",
"end",
"end"
] | Adds a callback that will be executed around each HTTP request.
@example
VCR.configure do |c|
c.around_http_request(lambda {|r| r.uri =~ /api.geocoder.com/}) do |request|
# extract an address like "1700 E Pine St, Seattle, WA"
# from a query like "address=1700+E+Pine+St%2C+Seattle%2C+WA"
address = CGI.unescape(URI(request.uri).query.split('=').last)
VCR.use_cassette("geocoding/#{address}", &request)
end
end
@yield the callback
@yieldparam request [VCR::Request::FiberAware] the request that is being made
@raise [VCR::Errors::NotSupportedError] if the fiber library cannot be loaded.
@param filters [optional splat of #to_proc] one or more filters to apply.
The objects provided will be converted to procs using `#to_proc`. If provided,
the callback will only be invoked if these procs all return `true`.
@note This method can only be used on ruby interpreters that support
fibers (i.e. 1.9+). On 1.8 you can use separate `before_http_request` and
`after_http_request` hooks.
@note You _must_ call `request.proceed` or pass the request as a proc on to a
method that yields to a block (i.e. `some_method(&request)`).
@see #before_http_request
@see #after_http_request | [
"Adds",
"a",
"callback",
"that",
"will",
"be",
"executed",
"around",
"each",
"HTTP",
"request",
"."
] | 945ca793a4b25c7ffc406b9fd7da1e94cbbb8141 | https://github.com/vcr/vcr/blob/945ca793a4b25c7ffc406b9fd7da1e94cbbb8141/lib/vcr/configuration.rb#L395-L414 | train |
floere/phony | lib/phony/dsl.rb | Phony.DSL.country | def country country_code, definition, options = {}
return unless Phony.config.load?(country_code)
definition.with country_code, options
Phony::CountryCodes.instance.add country_code, definition
end | ruby | def country country_code, definition, options = {}
return unless Phony.config.load?(country_code)
definition.with country_code, options
Phony::CountryCodes.instance.add country_code, definition
end | [
"def",
"country",
"country_code",
",",
"definition",
",",
"options",
"=",
"{",
"}",
"return",
"unless",
"Phony",
".",
"config",
".",
"load?",
"(",
"country_code",
")",
"definition",
".",
"with",
"country_code",
",",
"options",
"Phony",
"::",
"CountryCodes",
".",
"instance",
".",
"add",
"country_code",
",",
"definition",
"end"
] | Define a country's rules.
Use the other DSL methods to define the country's rules.
@param [String] country_code The country code of the country.
@param [Phony::CountryCodes] definition Rules for this country.
@return Undefined.
@example Add a country with country code 27.
country '27', # CC, followed by rules, for example fixed(2) >> ... | [
"Define",
"a",
"country",
"s",
"rules",
"."
] | 9ca50743499cf478a25fdb927bcdacd29d2c90c7 | https://github.com/floere/phony/blob/9ca50743499cf478a25fdb927bcdacd29d2c90c7/lib/phony/dsl.rb#L43-L48 | train |
floere/phony | lib/phony/dsl.rb | Phony.DSL.fixed | def fixed length, options = {}
options[:zero] = true if options[:zero].nil?
NationalSplitters::Fixed.instance_for length, options
end | ruby | def fixed length, options = {}
options[:zero] = true if options[:zero].nil?
NationalSplitters::Fixed.instance_for length, options
end | [
"def",
"fixed",
"length",
",",
"options",
"=",
"{",
"}",
"options",
"[",
":zero",
"]",
"=",
"true",
"if",
"options",
"[",
":zero",
"]",
".",
"nil?",
"NationalSplitters",
"::",
"Fixed",
".",
"instance_for",
"length",
",",
"options",
"end"
] | National matcher & splitters.
By default, a fixed length NDC
uses a zero prefix when formatted
with format :national.
@param [Fixnum] length The length of the fixed length NDC.
@param [Hash] options An options hash (set zero: false to not add a zero on format :national).
@return NationalSplitters::Fixed A fixed length national splitter.
@example France. Uses a fixed NDC of size 1.
country '33', fixed(1) >> split(2,2,2,2) | [
"National",
"matcher",
"&",
"splitters",
"."
] | 9ca50743499cf478a25fdb927bcdacd29d2c90c7 | https://github.com/floere/phony/blob/9ca50743499cf478a25fdb927bcdacd29d2c90c7/lib/phony/dsl.rb#L110-L113 | train |
floere/phony | lib/phony/country_codes.rb | Phony.CountryCodes.add | def add country_code, country
country_code = country_code.to_s
optimized_country_code_access = country_code.size
@countries ||= {}
@countries[optimized_country_code_access] ||= {}
@countries[optimized_country_code_access][country_code] = country
end | ruby | def add country_code, country
country_code = country_code.to_s
optimized_country_code_access = country_code.size
@countries ||= {}
@countries[optimized_country_code_access] ||= {}
@countries[optimized_country_code_access][country_code] = country
end | [
"def",
"add",
"country_code",
",",
"country",
"country_code",
"=",
"country_code",
".",
"to_s",
"optimized_country_code_access",
"=",
"country_code",
".",
"size",
"@countries",
"||=",
"{",
"}",
"@countries",
"[",
"optimized_country_code_access",
"]",
"||=",
"{",
"}",
"@countries",
"[",
"optimized_country_code_access",
"]",
"[",
"country_code",
"]",
"=",
"country",
"end"
] | Add the given country to the mapping under the
given country code. | [
"Add",
"the",
"given",
"country",
"to",
"the",
"mapping",
"under",
"the",
"given",
"country",
"code",
"."
] | 9ca50743499cf478a25fdb927bcdacd29d2c90c7 | https://github.com/floere/phony/blob/9ca50743499cf478a25fdb927bcdacd29d2c90c7/lib/phony/country_codes.rb#L21-L28 | train |
floere/phony | lib/phony/country_codes.rb | Phony.CountryCodes.split | def split number
# Split the number into country, cc, and national part.
country, cc, national_number = partial_split number
# Split the national number into ndc and local part.
_, ndc, *local = country.split national_number
[cc, ndc, *local]
end | ruby | def split number
# Split the number into country, cc, and national part.
country, cc, national_number = partial_split number
# Split the national number into ndc and local part.
_, ndc, *local = country.split national_number
[cc, ndc, *local]
end | [
"def",
"split",
"number",
"# Split the number into country, cc, and national part.",
"country",
",",
"cc",
",",
"national_number",
"=",
"partial_split",
"number",
"# Split the national number into ndc and local part.",
"_",
",",
"ndc",
",",
"*",
"local",
"=",
"country",
".",
"split",
"national_number",
"[",
"cc",
",",
"ndc",
",",
"local",
"]",
"end"
] | Splits this number into cc, ndc and locally split number parts. | [
"Splits",
"this",
"number",
"into",
"cc",
"ndc",
"and",
"locally",
"split",
"number",
"parts",
"."
] | 9ca50743499cf478a25fdb927bcdacd29d2c90c7 | https://github.com/floere/phony/blob/9ca50743499cf478a25fdb927bcdacd29d2c90c7/lib/phony/country_codes.rb#L75-L83 | train |
floere/phony | lib/phony/country_codes.rb | Phony.CountryCodes.format | def format number, options = {}
country, _, national_number = partial_split number
country.format national_number, options
end | ruby | def format number, options = {}
country, _, national_number = partial_split number
country.format national_number, options
end | [
"def",
"format",
"number",
",",
"options",
"=",
"{",
"}",
"country",
",",
"_",
",",
"national_number",
"=",
"partial_split",
"number",
"country",
".",
"format",
"national_number",
",",
"options",
"end"
] | Format the number. | [
"Format",
"the",
"number",
"."
] | 9ca50743499cf478a25fdb927bcdacd29d2c90c7 | https://github.com/floere/phony/blob/9ca50743499cf478a25fdb927bcdacd29d2c90c7/lib/phony/country_codes.rb#L87-L90 | train |
floere/phony | lib/phony/country_codes.rb | Phony.CountryCodes.plausible? | def plausible? number, hints = {}
normalized = clean number
# False if it fails the basic check.
#
return false unless (4..16) === normalized.size
country, cc, rest = partial_split normalized
# Country code plausible?
#
cc_needed = hints[:cc]
return false if cc_needed && !(cc_needed === cc)
# Country specific tests.
#
country.plausible? rest, hints
rescue StandardError
return false
end | ruby | def plausible? number, hints = {}
normalized = clean number
# False if it fails the basic check.
#
return false unless (4..16) === normalized.size
country, cc, rest = partial_split normalized
# Country code plausible?
#
cc_needed = hints[:cc]
return false if cc_needed && !(cc_needed === cc)
# Country specific tests.
#
country.plausible? rest, hints
rescue StandardError
return false
end | [
"def",
"plausible?",
"number",
",",
"hints",
"=",
"{",
"}",
"normalized",
"=",
"clean",
"number",
"# False if it fails the basic check.",
"#",
"return",
"false",
"unless",
"(",
"4",
"..",
"16",
")",
"===",
"normalized",
".",
"size",
"country",
",",
"cc",
",",
"rest",
"=",
"partial_split",
"normalized",
"# Country code plausible?",
"#",
"cc_needed",
"=",
"hints",
"[",
":cc",
"]",
"return",
"false",
"if",
"cc_needed",
"&&",
"!",
"(",
"cc_needed",
"===",
"cc",
")",
"# Country specific tests.",
"#",
"country",
".",
"plausible?",
"rest",
",",
"hints",
"rescue",
"StandardError",
"return",
"false",
"end"
] | Is this number plausible? | [
"Is",
"this",
"number",
"plausible?"
] | 9ca50743499cf478a25fdb927bcdacd29d2c90c7 | https://github.com/floere/phony/blob/9ca50743499cf478a25fdb927bcdacd29d2c90c7/lib/phony/country_codes.rb#L95-L114 | train |
floere/phony | lib/phony/country_codes.rb | Phony.CountryCodes.vanity? | def vanity? number
country, _, national = partial_split number
country.vanity? national
end | ruby | def vanity? number
country, _, national = partial_split number
country.vanity? national
end | [
"def",
"vanity?",
"number",
"country",
",",
"_",
",",
"national",
"=",
"partial_split",
"number",
"country",
".",
"vanity?",
"national",
"end"
] | Is the given number a vanity number? | [
"Is",
"the",
"given",
"number",
"a",
"vanity",
"number?"
] | 9ca50743499cf478a25fdb927bcdacd29d2c90c7 | https://github.com/floere/phony/blob/9ca50743499cf478a25fdb927bcdacd29d2c90c7/lib/phony/country_codes.rb#L118-L121 | train |
floere/phony | lib/phony/country_codes.rb | Phony.CountryCodes.partial_split | def partial_split number
cc = ''
1.upto(3) do |i|
cc << number.slice!(0..0)
country = countries[i][cc]
return [country, cc, number] if country
end
# This line is never reached as CCs are in prefix code.
end | ruby | def partial_split number
cc = ''
1.upto(3) do |i|
cc << number.slice!(0..0)
country = countries[i][cc]
return [country, cc, number] if country
end
# This line is never reached as CCs are in prefix code.
end | [
"def",
"partial_split",
"number",
"cc",
"=",
"''",
"1",
".",
"upto",
"(",
"3",
")",
"do",
"|",
"i",
"|",
"cc",
"<<",
"number",
".",
"slice!",
"(",
"0",
"..",
"0",
")",
"country",
"=",
"countries",
"[",
"i",
"]",
"[",
"cc",
"]",
"return",
"[",
"country",
",",
"cc",
",",
"number",
"]",
"if",
"country",
"end",
"# This line is never reached as CCs are in prefix code.",
"end"
] | Split off the country and the cc, and also return the national number part. | [
"Split",
"off",
"the",
"country",
"and",
"the",
"cc",
"and",
"also",
"return",
"the",
"national",
"number",
"part",
"."
] | 9ca50743499cf478a25fdb927bcdacd29d2c90c7 | https://github.com/floere/phony/blob/9ca50743499cf478a25fdb927bcdacd29d2c90c7/lib/phony/country_codes.rb#L140-L148 | train |
floere/phony | lib/phony/country.rb | Phony.Country.split | def split national_number
_, trunk, ndc, *rest = internal_split national_number
[trunk, ndc, *rest]
end | ruby | def split national_number
_, trunk, ndc, *rest = internal_split national_number
[trunk, ndc, *rest]
end | [
"def",
"split",
"national_number",
"_",
",",
"trunk",
",",
"ndc",
",",
"*",
"rest",
"=",
"internal_split",
"national_number",
"[",
"trunk",
",",
"ndc",
",",
"rest",
"]",
"end"
] | A number is split with the code handlers as given in the initializer.
Note: If the ndc is nil, it will not return it.
@return [Trunk, String (ndc), Array<String> (national pieces)] | [
"A",
"number",
"is",
"split",
"with",
"the",
"code",
"handlers",
"as",
"given",
"in",
"the",
"initializer",
"."
] | 9ca50743499cf478a25fdb927bcdacd29d2c90c7 | https://github.com/floere/phony/blob/9ca50743499cf478a25fdb927bcdacd29d2c90c7/lib/phony/country.rb#L55-L58 | train |
floere/phony | lib/phony/country.rb | Phony.Country.format | def format national_number, options = {}
type = options[:format] || @format
space = options[:spaces] || @space || @@default_space
local_space = options[:local_spaces] || @local_space || space || @@default_local_space
parentheses = options[:parentheses]
parentheses = @parentheses || @@default_parentheses if parentheses.nil?
use_trunk = options[:trunk]
trunk, ndc, *local_pieces = split national_number
local = format_local local_pieces, local_space
format_cc_ndc trunk, ndc, local, type, space, parentheses, use_trunk
end | ruby | def format national_number, options = {}
type = options[:format] || @format
space = options[:spaces] || @space || @@default_space
local_space = options[:local_spaces] || @local_space || space || @@default_local_space
parentheses = options[:parentheses]
parentheses = @parentheses || @@default_parentheses if parentheses.nil?
use_trunk = options[:trunk]
trunk, ndc, *local_pieces = split national_number
local = format_local local_pieces, local_space
format_cc_ndc trunk, ndc, local, type, space, parentheses, use_trunk
end | [
"def",
"format",
"national_number",
",",
"options",
"=",
"{",
"}",
"type",
"=",
"options",
"[",
":format",
"]",
"||",
"@format",
"space",
"=",
"options",
"[",
":spaces",
"]",
"||",
"@space",
"||",
"@@default_space",
"local_space",
"=",
"options",
"[",
":local_spaces",
"]",
"||",
"@local_space",
"||",
"space",
"||",
"@@default_local_space",
"parentheses",
"=",
"options",
"[",
":parentheses",
"]",
"parentheses",
"=",
"@parentheses",
"||",
"@@default_parentheses",
"if",
"parentheses",
".",
"nil?",
"use_trunk",
"=",
"options",
"[",
":trunk",
"]",
"trunk",
",",
"ndc",
",",
"*",
"local_pieces",
"=",
"split",
"national_number",
"local",
"=",
"format_local",
"local_pieces",
",",
"local_space",
"format_cc_ndc",
"trunk",
",",
"ndc",
",",
"local",
",",
"type",
",",
"space",
",",
"parentheses",
",",
"use_trunk",
"end"
] | Format the number, given the national part of it. | [
"Format",
"the",
"number",
"given",
"the",
"national",
"part",
"of",
"it",
"."
] | 9ca50743499cf478a25fdb927bcdacd29d2c90c7 | https://github.com/floere/phony/blob/9ca50743499cf478a25fdb927bcdacd29d2c90c7/lib/phony/country.rb#L77-L90 | train |
floere/phony | lib/phony/country.rb | Phony.Country.normalize | def normalize national_number
clean! national_number
normalized = @codes.reduce national_number do |number, code|
result = code.normalize number
break result if result
number
end
normalized
end | ruby | def normalize national_number
clean! national_number
normalized = @codes.reduce national_number do |number, code|
result = code.normalize number
break result if result
number
end
normalized
end | [
"def",
"normalize",
"national_number",
"clean!",
"national_number",
"normalized",
"=",
"@codes",
".",
"reduce",
"national_number",
"do",
"|",
"number",
",",
"code",
"|",
"result",
"=",
"code",
".",
"normalize",
"number",
"break",
"result",
"if",
"result",
"number",
"end",
"normalized",
"end"
] | Removes 0s from partially normalized numbers
such as 410443643533.
Example:
410443643533 -> 41443643533
In some cases it doesn't, like Italy. | [
"Removes",
"0s",
"from",
"partially",
"normalized",
"numbers",
"such",
"as",
"410443643533",
"."
] | 9ca50743499cf478a25fdb927bcdacd29d2c90c7 | https://github.com/floere/phony/blob/9ca50743499cf478a25fdb927bcdacd29d2c90c7/lib/phony/country.rb#L159-L167 | train |
floere/phony | lib/phony/country.rb | Phony.Country.plausible? | def plausible? rest, hints = {}
local, _, ndc, *rest = internal_split rest
# Element based checking.
#
# Note: ndc == false means the country has none.
#
return false if ndc.nil?
return false if ndc && ndc.empty?
return false if @invalid_ndcs && @invalid_ndcs === ndc
# # A valid range for the rest is 0 or 3+ total digits.
# #
# return false if (1..2) === rest_size
# National destination code plausible?
#
ndc_needed = hints[:ndc]
return false if ndc_needed && !(ndc_needed === ndc)
# If there is no local part, we can assume it's not a plausible number.
# (Or, not defined correctly in Phony yet)
return false unless local
# Local code specific checks.
#
return local.plausible? rest, hints
end | ruby | def plausible? rest, hints = {}
local, _, ndc, *rest = internal_split rest
# Element based checking.
#
# Note: ndc == false means the country has none.
#
return false if ndc.nil?
return false if ndc && ndc.empty?
return false if @invalid_ndcs && @invalid_ndcs === ndc
# # A valid range for the rest is 0 or 3+ total digits.
# #
# return false if (1..2) === rest_size
# National destination code plausible?
#
ndc_needed = hints[:ndc]
return false if ndc_needed && !(ndc_needed === ndc)
# If there is no local part, we can assume it's not a plausible number.
# (Or, not defined correctly in Phony yet)
return false unless local
# Local code specific checks.
#
return local.plausible? rest, hints
end | [
"def",
"plausible?",
"rest",
",",
"hints",
"=",
"{",
"}",
"local",
",",
"_",
",",
"ndc",
",",
"*",
"rest",
"=",
"internal_split",
"rest",
"# Element based checking.",
"#",
"# Note: ndc == false means the country has none.",
"#",
"return",
"false",
"if",
"ndc",
".",
"nil?",
"return",
"false",
"if",
"ndc",
"&&",
"ndc",
".",
"empty?",
"return",
"false",
"if",
"@invalid_ndcs",
"&&",
"@invalid_ndcs",
"===",
"ndc",
"# # A valid range for the rest is 0 or 3+ total digits.",
"# #",
"# return false if (1..2) === rest_size",
"# National destination code plausible?",
"#",
"ndc_needed",
"=",
"hints",
"[",
":ndc",
"]",
"return",
"false",
"if",
"ndc_needed",
"&&",
"!",
"(",
"ndc_needed",
"===",
"ndc",
")",
"# If there is no local part, we can assume it's not a plausible number.",
"# (Or, not defined correctly in Phony yet)",
"return",
"false",
"unless",
"local",
"# Local code specific checks.",
"#",
"return",
"local",
".",
"plausible?",
"rest",
",",
"hints",
"end"
] | Tests for plausibility of this national number. | [
"Tests",
"for",
"plausibility",
"of",
"this",
"national",
"number",
"."
] | 9ca50743499cf478a25fdb927bcdacd29d2c90c7 | https://github.com/floere/phony/blob/9ca50743499cf478a25fdb927bcdacd29d2c90c7/lib/phony/country.rb#L171-L198 | train |
mongodb/mongoid | lib/mongoid/criteria.rb | Mongoid.Criteria.merge! | def merge!(other)
criteria = other.to_criteria
selector.merge!(criteria.selector)
options.merge!(criteria.options)
self.documents = criteria.documents.dup unless criteria.documents.empty?
self.scoping_options = criteria.scoping_options
self.inclusions = (inclusions + criteria.inclusions).uniq
self
end | ruby | def merge!(other)
criteria = other.to_criteria
selector.merge!(criteria.selector)
options.merge!(criteria.options)
self.documents = criteria.documents.dup unless criteria.documents.empty?
self.scoping_options = criteria.scoping_options
self.inclusions = (inclusions + criteria.inclusions).uniq
self
end | [
"def",
"merge!",
"(",
"other",
")",
"criteria",
"=",
"other",
".",
"to_criteria",
"selector",
".",
"merge!",
"(",
"criteria",
".",
"selector",
")",
"options",
".",
"merge!",
"(",
"criteria",
".",
"options",
")",
"self",
".",
"documents",
"=",
"criteria",
".",
"documents",
".",
"dup",
"unless",
"criteria",
".",
"documents",
".",
"empty?",
"self",
".",
"scoping_options",
"=",
"criteria",
".",
"scoping_options",
"self",
".",
"inclusions",
"=",
"(",
"inclusions",
"+",
"criteria",
".",
"inclusions",
")",
".",
"uniq",
"self",
"end"
] | Merge the other criteria into this one.
@example Merge another criteria into this criteria.
criteria.merge(Person.where(name: "bob"))
@param [ Criteria ] other The criteria to merge in.
@return [ Criteria ] The merged criteria.
@since 3.0.0 | [
"Merge",
"the",
"other",
"criteria",
"into",
"this",
"one",
"."
] | 56976e32610f4c2450882b0bfe14da099f0703f4 | https://github.com/mongodb/mongoid/blob/56976e32610f4c2450882b0bfe14da099f0703f4/lib/mongoid/criteria.rb#L242-L250 | train |
mongodb/mongoid | lib/mongoid/criteria.rb | Mongoid.Criteria.only | def only(*args)
return clone if args.flatten.empty?
args = args.flatten
if (args & Fields::IDS).empty?
args.unshift(:_id)
end
if klass.hereditary?
super(*args.push(:_type))
else
super(*args)
end
end | ruby | def only(*args)
return clone if args.flatten.empty?
args = args.flatten
if (args & Fields::IDS).empty?
args.unshift(:_id)
end
if klass.hereditary?
super(*args.push(:_type))
else
super(*args)
end
end | [
"def",
"only",
"(",
"*",
"args",
")",
"return",
"clone",
"if",
"args",
".",
"flatten",
".",
"empty?",
"args",
"=",
"args",
".",
"flatten",
"if",
"(",
"args",
"&",
"Fields",
"::",
"IDS",
")",
".",
"empty?",
"args",
".",
"unshift",
"(",
":_id",
")",
"end",
"if",
"klass",
".",
"hereditary?",
"super",
"(",
"args",
".",
"push",
"(",
":_type",
")",
")",
"else",
"super",
"(",
"args",
")",
"end",
"end"
] | Overriden to include _type in the fields.
@example Limit the fields returned from the database.
Band.only(:name)
@param [ Array<Symbol> ] args The names of the fields.
@return [ Criteria ] The cloned criteria.
@since 1.0.0 | [
"Overriden",
"to",
"include",
"_type",
"in",
"the",
"fields",
"."
] | 56976e32610f4c2450882b0bfe14da099f0703f4 | https://github.com/mongodb/mongoid/blob/56976e32610f4c2450882b0bfe14da099f0703f4/lib/mongoid/criteria.rb#L287-L298 | train |
mongodb/mongoid | lib/mongoid/criteria.rb | Mongoid.Criteria.read | def read(value = nil)
clone.tap do |criteria|
criteria.options.merge!(read: value)
end
end | ruby | def read(value = nil)
clone.tap do |criteria|
criteria.options.merge!(read: value)
end
end | [
"def",
"read",
"(",
"value",
"=",
"nil",
")",
"clone",
".",
"tap",
"do",
"|",
"criteria",
"|",
"criteria",
".",
"options",
".",
"merge!",
"(",
"read",
":",
"value",
")",
"end",
"end"
] | Set the read preference for the criteria.
@example Set the read preference.
criteria.read(mode: :primary_preferred)
@param [ Hash ] value The mode preference.
@return [ Criteria ] The cloned criteria.
@since 5.0.0 | [
"Set",
"the",
"read",
"preference",
"for",
"the",
"criteria",
"."
] | 56976e32610f4c2450882b0bfe14da099f0703f4 | https://github.com/mongodb/mongoid/blob/56976e32610f4c2450882b0bfe14da099f0703f4/lib/mongoid/criteria.rb#L310-L314 | train |
mongodb/mongoid | lib/mongoid/criteria.rb | Mongoid.Criteria.respond_to? | def respond_to?(name, include_private = false)
super || klass.respond_to?(name) || CHECK.respond_to?(name, include_private)
end | ruby | def respond_to?(name, include_private = false)
super || klass.respond_to?(name) || CHECK.respond_to?(name, include_private)
end | [
"def",
"respond_to?",
"(",
"name",
",",
"include_private",
"=",
"false",
")",
"super",
"||",
"klass",
".",
"respond_to?",
"(",
"name",
")",
"||",
"CHECK",
".",
"respond_to?",
"(",
"name",
",",
"include_private",
")",
"end"
] | Returns true if criteria responds to the given method.
@example Does the criteria respond to the method?
crtiteria.respond_to?(:each)
@param [ Symbol ] name The name of the class method on the +Document+.
@param [ true, false ] include_private Whether to include privates.
@return [ true, false ] If the criteria responds to the method. | [
"Returns",
"true",
"if",
"criteria",
"responds",
"to",
"the",
"given",
"method",
"."
] | 56976e32610f4c2450882b0bfe14da099f0703f4 | https://github.com/mongodb/mongoid/blob/56976e32610f4c2450882b0bfe14da099f0703f4/lib/mongoid/criteria.rb#L340-L342 | train |
mongodb/mongoid | lib/mongoid/criteria.rb | Mongoid.Criteria.check_for_missing_documents! | def check_for_missing_documents!(result, ids)
if (result.size < ids.size) && Mongoid.raise_not_found_error
raise Errors::DocumentNotFound.new(klass, ids, ids - result.map(&:_id))
end
end | ruby | def check_for_missing_documents!(result, ids)
if (result.size < ids.size) && Mongoid.raise_not_found_error
raise Errors::DocumentNotFound.new(klass, ids, ids - result.map(&:_id))
end
end | [
"def",
"check_for_missing_documents!",
"(",
"result",
",",
"ids",
")",
"if",
"(",
"result",
".",
"size",
"<",
"ids",
".",
"size",
")",
"&&",
"Mongoid",
".",
"raise_not_found_error",
"raise",
"Errors",
"::",
"DocumentNotFound",
".",
"new",
"(",
"klass",
",",
"ids",
",",
"ids",
"-",
"result",
".",
"map",
"(",
":_id",
")",
")",
"end",
"end"
] | Are documents in the query missing, and are we configured to raise an
error?
@api private
@example Check for missing documents.
criteria.check_for_missing_documents!([], [ 1 ])
@param [ Array<Document> ] result The result.
@param [ Array<Object> ] ids The ids.
@raise [ Errors::DocumentNotFound ] If none are found and raising an
error.
@since 3.0.0 | [
"Are",
"documents",
"in",
"the",
"query",
"missing",
"and",
"are",
"we",
"configured",
"to",
"raise",
"an",
"error?"
] | 56976e32610f4c2450882b0bfe14da099f0703f4 | https://github.com/mongodb/mongoid/blob/56976e32610f4c2450882b0bfe14da099f0703f4/lib/mongoid/criteria.rb#L459-L463 | train |
mongodb/mongoid | lib/mongoid/criteria.rb | Mongoid.Criteria.initialize_copy | def initialize_copy(other)
@inclusions = other.inclusions.dup
@scoping_options = other.scoping_options
@documents = other.documents.dup
@context = nil
super
end | ruby | def initialize_copy(other)
@inclusions = other.inclusions.dup
@scoping_options = other.scoping_options
@documents = other.documents.dup
@context = nil
super
end | [
"def",
"initialize_copy",
"(",
"other",
")",
"@inclusions",
"=",
"other",
".",
"inclusions",
".",
"dup",
"@scoping_options",
"=",
"other",
".",
"scoping_options",
"@documents",
"=",
"other",
".",
"documents",
".",
"dup",
"@context",
"=",
"nil",
"super",
"end"
] | Clone or dup the current +Criteria+. This will return a new criteria with
the selector, options, klass, embedded options, etc intact.
@api private
@example Clone a criteria.
criteria.clone
@example Dup a criteria.
criteria.dup
@param [ Criteria ] other The criteria getting cloned.
@return [ nil ] nil.
@since 1.0.0 | [
"Clone",
"or",
"dup",
"the",
"current",
"+",
"Criteria",
"+",
".",
"This",
"will",
"return",
"a",
"new",
"criteria",
"with",
"the",
"selector",
"options",
"klass",
"embedded",
"options",
"etc",
"intact",
"."
] | 56976e32610f4c2450882b0bfe14da099f0703f4 | https://github.com/mongodb/mongoid/blob/56976e32610f4c2450882b0bfe14da099f0703f4/lib/mongoid/criteria.rb#L481-L487 | train |
mongodb/mongoid | lib/mongoid/criteria.rb | Mongoid.Criteria.type_selection | def type_selection
klasses = klass._types
if klasses.size > 1
{ _type: { "$in" => klass._types }}
else
{ _type: klass._types[0] }
end
end | ruby | def type_selection
klasses = klass._types
if klasses.size > 1
{ _type: { "$in" => klass._types }}
else
{ _type: klass._types[0] }
end
end | [
"def",
"type_selection",
"klasses",
"=",
"klass",
".",
"_types",
"if",
"klasses",
".",
"size",
">",
"1",
"{",
"_type",
":",
"{",
"\"$in\"",
"=>",
"klass",
".",
"_types",
"}",
"}",
"else",
"{",
"_type",
":",
"klass",
".",
"_types",
"[",
"0",
"]",
"}",
"end",
"end"
] | Get the selector for type selection.
@api private
@example Get a type selection hash.
criteria.type_selection
@return [ Hash ] The type selection.
@since 3.0.3 | [
"Get",
"the",
"selector",
"for",
"type",
"selection",
"."
] | 56976e32610f4c2450882b0bfe14da099f0703f4 | https://github.com/mongodb/mongoid/blob/56976e32610f4c2450882b0bfe14da099f0703f4/lib/mongoid/criteria.rb#L552-L559 | train |
mongodb/mongoid | lib/mongoid/positional.rb | Mongoid.Positional.positionally | def positionally(selector, operations, processed = {})
if selector.size == 1 || selector.values.any? { |val| val.nil? }
return operations
end
keys = selector.keys.map{ |m| m.sub('._id','') } - ['_id']
keys = keys.sort_by { |s| s.length*-1 }
process_operations(keys, operations, processed)
end | ruby | def positionally(selector, operations, processed = {})
if selector.size == 1 || selector.values.any? { |val| val.nil? }
return operations
end
keys = selector.keys.map{ |m| m.sub('._id','') } - ['_id']
keys = keys.sort_by { |s| s.length*-1 }
process_operations(keys, operations, processed)
end | [
"def",
"positionally",
"(",
"selector",
",",
"operations",
",",
"processed",
"=",
"{",
"}",
")",
"if",
"selector",
".",
"size",
"==",
"1",
"||",
"selector",
".",
"values",
".",
"any?",
"{",
"|",
"val",
"|",
"val",
".",
"nil?",
"}",
"return",
"operations",
"end",
"keys",
"=",
"selector",
".",
"keys",
".",
"map",
"{",
"|",
"m",
"|",
"m",
".",
"sub",
"(",
"'._id'",
",",
"''",
")",
"}",
"-",
"[",
"'_id'",
"]",
"keys",
"=",
"keys",
".",
"sort_by",
"{",
"|",
"s",
"|",
"s",
".",
"length",
"-",
"1",
"}",
"process_operations",
"(",
"keys",
",",
"operations",
",",
"processed",
")",
"end"
] | Takes the provided selector and atomic operations and replaces the
indexes of the embedded documents with the positional operator when
needed.
@note The only time we can accurately know when to use the positional
operator is at the exact time we are going to persist something. So
we can tell by the selector that we are sending if it is actually
possible to use the positional operator at all. For example, if the
selector is: { "_id" => 1 }, then we could not use the positional
operator for updating embedded documents since there would never be a
match - we base whether we can based on the number of levels deep the
selector goes, and if the id values are not nil.
@example Process the operations.
positionally(
{ "_id" => 1, "addresses._id" => 2 },
{ "$set" => { "addresses.0.street" => "hobrecht" }}
)
@param [ Hash ] selector The selector.
@param [ Hash ] operations The update operations.
@param [ Hash ] processed The processed update operations.
@return [ Hash ] The new operations.
@since 3.1.0 | [
"Takes",
"the",
"provided",
"selector",
"and",
"atomic",
"operations",
"and",
"replaces",
"the",
"indexes",
"of",
"the",
"embedded",
"documents",
"with",
"the",
"positional",
"operator",
"when",
"needed",
"."
] | 56976e32610f4c2450882b0bfe14da099f0703f4 | https://github.com/mongodb/mongoid/blob/56976e32610f4c2450882b0bfe14da099f0703f4/lib/mongoid/positional.rb#L37-L44 | train |
mongodb/mongoid | lib/mongoid/touchable.rb | Mongoid.Touchable.define_touchable! | def define_touchable!(association)
name = association.name
method_name = define_relation_touch_method(name, association)
association.inverse_class.tap do |klass|
klass.after_save method_name
klass.after_destroy method_name
klass.after_touch method_name
end
end | ruby | def define_touchable!(association)
name = association.name
method_name = define_relation_touch_method(name, association)
association.inverse_class.tap do |klass|
klass.after_save method_name
klass.after_destroy method_name
klass.after_touch method_name
end
end | [
"def",
"define_touchable!",
"(",
"association",
")",
"name",
"=",
"association",
".",
"name",
"method_name",
"=",
"define_relation_touch_method",
"(",
"name",
",",
"association",
")",
"association",
".",
"inverse_class",
".",
"tap",
"do",
"|",
"klass",
"|",
"klass",
".",
"after_save",
"method_name",
"klass",
".",
"after_destroy",
"method_name",
"klass",
".",
"after_touch",
"method_name",
"end",
"end"
] | Add the association to the touchable associations if the touch option was
provided.
@example Add the touchable.
Model.define_touchable!(assoc)
@param [ Association ] association The association metadata.
@return [ Class ] The model class.
@since 3.0.0 | [
"Add",
"the",
"association",
"to",
"the",
"touchable",
"associations",
"if",
"the",
"touch",
"option",
"was",
"provided",
"."
] | 56976e32610f4c2450882b0bfe14da099f0703f4 | https://github.com/mongodb/mongoid/blob/56976e32610f4c2450882b0bfe14da099f0703f4/lib/mongoid/touchable.rb#L55-L63 | train |
mongodb/mongoid | lib/mongoid/loggable.rb | Mongoid.Loggable.default_logger | def default_logger
logger = Logger.new($stdout)
logger.level = Mongoid::Config.log_level
logger
end | ruby | def default_logger
logger = Logger.new($stdout)
logger.level = Mongoid::Config.log_level
logger
end | [
"def",
"default_logger",
"logger",
"=",
"Logger",
".",
"new",
"(",
"$stdout",
")",
"logger",
".",
"level",
"=",
"Mongoid",
"::",
"Config",
".",
"log_level",
"logger",
"end"
] | Gets the default Mongoid logger - stdout.
@api private
@example Get the default logger.
Loggable.default_logger
@return [ Logger ] The default logger.
@since 3.0.0 | [
"Gets",
"the",
"default",
"Mongoid",
"logger",
"-",
"stdout",
"."
] | 56976e32610f4c2450882b0bfe14da099f0703f4 | https://github.com/mongodb/mongoid/blob/56976e32610f4c2450882b0bfe14da099f0703f4/lib/mongoid/loggable.rb#L50-L54 | train |
mongodb/mongoid | lib/mongoid/copyable.rb | Mongoid.Copyable.process_localized_attributes | def process_localized_attributes(klass, attrs)
klass.localized_fields.keys.each do |name|
if value = attrs.delete(name)
attrs["#{name}_translations"] = value
end
end
klass.embedded_relations.each do |_, association|
next unless attrs.present? && attrs[association.key].present?
if association.is_a?(Association::Embedded::EmbedsMany)
attrs[association.key].each do |attr|
embedded_klass = attr.fetch('_type', association.class_name).constantize
process_localized_attributes(embedded_klass, attr)
end
else
process_localized_attributes(association.klass, attrs[association.key])
end
end
end | ruby | def process_localized_attributes(klass, attrs)
klass.localized_fields.keys.each do |name|
if value = attrs.delete(name)
attrs["#{name}_translations"] = value
end
end
klass.embedded_relations.each do |_, association|
next unless attrs.present? && attrs[association.key].present?
if association.is_a?(Association::Embedded::EmbedsMany)
attrs[association.key].each do |attr|
embedded_klass = attr.fetch('_type', association.class_name).constantize
process_localized_attributes(embedded_klass, attr)
end
else
process_localized_attributes(association.klass, attrs[association.key])
end
end
end | [
"def",
"process_localized_attributes",
"(",
"klass",
",",
"attrs",
")",
"klass",
".",
"localized_fields",
".",
"keys",
".",
"each",
"do",
"|",
"name",
"|",
"if",
"value",
"=",
"attrs",
".",
"delete",
"(",
"name",
")",
"attrs",
"[",
"\"#{name}_translations\"",
"]",
"=",
"value",
"end",
"end",
"klass",
".",
"embedded_relations",
".",
"each",
"do",
"|",
"_",
",",
"association",
"|",
"next",
"unless",
"attrs",
".",
"present?",
"&&",
"attrs",
"[",
"association",
".",
"key",
"]",
".",
"present?",
"if",
"association",
".",
"is_a?",
"(",
"Association",
"::",
"Embedded",
"::",
"EmbedsMany",
")",
"attrs",
"[",
"association",
".",
"key",
"]",
".",
"each",
"do",
"|",
"attr",
"|",
"embedded_klass",
"=",
"attr",
".",
"fetch",
"(",
"'_type'",
",",
"association",
".",
"class_name",
")",
".",
"constantize",
"process_localized_attributes",
"(",
"embedded_klass",
",",
"attr",
")",
"end",
"else",
"process_localized_attributes",
"(",
"association",
".",
"klass",
",",
"attrs",
"[",
"association",
".",
"key",
"]",
")",
"end",
"end",
"end"
] | When cloning, if the document has localized fields we need to ensure they
are properly processed in the clone.
@api private
@example Process localized attributes.
model.process_localized_attributes(attributes)
@param [ Hash ] attrs The attributes.
@since 3.0.20 | [
"When",
"cloning",
"if",
"the",
"document",
"has",
"localized",
"fields",
"we",
"need",
"to",
"ensure",
"they",
"are",
"properly",
"processed",
"in",
"the",
"clone",
"."
] | 56976e32610f4c2450882b0bfe14da099f0703f4 | https://github.com/mongodb/mongoid/blob/56976e32610f4c2450882b0bfe14da099f0703f4/lib/mongoid/copyable.rb#L67-L85 | train |
mongodb/mongoid | lib/mongoid/shardable.rb | Mongoid.Shardable.shard_key_selector | def shard_key_selector
selector = {}
shard_key_fields.each do |field|
selector[field.to_s] = new_record? ? send(field) : attribute_was(field)
end
selector
end | ruby | def shard_key_selector
selector = {}
shard_key_fields.each do |field|
selector[field.to_s] = new_record? ? send(field) : attribute_was(field)
end
selector
end | [
"def",
"shard_key_selector",
"selector",
"=",
"{",
"}",
"shard_key_fields",
".",
"each",
"do",
"|",
"field",
"|",
"selector",
"[",
"field",
".",
"to_s",
"]",
"=",
"new_record?",
"?",
"send",
"(",
"field",
")",
":",
"attribute_was",
"(",
"field",
")",
"end",
"selector",
"end"
] | Get the document selector with the defined shard keys.
@example Get the selector for the shard keys.
person.shard_key_selector
@return [ Hash ] The shard key selector.
@since 2.0.0 | [
"Get",
"the",
"document",
"selector",
"with",
"the",
"defined",
"shard",
"keys",
"."
] | 56976e32610f4c2450882b0bfe14da099f0703f4 | https://github.com/mongodb/mongoid/blob/56976e32610f4c2450882b0bfe14da099f0703f4/lib/mongoid/shardable.rb#L38-L44 | train |
mongodb/mongoid | lib/mongoid/reloadable.rb | Mongoid.Reloadable.reload | def reload
reloaded = _reload
if Mongoid.raise_not_found_error && reloaded.empty?
raise Errors::DocumentNotFound.new(self.class, _id, _id)
end
@attributes = reloaded
@attributes_before_type_cast = {}
changed_attributes.clear
reset_readonly
apply_defaults
reload_relations
run_callbacks(:find) unless _find_callbacks.empty?
run_callbacks(:initialize) unless _initialize_callbacks.empty?
self
end | ruby | def reload
reloaded = _reload
if Mongoid.raise_not_found_error && reloaded.empty?
raise Errors::DocumentNotFound.new(self.class, _id, _id)
end
@attributes = reloaded
@attributes_before_type_cast = {}
changed_attributes.clear
reset_readonly
apply_defaults
reload_relations
run_callbacks(:find) unless _find_callbacks.empty?
run_callbacks(:initialize) unless _initialize_callbacks.empty?
self
end | [
"def",
"reload",
"reloaded",
"=",
"_reload",
"if",
"Mongoid",
".",
"raise_not_found_error",
"&&",
"reloaded",
".",
"empty?",
"raise",
"Errors",
"::",
"DocumentNotFound",
".",
"new",
"(",
"self",
".",
"class",
",",
"_id",
",",
"_id",
")",
"end",
"@attributes",
"=",
"reloaded",
"@attributes_before_type_cast",
"=",
"{",
"}",
"changed_attributes",
".",
"clear",
"reset_readonly",
"apply_defaults",
"reload_relations",
"run_callbacks",
"(",
":find",
")",
"unless",
"_find_callbacks",
".",
"empty?",
"run_callbacks",
"(",
":initialize",
")",
"unless",
"_initialize_callbacks",
".",
"empty?",
"self",
"end"
] | Reloads the +Document+ attributes from the database. If the document has
not been saved then an error will get raised if the configuration option
was set. This can reload root documents or embedded documents.
@example Reload the document.
person.reload
@raise [ Errors::DocumentNotFound ] If the document was deleted.
@return [ Document ] The document, reloaded.
@since 1.0.0 | [
"Reloads",
"the",
"+",
"Document",
"+",
"attributes",
"from",
"the",
"database",
".",
"If",
"the",
"document",
"has",
"not",
"been",
"saved",
"then",
"an",
"error",
"will",
"get",
"raised",
"if",
"the",
"configuration",
"option",
"was",
"set",
".",
"This",
"can",
"reload",
"root",
"documents",
"or",
"embedded",
"documents",
"."
] | 56976e32610f4c2450882b0bfe14da099f0703f4 | https://github.com/mongodb/mongoid/blob/56976e32610f4c2450882b0bfe14da099f0703f4/lib/mongoid/reloadable.rb#L22-L36 | train |
mongodb/mongoid | lib/mongoid/reloadable.rb | Mongoid.Reloadable.reload_root_document | def reload_root_document
{}.merge(collection.find({ _id: _id }, session: _session).read(mode: :primary).first || {})
end | ruby | def reload_root_document
{}.merge(collection.find({ _id: _id }, session: _session).read(mode: :primary).first || {})
end | [
"def",
"reload_root_document",
"{",
"}",
".",
"merge",
"(",
"collection",
".",
"find",
"(",
"{",
"_id",
":",
"_id",
"}",
",",
"session",
":",
"_session",
")",
".",
"read",
"(",
"mode",
":",
":primary",
")",
".",
"first",
"||",
"{",
"}",
")",
"end"
] | Reload the root document.
@example Reload the document.
document.reload_root_document
@return [ Hash ] The reloaded attributes.
@since 2.3.2 | [
"Reload",
"the",
"root",
"document",
"."
] | 56976e32610f4c2450882b0bfe14da099f0703f4 | https://github.com/mongodb/mongoid/blob/56976e32610f4c2450882b0bfe14da099f0703f4/lib/mongoid/reloadable.rb#L61-L63 | train |
mongodb/mongoid | lib/mongoid/reloadable.rb | Mongoid.Reloadable.reload_embedded_document | def reload_embedded_document
extract_embedded_attributes({}.merge(
collection(_root).find(_id: _root._id).read(mode: :primary).first
))
end | ruby | def reload_embedded_document
extract_embedded_attributes({}.merge(
collection(_root).find(_id: _root._id).read(mode: :primary).first
))
end | [
"def",
"reload_embedded_document",
"extract_embedded_attributes",
"(",
"{",
"}",
".",
"merge",
"(",
"collection",
"(",
"_root",
")",
".",
"find",
"(",
"_id",
":",
"_root",
".",
"_id",
")",
".",
"read",
"(",
"mode",
":",
":primary",
")",
".",
"first",
")",
")",
"end"
] | Reload the embedded document.
@example Reload the document.
document.reload_embedded_document
@return [ Hash ] The reloaded attributes.
@since 2.3.2 | [
"Reload",
"the",
"embedded",
"document",
"."
] | 56976e32610f4c2450882b0bfe14da099f0703f4 | https://github.com/mongodb/mongoid/blob/56976e32610f4c2450882b0bfe14da099f0703f4/lib/mongoid/reloadable.rb#L73-L77 | train |
mongodb/mongoid | lib/mongoid/reloadable.rb | Mongoid.Reloadable.extract_embedded_attributes | def extract_embedded_attributes(attributes)
atomic_position.split(".").inject(attributes) do |attrs, part|
attrs = attrs[part =~ /\d/ ? part.to_i : part]
attrs
end
end | ruby | def extract_embedded_attributes(attributes)
atomic_position.split(".").inject(attributes) do |attrs, part|
attrs = attrs[part =~ /\d/ ? part.to_i : part]
attrs
end
end | [
"def",
"extract_embedded_attributes",
"(",
"attributes",
")",
"atomic_position",
".",
"split",
"(",
"\".\"",
")",
".",
"inject",
"(",
"attributes",
")",
"do",
"|",
"attrs",
",",
"part",
"|",
"attrs",
"=",
"attrs",
"[",
"part",
"=~",
"/",
"\\d",
"/",
"?",
"part",
".",
"to_i",
":",
"part",
"]",
"attrs",
"end",
"end"
] | Extract only the desired embedded document from the attributes.
@example Extract the embedded document.
document.extract_embedded_attributes(attributes)
@param [ Hash ] attributes The document in the db.
@return [ Hash ] The document's extracted attributes.
@since 2.3.2 | [
"Extract",
"only",
"the",
"desired",
"embedded",
"document",
"from",
"the",
"attributes",
"."
] | 56976e32610f4c2450882b0bfe14da099f0703f4 | https://github.com/mongodb/mongoid/blob/56976e32610f4c2450882b0bfe14da099f0703f4/lib/mongoid/reloadable.rb#L89-L94 | train |
mongodb/mongoid | lib/mongoid/attributes.rb | Mongoid.Attributes.attribute_present? | def attribute_present?(name)
attribute = read_raw_attribute(name)
!attribute.blank? || attribute == false
rescue ActiveModel::MissingAttributeError
false
end | ruby | def attribute_present?(name)
attribute = read_raw_attribute(name)
!attribute.blank? || attribute == false
rescue ActiveModel::MissingAttributeError
false
end | [
"def",
"attribute_present?",
"(",
"name",
")",
"attribute",
"=",
"read_raw_attribute",
"(",
"name",
")",
"!",
"attribute",
".",
"blank?",
"||",
"attribute",
"==",
"false",
"rescue",
"ActiveModel",
"::",
"MissingAttributeError",
"false",
"end"
] | Determine if an attribute is present.
@example Is the attribute present?
person.attribute_present?("title")
@param [ String, Symbol ] name The name of the attribute.
@return [ true, false ] True if present, false if not.
@since 1.0.0 | [
"Determine",
"if",
"an",
"attribute",
"is",
"present",
"."
] | 56976e32610f4c2450882b0bfe14da099f0703f4 | https://github.com/mongodb/mongoid/blob/56976e32610f4c2450882b0bfe14da099f0703f4/lib/mongoid/attributes.rb#L32-L37 | train |
mongodb/mongoid | lib/mongoid/attributes.rb | Mongoid.Attributes.read_attribute | def read_attribute(name)
field = fields[name.to_s]
raw = read_raw_attribute(name)
field ? field.demongoize(raw) : raw
end | ruby | def read_attribute(name)
field = fields[name.to_s]
raw = read_raw_attribute(name)
field ? field.demongoize(raw) : raw
end | [
"def",
"read_attribute",
"(",
"name",
")",
"field",
"=",
"fields",
"[",
"name",
".",
"to_s",
"]",
"raw",
"=",
"read_raw_attribute",
"(",
"name",
")",
"field",
"?",
"field",
".",
"demongoize",
"(",
"raw",
")",
":",
"raw",
"end"
] | Read a value from the document attributes. If the value does not exist
it will return nil.
@example Read an attribute.
person.read_attribute(:title)
@example Read an attribute (alternate syntax.)
person[:title]
@param [ String, Symbol ] name The name of the attribute to get.
@return [ Object ] The value of the attribute.
@since 1.0.0 | [
"Read",
"a",
"value",
"from",
"the",
"document",
"attributes",
".",
"If",
"the",
"value",
"does",
"not",
"exist",
"it",
"will",
"return",
"nil",
"."
] | 56976e32610f4c2450882b0bfe14da099f0703f4 | https://github.com/mongodb/mongoid/blob/56976e32610f4c2450882b0bfe14da099f0703f4/lib/mongoid/attributes.rb#L95-L99 | train |
mongodb/mongoid | lib/mongoid/attributes.rb | Mongoid.Attributes.read_attribute_before_type_cast | def read_attribute_before_type_cast(name)
attr = name.to_s
if attributes_before_type_cast.key?(attr)
attributes_before_type_cast[attr]
else
read_raw_attribute(attr)
end
end | ruby | def read_attribute_before_type_cast(name)
attr = name.to_s
if attributes_before_type_cast.key?(attr)
attributes_before_type_cast[attr]
else
read_raw_attribute(attr)
end
end | [
"def",
"read_attribute_before_type_cast",
"(",
"name",
")",
"attr",
"=",
"name",
".",
"to_s",
"if",
"attributes_before_type_cast",
".",
"key?",
"(",
"attr",
")",
"attributes_before_type_cast",
"[",
"attr",
"]",
"else",
"read_raw_attribute",
"(",
"attr",
")",
"end",
"end"
] | Read a value from the attributes before type cast. If the value has not
yet been assigned then this will return the attribute's existing value
using read_raw_attribute.
@example Read an attribute before type cast.
person.read_attribute_before_type_cast(:price)
@param [ String, Symbol ] name The name of the attribute to get.
@return [ Object ] The value of the attribute before type cast, if
available. Otherwise, the value of the attribute.
@since 3.1.0 | [
"Read",
"a",
"value",
"from",
"the",
"attributes",
"before",
"type",
"cast",
".",
"If",
"the",
"value",
"has",
"not",
"yet",
"been",
"assigned",
"then",
"this",
"will",
"return",
"the",
"attribute",
"s",
"existing",
"value",
"using",
"read_raw_attribute",
"."
] | 56976e32610f4c2450882b0bfe14da099f0703f4 | https://github.com/mongodb/mongoid/blob/56976e32610f4c2450882b0bfe14da099f0703f4/lib/mongoid/attributes.rb#L115-L122 | train |
mongodb/mongoid | lib/mongoid/attributes.rb | Mongoid.Attributes.remove_attribute | def remove_attribute(name)
as_writable_attribute!(name) do |access|
_assigning do
attribute_will_change!(access)
delayed_atomic_unsets[atomic_attribute_name(access)] = [] unless new_record?
attributes.delete(access)
end
end
end | ruby | def remove_attribute(name)
as_writable_attribute!(name) do |access|
_assigning do
attribute_will_change!(access)
delayed_atomic_unsets[atomic_attribute_name(access)] = [] unless new_record?
attributes.delete(access)
end
end
end | [
"def",
"remove_attribute",
"(",
"name",
")",
"as_writable_attribute!",
"(",
"name",
")",
"do",
"|",
"access",
"|",
"_assigning",
"do",
"attribute_will_change!",
"(",
"access",
")",
"delayed_atomic_unsets",
"[",
"atomic_attribute_name",
"(",
"access",
")",
"]",
"=",
"[",
"]",
"unless",
"new_record?",
"attributes",
".",
"delete",
"(",
"access",
")",
"end",
"end",
"end"
] | Remove a value from the +Document+ attributes. If the value does not exist
it will fail gracefully.
@example Remove the attribute.
person.remove_attribute(:title)
@param [ String, Symbol ] name The name of the attribute to remove.
@raise [ Errors::ReadonlyAttribute ] If the field cannot be removed due
to being flagged as reaodnly.
@since 1.0.0 | [
"Remove",
"a",
"value",
"from",
"the",
"+",
"Document",
"+",
"attributes",
".",
"If",
"the",
"value",
"does",
"not",
"exist",
"it",
"will",
"fail",
"gracefully",
"."
] | 56976e32610f4c2450882b0bfe14da099f0703f4 | https://github.com/mongodb/mongoid/blob/56976e32610f4c2450882b0bfe14da099f0703f4/lib/mongoid/attributes.rb#L136-L144 | train |
mongodb/mongoid | lib/mongoid/attributes.rb | Mongoid.Attributes.write_attribute | def write_attribute(name, value)
access = database_field_name(name)
if attribute_writable?(access)
_assigning do
validate_attribute_value(access, value)
localized = fields[access].try(:localized?)
attributes_before_type_cast[name.to_s] = value
typed_value = typed_value_for(access, value)
unless attributes[access] == typed_value || attribute_changed?(access)
attribute_will_change!(access)
end
if localized
attributes[access] ||= {}
attributes[access].merge!(typed_value)
else
attributes[access] = typed_value
end
typed_value
end
end
end | ruby | def write_attribute(name, value)
access = database_field_name(name)
if attribute_writable?(access)
_assigning do
validate_attribute_value(access, value)
localized = fields[access].try(:localized?)
attributes_before_type_cast[name.to_s] = value
typed_value = typed_value_for(access, value)
unless attributes[access] == typed_value || attribute_changed?(access)
attribute_will_change!(access)
end
if localized
attributes[access] ||= {}
attributes[access].merge!(typed_value)
else
attributes[access] = typed_value
end
typed_value
end
end
end | [
"def",
"write_attribute",
"(",
"name",
",",
"value",
")",
"access",
"=",
"database_field_name",
"(",
"name",
")",
"if",
"attribute_writable?",
"(",
"access",
")",
"_assigning",
"do",
"validate_attribute_value",
"(",
"access",
",",
"value",
")",
"localized",
"=",
"fields",
"[",
"access",
"]",
".",
"try",
"(",
":localized?",
")",
"attributes_before_type_cast",
"[",
"name",
".",
"to_s",
"]",
"=",
"value",
"typed_value",
"=",
"typed_value_for",
"(",
"access",
",",
"value",
")",
"unless",
"attributes",
"[",
"access",
"]",
"==",
"typed_value",
"||",
"attribute_changed?",
"(",
"access",
")",
"attribute_will_change!",
"(",
"access",
")",
"end",
"if",
"localized",
"attributes",
"[",
"access",
"]",
"||=",
"{",
"}",
"attributes",
"[",
"access",
"]",
".",
"merge!",
"(",
"typed_value",
")",
"else",
"attributes",
"[",
"access",
"]",
"=",
"typed_value",
"end",
"typed_value",
"end",
"end",
"end"
] | Write a single attribute to the document attribute hash. This will
also fire the before and after update callbacks, and perform any
necessary typecasting.
@example Write the attribute.
person.write_attribute(:title, "Mr.")
@example Write the attribute (alternate syntax.)
person[:title] = "Mr."
@param [ String, Symbol ] name The name of the attribute to update.
@param [ Object ] value The value to set for the attribute.
@since 1.0.0 | [
"Write",
"a",
"single",
"attribute",
"to",
"the",
"document",
"attribute",
"hash",
".",
"This",
"will",
"also",
"fire",
"the",
"before",
"and",
"after",
"update",
"callbacks",
"and",
"perform",
"any",
"necessary",
"typecasting",
"."
] | 56976e32610f4c2450882b0bfe14da099f0703f4 | https://github.com/mongodb/mongoid/blob/56976e32610f4c2450882b0bfe14da099f0703f4/lib/mongoid/attributes.rb#L160-L180 | train |
mongodb/mongoid | lib/mongoid/attributes.rb | Mongoid.Attributes.attribute_missing? | def attribute_missing?(name)
selection = __selected_fields
return false unless selection
field = fields[name]
(selection.values.first == 0 && selection_excluded?(name, selection, field)) ||
(selection.values.first == 1 && !selection_included?(name, selection, field))
end | ruby | def attribute_missing?(name)
selection = __selected_fields
return false unless selection
field = fields[name]
(selection.values.first == 0 && selection_excluded?(name, selection, field)) ||
(selection.values.first == 1 && !selection_included?(name, selection, field))
end | [
"def",
"attribute_missing?",
"(",
"name",
")",
"selection",
"=",
"__selected_fields",
"return",
"false",
"unless",
"selection",
"field",
"=",
"fields",
"[",
"name",
"]",
"(",
"selection",
".",
"values",
".",
"first",
"==",
"0",
"&&",
"selection_excluded?",
"(",
"name",
",",
"selection",
",",
"field",
")",
")",
"||",
"(",
"selection",
".",
"values",
".",
"first",
"==",
"1",
"&&",
"!",
"selection_included?",
"(",
"name",
",",
"selection",
",",
"field",
")",
")",
"end"
] | Determine if the attribute is missing from the document, due to loading
it from the database with missing fields.
@example Is the attribute missing?
document.attribute_missing?("test")
@param [ String ] name The name of the attribute.
@return [ true, false ] If the attribute is missing.
@since 4.0.0 | [
"Determine",
"if",
"the",
"attribute",
"is",
"missing",
"from",
"the",
"document",
"due",
"to",
"loading",
"it",
"from",
"the",
"database",
"with",
"missing",
"fields",
"."
] | 56976e32610f4c2450882b0bfe14da099f0703f4 | https://github.com/mongodb/mongoid/blob/56976e32610f4c2450882b0bfe14da099f0703f4/lib/mongoid/attributes.rb#L232-L238 | train |
mongodb/mongoid | lib/mongoid/attributes.rb | Mongoid.Attributes.typed_value_for | def typed_value_for(key, value)
fields.key?(key) ? fields[key].mongoize(value) : value.mongoize
end | ruby | def typed_value_for(key, value)
fields.key?(key) ? fields[key].mongoize(value) : value.mongoize
end | [
"def",
"typed_value_for",
"(",
"key",
",",
"value",
")",
"fields",
".",
"key?",
"(",
"key",
")",
"?",
"fields",
"[",
"key",
"]",
".",
"mongoize",
"(",
"value",
")",
":",
"value",
".",
"mongoize",
"end"
] | Return the typecasted value for a field.
@example Get the value typecasted.
person.typed_value_for(:title, :sir)
@param [ String, Symbol ] key The field name.
@param [ Object ] value The uncast value.
@return [ Object ] The cast value.
@since 1.0.0 | [
"Return",
"the",
"typecasted",
"value",
"for",
"a",
"field",
"."
] | 56976e32610f4c2450882b0bfe14da099f0703f4 | https://github.com/mongodb/mongoid/blob/56976e32610f4c2450882b0bfe14da099f0703f4/lib/mongoid/attributes.rb#L287-L289 | train |
mongodb/mongoid | lib/mongoid/attributes.rb | Mongoid.Attributes.validate_attribute_value | def validate_attribute_value(access, value)
return unless fields[access] && value
validatable_types = [ Hash, Array ]
if validatable_types.include? fields[access].type
unless value.is_a? fields[access].type
raise Mongoid::Errors::InvalidValue.new(fields[access].type, value.class)
end
end
end | ruby | def validate_attribute_value(access, value)
return unless fields[access] && value
validatable_types = [ Hash, Array ]
if validatable_types.include? fields[access].type
unless value.is_a? fields[access].type
raise Mongoid::Errors::InvalidValue.new(fields[access].type, value.class)
end
end
end | [
"def",
"validate_attribute_value",
"(",
"access",
",",
"value",
")",
"return",
"unless",
"fields",
"[",
"access",
"]",
"&&",
"value",
"validatable_types",
"=",
"[",
"Hash",
",",
"Array",
"]",
"if",
"validatable_types",
".",
"include?",
"fields",
"[",
"access",
"]",
".",
"type",
"unless",
"value",
".",
"is_a?",
"fields",
"[",
"access",
"]",
".",
"type",
"raise",
"Mongoid",
"::",
"Errors",
"::",
"InvalidValue",
".",
"new",
"(",
"fields",
"[",
"access",
"]",
".",
"type",
",",
"value",
".",
"class",
")",
"end",
"end",
"end"
] | Validates an attribute value. This provides validation checking if
the value is valid for given a field.
For now, only Hash and Array fields are validated.
@param [ String, Symbol ] access The name of the attribute to validate.
@param [ Object ] value The to be validated.
@since 3.0.10 | [
"Validates",
"an",
"attribute",
"value",
".",
"This",
"provides",
"validation",
"checking",
"if",
"the",
"value",
"is",
"valid",
"for",
"given",
"a",
"field",
".",
"For",
"now",
"only",
"Hash",
"and",
"Array",
"fields",
"are",
"validated",
"."
] | 56976e32610f4c2450882b0bfe14da099f0703f4 | https://github.com/mongodb/mongoid/blob/56976e32610f4c2450882b0bfe14da099f0703f4/lib/mongoid/attributes.rb#L349-L357 | train |
mongodb/mongoid | lib/mongoid/factory.rb | Mongoid.Factory.build | def build(klass, attributes = nil)
attributes ||= {}
type = attributes[TYPE] || attributes[TYPE.to_sym]
if type && klass._types.include?(type)
type.constantize.new(attributes)
else
klass.new(attributes)
end
end | ruby | def build(klass, attributes = nil)
attributes ||= {}
type = attributes[TYPE] || attributes[TYPE.to_sym]
if type && klass._types.include?(type)
type.constantize.new(attributes)
else
klass.new(attributes)
end
end | [
"def",
"build",
"(",
"klass",
",",
"attributes",
"=",
"nil",
")",
"attributes",
"||=",
"{",
"}",
"type",
"=",
"attributes",
"[",
"TYPE",
"]",
"||",
"attributes",
"[",
"TYPE",
".",
"to_sym",
"]",
"if",
"type",
"&&",
"klass",
".",
"_types",
".",
"include?",
"(",
"type",
")",
"type",
".",
"constantize",
".",
"new",
"(",
"attributes",
")",
"else",
"klass",
".",
"new",
"(",
"attributes",
")",
"end",
"end"
] | Builds a new +Document+ from the supplied attributes.
@example Build the document.
Mongoid::Factory.build(Person, { "name" => "Durran" })
@param [ Class ] klass The class to instantiate from if _type is not present.
@param [ Hash ] attributes The document attributes.
@return [ Document ] The instantiated document. | [
"Builds",
"a",
"new",
"+",
"Document",
"+",
"from",
"the",
"supplied",
"attributes",
"."
] | 56976e32610f4c2450882b0bfe14da099f0703f4 | https://github.com/mongodb/mongoid/blob/56976e32610f4c2450882b0bfe14da099f0703f4/lib/mongoid/factory.rb#L20-L28 | train |
mongodb/mongoid | lib/mongoid/factory.rb | Mongoid.Factory.from_db | def from_db(klass, attributes = nil, criteria = nil, selected_fields = nil)
if criteria
selected_fields ||= criteria.options[:fields]
end
type = (attributes || {})[TYPE]
if type.blank?
obj = klass.instantiate(attributes, selected_fields)
if criteria && criteria.association && criteria.parent_document
obj.set_relation(criteria.association.inverse, criteria.parent_document)
end
obj
else
camelized = type.camelize
# Check if the class exists
begin
constantized = camelized.constantize
rescue NameError
raise Errors::UnknownModel.new(camelized, type)
end
# Check if the class is a Document class
if !constantized.respond_to?(:instantiate)
raise Errors::UnknownModel.new(camelized, type)
end
constantized.instantiate(attributes, selected_fields)
end
end | ruby | def from_db(klass, attributes = nil, criteria = nil, selected_fields = nil)
if criteria
selected_fields ||= criteria.options[:fields]
end
type = (attributes || {})[TYPE]
if type.blank?
obj = klass.instantiate(attributes, selected_fields)
if criteria && criteria.association && criteria.parent_document
obj.set_relation(criteria.association.inverse, criteria.parent_document)
end
obj
else
camelized = type.camelize
# Check if the class exists
begin
constantized = camelized.constantize
rescue NameError
raise Errors::UnknownModel.new(camelized, type)
end
# Check if the class is a Document class
if !constantized.respond_to?(:instantiate)
raise Errors::UnknownModel.new(camelized, type)
end
constantized.instantiate(attributes, selected_fields)
end
end | [
"def",
"from_db",
"(",
"klass",
",",
"attributes",
"=",
"nil",
",",
"criteria",
"=",
"nil",
",",
"selected_fields",
"=",
"nil",
")",
"if",
"criteria",
"selected_fields",
"||=",
"criteria",
".",
"options",
"[",
":fields",
"]",
"end",
"type",
"=",
"(",
"attributes",
"||",
"{",
"}",
")",
"[",
"TYPE",
"]",
"if",
"type",
".",
"blank?",
"obj",
"=",
"klass",
".",
"instantiate",
"(",
"attributes",
",",
"selected_fields",
")",
"if",
"criteria",
"&&",
"criteria",
".",
"association",
"&&",
"criteria",
".",
"parent_document",
"obj",
".",
"set_relation",
"(",
"criteria",
".",
"association",
".",
"inverse",
",",
"criteria",
".",
"parent_document",
")",
"end",
"obj",
"else",
"camelized",
"=",
"type",
".",
"camelize",
"# Check if the class exists",
"begin",
"constantized",
"=",
"camelized",
".",
"constantize",
"rescue",
"NameError",
"raise",
"Errors",
"::",
"UnknownModel",
".",
"new",
"(",
"camelized",
",",
"type",
")",
"end",
"# Check if the class is a Document class",
"if",
"!",
"constantized",
".",
"respond_to?",
"(",
":instantiate",
")",
"raise",
"Errors",
"::",
"UnknownModel",
".",
"new",
"(",
"camelized",
",",
"type",
")",
"end",
"constantized",
".",
"instantiate",
"(",
"attributes",
",",
"selected_fields",
")",
"end",
"end"
] | Builds a new +Document+ from the supplied attributes loaded from the
database.
If a criteria object is given, it is used in two ways:
1. If the criteria has a list of fields specified via #only,
only those fields are populated in the returned document.
2. If the criteria has a referencing association (i.e., this document
is being instantiated as an association of another document),
the other document is also populated in the returned document's
reverse association, if one exists.
@example Build the document.
Mongoid::Factory.from_db(Person, { "name" => "Durran" })
@param [ Class ] klass The class to instantiate from if _type is not present.
@param [ Hash ] attributes The document attributes.
@param [ Criteria ] criteria Optional criteria object.
@param [ Hash ] selected_fields Fields which were retrieved via
#only. If selected_fields are specified, fields not listed in it
will not be accessible in the returned document.
@return [ Document ] The instantiated document. | [
"Builds",
"a",
"new",
"+",
"Document",
"+",
"from",
"the",
"supplied",
"attributes",
"loaded",
"from",
"the",
"database",
"."
] | 56976e32610f4c2450882b0bfe14da099f0703f4 | https://github.com/mongodb/mongoid/blob/56976e32610f4c2450882b0bfe14da099f0703f4/lib/mongoid/factory.rb#L52-L80 | train |
mongodb/mongoid | lib/mongoid/atomic.rb | Mongoid.Atomic.add_atomic_pull | def add_atomic_pull(document)
document.flagged_for_destroy = true
(delayed_atomic_pulls[document.association_name.to_s] ||= []).push(document)
end | ruby | def add_atomic_pull(document)
document.flagged_for_destroy = true
(delayed_atomic_pulls[document.association_name.to_s] ||= []).push(document)
end | [
"def",
"add_atomic_pull",
"(",
"document",
")",
"document",
".",
"flagged_for_destroy",
"=",
"true",
"(",
"delayed_atomic_pulls",
"[",
"document",
".",
"association_name",
".",
"to_s",
"]",
"||=",
"[",
"]",
")",
".",
"push",
"(",
"document",
")",
"end"
] | Add the document as an atomic pull.
@example Add the atomic pull.
person.add_atomic_pull(address)
@param [ Document ] document The embedded document to pull.
@since 2.2.0 | [
"Add",
"the",
"document",
"as",
"an",
"atomic",
"pull",
"."
] | 56976e32610f4c2450882b0bfe14da099f0703f4 | https://github.com/mongodb/mongoid/blob/56976e32610f4c2450882b0bfe14da099f0703f4/lib/mongoid/atomic.rb#L38-L41 | train |
mongodb/mongoid | lib/mongoid/atomic.rb | Mongoid.Atomic.add_atomic_unset | def add_atomic_unset(document)
document.flagged_for_destroy = true
(delayed_atomic_unsets[document.association_name.to_s] ||= []).push(document)
end | ruby | def add_atomic_unset(document)
document.flagged_for_destroy = true
(delayed_atomic_unsets[document.association_name.to_s] ||= []).push(document)
end | [
"def",
"add_atomic_unset",
"(",
"document",
")",
"document",
".",
"flagged_for_destroy",
"=",
"true",
"(",
"delayed_atomic_unsets",
"[",
"document",
".",
"association_name",
".",
"to_s",
"]",
"||=",
"[",
"]",
")",
".",
"push",
"(",
"document",
")",
"end"
] | Add an atomic unset for the document.
@example Add an atomic unset.
document.add_atomic_unset(doc)
@param [ Document ] document The child document.
@return [ Array<Document> ] The children.
@since 3.0.0 | [
"Add",
"an",
"atomic",
"unset",
"for",
"the",
"document",
"."
] | 56976e32610f4c2450882b0bfe14da099f0703f4 | https://github.com/mongodb/mongoid/blob/56976e32610f4c2450882b0bfe14da099f0703f4/lib/mongoid/atomic.rb#L53-L56 | train |
mongodb/mongoid | lib/mongoid/atomic.rb | Mongoid.Atomic.atomic_updates | def atomic_updates(_use_indexes = false)
process_flagged_destroys
mods = Modifiers.new
generate_atomic_updates(mods, self)
_children.each do |child|
child.process_flagged_destroys
generate_atomic_updates(mods, child)
end
mods
end | ruby | def atomic_updates(_use_indexes = false)
process_flagged_destroys
mods = Modifiers.new
generate_atomic_updates(mods, self)
_children.each do |child|
child.process_flagged_destroys
generate_atomic_updates(mods, child)
end
mods
end | [
"def",
"atomic_updates",
"(",
"_use_indexes",
"=",
"false",
")",
"process_flagged_destroys",
"mods",
"=",
"Modifiers",
".",
"new",
"generate_atomic_updates",
"(",
"mods",
",",
"self",
")",
"_children",
".",
"each",
"do",
"|",
"child",
"|",
"child",
".",
"process_flagged_destroys",
"generate_atomic_updates",
"(",
"mods",
",",
"child",
")",
"end",
"mods",
"end"
] | Get all the atomic updates that need to happen for the current
+Document+. This includes all changes that need to happen in the
entire hierarchy that exists below where the save call was made.
@note MongoDB does not allow "conflicting modifications" to be
performed in a single operation. Conflicting modifications are
detected by the 'haveConflictingMod' function in MongoDB.
Examination of the code suggests that two modifications (a $set
and a $push with $each, for example) conflict if:
(1) the key paths being modified are equal.
(2) one key path is a prefix of the other.
So a $set of 'addresses.0.street' will conflict with a $push and $each
to 'addresses', and we will need to split our update into two
pieces. We do not, however, attempt to match MongoDB's logic
exactly. Instead, we assume that two updates conflict if the
first component of the two key paths matches.
@example Get the updates that need to occur.
person.atomic_updates(children)
@return [ Hash ] The updates and their modifiers.
@since 2.1.0 | [
"Get",
"all",
"the",
"atomic",
"updates",
"that",
"need",
"to",
"happen",
"for",
"the",
"current",
"+",
"Document",
"+",
".",
"This",
"includes",
"all",
"changes",
"that",
"need",
"to",
"happen",
"in",
"the",
"entire",
"hierarchy",
"that",
"exists",
"below",
"where",
"the",
"save",
"call",
"was",
"made",
"."
] | 56976e32610f4c2450882b0bfe14da099f0703f4 | https://github.com/mongodb/mongoid/blob/56976e32610f4c2450882b0bfe14da099f0703f4/lib/mongoid/atomic.rb#L129-L138 | train |
mongodb/mongoid | lib/mongoid/atomic.rb | Mongoid.Atomic.atomic_pulls | def atomic_pulls
pulls = {}
delayed_atomic_pulls.each_pair do |_, docs|
path = nil
ids = docs.map do |doc|
path ||= doc.flag_as_destroyed
doc._id
end
pulls[path] = { "_id" => { "$in" => ids }} and path = nil
end
pulls
end | ruby | def atomic_pulls
pulls = {}
delayed_atomic_pulls.each_pair do |_, docs|
path = nil
ids = docs.map do |doc|
path ||= doc.flag_as_destroyed
doc._id
end
pulls[path] = { "_id" => { "$in" => ids }} and path = nil
end
pulls
end | [
"def",
"atomic_pulls",
"pulls",
"=",
"{",
"}",
"delayed_atomic_pulls",
".",
"each_pair",
"do",
"|",
"_",
",",
"docs",
"|",
"path",
"=",
"nil",
"ids",
"=",
"docs",
".",
"map",
"do",
"|",
"doc",
"|",
"path",
"||=",
"doc",
".",
"flag_as_destroyed",
"doc",
".",
"_id",
"end",
"pulls",
"[",
"path",
"]",
"=",
"{",
"\"_id\"",
"=>",
"{",
"\"$in\"",
"=>",
"ids",
"}",
"}",
"and",
"path",
"=",
"nil",
"end",
"pulls",
"end"
] | Get all the attributes that need to be pulled.
@example Get the pulls.
person.atomic_pulls
@return [ Array<Hash> ] The $pullAll operations.
@since 2.2.0 | [
"Get",
"all",
"the",
"attributes",
"that",
"need",
"to",
"be",
"pulled",
"."
] | 56976e32610f4c2450882b0bfe14da099f0703f4 | https://github.com/mongodb/mongoid/blob/56976e32610f4c2450882b0bfe14da099f0703f4/lib/mongoid/atomic.rb#L204-L215 | train |
mongodb/mongoid | lib/mongoid/atomic.rb | Mongoid.Atomic.atomic_unsets | def atomic_unsets
unsets = []
delayed_atomic_unsets.each_pair do |name, docs|
path = nil
docs.each do |doc|
path ||= doc.flag_as_destroyed
end
unsets.push(path || name)
end
unsets
end | ruby | def atomic_unsets
unsets = []
delayed_atomic_unsets.each_pair do |name, docs|
path = nil
docs.each do |doc|
path ||= doc.flag_as_destroyed
end
unsets.push(path || name)
end
unsets
end | [
"def",
"atomic_unsets",
"unsets",
"=",
"[",
"]",
"delayed_atomic_unsets",
".",
"each_pair",
"do",
"|",
"name",
",",
"docs",
"|",
"path",
"=",
"nil",
"docs",
".",
"each",
"do",
"|",
"doc",
"|",
"path",
"||=",
"doc",
".",
"flag_as_destroyed",
"end",
"unsets",
".",
"push",
"(",
"path",
"||",
"name",
")",
"end",
"unsets",
"end"
] | Get all the attributes that need to be unset.
@example Get the unsets.
person.atomic_unsets
@return [ Array<Hash> ] The $unset operations.
@since 2.2.0 | [
"Get",
"all",
"the",
"attributes",
"that",
"need",
"to",
"be",
"unset",
"."
] | 56976e32610f4c2450882b0bfe14da099f0703f4 | https://github.com/mongodb/mongoid/blob/56976e32610f4c2450882b0bfe14da099f0703f4/lib/mongoid/atomic.rb#L249-L259 | train |
mongodb/mongoid | lib/mongoid/atomic.rb | Mongoid.Atomic.generate_atomic_updates | def generate_atomic_updates(mods, doc)
mods.unset(doc.atomic_unsets)
mods.pull(doc.atomic_pulls)
mods.set(doc.atomic_sets)
mods.set(doc.delayed_atomic_sets)
mods.push(doc.atomic_pushes)
mods.push(doc.atomic_array_pushes)
mods.add_to_set(doc.atomic_array_add_to_sets)
mods.pull_all(doc.atomic_array_pulls)
end | ruby | def generate_atomic_updates(mods, doc)
mods.unset(doc.atomic_unsets)
mods.pull(doc.atomic_pulls)
mods.set(doc.atomic_sets)
mods.set(doc.delayed_atomic_sets)
mods.push(doc.atomic_pushes)
mods.push(doc.atomic_array_pushes)
mods.add_to_set(doc.atomic_array_add_to_sets)
mods.pull_all(doc.atomic_array_pulls)
end | [
"def",
"generate_atomic_updates",
"(",
"mods",
",",
"doc",
")",
"mods",
".",
"unset",
"(",
"doc",
".",
"atomic_unsets",
")",
"mods",
".",
"pull",
"(",
"doc",
".",
"atomic_pulls",
")",
"mods",
".",
"set",
"(",
"doc",
".",
"atomic_sets",
")",
"mods",
".",
"set",
"(",
"doc",
".",
"delayed_atomic_sets",
")",
"mods",
".",
"push",
"(",
"doc",
".",
"atomic_pushes",
")",
"mods",
".",
"push",
"(",
"doc",
".",
"atomic_array_pushes",
")",
"mods",
".",
"add_to_set",
"(",
"doc",
".",
"atomic_array_add_to_sets",
")",
"mods",
".",
"pull_all",
"(",
"doc",
".",
"atomic_array_pulls",
")",
"end"
] | Generates the atomic updates in the correct order.
@example Generate the updates.
model.generate_atomic_updates(mods, doc)
@param [ Modifiers ] mods The atomic modifications.
@param [ Document ] doc The document to update for.
@since 2.2.0 | [
"Generates",
"the",
"atomic",
"updates",
"in",
"the",
"correct",
"order",
"."
] | 56976e32610f4c2450882b0bfe14da099f0703f4 | https://github.com/mongodb/mongoid/blob/56976e32610f4c2450882b0bfe14da099f0703f4/lib/mongoid/atomic.rb#L349-L358 | train |
mongodb/mongoid | lib/mongoid/persistence_context.rb | Mongoid.PersistenceContext.collection | def collection(parent = nil)
parent ? parent.collection.with(client_options) : client[collection_name.to_sym]
end | ruby | def collection(parent = nil)
parent ? parent.collection.with(client_options) : client[collection_name.to_sym]
end | [
"def",
"collection",
"(",
"parent",
"=",
"nil",
")",
"parent",
"?",
"parent",
".",
"collection",
".",
"with",
"(",
"client_options",
")",
":",
"client",
"[",
"collection_name",
".",
"to_sym",
"]",
"end"
] | Initialize the persistence context object.
@example Create a new persistence context.
PersistenceContext.new(model, collection: 'other')
@param [ Object ] object The class or model instance for which a persistence context
should be created.
@param [ Hash ] opts The persistence context options.
@since 6.0.0
Get the collection for this persistence context.
@example Get the collection for this persistence context.
context.collection
@param [ Object ] parent The parent object whose collection name is used
instead of this persistence context's collection name.
@return [ Mongo::Collection ] The collection for this persistence
context.
@since 6.0.0 | [
"Initialize",
"the",
"persistence",
"context",
"object",
"."
] | 56976e32610f4c2450882b0bfe14da099f0703f4 | https://github.com/mongodb/mongoid/blob/56976e32610f4c2450882b0bfe14da099f0703f4/lib/mongoid/persistence_context.rb#L71-L73 | train |
mongodb/mongoid | lib/mongoid/persistence_context.rb | Mongoid.PersistenceContext.client | def client
@client ||= (client = Clients.with_name(client_name)
client = client.use(database_name) if database_name_option
client.with(client_options))
end | ruby | def client
@client ||= (client = Clients.with_name(client_name)
client = client.use(database_name) if database_name_option
client.with(client_options))
end | [
"def",
"client",
"@client",
"||=",
"(",
"client",
"=",
"Clients",
".",
"with_name",
"(",
"client_name",
")",
"client",
"=",
"client",
".",
"use",
"(",
"database_name",
")",
"if",
"database_name_option",
"client",
".",
"with",
"(",
"client_options",
")",
")",
"end"
] | Get the client for this persistence context.
@example Get the client for this persistence context.
context.client
@return [ Mongo::Client ] The client for this persistence
context.
@since 6.0.0 | [
"Get",
"the",
"client",
"for",
"this",
"persistence",
"context",
"."
] | 56976e32610f4c2450882b0bfe14da099f0703f4 | https://github.com/mongodb/mongoid/blob/56976e32610f4c2450882b0bfe14da099f0703f4/lib/mongoid/persistence_context.rb#L111-L115 | train |
mongodb/mongoid | lib/mongoid/changeable.rb | Mongoid.Changeable.changes | def changes
_changes = {}
changed.each do |attr|
change = attribute_change(attr)
_changes[attr] = change if change
end
_changes.with_indifferent_access
end | ruby | def changes
_changes = {}
changed.each do |attr|
change = attribute_change(attr)
_changes[attr] = change if change
end
_changes.with_indifferent_access
end | [
"def",
"changes",
"_changes",
"=",
"{",
"}",
"changed",
".",
"each",
"do",
"|",
"attr",
"|",
"change",
"=",
"attribute_change",
"(",
"attr",
")",
"_changes",
"[",
"attr",
"]",
"=",
"change",
"if",
"change",
"end",
"_changes",
".",
"with_indifferent_access",
"end"
] | Get all the changes for the document.
@example Get all the changes.
model.changes
@return [ Hash<String, Array<Object, Object> ] The changes.
@since 2.4.0 | [
"Get",
"all",
"the",
"changes",
"for",
"the",
"document",
"."
] | 56976e32610f4c2450882b0bfe14da099f0703f4 | https://github.com/mongodb/mongoid/blob/56976e32610f4c2450882b0bfe14da099f0703f4/lib/mongoid/changeable.rb#L67-L74 | train |
mongodb/mongoid | lib/mongoid/changeable.rb | Mongoid.Changeable.move_changes | def move_changes
@previous_changes = changes
Atomic::UPDATES.each do |update|
send(update).clear
end
changed_attributes.clear
end | ruby | def move_changes
@previous_changes = changes
Atomic::UPDATES.each do |update|
send(update).clear
end
changed_attributes.clear
end | [
"def",
"move_changes",
"@previous_changes",
"=",
"changes",
"Atomic",
"::",
"UPDATES",
".",
"each",
"do",
"|",
"update",
"|",
"send",
"(",
"update",
")",
".",
"clear",
"end",
"changed_attributes",
".",
"clear",
"end"
] | Call this method after save, so the changes can be properly switched.
This will unset the memoized children array, set new record to
false, set the document as validated, and move the dirty changes.
@example Move the changes to previous.
person.move_changes
@since 2.1.0 | [
"Call",
"this",
"method",
"after",
"save",
"so",
"the",
"changes",
"can",
"be",
"properly",
"switched",
"."
] | 56976e32610f4c2450882b0bfe14da099f0703f4 | https://github.com/mongodb/mongoid/blob/56976e32610f4c2450882b0bfe14da099f0703f4/lib/mongoid/changeable.rb#L85-L91 | train |
mongodb/mongoid | lib/mongoid/changeable.rb | Mongoid.Changeable.attribute_change | def attribute_change(attr)
attr = database_field_name(attr)
[changed_attributes[attr], attributes[attr]] if attribute_changed?(attr)
end | ruby | def attribute_change(attr)
attr = database_field_name(attr)
[changed_attributes[attr], attributes[attr]] if attribute_changed?(attr)
end | [
"def",
"attribute_change",
"(",
"attr",
")",
"attr",
"=",
"database_field_name",
"(",
"attr",
")",
"[",
"changed_attributes",
"[",
"attr",
"]",
",",
"attributes",
"[",
"attr",
"]",
"]",
"if",
"attribute_changed?",
"(",
"attr",
")",
"end"
] | Get the old and new value for the provided attribute.
@example Get the attribute change.
model.attribute_change("name")
@param [ String ] attr The name of the attribute.
@return [ Array<Object> ] The old and new values.
@since 2.1.0 | [
"Get",
"the",
"old",
"and",
"new",
"value",
"for",
"the",
"provided",
"attribute",
"."
] | 56976e32610f4c2450882b0bfe14da099f0703f4 | https://github.com/mongodb/mongoid/blob/56976e32610f4c2450882b0bfe14da099f0703f4/lib/mongoid/changeable.rb#L169-L172 | train |
mongodb/mongoid | lib/mongoid/changeable.rb | Mongoid.Changeable.attribute_changed? | def attribute_changed?(attr)
attr = database_field_name(attr)
return false unless changed_attributes.key?(attr)
changed_attributes[attr] != attributes[attr]
end | ruby | def attribute_changed?(attr)
attr = database_field_name(attr)
return false unless changed_attributes.key?(attr)
changed_attributes[attr] != attributes[attr]
end | [
"def",
"attribute_changed?",
"(",
"attr",
")",
"attr",
"=",
"database_field_name",
"(",
"attr",
")",
"return",
"false",
"unless",
"changed_attributes",
".",
"key?",
"(",
"attr",
")",
"changed_attributes",
"[",
"attr",
"]",
"!=",
"attributes",
"[",
"attr",
"]",
"end"
] | Determine if a specific attribute has changed.
@example Has the attribute changed?
model.attribute_changed?("name")
@param [ String ] attr The name of the attribute.
@return [ true, false ] Whether the attribute has changed.
@since 2.1.6 | [
"Determine",
"if",
"a",
"specific",
"attribute",
"has",
"changed",
"."
] | 56976e32610f4c2450882b0bfe14da099f0703f4 | https://github.com/mongodb/mongoid/blob/56976e32610f4c2450882b0bfe14da099f0703f4/lib/mongoid/changeable.rb#L184-L188 | train |
mongodb/mongoid | lib/mongoid/changeable.rb | Mongoid.Changeable.attribute_changed_from_default? | def attribute_changed_from_default?(attr)
field = fields[attr]
return false unless field
attributes[attr] != field.eval_default(self)
end | ruby | def attribute_changed_from_default?(attr)
field = fields[attr]
return false unless field
attributes[attr] != field.eval_default(self)
end | [
"def",
"attribute_changed_from_default?",
"(",
"attr",
")",
"field",
"=",
"fields",
"[",
"attr",
"]",
"return",
"false",
"unless",
"field",
"attributes",
"[",
"attr",
"]",
"!=",
"field",
".",
"eval_default",
"(",
"self",
")",
"end"
] | Get whether or not the field has a different value from the default.
@example Is the field different from the default?
model.attribute_changed_from_default?
@param [ String ] attr The name of the attribute.
@return [ true, false ] If the attribute differs.
@since 3.0.0 | [
"Get",
"whether",
"or",
"not",
"the",
"field",
"has",
"a",
"different",
"value",
"from",
"the",
"default",
"."
] | 56976e32610f4c2450882b0bfe14da099f0703f4 | https://github.com/mongodb/mongoid/blob/56976e32610f4c2450882b0bfe14da099f0703f4/lib/mongoid/changeable.rb#L200-L204 | train |
mongodb/mongoid | lib/mongoid/changeable.rb | Mongoid.Changeable.attribute_was | def attribute_was(attr)
attr = database_field_name(attr)
attribute_changed?(attr) ? changed_attributes[attr] : attributes[attr]
end | ruby | def attribute_was(attr)
attr = database_field_name(attr)
attribute_changed?(attr) ? changed_attributes[attr] : attributes[attr]
end | [
"def",
"attribute_was",
"(",
"attr",
")",
"attr",
"=",
"database_field_name",
"(",
"attr",
")",
"attribute_changed?",
"(",
"attr",
")",
"?",
"changed_attributes",
"[",
"attr",
"]",
":",
"attributes",
"[",
"attr",
"]",
"end"
] | Get the previous value for the attribute.
@example Get the previous value.
model.attribute_was("name")
@param [ String ] attr The attribute name.
@since 2.4.0 | [
"Get",
"the",
"previous",
"value",
"for",
"the",
"attribute",
"."
] | 56976e32610f4c2450882b0bfe14da099f0703f4 | https://github.com/mongodb/mongoid/blob/56976e32610f4c2450882b0bfe14da099f0703f4/lib/mongoid/changeable.rb#L214-L217 | train |
mongodb/mongoid | lib/mongoid/changeable.rb | Mongoid.Changeable.attribute_will_change! | def attribute_will_change!(attr)
unless changed_attributes.key?(attr)
changed_attributes[attr] = read_raw_attribute(attr).__deep_copy__
end
end | ruby | def attribute_will_change!(attr)
unless changed_attributes.key?(attr)
changed_attributes[attr] = read_raw_attribute(attr).__deep_copy__
end
end | [
"def",
"attribute_will_change!",
"(",
"attr",
")",
"unless",
"changed_attributes",
".",
"key?",
"(",
"attr",
")",
"changed_attributes",
"[",
"attr",
"]",
"=",
"read_raw_attribute",
"(",
"attr",
")",
".",
"__deep_copy__",
"end",
"end"
] | Flag an attribute as going to change.
@example Flag the attribute.
model.attribute_will_change!("name")
@param [ String ] attr The name of the attribute.
@return [ Object ] The old value.
@since 2.3.0 | [
"Flag",
"an",
"attribute",
"as",
"going",
"to",
"change",
"."
] | 56976e32610f4c2450882b0bfe14da099f0703f4 | https://github.com/mongodb/mongoid/blob/56976e32610f4c2450882b0bfe14da099f0703f4/lib/mongoid/changeable.rb#L229-L233 | train |
mongodb/mongoid | lib/mongoid/changeable.rb | Mongoid.Changeable.reset_attribute! | def reset_attribute!(attr)
attr = database_field_name(attr)
attributes[attr] = changed_attributes.delete(attr) if attribute_changed?(attr)
end | ruby | def reset_attribute!(attr)
attr = database_field_name(attr)
attributes[attr] = changed_attributes.delete(attr) if attribute_changed?(attr)
end | [
"def",
"reset_attribute!",
"(",
"attr",
")",
"attr",
"=",
"database_field_name",
"(",
"attr",
")",
"attributes",
"[",
"attr",
"]",
"=",
"changed_attributes",
".",
"delete",
"(",
"attr",
")",
"if",
"attribute_changed?",
"(",
"attr",
")",
"end"
] | Set the attribute back to its old value.
@example Reset the attribute.
model.reset_attribute!("name")
@param [ String ] attr The name of the attribute.
@return [ Object ] The old value.
@since 2.4.0 | [
"Set",
"the",
"attribute",
"back",
"to",
"its",
"old",
"value",
"."
] | 56976e32610f4c2450882b0bfe14da099f0703f4 | https://github.com/mongodb/mongoid/blob/56976e32610f4c2450882b0bfe14da099f0703f4/lib/mongoid/changeable.rb#L245-L248 | train |
Subsets and Splits