id
int32 0
24.9k
| repo
stringlengths 5
58
| path
stringlengths 9
168
| func_name
stringlengths 9
130
| original_string
stringlengths 66
10.5k
| language
stringclasses 1
value | code
stringlengths 66
10.5k
| code_tokens
list | docstring
stringlengths 8
16k
| docstring_tokens
list | sha
stringlengths 40
40
| url
stringlengths 94
266
|
|---|---|---|---|---|---|---|---|---|---|---|---|
11,200
|
backup/backup
|
lib/backup/model.rb
|
Backup.Model.database
|
def database(name, database_id = nil, &block)
@databases << get_class_from_scope(Database, name)
.new(self, database_id, &block)
end
|
ruby
|
def database(name, database_id = nil, &block)
@databases << get_class_from_scope(Database, name)
.new(self, database_id, &block)
end
|
[
"def",
"database",
"(",
"name",
",",
"database_id",
"=",
"nil",
",",
"&",
"block",
")",
"@databases",
"<<",
"get_class_from_scope",
"(",
"Database",
",",
"name",
")",
".",
"new",
"(",
"self",
",",
"database_id",
",",
"block",
")",
"end"
] |
Adds an Database. Multiple Databases may be added to the model.
|
[
"Adds",
"an",
"Database",
".",
"Multiple",
"Databases",
"may",
"be",
"added",
"to",
"the",
"model",
"."
] |
64370f925e859f858766b674717a3dbee0de7a26
|
https://github.com/backup/backup/blob/64370f925e859f858766b674717a3dbee0de7a26/lib/backup/model.rb#L142-L145
|
11,201
|
backup/backup
|
lib/backup/model.rb
|
Backup.Model.store_with
|
def store_with(name, storage_id = nil, &block)
@storages << get_class_from_scope(Storage, name)
.new(self, storage_id, &block)
end
|
ruby
|
def store_with(name, storage_id = nil, &block)
@storages << get_class_from_scope(Storage, name)
.new(self, storage_id, &block)
end
|
[
"def",
"store_with",
"(",
"name",
",",
"storage_id",
"=",
"nil",
",",
"&",
"block",
")",
"@storages",
"<<",
"get_class_from_scope",
"(",
"Storage",
",",
"name",
")",
".",
"new",
"(",
"self",
",",
"storage_id",
",",
"block",
")",
"end"
] |
Adds an Storage. Multiple Storages may be added to the model.
|
[
"Adds",
"an",
"Storage",
".",
"Multiple",
"Storages",
"may",
"be",
"added",
"to",
"the",
"model",
"."
] |
64370f925e859f858766b674717a3dbee0de7a26
|
https://github.com/backup/backup/blob/64370f925e859f858766b674717a3dbee0de7a26/lib/backup/model.rb#L149-L152
|
11,202
|
backup/backup
|
lib/backup/model.rb
|
Backup.Model.sync_with
|
def sync_with(name, syncer_id = nil, &block)
@syncers << get_class_from_scope(Syncer, name).new(syncer_id, &block)
end
|
ruby
|
def sync_with(name, syncer_id = nil, &block)
@syncers << get_class_from_scope(Syncer, name).new(syncer_id, &block)
end
|
[
"def",
"sync_with",
"(",
"name",
",",
"syncer_id",
"=",
"nil",
",",
"&",
"block",
")",
"@syncers",
"<<",
"get_class_from_scope",
"(",
"Syncer",
",",
"name",
")",
".",
"new",
"(",
"syncer_id",
",",
"block",
")",
"end"
] |
Adds an Syncer. Multiple Syncers may be added to the model.
|
[
"Adds",
"an",
"Syncer",
".",
"Multiple",
"Syncers",
"may",
"be",
"added",
"to",
"the",
"model",
"."
] |
64370f925e859f858766b674717a3dbee0de7a26
|
https://github.com/backup/backup/blob/64370f925e859f858766b674717a3dbee0de7a26/lib/backup/model.rb#L156-L158
|
11,203
|
backup/backup
|
lib/backup/model.rb
|
Backup.Model.split_into_chunks_of
|
def split_into_chunks_of(chunk_size, suffix_length = 3)
if chunk_size.is_a?(Integer) && suffix_length.is_a?(Integer)
@splitter = Splitter.new(self, chunk_size, suffix_length)
else
raise Error, <<-EOS
Invalid arguments for #split_into_chunks_of()
+chunk_size+ (and optional +suffix_length+) must be Integers.
EOS
end
end
|
ruby
|
def split_into_chunks_of(chunk_size, suffix_length = 3)
if chunk_size.is_a?(Integer) && suffix_length.is_a?(Integer)
@splitter = Splitter.new(self, chunk_size, suffix_length)
else
raise Error, <<-EOS
Invalid arguments for #split_into_chunks_of()
+chunk_size+ (and optional +suffix_length+) must be Integers.
EOS
end
end
|
[
"def",
"split_into_chunks_of",
"(",
"chunk_size",
",",
"suffix_length",
"=",
"3",
")",
"if",
"chunk_size",
".",
"is_a?",
"(",
"Integer",
")",
"&&",
"suffix_length",
".",
"is_a?",
"(",
"Integer",
")",
"@splitter",
"=",
"Splitter",
".",
"new",
"(",
"self",
",",
"chunk_size",
",",
"suffix_length",
")",
"else",
"raise",
"Error",
",",
"<<-EOS",
"EOS",
"end",
"end"
] |
Adds a Splitter to split the final backup package into multiple files.
+chunk_size+ is specified in MiB and must be given as an Integer.
+suffix_length+ controls the number of characters used in the suffix
(and the maximum number of chunks possible).
ie. 1 (-a, -b), 2 (-aa, -ab), 3 (-aaa, -aab)
|
[
"Adds",
"a",
"Splitter",
"to",
"split",
"the",
"final",
"backup",
"package",
"into",
"multiple",
"files",
"."
] |
64370f925e859f858766b674717a3dbee0de7a26
|
https://github.com/backup/backup/blob/64370f925e859f858766b674717a3dbee0de7a26/lib/backup/model.rb#L188-L197
|
11,204
|
backup/backup
|
lib/backup/model.rb
|
Backup.Model.perform!
|
def perform!
@started_at = Time.now.utc
@time = package.time = started_at.strftime("%Y.%m.%d.%H.%M.%S")
log!(:started)
before_hook
procedures.each do |procedure|
procedure.is_a?(Proc) ? procedure.call : procedure.each(&:perform!)
end
syncers.each(&:perform!)
rescue Interrupt
@interrupted = true
raise
rescue Exception => err
@exception = err
ensure
unless @interrupted
set_exit_status
@finished_at = Time.now.utc
log!(:finished)
after_hook
end
end
|
ruby
|
def perform!
@started_at = Time.now.utc
@time = package.time = started_at.strftime("%Y.%m.%d.%H.%M.%S")
log!(:started)
before_hook
procedures.each do |procedure|
procedure.is_a?(Proc) ? procedure.call : procedure.each(&:perform!)
end
syncers.each(&:perform!)
rescue Interrupt
@interrupted = true
raise
rescue Exception => err
@exception = err
ensure
unless @interrupted
set_exit_status
@finished_at = Time.now.utc
log!(:finished)
after_hook
end
end
|
[
"def",
"perform!",
"@started_at",
"=",
"Time",
".",
"now",
".",
"utc",
"@time",
"=",
"package",
".",
"time",
"=",
"started_at",
".",
"strftime",
"(",
"\"%Y.%m.%d.%H.%M.%S\"",
")",
"log!",
"(",
":started",
")",
"before_hook",
"procedures",
".",
"each",
"do",
"|",
"procedure",
"|",
"procedure",
".",
"is_a?",
"(",
"Proc",
")",
"?",
"procedure",
".",
"call",
":",
"procedure",
".",
"each",
"(",
":perform!",
")",
"end",
"syncers",
".",
"each",
"(",
":perform!",
")",
"rescue",
"Interrupt",
"@interrupted",
"=",
"true",
"raise",
"rescue",
"Exception",
"=>",
"err",
"@exception",
"=",
"err",
"ensure",
"unless",
"@interrupted",
"set_exit_status",
"@finished_at",
"=",
"Time",
".",
"now",
".",
"utc",
"log!",
"(",
":finished",
")",
"after_hook",
"end",
"end"
] |
Performs the backup process
Once complete, #exit_status will indicate the result of this process.
If any errors occur during the backup process, all temporary files will
be left in place. If the error occurs before Packaging, then the
temporary folder (tmp_path/trigger) will remain and may contain all or
some of the configured Archives and/or Database dumps. If the error
occurs after Packaging, but before the Storages complete, then the final
packaged files (located in the root of tmp_path) will remain.
*** Important ***
If an error occurs and any of the above mentioned temporary files remain,
those files *** will be removed *** before the next scheduled backup for
the same trigger.
|
[
"Performs",
"the",
"backup",
"process"
] |
64370f925e859f858766b674717a3dbee0de7a26
|
https://github.com/backup/backup/blob/64370f925e859f858766b674717a3dbee0de7a26/lib/backup/model.rb#L259-L283
|
11,205
|
backup/backup
|
lib/backup/model.rb
|
Backup.Model.procedures
|
def procedures
return [] unless databases.any? || archives.any?
[-> { prepare! }, databases, archives,
-> { package! }, -> { store! }, -> { clean! }]
end
|
ruby
|
def procedures
return [] unless databases.any? || archives.any?
[-> { prepare! }, databases, archives,
-> { package! }, -> { store! }, -> { clean! }]
end
|
[
"def",
"procedures",
"return",
"[",
"]",
"unless",
"databases",
".",
"any?",
"||",
"archives",
".",
"any?",
"[",
"->",
"{",
"prepare!",
"}",
",",
"databases",
",",
"archives",
",",
"->",
"{",
"package!",
"}",
",",
"->",
"{",
"store!",
"}",
",",
"->",
"{",
"clean!",
"}",
"]",
"end"
] |
Returns an array of procedures that will be performed if any
Archives or Databases are configured for the model.
|
[
"Returns",
"an",
"array",
"of",
"procedures",
"that",
"will",
"be",
"performed",
"if",
"any",
"Archives",
"or",
"Databases",
"are",
"configured",
"for",
"the",
"model",
"."
] |
64370f925e859f858766b674717a3dbee0de7a26
|
https://github.com/backup/backup/blob/64370f925e859f858766b674717a3dbee0de7a26/lib/backup/model.rb#L297-L302
|
11,206
|
backup/backup
|
lib/backup/model.rb
|
Backup.Model.store!
|
def store!
storage_results = storages.map do |storage|
begin
storage.perform!
rescue => ex
ex
end
end
first_exception, *other_exceptions = storage_results.select { |result| result.is_a? Exception }
if first_exception
other_exceptions.each do |exception|
Logger.error exception.to_s
Logger.error exception.backtrace.join('\n')
end
raise first_exception
else
true
end
end
|
ruby
|
def store!
storage_results = storages.map do |storage|
begin
storage.perform!
rescue => ex
ex
end
end
first_exception, *other_exceptions = storage_results.select { |result| result.is_a? Exception }
if first_exception
other_exceptions.each do |exception|
Logger.error exception.to_s
Logger.error exception.backtrace.join('\n')
end
raise first_exception
else
true
end
end
|
[
"def",
"store!",
"storage_results",
"=",
"storages",
".",
"map",
"do",
"|",
"storage",
"|",
"begin",
"storage",
".",
"perform!",
"rescue",
"=>",
"ex",
"ex",
"end",
"end",
"first_exception",
",",
"*",
"other_exceptions",
"=",
"storage_results",
".",
"select",
"{",
"|",
"result",
"|",
"result",
".",
"is_a?",
"Exception",
"}",
"if",
"first_exception",
"other_exceptions",
".",
"each",
"do",
"|",
"exception",
"|",
"Logger",
".",
"error",
"exception",
".",
"to_s",
"Logger",
".",
"error",
"exception",
".",
"backtrace",
".",
"join",
"(",
"'\\n'",
")",
"end",
"raise",
"first_exception",
"else",
"true",
"end",
"end"
] |
Attempts to use all configured Storages, even if some of them result in exceptions.
Returns true or raises first encountered exception.
|
[
"Attempts",
"to",
"use",
"all",
"configured",
"Storages",
"even",
"if",
"some",
"of",
"them",
"result",
"in",
"exceptions",
".",
"Returns",
"true",
"or",
"raises",
"first",
"encountered",
"exception",
"."
] |
64370f925e859f858766b674717a3dbee0de7a26
|
https://github.com/backup/backup/blob/64370f925e859f858766b674717a3dbee0de7a26/lib/backup/model.rb#L326-L346
|
11,207
|
backup/backup
|
lib/backup/model.rb
|
Backup.Model.log!
|
def log!(action)
case action
when :started
Logger.info "Performing Backup for '#{label} (#{trigger})'!\n" \
"[ backup #{VERSION} : #{RUBY_DESCRIPTION} ]"
when :finished
if exit_status > 1
ex = exit_status == 2 ? Error : FatalError
err = ex.wrap(exception, "Backup for #{label} (#{trigger}) Failed!")
Logger.error err
Logger.error "\nBacktrace:\n\s\s" + err.backtrace.join("\n\s\s") + "\n\n"
Cleaner.warnings(self)
else
msg = "Backup for '#{label} (#{trigger})' "
if exit_status == 1
msg << "Completed Successfully (with Warnings) in #{duration}"
Logger.warn msg
else
msg << "Completed Successfully in #{duration}"
Logger.info msg
end
end
end
end
|
ruby
|
def log!(action)
case action
when :started
Logger.info "Performing Backup for '#{label} (#{trigger})'!\n" \
"[ backup #{VERSION} : #{RUBY_DESCRIPTION} ]"
when :finished
if exit_status > 1
ex = exit_status == 2 ? Error : FatalError
err = ex.wrap(exception, "Backup for #{label} (#{trigger}) Failed!")
Logger.error err
Logger.error "\nBacktrace:\n\s\s" + err.backtrace.join("\n\s\s") + "\n\n"
Cleaner.warnings(self)
else
msg = "Backup for '#{label} (#{trigger})' "
if exit_status == 1
msg << "Completed Successfully (with Warnings) in #{duration}"
Logger.warn msg
else
msg << "Completed Successfully in #{duration}"
Logger.info msg
end
end
end
end
|
[
"def",
"log!",
"(",
"action",
")",
"case",
"action",
"when",
":started",
"Logger",
".",
"info",
"\"Performing Backup for '#{label} (#{trigger})'!\\n\"",
"\"[ backup #{VERSION} : #{RUBY_DESCRIPTION} ]\"",
"when",
":finished",
"if",
"exit_status",
">",
"1",
"ex",
"=",
"exit_status",
"==",
"2",
"?",
"Error",
":",
"FatalError",
"err",
"=",
"ex",
".",
"wrap",
"(",
"exception",
",",
"\"Backup for #{label} (#{trigger}) Failed!\"",
")",
"Logger",
".",
"error",
"err",
"Logger",
".",
"error",
"\"\\nBacktrace:\\n\\s\\s\"",
"+",
"err",
".",
"backtrace",
".",
"join",
"(",
"\"\\n\\s\\s\"",
")",
"+",
"\"\\n\\n\"",
"Cleaner",
".",
"warnings",
"(",
"self",
")",
"else",
"msg",
"=",
"\"Backup for '#{label} (#{trigger})' \"",
"if",
"exit_status",
"==",
"1",
"msg",
"<<",
"\"Completed Successfully (with Warnings) in #{duration}\"",
"Logger",
".",
"warn",
"msg",
"else",
"msg",
"<<",
"\"Completed Successfully in #{duration}\"",
"Logger",
".",
"info",
"msg",
"end",
"end",
"end",
"end"
] |
Logs messages when the model starts and finishes.
#exception will be set here if #exit_status is > 1,
since log(:finished) is called before the +after+ hook.
|
[
"Logs",
"messages",
"when",
"the",
"model",
"starts",
"and",
"finishes",
"."
] |
64370f925e859f858766b674717a3dbee0de7a26
|
https://github.com/backup/backup/blob/64370f925e859f858766b674717a3dbee0de7a26/lib/backup/model.rb#L434-L459
|
11,208
|
backup/backup
|
lib/backup/splitter.rb
|
Backup.Splitter.after_packaging
|
def after_packaging
suffixes = chunk_suffixes
first_suffix = "a" * suffix_length
if suffixes == [first_suffix]
FileUtils.mv(
File.join(Config.tmp_path, "#{package.basename}-#{first_suffix}"),
File.join(Config.tmp_path, package.basename)
)
else
package.chunk_suffixes = suffixes
end
end
|
ruby
|
def after_packaging
suffixes = chunk_suffixes
first_suffix = "a" * suffix_length
if suffixes == [first_suffix]
FileUtils.mv(
File.join(Config.tmp_path, "#{package.basename}-#{first_suffix}"),
File.join(Config.tmp_path, package.basename)
)
else
package.chunk_suffixes = suffixes
end
end
|
[
"def",
"after_packaging",
"suffixes",
"=",
"chunk_suffixes",
"first_suffix",
"=",
"\"a\"",
"*",
"suffix_length",
"if",
"suffixes",
"==",
"[",
"first_suffix",
"]",
"FileUtils",
".",
"mv",
"(",
"File",
".",
"join",
"(",
"Config",
".",
"tmp_path",
",",
"\"#{package.basename}-#{first_suffix}\"",
")",
",",
"File",
".",
"join",
"(",
"Config",
".",
"tmp_path",
",",
"package",
".",
"basename",
")",
")",
"else",
"package",
".",
"chunk_suffixes",
"=",
"suffixes",
"end",
"end"
] |
Finds the resulting files from the packaging procedure
and stores an Array of suffixes used in @package.chunk_suffixes.
If the @chunk_size was never reached and only one file
was written, that file will be suffixed with '-aa' (or -a; -aaa; etc
depending upon suffix_length). In which case, it will simply
remove the suffix from the filename.
|
[
"Finds",
"the",
"resulting",
"files",
"from",
"the",
"packaging",
"procedure",
"and",
"stores",
"an",
"Array",
"of",
"suffixes",
"used",
"in"
] |
64370f925e859f858766b674717a3dbee0de7a26
|
https://github.com/backup/backup/blob/64370f925e859f858766b674717a3dbee0de7a26/lib/backup/splitter.rb#L46-L57
|
11,209
|
Sorcery/sorcery
|
lib/sorcery/model.rb
|
Sorcery.Model.include_required_submodules!
|
def include_required_submodules!
class_eval do
@sorcery_config.submodules = ::Sorcery::Controller::Config.submodules
@sorcery_config.submodules.each do |mod|
# TODO: Is there a cleaner way to handle missing submodules?
# rubocop:disable Lint/HandleExceptions
begin
include Submodules.const_get(mod.to_s.split('_').map(&:capitalize).join)
rescue NameError
# don't stop on a missing submodule. Needed because some submodules are only defined
# in the controller side.
end
# rubocop:enable Lint/HandleExceptions
end
end
end
|
ruby
|
def include_required_submodules!
class_eval do
@sorcery_config.submodules = ::Sorcery::Controller::Config.submodules
@sorcery_config.submodules.each do |mod|
# TODO: Is there a cleaner way to handle missing submodules?
# rubocop:disable Lint/HandleExceptions
begin
include Submodules.const_get(mod.to_s.split('_').map(&:capitalize).join)
rescue NameError
# don't stop on a missing submodule. Needed because some submodules are only defined
# in the controller side.
end
# rubocop:enable Lint/HandleExceptions
end
end
end
|
[
"def",
"include_required_submodules!",
"class_eval",
"do",
"@sorcery_config",
".",
"submodules",
"=",
"::",
"Sorcery",
"::",
"Controller",
"::",
"Config",
".",
"submodules",
"@sorcery_config",
".",
"submodules",
".",
"each",
"do",
"|",
"mod",
"|",
"# TODO: Is there a cleaner way to handle missing submodules?",
"# rubocop:disable Lint/HandleExceptions",
"begin",
"include",
"Submodules",
".",
"const_get",
"(",
"mod",
".",
"to_s",
".",
"split",
"(",
"'_'",
")",
".",
"map",
"(",
":capitalize",
")",
".",
"join",
")",
"rescue",
"NameError",
"# don't stop on a missing submodule. Needed because some submodules are only defined",
"# in the controller side.",
"end",
"# rubocop:enable Lint/HandleExceptions",
"end",
"end",
"end"
] |
includes required submodules into the model class,
which usually is called User.
|
[
"includes",
"required",
"submodules",
"into",
"the",
"model",
"class",
"which",
"usually",
"is",
"called",
"User",
"."
] |
ae4141e7059fa5c79d4135e81efb839a016d39ac
|
https://github.com/Sorcery/sorcery/blob/ae4141e7059fa5c79d4135e81efb839a016d39ac/lib/sorcery/model.rb#L46-L61
|
11,210
|
Sorcery/sorcery
|
lib/sorcery/model.rb
|
Sorcery.Model.init_orm_hooks!
|
def init_orm_hooks!
sorcery_adapter.define_callback :before, :validation, :encrypt_password, if: proc { |record|
record.send(sorcery_config.password_attribute_name).present?
}
sorcery_adapter.define_callback :after, :save, :clear_virtual_password, if: proc { |record|
record.send(sorcery_config.password_attribute_name).present?
}
attr_accessor sorcery_config.password_attribute_name
end
|
ruby
|
def init_orm_hooks!
sorcery_adapter.define_callback :before, :validation, :encrypt_password, if: proc { |record|
record.send(sorcery_config.password_attribute_name).present?
}
sorcery_adapter.define_callback :after, :save, :clear_virtual_password, if: proc { |record|
record.send(sorcery_config.password_attribute_name).present?
}
attr_accessor sorcery_config.password_attribute_name
end
|
[
"def",
"init_orm_hooks!",
"sorcery_adapter",
".",
"define_callback",
":before",
",",
":validation",
",",
":encrypt_password",
",",
"if",
":",
"proc",
"{",
"|",
"record",
"|",
"record",
".",
"send",
"(",
"sorcery_config",
".",
"password_attribute_name",
")",
".",
"present?",
"}",
"sorcery_adapter",
".",
"define_callback",
":after",
",",
":save",
",",
":clear_virtual_password",
",",
"if",
":",
"proc",
"{",
"|",
"record",
"|",
"record",
".",
"send",
"(",
"sorcery_config",
".",
"password_attribute_name",
")",
".",
"present?",
"}",
"attr_accessor",
"sorcery_config",
".",
"password_attribute_name",
"end"
] |
add virtual password accessor and ORM callbacks.
|
[
"add",
"virtual",
"password",
"accessor",
"and",
"ORM",
"callbacks",
"."
] |
ae4141e7059fa5c79d4135e81efb839a016d39ac
|
https://github.com/Sorcery/sorcery/blob/ae4141e7059fa5c79d4135e81efb839a016d39ac/lib/sorcery/model.rb#L64-L74
|
11,211
|
toptal/chewy
|
lib/chewy/query.rb
|
Chewy.Query.explain
|
def explain(value = nil)
chain { criteria.update_request_options explain: (value.nil? ? true : value) }
end
|
ruby
|
def explain(value = nil)
chain { criteria.update_request_options explain: (value.nil? ? true : value) }
end
|
[
"def",
"explain",
"(",
"value",
"=",
"nil",
")",
"chain",
"{",
"criteria",
".",
"update_request_options",
"explain",
":",
"(",
"value",
".",
"nil?",
"?",
"true",
":",
"value",
")",
"}",
"end"
] |
Comparation with other query or collection
If other is collection - search request is executed and
result is used for comparation
@example
UsersIndex.filter(term: {name: 'Johny'}) == UsersIndex.filter(term: {name: 'Johny'}) # => true
UsersIndex.filter(term: {name: 'Johny'}) == UsersIndex.filter(term: {name: 'Johny'}).to_a # => true
UsersIndex.filter(term: {name: 'Johny'}) == UsersIndex.filter(term: {name: 'Winnie'}) # => false
Adds `explain` parameter to search request.
@example
UsersIndex.filter(term: {name: 'Johny'}).explain
UsersIndex.filter(term: {name: 'Johny'}).explain(true)
UsersIndex.filter(term: {name: 'Johny'}).explain(false)
Calling explain without any arguments sets explanation flag to true.
With `explain: true`, every result object has `_explanation`
method
@example
UsersIndex::User.filter(term: {name: 'Johny'}).explain.first._explanation # => {...}
|
[
"Comparation",
"with",
"other",
"query",
"or",
"collection",
"If",
"other",
"is",
"collection",
"-",
"search",
"request",
"is",
"executed",
"and",
"result",
"is",
"used",
"for",
"comparation"
] |
cb1bb3efb1bd8a31e7e31add6072189cb1f4f01b
|
https://github.com/toptal/chewy/blob/cb1bb3efb1bd8a31e7e31add6072189cb1f4f01b/lib/chewy/query.rb#L75-L77
|
11,212
|
toptal/chewy
|
lib/chewy/query.rb
|
Chewy.Query.limit
|
def limit(value = nil, &block)
chain { criteria.update_request_options size: block || Integer(value) }
end
|
ruby
|
def limit(value = nil, &block)
chain { criteria.update_request_options size: block || Integer(value) }
end
|
[
"def",
"limit",
"(",
"value",
"=",
"nil",
",",
"&",
"block",
")",
"chain",
"{",
"criteria",
".",
"update_request_options",
"size",
":",
"block",
"||",
"Integer",
"(",
"value",
")",
"}",
"end"
] |
Sets elasticsearch `size` search request param
Default value is set in the elasticsearch and is 10.
@example
UsersIndex.filter{ name == 'Johny' }.limit(100)
# => {body: {
query: {...},
size: 100
}}
|
[
"Sets",
"elasticsearch",
"size",
"search",
"request",
"param",
"Default",
"value",
"is",
"set",
"in",
"the",
"elasticsearch",
"and",
"is",
"10",
"."
] |
cb1bb3efb1bd8a31e7e31add6072189cb1f4f01b
|
https://github.com/toptal/chewy/blob/cb1bb3efb1bd8a31e7e31add6072189cb1f4f01b/lib/chewy/query.rb#L303-L305
|
11,213
|
toptal/chewy
|
lib/chewy/query.rb
|
Chewy.Query.offset
|
def offset(value = nil, &block)
chain { criteria.update_request_options from: block || Integer(value) }
end
|
ruby
|
def offset(value = nil, &block)
chain { criteria.update_request_options from: block || Integer(value) }
end
|
[
"def",
"offset",
"(",
"value",
"=",
"nil",
",",
"&",
"block",
")",
"chain",
"{",
"criteria",
".",
"update_request_options",
"from",
":",
"block",
"||",
"Integer",
"(",
"value",
")",
"}",
"end"
] |
Sets elasticsearch `from` search request param
@example
UsersIndex.filter{ name == 'Johny' }.offset(300)
# => {body: {
query: {...},
from: 300
}}
|
[
"Sets",
"elasticsearch",
"from",
"search",
"request",
"param"
] |
cb1bb3efb1bd8a31e7e31add6072189cb1f4f01b
|
https://github.com/toptal/chewy/blob/cb1bb3efb1bd8a31e7e31add6072189cb1f4f01b/lib/chewy/query.rb#L316-L318
|
11,214
|
toptal/chewy
|
lib/chewy/query.rb
|
Chewy.Query.facets
|
def facets(params = nil)
raise RemovedFeature, 'removed in elasticsearch 2.0' if Runtime.version >= '2.0'
if params
chain { criteria.update_facets params }
else
_response['facets'] || {}
end
end
|
ruby
|
def facets(params = nil)
raise RemovedFeature, 'removed in elasticsearch 2.0' if Runtime.version >= '2.0'
if params
chain { criteria.update_facets params }
else
_response['facets'] || {}
end
end
|
[
"def",
"facets",
"(",
"params",
"=",
"nil",
")",
"raise",
"RemovedFeature",
",",
"'removed in elasticsearch 2.0'",
"if",
"Runtime",
".",
"version",
">=",
"'2.0'",
"if",
"params",
"chain",
"{",
"criteria",
".",
"update_facets",
"params",
"}",
"else",
"_response",
"[",
"'facets'",
"]",
"||",
"{",
"}",
"end",
"end"
] |
Adds facets section to the search request.
All the chained facets a merged and added to the
search request
@example
UsersIndex.facets(tags: {terms: {field: 'tags'}}).facets(ages: {terms: {field: 'age'}})
# => {body: {
query: {...},
facets: {tags: {terms: {field: 'tags'}}, ages: {terms: {field: 'age'}}}
}}
If called parameterless - returns result facets from ES performing request.
Returns empty hash if no facets was requested or resulted.
|
[
"Adds",
"facets",
"section",
"to",
"the",
"search",
"request",
".",
"All",
"the",
"chained",
"facets",
"a",
"merged",
"and",
"added",
"to",
"the",
"search",
"request"
] |
cb1bb3efb1bd8a31e7e31add6072189cb1f4f01b
|
https://github.com/toptal/chewy/blob/cb1bb3efb1bd8a31e7e31add6072189cb1f4f01b/lib/chewy/query.rb#L370-L377
|
11,215
|
toptal/chewy
|
lib/chewy/query.rb
|
Chewy.Query.script_score
|
def script_score(script, options = {})
scoring = {script_score: {script: script}.merge(options)}
chain { criteria.update_scores scoring }
end
|
ruby
|
def script_score(script, options = {})
scoring = {script_score: {script: script}.merge(options)}
chain { criteria.update_scores scoring }
end
|
[
"def",
"script_score",
"(",
"script",
",",
"options",
"=",
"{",
"}",
")",
"scoring",
"=",
"{",
"script_score",
":",
"{",
"script",
":",
"script",
"}",
".",
"merge",
"(",
"options",
")",
"}",
"chain",
"{",
"criteria",
".",
"update_scores",
"scoring",
"}",
"end"
] |
Adds a script function to score the search request. All scores are
added to the search request and combinded according to
`boost_mode` and `score_mode`
@example
UsersIndex.script_score("doc['boost'].value", params: { modifier: 2 })
# => {body:
query: {
function_score: {
query: { ...},
functions: [{
script_score: {
script: "doc['boost'].value * modifier",
params: { modifier: 2 }
}
}
}]
} } }
|
[
"Adds",
"a",
"script",
"function",
"to",
"score",
"the",
"search",
"request",
".",
"All",
"scores",
"are",
"added",
"to",
"the",
"search",
"request",
"and",
"combinded",
"according",
"to",
"boost_mode",
"and",
"score_mode"
] |
cb1bb3efb1bd8a31e7e31add6072189cb1f4f01b
|
https://github.com/toptal/chewy/blob/cb1bb3efb1bd8a31e7e31add6072189cb1f4f01b/lib/chewy/query.rb#L397-L400
|
11,216
|
toptal/chewy
|
lib/chewy/query.rb
|
Chewy.Query.boost_factor
|
def boost_factor(factor, options = {})
scoring = options.merge(boost_factor: factor.to_i)
chain { criteria.update_scores scoring }
end
|
ruby
|
def boost_factor(factor, options = {})
scoring = options.merge(boost_factor: factor.to_i)
chain { criteria.update_scores scoring }
end
|
[
"def",
"boost_factor",
"(",
"factor",
",",
"options",
"=",
"{",
"}",
")",
"scoring",
"=",
"options",
".",
"merge",
"(",
"boost_factor",
":",
"factor",
".",
"to_i",
")",
"chain",
"{",
"criteria",
".",
"update_scores",
"scoring",
"}",
"end"
] |
Adds a boost factor to the search request. All scores are
added to the search request and combinded according to
`boost_mode` and `score_mode`
This probably only makes sense if you specify a filter
for the boost factor as well
@example
UsersIndex.boost_factor(23, filter: { term: { foo: :bar} })
# => {body:
query: {
function_score: {
query: { ...},
functions: [{
boost_factor: 23,
filter: { term: { foo: :bar } }
}]
} } }
|
[
"Adds",
"a",
"boost",
"factor",
"to",
"the",
"search",
"request",
".",
"All",
"scores",
"are",
"added",
"to",
"the",
"search",
"request",
"and",
"combinded",
"according",
"to",
"boost_mode",
"and",
"score_mode"
] |
cb1bb3efb1bd8a31e7e31add6072189cb1f4f01b
|
https://github.com/toptal/chewy/blob/cb1bb3efb1bd8a31e7e31add6072189cb1f4f01b/lib/chewy/query.rb#L420-L423
|
11,217
|
toptal/chewy
|
lib/chewy/query.rb
|
Chewy.Query.random_score
|
def random_score(seed = Time.now, options = {})
scoring = options.merge(random_score: {seed: seed.to_i})
chain { criteria.update_scores scoring }
end
|
ruby
|
def random_score(seed = Time.now, options = {})
scoring = options.merge(random_score: {seed: seed.to_i})
chain { criteria.update_scores scoring }
end
|
[
"def",
"random_score",
"(",
"seed",
"=",
"Time",
".",
"now",
",",
"options",
"=",
"{",
"}",
")",
"scoring",
"=",
"options",
".",
"merge",
"(",
"random_score",
":",
"{",
"seed",
":",
"seed",
".",
"to_i",
"}",
")",
"chain",
"{",
"criteria",
".",
"update_scores",
"scoring",
"}",
"end"
] |
Adds a random score to the search request. All scores are
added to the search request and combinded according to
`boost_mode` and `score_mode`
This probably only makes sense if you specify a filter
for the random score as well.
If you do not pass in a seed value, Time.now will be used
@example
UsersIndex.random_score(23, filter: { foo: :bar})
# => {body:
query: {
function_score: {
query: { ...},
functions: [{
random_score: { seed: 23 },
filter: { foo: :bar }
}]
} } }
|
[
"Adds",
"a",
"random",
"score",
"to",
"the",
"search",
"request",
".",
"All",
"scores",
"are",
"added",
"to",
"the",
"search",
"request",
"and",
"combinded",
"according",
"to",
"boost_mode",
"and",
"score_mode"
] |
cb1bb3efb1bd8a31e7e31add6072189cb1f4f01b
|
https://github.com/toptal/chewy/blob/cb1bb3efb1bd8a31e7e31add6072189cb1f4f01b/lib/chewy/query.rb#L468-L471
|
11,218
|
toptal/chewy
|
lib/chewy/query.rb
|
Chewy.Query.field_value_factor
|
def field_value_factor(settings, options = {})
scoring = options.merge(field_value_factor: settings)
chain { criteria.update_scores scoring }
end
|
ruby
|
def field_value_factor(settings, options = {})
scoring = options.merge(field_value_factor: settings)
chain { criteria.update_scores scoring }
end
|
[
"def",
"field_value_factor",
"(",
"settings",
",",
"options",
"=",
"{",
"}",
")",
"scoring",
"=",
"options",
".",
"merge",
"(",
"field_value_factor",
":",
"settings",
")",
"chain",
"{",
"criteria",
".",
"update_scores",
"scoring",
"}",
"end"
] |
Add a field value scoring to the search. All scores are
added to the search request and combinded according to
`boost_mode` and `score_mode`
This function is only available in Elasticsearch 1.2 and
greater
@example
UsersIndex.field_value_factor(
{
field: :boost,
factor: 1.2,
modifier: :sqrt
}, filter: { foo: :bar})
# => {body:
query: {
function_score: {
query: { ...},
functions: [{
field_value_factor: {
field: :boost,
factor: 1.2,
modifier: :sqrt
},
filter: { foo: :bar }
}]
} } }
|
[
"Add",
"a",
"field",
"value",
"scoring",
"to",
"the",
"search",
".",
"All",
"scores",
"are",
"added",
"to",
"the",
"search",
"request",
"and",
"combinded",
"according",
"to",
"boost_mode",
"and",
"score_mode"
] |
cb1bb3efb1bd8a31e7e31add6072189cb1f4f01b
|
https://github.com/toptal/chewy/blob/cb1bb3efb1bd8a31e7e31add6072189cb1f4f01b/lib/chewy/query.rb#L500-L503
|
11,219
|
toptal/chewy
|
lib/chewy/query.rb
|
Chewy.Query.decay
|
def decay(function, field, options = {})
field_options = options.extract!(:origin, :scale, :offset, :decay).delete_if { |_, v| v.nil? }
scoring = options.merge(function => {
field => field_options
})
chain { criteria.update_scores scoring }
end
|
ruby
|
def decay(function, field, options = {})
field_options = options.extract!(:origin, :scale, :offset, :decay).delete_if { |_, v| v.nil? }
scoring = options.merge(function => {
field => field_options
})
chain { criteria.update_scores scoring }
end
|
[
"def",
"decay",
"(",
"function",
",",
"field",
",",
"options",
"=",
"{",
"}",
")",
"field_options",
"=",
"options",
".",
"extract!",
"(",
":origin",
",",
":scale",
",",
":offset",
",",
":decay",
")",
".",
"delete_if",
"{",
"|",
"_",
",",
"v",
"|",
"v",
".",
"nil?",
"}",
"scoring",
"=",
"options",
".",
"merge",
"(",
"function",
"=>",
"{",
"field",
"=>",
"field_options",
"}",
")",
"chain",
"{",
"criteria",
".",
"update_scores",
"scoring",
"}",
"end"
] |
Add a decay scoring to the search. All scores are
added to the search request and combinded according to
`boost_mode` and `score_mode`
The parameters have default values, but those may not
be very useful for most applications.
@example
UsersIndex.decay(
:gauss,
:field,
origin: '11, 12',
scale: '2km',
offset: '5km',
decay: 0.4,
filter: { foo: :bar})
# => {body:
query: {
gauss: {
query: { ...},
functions: [{
gauss: {
field: {
origin: '11, 12',
scale: '2km',
offset: '5km',
decay: 0.4
}
},
filter: { foo: :bar }
}]
} } }
|
[
"Add",
"a",
"decay",
"scoring",
"to",
"the",
"search",
".",
"All",
"scores",
"are",
"added",
"to",
"the",
"search",
"request",
"and",
"combinded",
"according",
"to",
"boost_mode",
"and",
"score_mode"
] |
cb1bb3efb1bd8a31e7e31add6072189cb1f4f01b
|
https://github.com/toptal/chewy/blob/cb1bb3efb1bd8a31e7e31add6072189cb1f4f01b/lib/chewy/query.rb#L537-L543
|
11,220
|
toptal/chewy
|
lib/chewy/query.rb
|
Chewy.Query.aggregations
|
def aggregations(params = nil)
@_named_aggs ||= _build_named_aggs
@_fully_qualified_named_aggs ||= _build_fqn_aggs
if params
params = {params => @_named_aggs[params]} if params.is_a?(Symbol)
params = {params => _get_fully_qualified_named_agg(params)} if params.is_a?(String) && params =~ /\A\S+#\S+\.\S+\z/
chain { criteria.update_aggregations params }
else
_response['aggregations'] || {}
end
end
|
ruby
|
def aggregations(params = nil)
@_named_aggs ||= _build_named_aggs
@_fully_qualified_named_aggs ||= _build_fqn_aggs
if params
params = {params => @_named_aggs[params]} if params.is_a?(Symbol)
params = {params => _get_fully_qualified_named_agg(params)} if params.is_a?(String) && params =~ /\A\S+#\S+\.\S+\z/
chain { criteria.update_aggregations params }
else
_response['aggregations'] || {}
end
end
|
[
"def",
"aggregations",
"(",
"params",
"=",
"nil",
")",
"@_named_aggs",
"||=",
"_build_named_aggs",
"@_fully_qualified_named_aggs",
"||=",
"_build_fqn_aggs",
"if",
"params",
"params",
"=",
"{",
"params",
"=>",
"@_named_aggs",
"[",
"params",
"]",
"}",
"if",
"params",
".",
"is_a?",
"(",
"Symbol",
")",
"params",
"=",
"{",
"params",
"=>",
"_get_fully_qualified_named_agg",
"(",
"params",
")",
"}",
"if",
"params",
".",
"is_a?",
"(",
"String",
")",
"&&",
"params",
"=~",
"/",
"\\A",
"\\S",
"\\S",
"\\.",
"\\S",
"\\z",
"/",
"chain",
"{",
"criteria",
".",
"update_aggregations",
"params",
"}",
"else",
"_response",
"[",
"'aggregations'",
"]",
"||",
"{",
"}",
"end",
"end"
] |
Sets elasticsearch `aggregations` search request param
@example
UsersIndex.filter{ name == 'Johny' }.aggregations(category_id: {terms: {field: 'category_ids'}})
# => {body: {
query: {...},
aggregations: {
terms: {
field: 'category_ids'
}
}
}}
|
[
"Sets",
"elasticsearch",
"aggregations",
"search",
"request",
"param"
] |
cb1bb3efb1bd8a31e7e31add6072189cb1f4f01b
|
https://github.com/toptal/chewy/blob/cb1bb3efb1bd8a31e7e31add6072189cb1f4f01b/lib/chewy/query.rb#L568-L578
|
11,221
|
toptal/chewy
|
lib/chewy/query.rb
|
Chewy.Query._build_named_aggs
|
def _build_named_aggs
named_aggs = {}
@_indexes.each do |index|
index.types.each do |type|
type._agg_defs.each do |agg_name, prc|
named_aggs[agg_name] = prc.call
end
end
end
named_aggs
end
|
ruby
|
def _build_named_aggs
named_aggs = {}
@_indexes.each do |index|
index.types.each do |type|
type._agg_defs.each do |agg_name, prc|
named_aggs[agg_name] = prc.call
end
end
end
named_aggs
end
|
[
"def",
"_build_named_aggs",
"named_aggs",
"=",
"{",
"}",
"@_indexes",
".",
"each",
"do",
"|",
"index",
"|",
"index",
".",
"types",
".",
"each",
"do",
"|",
"type",
"|",
"type",
".",
"_agg_defs",
".",
"each",
"do",
"|",
"agg_name",
",",
"prc",
"|",
"named_aggs",
"[",
"agg_name",
"]",
"=",
"prc",
".",
"call",
"end",
"end",
"end",
"named_aggs",
"end"
] |
In this simplest of implementations each named aggregation must be uniquely named
|
[
"In",
"this",
"simplest",
"of",
"implementations",
"each",
"named",
"aggregation",
"must",
"be",
"uniquely",
"named"
] |
cb1bb3efb1bd8a31e7e31add6072189cb1f4f01b
|
https://github.com/toptal/chewy/blob/cb1bb3efb1bd8a31e7e31add6072189cb1f4f01b/lib/chewy/query.rb#L582-L592
|
11,222
|
toptal/chewy
|
lib/chewy/query.rb
|
Chewy.Query.delete_all
|
def delete_all
if Runtime.version >= '2.0'
plugins = Chewy.client.nodes.info(plugins: true)['nodes'].values.map { |item| item['plugins'] }.flatten
raise PluginMissing, 'install delete-by-query plugin' unless plugins.find { |item| item['name'] == 'delete-by-query' }
end
request = chain { criteria.update_options simple: true }.send(:_request)
ActiveSupport::Notifications.instrument 'delete_query.chewy',
request: request, indexes: _indexes, types: _types,
index: _indexes.one? ? _indexes.first : _indexes,
type: _types.one? ? _types.first : _types do
if Runtime.version >= '2.0'
path = Elasticsearch::API::Utils.__pathify(
Elasticsearch::API::Utils.__listify(request[:index]),
Elasticsearch::API::Utils.__listify(request[:type]),
'/_query'
)
Chewy.client.perform_request(Elasticsearch::API::HTTP_DELETE, path, {}, request[:body]).body
else
Chewy.client.delete_by_query(request)
end
end
end
|
ruby
|
def delete_all
if Runtime.version >= '2.0'
plugins = Chewy.client.nodes.info(plugins: true)['nodes'].values.map { |item| item['plugins'] }.flatten
raise PluginMissing, 'install delete-by-query plugin' unless plugins.find { |item| item['name'] == 'delete-by-query' }
end
request = chain { criteria.update_options simple: true }.send(:_request)
ActiveSupport::Notifications.instrument 'delete_query.chewy',
request: request, indexes: _indexes, types: _types,
index: _indexes.one? ? _indexes.first : _indexes,
type: _types.one? ? _types.first : _types do
if Runtime.version >= '2.0'
path = Elasticsearch::API::Utils.__pathify(
Elasticsearch::API::Utils.__listify(request[:index]),
Elasticsearch::API::Utils.__listify(request[:type]),
'/_query'
)
Chewy.client.perform_request(Elasticsearch::API::HTTP_DELETE, path, {}, request[:body]).body
else
Chewy.client.delete_by_query(request)
end
end
end
|
[
"def",
"delete_all",
"if",
"Runtime",
".",
"version",
">=",
"'2.0'",
"plugins",
"=",
"Chewy",
".",
"client",
".",
"nodes",
".",
"info",
"(",
"plugins",
":",
"true",
")",
"[",
"'nodes'",
"]",
".",
"values",
".",
"map",
"{",
"|",
"item",
"|",
"item",
"[",
"'plugins'",
"]",
"}",
".",
"flatten",
"raise",
"PluginMissing",
",",
"'install delete-by-query plugin'",
"unless",
"plugins",
".",
"find",
"{",
"|",
"item",
"|",
"item",
"[",
"'name'",
"]",
"==",
"'delete-by-query'",
"}",
"end",
"request",
"=",
"chain",
"{",
"criteria",
".",
"update_options",
"simple",
":",
"true",
"}",
".",
"send",
"(",
":_request",
")",
"ActiveSupport",
"::",
"Notifications",
".",
"instrument",
"'delete_query.chewy'",
",",
"request",
":",
"request",
",",
"indexes",
":",
"_indexes",
",",
"types",
":",
"_types",
",",
"index",
":",
"_indexes",
".",
"one?",
"?",
"_indexes",
".",
"first",
":",
"_indexes",
",",
"type",
":",
"_types",
".",
"one?",
"?",
"_types",
".",
"first",
":",
"_types",
"do",
"if",
"Runtime",
".",
"version",
">=",
"'2.0'",
"path",
"=",
"Elasticsearch",
"::",
"API",
"::",
"Utils",
".",
"__pathify",
"(",
"Elasticsearch",
"::",
"API",
"::",
"Utils",
".",
"__listify",
"(",
"request",
"[",
":index",
"]",
")",
",",
"Elasticsearch",
"::",
"API",
"::",
"Utils",
".",
"__listify",
"(",
"request",
"[",
":type",
"]",
")",
",",
"'/_query'",
")",
"Chewy",
".",
"client",
".",
"perform_request",
"(",
"Elasticsearch",
"::",
"API",
"::",
"HTTP_DELETE",
",",
"path",
",",
"{",
"}",
",",
"request",
"[",
":body",
"]",
")",
".",
"body",
"else",
"Chewy",
".",
"client",
".",
"delete_by_query",
"(",
"request",
")",
"end",
"end",
"end"
] |
Deletes all documents matching a query.
@example
UsersIndex.delete_all
UsersIndex.filter{ age <= 42 }.delete_all
UsersIndex::User.delete_all
UsersIndex::User.filter{ age <= 42 }.delete_all
|
[
"Deletes",
"all",
"documents",
"matching",
"a",
"query",
"."
] |
cb1bb3efb1bd8a31e7e31add6072189cb1f4f01b
|
https://github.com/toptal/chewy/blob/cb1bb3efb1bd8a31e7e31add6072189cb1f4f01b/lib/chewy/query.rb#L980-L1003
|
11,223
|
toptal/chewy
|
lib/chewy/query.rb
|
Chewy.Query.find
|
def find(*ids)
results = chain { criteria.update_options simple: true }.filter { _id == ids.flatten }.to_a
raise Chewy::DocumentNotFound, "Could not find documents for ids #{ids.flatten}" if results.empty?
ids.one? && !ids.first.is_a?(Array) ? results.first : results
end
|
ruby
|
def find(*ids)
results = chain { criteria.update_options simple: true }.filter { _id == ids.flatten }.to_a
raise Chewy::DocumentNotFound, "Could not find documents for ids #{ids.flatten}" if results.empty?
ids.one? && !ids.first.is_a?(Array) ? results.first : results
end
|
[
"def",
"find",
"(",
"*",
"ids",
")",
"results",
"=",
"chain",
"{",
"criteria",
".",
"update_options",
"simple",
":",
"true",
"}",
".",
"filter",
"{",
"_id",
"==",
"ids",
".",
"flatten",
"}",
".",
"to_a",
"raise",
"Chewy",
"::",
"DocumentNotFound",
",",
"\"Could not find documents for ids #{ids.flatten}\"",
"if",
"results",
".",
"empty?",
"ids",
".",
"one?",
"&&",
"!",
"ids",
".",
"first",
".",
"is_a?",
"(",
"Array",
")",
"?",
"results",
".",
"first",
":",
"results",
"end"
] |
Find all documents matching a query.
@example
UsersIndex.find(42)
UsersIndex.filter{ age <= 42 }.find(42)
UsersIndex::User.find(42)
UsersIndex::User.filter{ age <= 42 }.find(42)
In all the previous examples find will return a single object.
To get a collection - pass an array of ids.
@example
UsersIndex::User.find(42, 7, 3) # array of objects with ids in [42, 7, 3]
UsersIndex::User.find([8, 13]) # array of objects with ids in [8, 13]
UsersIndex::User.find([42]) # array of the object with id == 42
|
[
"Find",
"all",
"documents",
"matching",
"a",
"query",
"."
] |
cb1bb3efb1bd8a31e7e31add6072189cb1f4f01b
|
https://github.com/toptal/chewy/blob/cb1bb3efb1bd8a31e7e31add6072189cb1f4f01b/lib/chewy/query.rb#L1021-L1026
|
11,224
|
puppetlabs/bolt
|
acceptance/lib/acceptance/bolt_command_helper.rb
|
Acceptance.BoltCommandHelper.bolt_command_on
|
def bolt_command_on(host, command, flags = {}, opts = {})
bolt_command = command.dup
flags.each { |k, v| bolt_command << " #{k} #{v}" }
case host['platform']
when /windows/
execute_powershell_script_on(host, bolt_command, opts)
when /osx/
# Ensure Bolt runs with UTF-8 under macOS. Otherwise we get issues with
# UTF-8 content in task results.
env = 'source /etc/profile ~/.bash_profile ~/.bash_login ~/.profile && env LANG=en_US.UTF-8'
on(host, env + ' ' + bolt_command)
else
on(host, bolt_command, opts)
end
end
|
ruby
|
def bolt_command_on(host, command, flags = {}, opts = {})
bolt_command = command.dup
flags.each { |k, v| bolt_command << " #{k} #{v}" }
case host['platform']
when /windows/
execute_powershell_script_on(host, bolt_command, opts)
when /osx/
# Ensure Bolt runs with UTF-8 under macOS. Otherwise we get issues with
# UTF-8 content in task results.
env = 'source /etc/profile ~/.bash_profile ~/.bash_login ~/.profile && env LANG=en_US.UTF-8'
on(host, env + ' ' + bolt_command)
else
on(host, bolt_command, opts)
end
end
|
[
"def",
"bolt_command_on",
"(",
"host",
",",
"command",
",",
"flags",
"=",
"{",
"}",
",",
"opts",
"=",
"{",
"}",
")",
"bolt_command",
"=",
"command",
".",
"dup",
"flags",
".",
"each",
"{",
"|",
"k",
",",
"v",
"|",
"bolt_command",
"<<",
"\" #{k} #{v}\"",
"}",
"case",
"host",
"[",
"'platform'",
"]",
"when",
"/",
"/",
"execute_powershell_script_on",
"(",
"host",
",",
"bolt_command",
",",
"opts",
")",
"when",
"/",
"/",
"# Ensure Bolt runs with UTF-8 under macOS. Otherwise we get issues with",
"# UTF-8 content in task results.",
"env",
"=",
"'source /etc/profile ~/.bash_profile ~/.bash_login ~/.profile && env LANG=en_US.UTF-8'",
"on",
"(",
"host",
",",
"env",
"+",
"' '",
"+",
"bolt_command",
")",
"else",
"on",
"(",
"host",
",",
"bolt_command",
",",
"opts",
")",
"end",
"end"
] |
A helper to build a bolt command used in acceptance testing
@param [Beaker::Host] host the host to execute the command on
@param [String] command the command to execute on the bolt SUT
@param [Hash] flags the command flags to append to the command
@option flags [String] '--nodes' the nodes to run on
@option flags [String] '--user' the user to run the command as
@option flags [String] '--password' the password for the user
@option flags [nil] '--no-host-key-check' specify nil to use
@option flags [nil] '--no-ssl' specify nil to use
@param [Hash] opts the options hash for this method
|
[
"A",
"helper",
"to",
"build",
"a",
"bolt",
"command",
"used",
"in",
"acceptance",
"testing"
] |
50689a33699939d262ea7c822a4b24fd8c4f8d8a
|
https://github.com/puppetlabs/bolt/blob/50689a33699939d262ea7c822a4b24fd8c4f8d8a/acceptance/lib/acceptance/bolt_command_helper.rb#L15-L30
|
11,225
|
puppetlabs/bolt
|
lib/bolt/applicator.rb
|
Bolt.Applicator.count_statements
|
def count_statements(ast)
case ast
when Puppet::Pops::Model::Program
count_statements(ast.body)
when Puppet::Pops::Model::BlockExpression
ast.statements.count
else
1
end
end
|
ruby
|
def count_statements(ast)
case ast
when Puppet::Pops::Model::Program
count_statements(ast.body)
when Puppet::Pops::Model::BlockExpression
ast.statements.count
else
1
end
end
|
[
"def",
"count_statements",
"(",
"ast",
")",
"case",
"ast",
"when",
"Puppet",
"::",
"Pops",
"::",
"Model",
"::",
"Program",
"count_statements",
"(",
"ast",
".",
"body",
")",
"when",
"Puppet",
"::",
"Pops",
"::",
"Model",
"::",
"BlockExpression",
"ast",
".",
"statements",
".",
"count",
"else",
"1",
"end",
"end"
] |
Count the number of top-level statements in the AST.
|
[
"Count",
"the",
"number",
"of",
"top",
"-",
"level",
"statements",
"in",
"the",
"AST",
"."
] |
50689a33699939d262ea7c822a4b24fd8c4f8d8a
|
https://github.com/puppetlabs/bolt/blob/50689a33699939d262ea7c822a4b24fd8c4f8d8a/lib/bolt/applicator.rb#L166-L175
|
11,226
|
puppetlabs/bolt
|
lib/bolt_server/file_cache.rb
|
BoltServer.FileCache.create_cache_dir
|
def create_cache_dir(sha)
file_dir = File.join(@cache_dir, sha)
@cache_dir_mutex.with_read_lock do
# mkdir_p doesn't error if the file exists
FileUtils.mkdir_p(file_dir, mode: 0o750)
FileUtils.touch(file_dir)
end
file_dir
end
|
ruby
|
def create_cache_dir(sha)
file_dir = File.join(@cache_dir, sha)
@cache_dir_mutex.with_read_lock do
# mkdir_p doesn't error if the file exists
FileUtils.mkdir_p(file_dir, mode: 0o750)
FileUtils.touch(file_dir)
end
file_dir
end
|
[
"def",
"create_cache_dir",
"(",
"sha",
")",
"file_dir",
"=",
"File",
".",
"join",
"(",
"@cache_dir",
",",
"sha",
")",
"@cache_dir_mutex",
".",
"with_read_lock",
"do",
"# mkdir_p doesn't error if the file exists",
"FileUtils",
".",
"mkdir_p",
"(",
"file_dir",
",",
"mode",
":",
"0o750",
")",
"FileUtils",
".",
"touch",
"(",
"file_dir",
")",
"end",
"file_dir",
"end"
] |
Create a cache dir if necessary and update it's last write time. Returns the dir.
Acquires @cache_dir_mutex to ensure we don't try to purge the directory at the same time.
Uses the directory mtime because it's simpler to ensure the directory exists and update
mtime in a single place than with a file in a directory that may not exist.
|
[
"Create",
"a",
"cache",
"dir",
"if",
"necessary",
"and",
"update",
"it",
"s",
"last",
"write",
"time",
".",
"Returns",
"the",
"dir",
".",
"Acquires"
] |
50689a33699939d262ea7c822a4b24fd8c4f8d8a
|
https://github.com/puppetlabs/bolt/blob/50689a33699939d262ea7c822a4b24fd8c4f8d8a/lib/bolt_server/file_cache.rb#L120-L128
|
11,227
|
puppetlabs/bolt
|
lib/bolt_server/file_cache.rb
|
BoltServer.FileCache.update_file
|
def update_file(file_data)
sha = file_data['sha256']
file_dir = create_cache_dir(file_data['sha256'])
file_path = File.join(file_dir, File.basename(file_data['filename']))
if check_file(file_path, sha)
@logger.debug("Using prexisting task file: #{file_path}")
return file_path
end
@logger.debug("Queueing download for: #{file_path}")
serial_execute { download_file(file_path, sha, file_data['uri']) }
end
|
ruby
|
def update_file(file_data)
sha = file_data['sha256']
file_dir = create_cache_dir(file_data['sha256'])
file_path = File.join(file_dir, File.basename(file_data['filename']))
if check_file(file_path, sha)
@logger.debug("Using prexisting task file: #{file_path}")
return file_path
end
@logger.debug("Queueing download for: #{file_path}")
serial_execute { download_file(file_path, sha, file_data['uri']) }
end
|
[
"def",
"update_file",
"(",
"file_data",
")",
"sha",
"=",
"file_data",
"[",
"'sha256'",
"]",
"file_dir",
"=",
"create_cache_dir",
"(",
"file_data",
"[",
"'sha256'",
"]",
")",
"file_path",
"=",
"File",
".",
"join",
"(",
"file_dir",
",",
"File",
".",
"basename",
"(",
"file_data",
"[",
"'filename'",
"]",
")",
")",
"if",
"check_file",
"(",
"file_path",
",",
"sha",
")",
"@logger",
".",
"debug",
"(",
"\"Using prexisting task file: #{file_path}\"",
")",
"return",
"file_path",
"end",
"@logger",
".",
"debug",
"(",
"\"Queueing download for: #{file_path}\"",
")",
"serial_execute",
"{",
"download_file",
"(",
"file_path",
",",
"sha",
",",
"file_data",
"[",
"'uri'",
"]",
")",
"}",
"end"
] |
If the file doesn't exist or is invalid redownload it
This downloads, validates and moves into place
|
[
"If",
"the",
"file",
"doesn",
"t",
"exist",
"or",
"is",
"invalid",
"redownload",
"it",
"This",
"downloads",
"validates",
"and",
"moves",
"into",
"place"
] |
50689a33699939d262ea7c822a4b24fd8c4f8d8a
|
https://github.com/puppetlabs/bolt/blob/50689a33699939d262ea7c822a4b24fd8c4f8d8a/lib/bolt_server/file_cache.rb#L155-L166
|
11,228
|
puppetlabs/bolt
|
lib/plan_executor/executor.rb
|
PlanExecutor.Executor.as_resultset
|
def as_resultset(targets)
result_array = begin
yield
rescue StandardError => e
@logger.warn(e)
# CODEREVIEW how should we fail if there's an error?
Array(Bolt::Result.from_exception(targets[0], e))
end
Bolt::ResultSet.new(result_array)
end
|
ruby
|
def as_resultset(targets)
result_array = begin
yield
rescue StandardError => e
@logger.warn(e)
# CODEREVIEW how should we fail if there's an error?
Array(Bolt::Result.from_exception(targets[0], e))
end
Bolt::ResultSet.new(result_array)
end
|
[
"def",
"as_resultset",
"(",
"targets",
")",
"result_array",
"=",
"begin",
"yield",
"rescue",
"StandardError",
"=>",
"e",
"@logger",
".",
"warn",
"(",
"e",
")",
"# CODEREVIEW how should we fail if there's an error?",
"Array",
"(",
"Bolt",
"::",
"Result",
".",
"from_exception",
"(",
"targets",
"[",
"0",
"]",
",",
"e",
")",
")",
"end",
"Bolt",
"::",
"ResultSet",
".",
"new",
"(",
"result_array",
")",
"end"
] |
This handles running the job, catching errors, and turning the result
into a result set
|
[
"This",
"handles",
"running",
"the",
"job",
"catching",
"errors",
"and",
"turning",
"the",
"result",
"into",
"a",
"result",
"set"
] |
50689a33699939d262ea7c822a4b24fd8c4f8d8a
|
https://github.com/puppetlabs/bolt/blob/50689a33699939d262ea7c822a4b24fd8c4f8d8a/lib/plan_executor/executor.rb#L29-L38
|
11,229
|
puppetlabs/bolt
|
lib/bolt/executor.rb
|
Bolt.Executor.queue_execute
|
def queue_execute(targets)
targets.group_by(&:transport).flat_map do |protocol, protocol_targets|
transport = transport(protocol)
report_transport(transport, protocol_targets.count)
transport.batches(protocol_targets).flat_map do |batch|
batch_promises = Array(batch).each_with_object({}) do |target, h|
h[target] = Concurrent::Promise.new(executor: :immediate)
end
# Pass this argument through to avoid retaining a reference to a
# local variable that will change on the next iteration of the loop.
@pool.post(batch_promises) do |result_promises|
begin
results = yield transport, batch
Array(results).each do |result|
result_promises[result.target].set(result)
end
# NotImplementedError can be thrown if the transport is not implemented improperly
rescue StandardError, NotImplementedError => e
result_promises.each do |target, promise|
# If an exception happens while running, the result won't be logged
# by the CLI. Log a warning, as this is probably a problem with the transport.
# If batch_* commands are used from the Base transport, then exceptions
# normally shouldn't reach here.
@logger.warn(e)
promise.set(Bolt::Result.from_exception(target, e))
end
ensure
# Make absolutely sure every promise gets a result to avoid a
# deadlock. Use whatever exception is causing this block to
# execute, or generate one if we somehow got here without an
# exception and some promise is still missing a result.
result_promises.each do |target, promise|
next if promise.fulfilled?
error = $ERROR_INFO || Bolt::Error.new("No result was returned for #{target.uri}",
"puppetlabs.bolt/missing-result-error")
promise.set(Bolt::Result.from_exception(target, error))
end
end
end
batch_promises.values
end
end
end
|
ruby
|
def queue_execute(targets)
targets.group_by(&:transport).flat_map do |protocol, protocol_targets|
transport = transport(protocol)
report_transport(transport, protocol_targets.count)
transport.batches(protocol_targets).flat_map do |batch|
batch_promises = Array(batch).each_with_object({}) do |target, h|
h[target] = Concurrent::Promise.new(executor: :immediate)
end
# Pass this argument through to avoid retaining a reference to a
# local variable that will change on the next iteration of the loop.
@pool.post(batch_promises) do |result_promises|
begin
results = yield transport, batch
Array(results).each do |result|
result_promises[result.target].set(result)
end
# NotImplementedError can be thrown if the transport is not implemented improperly
rescue StandardError, NotImplementedError => e
result_promises.each do |target, promise|
# If an exception happens while running, the result won't be logged
# by the CLI. Log a warning, as this is probably a problem with the transport.
# If batch_* commands are used from the Base transport, then exceptions
# normally shouldn't reach here.
@logger.warn(e)
promise.set(Bolt::Result.from_exception(target, e))
end
ensure
# Make absolutely sure every promise gets a result to avoid a
# deadlock. Use whatever exception is causing this block to
# execute, or generate one if we somehow got here without an
# exception and some promise is still missing a result.
result_promises.each do |target, promise|
next if promise.fulfilled?
error = $ERROR_INFO || Bolt::Error.new("No result was returned for #{target.uri}",
"puppetlabs.bolt/missing-result-error")
promise.set(Bolt::Result.from_exception(target, error))
end
end
end
batch_promises.values
end
end
end
|
[
"def",
"queue_execute",
"(",
"targets",
")",
"targets",
".",
"group_by",
"(",
":transport",
")",
".",
"flat_map",
"do",
"|",
"protocol",
",",
"protocol_targets",
"|",
"transport",
"=",
"transport",
"(",
"protocol",
")",
"report_transport",
"(",
"transport",
",",
"protocol_targets",
".",
"count",
")",
"transport",
".",
"batches",
"(",
"protocol_targets",
")",
".",
"flat_map",
"do",
"|",
"batch",
"|",
"batch_promises",
"=",
"Array",
"(",
"batch",
")",
".",
"each_with_object",
"(",
"{",
"}",
")",
"do",
"|",
"target",
",",
"h",
"|",
"h",
"[",
"target",
"]",
"=",
"Concurrent",
"::",
"Promise",
".",
"new",
"(",
"executor",
":",
":immediate",
")",
"end",
"# Pass this argument through to avoid retaining a reference to a",
"# local variable that will change on the next iteration of the loop.",
"@pool",
".",
"post",
"(",
"batch_promises",
")",
"do",
"|",
"result_promises",
"|",
"begin",
"results",
"=",
"yield",
"transport",
",",
"batch",
"Array",
"(",
"results",
")",
".",
"each",
"do",
"|",
"result",
"|",
"result_promises",
"[",
"result",
".",
"target",
"]",
".",
"set",
"(",
"result",
")",
"end",
"# NotImplementedError can be thrown if the transport is not implemented improperly",
"rescue",
"StandardError",
",",
"NotImplementedError",
"=>",
"e",
"result_promises",
".",
"each",
"do",
"|",
"target",
",",
"promise",
"|",
"# If an exception happens while running, the result won't be logged",
"# by the CLI. Log a warning, as this is probably a problem with the transport.",
"# If batch_* commands are used from the Base transport, then exceptions",
"# normally shouldn't reach here.",
"@logger",
".",
"warn",
"(",
"e",
")",
"promise",
".",
"set",
"(",
"Bolt",
"::",
"Result",
".",
"from_exception",
"(",
"target",
",",
"e",
")",
")",
"end",
"ensure",
"# Make absolutely sure every promise gets a result to avoid a",
"# deadlock. Use whatever exception is causing this block to",
"# execute, or generate one if we somehow got here without an",
"# exception and some promise is still missing a result.",
"result_promises",
".",
"each",
"do",
"|",
"target",
",",
"promise",
"|",
"next",
"if",
"promise",
".",
"fulfilled?",
"error",
"=",
"$ERROR_INFO",
"||",
"Bolt",
"::",
"Error",
".",
"new",
"(",
"\"No result was returned for #{target.uri}\"",
",",
"\"puppetlabs.bolt/missing-result-error\"",
")",
"promise",
".",
"set",
"(",
"Bolt",
"::",
"Result",
".",
"from_exception",
"(",
"target",
",",
"error",
")",
")",
"end",
"end",
"end",
"batch_promises",
".",
"values",
"end",
"end",
"end"
] |
Starts executing the given block on a list of nodes in parallel, one thread per "batch".
This is the main driver of execution on a list of targets. It first
groups targets by transport, then divides each group into batches as
defined by the transport. Yields each batch, along with the corresponding
transport, to the block in turn and returns an array of result promises.
|
[
"Starts",
"executing",
"the",
"given",
"block",
"on",
"a",
"list",
"of",
"nodes",
"in",
"parallel",
"one",
"thread",
"per",
"batch",
"."
] |
50689a33699939d262ea7c822a4b24fd8c4f8d8a
|
https://github.com/puppetlabs/bolt/blob/50689a33699939d262ea7c822a4b24fd8c4f8d8a/lib/bolt/executor.rb#L70-L112
|
11,230
|
puppetlabs/bolt
|
lib/bolt/pal.rb
|
Bolt.PAL.parse_manifest
|
def parse_manifest(code, filename)
Puppet::Pops::Parser::EvaluatingParser.new.parse_string(code, filename)
rescue Puppet::Error => e
raise Bolt::PAL::PALError, "Failed to parse manifest: #{e}"
end
|
ruby
|
def parse_manifest(code, filename)
Puppet::Pops::Parser::EvaluatingParser.new.parse_string(code, filename)
rescue Puppet::Error => e
raise Bolt::PAL::PALError, "Failed to parse manifest: #{e}"
end
|
[
"def",
"parse_manifest",
"(",
"code",
",",
"filename",
")",
"Puppet",
"::",
"Pops",
"::",
"Parser",
"::",
"EvaluatingParser",
".",
"new",
".",
"parse_string",
"(",
"code",
",",
"filename",
")",
"rescue",
"Puppet",
"::",
"Error",
"=>",
"e",
"raise",
"Bolt",
"::",
"PAL",
"::",
"PALError",
",",
"\"Failed to parse manifest: #{e}\"",
"end"
] |
Parses a snippet of Puppet manifest code and returns the AST represented
in JSON.
|
[
"Parses",
"a",
"snippet",
"of",
"Puppet",
"manifest",
"code",
"and",
"returns",
"the",
"AST",
"represented",
"in",
"JSON",
"."
] |
50689a33699939d262ea7c822a4b24fd8c4f8d8a
|
https://github.com/puppetlabs/bolt/blob/50689a33699939d262ea7c822a4b24fd8c4f8d8a/lib/bolt/pal.rb#L190-L194
|
11,231
|
puppetlabs/bolt
|
lib/bolt/pal.rb
|
Bolt.PAL.plan_hash
|
def plan_hash(plan_name, plan)
elements = plan.params_type.elements || []
parameters = elements.each_with_object({}) do |param, acc|
type = if param.value_type.is_a?(Puppet::Pops::Types::PTypeAliasType)
param.value_type.name
else
param.value_type.to_s
end
acc[param.name] = { 'type' => type }
acc[param.name]['default_value'] = nil if param.key_type.is_a?(Puppet::Pops::Types::POptionalType)
end
{
'name' => plan_name,
'parameters' => parameters
}
end
|
ruby
|
def plan_hash(plan_name, plan)
elements = plan.params_type.elements || []
parameters = elements.each_with_object({}) do |param, acc|
type = if param.value_type.is_a?(Puppet::Pops::Types::PTypeAliasType)
param.value_type.name
else
param.value_type.to_s
end
acc[param.name] = { 'type' => type }
acc[param.name]['default_value'] = nil if param.key_type.is_a?(Puppet::Pops::Types::POptionalType)
end
{
'name' => plan_name,
'parameters' => parameters
}
end
|
[
"def",
"plan_hash",
"(",
"plan_name",
",",
"plan",
")",
"elements",
"=",
"plan",
".",
"params_type",
".",
"elements",
"||",
"[",
"]",
"parameters",
"=",
"elements",
".",
"each_with_object",
"(",
"{",
"}",
")",
"do",
"|",
"param",
",",
"acc",
"|",
"type",
"=",
"if",
"param",
".",
"value_type",
".",
"is_a?",
"(",
"Puppet",
"::",
"Pops",
"::",
"Types",
"::",
"PTypeAliasType",
")",
"param",
".",
"value_type",
".",
"name",
"else",
"param",
".",
"value_type",
".",
"to_s",
"end",
"acc",
"[",
"param",
".",
"name",
"]",
"=",
"{",
"'type'",
"=>",
"type",
"}",
"acc",
"[",
"param",
".",
"name",
"]",
"[",
"'default_value'",
"]",
"=",
"nil",
"if",
"param",
".",
"key_type",
".",
"is_a?",
"(",
"Puppet",
"::",
"Pops",
"::",
"Types",
"::",
"POptionalType",
")",
"end",
"{",
"'name'",
"=>",
"plan_name",
",",
"'parameters'",
"=>",
"parameters",
"}",
"end"
] |
This converts a plan signature object into a format used by the outputter.
Must be called from within bolt compiler to pickup type aliases used in the plan signature.
|
[
"This",
"converts",
"a",
"plan",
"signature",
"object",
"into",
"a",
"format",
"used",
"by",
"the",
"outputter",
".",
"Must",
"be",
"called",
"from",
"within",
"bolt",
"compiler",
"to",
"pickup",
"type",
"aliases",
"used",
"in",
"the",
"plan",
"signature",
"."
] |
50689a33699939d262ea7c822a4b24fd8c4f8d8a
|
https://github.com/puppetlabs/bolt/blob/50689a33699939d262ea7c822a4b24fd8c4f8d8a/lib/bolt/pal.rb#L268-L283
|
11,232
|
puppetlabs/bolt
|
lib/bolt/pal.rb
|
Bolt.PAL.list_modules
|
def list_modules
internal_module_groups = { BOLTLIB_PATH => 'Plan Language Modules',
MODULES_PATH => 'Packaged Modules' }
in_bolt_compiler do
# NOTE: Can replace map+to_h with transform_values when Ruby 2.4
# is the minimum supported version.
Puppet.lookup(:current_environment).modules_by_path.map do |path, modules|
module_group = internal_module_groups[path]
values = modules.map do |mod|
mod_info = { name: (mod.forge_name || mod.name),
version: mod.version }
mod_info[:internal_module_group] = module_group unless module_group.nil?
mod_info
end
[path, values]
end.to_h
end
end
|
ruby
|
def list_modules
internal_module_groups = { BOLTLIB_PATH => 'Plan Language Modules',
MODULES_PATH => 'Packaged Modules' }
in_bolt_compiler do
# NOTE: Can replace map+to_h with transform_values when Ruby 2.4
# is the minimum supported version.
Puppet.lookup(:current_environment).modules_by_path.map do |path, modules|
module_group = internal_module_groups[path]
values = modules.map do |mod|
mod_info = { name: (mod.forge_name || mod.name),
version: mod.version }
mod_info[:internal_module_group] = module_group unless module_group.nil?
mod_info
end
[path, values]
end.to_h
end
end
|
[
"def",
"list_modules",
"internal_module_groups",
"=",
"{",
"BOLTLIB_PATH",
"=>",
"'Plan Language Modules'",
",",
"MODULES_PATH",
"=>",
"'Packaged Modules'",
"}",
"in_bolt_compiler",
"do",
"# NOTE: Can replace map+to_h with transform_values when Ruby 2.4",
"# is the minimum supported version.",
"Puppet",
".",
"lookup",
"(",
":current_environment",
")",
".",
"modules_by_path",
".",
"map",
"do",
"|",
"path",
",",
"modules",
"|",
"module_group",
"=",
"internal_module_groups",
"[",
"path",
"]",
"values",
"=",
"modules",
".",
"map",
"do",
"|",
"mod",
"|",
"mod_info",
"=",
"{",
"name",
":",
"(",
"mod",
".",
"forge_name",
"||",
"mod",
".",
"name",
")",
",",
"version",
":",
"mod",
".",
"version",
"}",
"mod_info",
"[",
":internal_module_group",
"]",
"=",
"module_group",
"unless",
"module_group",
".",
"nil?",
"mod_info",
"end",
"[",
"path",
",",
"values",
"]",
"end",
".",
"to_h",
"end",
"end"
] |
Returns a mapping of all modules available to the Bolt compiler
@return [Hash{String => Array<Hash{Symbol => String,nil}>}]
A hash that associates each directory on the module path with an array
containing a hash of information for each module in that directory.
The information hash provides the name, version, and a string
indicating whether the module belongs to an internal module group.
|
[
"Returns",
"a",
"mapping",
"of",
"all",
"modules",
"available",
"to",
"the",
"Bolt",
"compiler"
] |
50689a33699939d262ea7c822a4b24fd8c4f8d8a
|
https://github.com/puppetlabs/bolt/blob/50689a33699939d262ea7c822a4b24fd8c4f8d8a/lib/bolt/pal.rb#L313-L334
|
11,233
|
puppetlabs/bolt
|
lib/bolt/target.rb
|
Bolt.Target.update_conf
|
def update_conf(conf)
@protocol = conf[:transport]
t_conf = conf[:transports][transport.to_sym] || {}
# Override url methods
@user = t_conf['user']
@password = t_conf['password']
@port = t_conf['port']
@host = t_conf['host']
# Preserve everything in options so we can easily create copies of a Target.
@options = t_conf.merge(@options)
self
end
|
ruby
|
def update_conf(conf)
@protocol = conf[:transport]
t_conf = conf[:transports][transport.to_sym] || {}
# Override url methods
@user = t_conf['user']
@password = t_conf['password']
@port = t_conf['port']
@host = t_conf['host']
# Preserve everything in options so we can easily create copies of a Target.
@options = t_conf.merge(@options)
self
end
|
[
"def",
"update_conf",
"(",
"conf",
")",
"@protocol",
"=",
"conf",
"[",
":transport",
"]",
"t_conf",
"=",
"conf",
"[",
":transports",
"]",
"[",
"transport",
".",
"to_sym",
"]",
"||",
"{",
"}",
"# Override url methods",
"@user",
"=",
"t_conf",
"[",
"'user'",
"]",
"@password",
"=",
"t_conf",
"[",
"'password'",
"]",
"@port",
"=",
"t_conf",
"[",
"'port'",
"]",
"@host",
"=",
"t_conf",
"[",
"'host'",
"]",
"# Preserve everything in options so we can easily create copies of a Target.",
"@options",
"=",
"t_conf",
".",
"merge",
"(",
"@options",
")",
"self",
"end"
] |
URI can be passes as nil
|
[
"URI",
"can",
"be",
"passes",
"as",
"nil"
] |
50689a33699939d262ea7c822a4b24fd8c4f8d8a
|
https://github.com/puppetlabs/bolt/blob/50689a33699939d262ea7c822a4b24fd8c4f8d8a/lib/bolt/target.rb#L53-L67
|
11,234
|
puppetlabs/bolt
|
lib/bolt_spec/plans.rb
|
BoltSpec.Plans.config
|
def config
@config ||= begin
conf = Bolt::Config.new(Bolt::Boltdir.new('.'), {})
conf.modulepath = [modulepath].flatten
conf
end
end
|
ruby
|
def config
@config ||= begin
conf = Bolt::Config.new(Bolt::Boltdir.new('.'), {})
conf.modulepath = [modulepath].flatten
conf
end
end
|
[
"def",
"config",
"@config",
"||=",
"begin",
"conf",
"=",
"Bolt",
"::",
"Config",
".",
"new",
"(",
"Bolt",
"::",
"Boltdir",
".",
"new",
"(",
"'.'",
")",
",",
"{",
"}",
")",
"conf",
".",
"modulepath",
"=",
"[",
"modulepath",
"]",
".",
"flatten",
"conf",
"end",
"end"
] |
Override in your tests
|
[
"Override",
"in",
"your",
"tests"
] |
50689a33699939d262ea7c822a4b24fd8c4f8d8a
|
https://github.com/puppetlabs/bolt/blob/50689a33699939d262ea7c822a4b24fd8c4f8d8a/lib/bolt_spec/plans.rb#L154-L160
|
11,235
|
puppetlabs/bolt
|
lib/bolt/r10k_log_proxy.rb
|
Bolt.R10KLogProxy.to_bolt_level
|
def to_bolt_level(level_num)
level_str = Log4r::LNAMES[level_num]&.downcase || 'debug'
if level_str =~ /debug/
:debug
else
level_str.to_sym
end
end
|
ruby
|
def to_bolt_level(level_num)
level_str = Log4r::LNAMES[level_num]&.downcase || 'debug'
if level_str =~ /debug/
:debug
else
level_str.to_sym
end
end
|
[
"def",
"to_bolt_level",
"(",
"level_num",
")",
"level_str",
"=",
"Log4r",
"::",
"LNAMES",
"[",
"level_num",
"]",
"&.",
"downcase",
"||",
"'debug'",
"if",
"level_str",
"=~",
"/",
"/",
":debug",
"else",
"level_str",
".",
"to_sym",
"end",
"end"
] |
Convert an r10k log level to a bolt log level. These correspond 1-to-1
except that r10k has debug, debug1, and debug2. The log event has the log
level as an integer that we need to look up.
|
[
"Convert",
"an",
"r10k",
"log",
"level",
"to",
"a",
"bolt",
"log",
"level",
".",
"These",
"correspond",
"1",
"-",
"to",
"-",
"1",
"except",
"that",
"r10k",
"has",
"debug",
"debug1",
"and",
"debug2",
".",
"The",
"log",
"event",
"has",
"the",
"log",
"level",
"as",
"an",
"integer",
"that",
"we",
"need",
"to",
"look",
"up",
"."
] |
50689a33699939d262ea7c822a4b24fd8c4f8d8a
|
https://github.com/puppetlabs/bolt/blob/50689a33699939d262ea7c822a4b24fd8c4f8d8a/lib/bolt/r10k_log_proxy.rb#L21-L28
|
11,236
|
puppetlabs/bolt
|
lib/bolt/inventory.rb
|
Bolt.Inventory.update_target
|
def update_target(target)
data = @groups.data_for(target.name)
data ||= {}
unless data['config']
@logger.debug("Did not find config for #{target.name} in inventory")
data['config'] = {}
end
data = self.class.localhost_defaults(data) if target.name == 'localhost'
# These should only get set from the inventory if they have not yet
# been instantiated
set_vars_from_hash(target.name, data['vars']) unless @target_vars[target.name]
set_facts(target.name, data['facts']) unless @target_facts[target.name]
data['features']&.each { |feature| set_feature(target, feature) } unless @target_features[target.name]
# Use Config object to ensure config section is treated consistently with config file
conf = @config.deep_clone
conf.update_from_inventory(data['config'])
conf.validate
target.update_conf(conf.transport_conf)
unless target.transport.nil? || Bolt::TRANSPORTS.include?(target.transport.to_sym)
raise Bolt::UnknownTransportError.new(target.transport, target.uri)
end
target
end
|
ruby
|
def update_target(target)
data = @groups.data_for(target.name)
data ||= {}
unless data['config']
@logger.debug("Did not find config for #{target.name} in inventory")
data['config'] = {}
end
data = self.class.localhost_defaults(data) if target.name == 'localhost'
# These should only get set from the inventory if they have not yet
# been instantiated
set_vars_from_hash(target.name, data['vars']) unless @target_vars[target.name]
set_facts(target.name, data['facts']) unless @target_facts[target.name]
data['features']&.each { |feature| set_feature(target, feature) } unless @target_features[target.name]
# Use Config object to ensure config section is treated consistently with config file
conf = @config.deep_clone
conf.update_from_inventory(data['config'])
conf.validate
target.update_conf(conf.transport_conf)
unless target.transport.nil? || Bolt::TRANSPORTS.include?(target.transport.to_sym)
raise Bolt::UnknownTransportError.new(target.transport, target.uri)
end
target
end
|
[
"def",
"update_target",
"(",
"target",
")",
"data",
"=",
"@groups",
".",
"data_for",
"(",
"target",
".",
"name",
")",
"data",
"||=",
"{",
"}",
"unless",
"data",
"[",
"'config'",
"]",
"@logger",
".",
"debug",
"(",
"\"Did not find config for #{target.name} in inventory\"",
")",
"data",
"[",
"'config'",
"]",
"=",
"{",
"}",
"end",
"data",
"=",
"self",
".",
"class",
".",
"localhost_defaults",
"(",
"data",
")",
"if",
"target",
".",
"name",
"==",
"'localhost'",
"# These should only get set from the inventory if they have not yet",
"# been instantiated",
"set_vars_from_hash",
"(",
"target",
".",
"name",
",",
"data",
"[",
"'vars'",
"]",
")",
"unless",
"@target_vars",
"[",
"target",
".",
"name",
"]",
"set_facts",
"(",
"target",
".",
"name",
",",
"data",
"[",
"'facts'",
"]",
")",
"unless",
"@target_facts",
"[",
"target",
".",
"name",
"]",
"data",
"[",
"'features'",
"]",
"&.",
"each",
"{",
"|",
"feature",
"|",
"set_feature",
"(",
"target",
",",
"feature",
")",
"}",
"unless",
"@target_features",
"[",
"target",
".",
"name",
"]",
"# Use Config object to ensure config section is treated consistently with config file",
"conf",
"=",
"@config",
".",
"deep_clone",
"conf",
".",
"update_from_inventory",
"(",
"data",
"[",
"'config'",
"]",
")",
"conf",
".",
"validate",
"target",
".",
"update_conf",
"(",
"conf",
".",
"transport_conf",
")",
"unless",
"target",
".",
"transport",
".",
"nil?",
"||",
"Bolt",
"::",
"TRANSPORTS",
".",
"include?",
"(",
"target",
".",
"transport",
".",
"to_sym",
")",
"raise",
"Bolt",
"::",
"UnknownTransportError",
".",
"new",
"(",
"target",
".",
"transport",
",",
"target",
".",
"uri",
")",
"end",
"target",
"end"
] |
Pass a target to get_targets for a public version of this
Should this reconfigure configured targets?
|
[
"Pass",
"a",
"target",
"to",
"get_targets",
"for",
"a",
"public",
"version",
"of",
"this",
"Should",
"this",
"reconfigure",
"configured",
"targets?"
] |
50689a33699939d262ea7c822a4b24fd8c4f8d8a
|
https://github.com/puppetlabs/bolt/blob/50689a33699939d262ea7c822a4b24fd8c4f8d8a/lib/bolt/inventory.rb#L197-L225
|
11,237
|
deivid-rodriguez/byebug
|
lib/byebug/breakpoint.rb
|
Byebug.Breakpoint.inspect
|
def inspect
meths = %w[id pos source expr hit_condition hit_count hit_value enabled?]
values = meths.map { |field| "#{field}: #{send(field)}" }.join(", ")
"#<Byebug::Breakpoint #{values}>"
end
|
ruby
|
def inspect
meths = %w[id pos source expr hit_condition hit_count hit_value enabled?]
values = meths.map { |field| "#{field}: #{send(field)}" }.join(", ")
"#<Byebug::Breakpoint #{values}>"
end
|
[
"def",
"inspect",
"meths",
"=",
"%w[",
"id",
"pos",
"source",
"expr",
"hit_condition",
"hit_count",
"hit_value",
"enabled?",
"]",
"values",
"=",
"meths",
".",
"map",
"{",
"|",
"field",
"|",
"\"#{field}: #{send(field)}\"",
"}",
".",
"join",
"(",
"\", \"",
")",
"\"#<Byebug::Breakpoint #{values}>\"",
"end"
] |
Prints all information associated to the breakpoint
|
[
"Prints",
"all",
"information",
"associated",
"to",
"the",
"breakpoint"
] |
bf41a63858a648baa7fb621600d6451786d1572a
|
https://github.com/deivid-rodriguez/byebug/blob/bf41a63858a648baa7fb621600d6451786d1572a/lib/byebug/breakpoint.rb#L105-L109
|
11,238
|
deivid-rodriguez/byebug
|
lib/byebug/processors/command_processor.rb
|
Byebug.CommandProcessor.repl
|
def repl
until @proceed
cmd = interface.read_command(prompt)
return if cmd.nil?
next if cmd == ""
run_cmd(cmd)
end
end
|
ruby
|
def repl
until @proceed
cmd = interface.read_command(prompt)
return if cmd.nil?
next if cmd == ""
run_cmd(cmd)
end
end
|
[
"def",
"repl",
"until",
"@proceed",
"cmd",
"=",
"interface",
".",
"read_command",
"(",
"prompt",
")",
"return",
"if",
"cmd",
".",
"nil?",
"next",
"if",
"cmd",
"==",
"\"\"",
"run_cmd",
"(",
"cmd",
")",
"end",
"end"
] |
Main byebug's REPL
|
[
"Main",
"byebug",
"s",
"REPL"
] |
bf41a63858a648baa7fb621600d6451786d1572a
|
https://github.com/deivid-rodriguez/byebug/blob/bf41a63858a648baa7fb621600d6451786d1572a/lib/byebug/processors/command_processor.rb#L126-L135
|
11,239
|
deivid-rodriguez/byebug
|
lib/byebug/processors/command_processor.rb
|
Byebug.CommandProcessor.run_auto_cmds
|
def run_auto_cmds(run_level)
safely do
auto_cmds_for(run_level).each { |cmd| cmd.new(self).execute }
end
end
|
ruby
|
def run_auto_cmds(run_level)
safely do
auto_cmds_for(run_level).each { |cmd| cmd.new(self).execute }
end
end
|
[
"def",
"run_auto_cmds",
"(",
"run_level",
")",
"safely",
"do",
"auto_cmds_for",
"(",
"run_level",
")",
".",
"each",
"{",
"|",
"cmd",
"|",
"cmd",
".",
"new",
"(",
"self",
")",
".",
"execute",
"}",
"end",
"end"
] |
Run permanent commands.
|
[
"Run",
"permanent",
"commands",
"."
] |
bf41a63858a648baa7fb621600d6451786d1572a
|
https://github.com/deivid-rodriguez/byebug/blob/bf41a63858a648baa7fb621600d6451786d1572a/lib/byebug/processors/command_processor.rb#L146-L150
|
11,240
|
deivid-rodriguez/byebug
|
lib/byebug/processors/command_processor.rb
|
Byebug.CommandProcessor.run_cmd
|
def run_cmd(input)
safely do
command = command_list.match(input)
return command.new(self, input).execute if command
puts safe_inspect(multiple_thread_eval(input))
end
end
|
ruby
|
def run_cmd(input)
safely do
command = command_list.match(input)
return command.new(self, input).execute if command
puts safe_inspect(multiple_thread_eval(input))
end
end
|
[
"def",
"run_cmd",
"(",
"input",
")",
"safely",
"do",
"command",
"=",
"command_list",
".",
"match",
"(",
"input",
")",
"return",
"command",
".",
"new",
"(",
"self",
",",
"input",
")",
".",
"execute",
"if",
"command",
"puts",
"safe_inspect",
"(",
"multiple_thread_eval",
"(",
"input",
")",
")",
"end",
"end"
] |
Executes the received input
Instantiates a command matching the input and runs it. If a matching
command is not found, it evaluates the unknown input.
|
[
"Executes",
"the",
"received",
"input"
] |
bf41a63858a648baa7fb621600d6451786d1572a
|
https://github.com/deivid-rodriguez/byebug/blob/bf41a63858a648baa7fb621600d6451786d1572a/lib/byebug/processors/command_processor.rb#L158-L165
|
11,241
|
deivid-rodriguez/byebug
|
lib/byebug/history.rb
|
Byebug.History.restore
|
def restore
return unless File.exist?(Setting[:histfile])
File.readlines(Setting[:histfile]).reverse_each { |l| push(l.chomp) }
end
|
ruby
|
def restore
return unless File.exist?(Setting[:histfile])
File.readlines(Setting[:histfile]).reverse_each { |l| push(l.chomp) }
end
|
[
"def",
"restore",
"return",
"unless",
"File",
".",
"exist?",
"(",
"Setting",
"[",
":histfile",
"]",
")",
"File",
".",
"readlines",
"(",
"Setting",
"[",
":histfile",
"]",
")",
".",
"reverse_each",
"{",
"|",
"l",
"|",
"push",
"(",
"l",
".",
"chomp",
")",
"}",
"end"
] |
Restores history from disk.
|
[
"Restores",
"history",
"from",
"disk",
"."
] |
bf41a63858a648baa7fb621600d6451786d1572a
|
https://github.com/deivid-rodriguez/byebug/blob/bf41a63858a648baa7fb621600d6451786d1572a/lib/byebug/history.rb#L36-L40
|
11,242
|
deivid-rodriguez/byebug
|
lib/byebug/history.rb
|
Byebug.History.save
|
def save
n_cmds = Setting[:histsize] > size ? size : Setting[:histsize]
File.open(Setting[:histfile], "w") do |file|
n_cmds.times { file.puts(pop) }
end
clear
end
|
ruby
|
def save
n_cmds = Setting[:histsize] > size ? size : Setting[:histsize]
File.open(Setting[:histfile], "w") do |file|
n_cmds.times { file.puts(pop) }
end
clear
end
|
[
"def",
"save",
"n_cmds",
"=",
"Setting",
"[",
":histsize",
"]",
">",
"size",
"?",
"size",
":",
"Setting",
"[",
":histsize",
"]",
"File",
".",
"open",
"(",
"Setting",
"[",
":histfile",
"]",
",",
"\"w\"",
")",
"do",
"|",
"file",
"|",
"n_cmds",
".",
"times",
"{",
"file",
".",
"puts",
"(",
"pop",
")",
"}",
"end",
"clear",
"end"
] |
Saves history to disk.
|
[
"Saves",
"history",
"to",
"disk",
"."
] |
bf41a63858a648baa7fb621600d6451786d1572a
|
https://github.com/deivid-rodriguez/byebug/blob/bf41a63858a648baa7fb621600d6451786d1572a/lib/byebug/history.rb#L45-L53
|
11,243
|
deivid-rodriguez/byebug
|
lib/byebug/history.rb
|
Byebug.History.to_s
|
def to_s(n_cmds)
show_size = n_cmds ? specific_max_size(n_cmds) : default_max_size
commands = buffer.last(show_size)
last_ids(show_size).zip(commands).map do |l|
format("%<position>5d %<command>s", position: l[0], command: l[1])
end.join("\n") + "\n"
end
|
ruby
|
def to_s(n_cmds)
show_size = n_cmds ? specific_max_size(n_cmds) : default_max_size
commands = buffer.last(show_size)
last_ids(show_size).zip(commands).map do |l|
format("%<position>5d %<command>s", position: l[0], command: l[1])
end.join("\n") + "\n"
end
|
[
"def",
"to_s",
"(",
"n_cmds",
")",
"show_size",
"=",
"n_cmds",
"?",
"specific_max_size",
"(",
"n_cmds",
")",
":",
"default_max_size",
"commands",
"=",
"buffer",
".",
"last",
"(",
"show_size",
")",
"last_ids",
"(",
"show_size",
")",
".",
"zip",
"(",
"commands",
")",
".",
"map",
"do",
"|",
"l",
"|",
"format",
"(",
"\"%<position>5d %<command>s\"",
",",
"position",
":",
"l",
"[",
"0",
"]",
",",
"command",
":",
"l",
"[",
"1",
"]",
")",
"end",
".",
"join",
"(",
"\"\\n\"",
")",
"+",
"\"\\n\"",
"end"
] |
Prints the requested numbers of history entries.
|
[
"Prints",
"the",
"requested",
"numbers",
"of",
"history",
"entries",
"."
] |
bf41a63858a648baa7fb621600d6451786d1572a
|
https://github.com/deivid-rodriguez/byebug/blob/bf41a63858a648baa7fb621600d6451786d1572a/lib/byebug/history.rb#L83-L91
|
11,244
|
deivid-rodriguez/byebug
|
lib/byebug/history.rb
|
Byebug.History.ignore?
|
def ignore?(buf)
return true if /^\s*$/ =~ buf
return false if Readline::HISTORY.empty?
buffer[Readline::HISTORY.length - 1] == buf
end
|
ruby
|
def ignore?(buf)
return true if /^\s*$/ =~ buf
return false if Readline::HISTORY.empty?
buffer[Readline::HISTORY.length - 1] == buf
end
|
[
"def",
"ignore?",
"(",
"buf",
")",
"return",
"true",
"if",
"/",
"\\s",
"/",
"=~",
"buf",
"return",
"false",
"if",
"Readline",
"::",
"HISTORY",
".",
"empty?",
"buffer",
"[",
"Readline",
"::",
"HISTORY",
".",
"length",
"-",
"1",
"]",
"==",
"buf",
"end"
] |
Whether a specific command should not be stored in history.
For now, empty lines and consecutive duplicates.
|
[
"Whether",
"a",
"specific",
"command",
"should",
"not",
"be",
"stored",
"in",
"history",
"."
] |
bf41a63858a648baa7fb621600d6451786d1572a
|
https://github.com/deivid-rodriguez/byebug/blob/bf41a63858a648baa7fb621600d6451786d1572a/lib/byebug/history.rb#L123-L128
|
11,245
|
deivid-rodriguez/byebug
|
lib/byebug/subcommands.rb
|
Byebug.Subcommands.execute
|
def execute
subcmd_name = @match[1]
return puts(help) unless subcmd_name
subcmd = subcommand_list.match(subcmd_name)
raise CommandNotFound.new(subcmd_name, self.class) unless subcmd
subcmd.new(processor, arguments).execute
end
|
ruby
|
def execute
subcmd_name = @match[1]
return puts(help) unless subcmd_name
subcmd = subcommand_list.match(subcmd_name)
raise CommandNotFound.new(subcmd_name, self.class) unless subcmd
subcmd.new(processor, arguments).execute
end
|
[
"def",
"execute",
"subcmd_name",
"=",
"@match",
"[",
"1",
"]",
"return",
"puts",
"(",
"help",
")",
"unless",
"subcmd_name",
"subcmd",
"=",
"subcommand_list",
".",
"match",
"(",
"subcmd_name",
")",
"raise",
"CommandNotFound",
".",
"new",
"(",
"subcmd_name",
",",
"self",
".",
"class",
")",
"unless",
"subcmd",
"subcmd",
".",
"new",
"(",
"processor",
",",
"arguments",
")",
".",
"execute",
"end"
] |
Delegates to subcommands or prints help if no subcommand specified.
|
[
"Delegates",
"to",
"subcommands",
"or",
"prints",
"help",
"if",
"no",
"subcommand",
"specified",
"."
] |
bf41a63858a648baa7fb621600d6451786d1572a
|
https://github.com/deivid-rodriguez/byebug/blob/bf41a63858a648baa7fb621600d6451786d1572a/lib/byebug/subcommands.rb#L23-L31
|
11,246
|
deivid-rodriguez/byebug
|
lib/byebug/frame.rb
|
Byebug.Frame.locals
|
def locals
return [] unless _binding
_binding.local_variables.each_with_object({}) do |e, a|
a[e] = _binding.local_variable_get(e)
a
end
end
|
ruby
|
def locals
return [] unless _binding
_binding.local_variables.each_with_object({}) do |e, a|
a[e] = _binding.local_variable_get(e)
a
end
end
|
[
"def",
"locals",
"return",
"[",
"]",
"unless",
"_binding",
"_binding",
".",
"local_variables",
".",
"each_with_object",
"(",
"{",
"}",
")",
"do",
"|",
"e",
",",
"a",
"|",
"a",
"[",
"e",
"]",
"=",
"_binding",
".",
"local_variable_get",
"(",
"e",
")",
"a",
"end",
"end"
] |
Gets local variables for the frame.
|
[
"Gets",
"local",
"variables",
"for",
"the",
"frame",
"."
] |
bf41a63858a648baa7fb621600d6451786d1572a
|
https://github.com/deivid-rodriguez/byebug/blob/bf41a63858a648baa7fb621600d6451786d1572a/lib/byebug/frame.rb#L50-L57
|
11,247
|
deivid-rodriguez/byebug
|
lib/byebug/frame.rb
|
Byebug.Frame.deco_args
|
def deco_args
return "" if args.empty?
my_args = args.map do |arg|
prefix, default = prefix_and_default(arg[0])
kls = use_short_style?(arg) ? "" : "##{locals[arg[1]].class}"
"#{prefix}#{arg[1] || default}#{kls}"
end
"(#{my_args.join(', ')})"
end
|
ruby
|
def deco_args
return "" if args.empty?
my_args = args.map do |arg|
prefix, default = prefix_and_default(arg[0])
kls = use_short_style?(arg) ? "" : "##{locals[arg[1]].class}"
"#{prefix}#{arg[1] || default}#{kls}"
end
"(#{my_args.join(', ')})"
end
|
[
"def",
"deco_args",
"return",
"\"\"",
"if",
"args",
".",
"empty?",
"my_args",
"=",
"args",
".",
"map",
"do",
"|",
"arg",
"|",
"prefix",
",",
"default",
"=",
"prefix_and_default",
"(",
"arg",
"[",
"0",
"]",
")",
"kls",
"=",
"use_short_style?",
"(",
"arg",
")",
"?",
"\"\"",
":",
"\"##{locals[arg[1]].class}\"",
"\"#{prefix}#{arg[1] || default}#{kls}\"",
"end",
"\"(#{my_args.join(', ')})\"",
"end"
] |
Builds a string containing all available args in the frame number, in a
verbose or non verbose way according to the value of the +callstyle+
setting
|
[
"Builds",
"a",
"string",
"containing",
"all",
"available",
"args",
"in",
"the",
"frame",
"number",
"in",
"a",
"verbose",
"or",
"non",
"verbose",
"way",
"according",
"to",
"the",
"value",
"of",
"the",
"+",
"callstyle",
"+",
"setting"
] |
bf41a63858a648baa7fb621600d6451786d1572a
|
https://github.com/deivid-rodriguez/byebug/blob/bf41a63858a648baa7fb621600d6451786d1572a/lib/byebug/frame.rb#L89-L101
|
11,248
|
deivid-rodriguez/byebug
|
lib/byebug/context.rb
|
Byebug.Context.stack_size
|
def stack_size
return 0 unless backtrace
backtrace.drop_while { |l| ignored_file?(l.first.path) }
.take_while { |l| !ignored_file?(l.first.path) }
.size
end
|
ruby
|
def stack_size
return 0 unless backtrace
backtrace.drop_while { |l| ignored_file?(l.first.path) }
.take_while { |l| !ignored_file?(l.first.path) }
.size
end
|
[
"def",
"stack_size",
"return",
"0",
"unless",
"backtrace",
"backtrace",
".",
"drop_while",
"{",
"|",
"l",
"|",
"ignored_file?",
"(",
"l",
".",
"first",
".",
"path",
")",
"}",
".",
"take_while",
"{",
"|",
"l",
"|",
"!",
"ignored_file?",
"(",
"l",
".",
"first",
".",
"path",
")",
"}",
".",
"size",
"end"
] |
Context's stack size
|
[
"Context",
"s",
"stack",
"size"
] |
bf41a63858a648baa7fb621600d6451786d1572a
|
https://github.com/deivid-rodriguez/byebug/blob/bf41a63858a648baa7fb621600d6451786d1572a/lib/byebug/context.rb#L79-L85
|
11,249
|
deivid-rodriguez/byebug
|
lib/byebug/commands/list.rb
|
Byebug.ListCommand.range
|
def range(input)
return auto_range(@match[1] || "+") unless input
b, e = parse_range(input)
raise("Invalid line range") unless valid_range?(b, e)
[b, e]
end
|
ruby
|
def range(input)
return auto_range(@match[1] || "+") unless input
b, e = parse_range(input)
raise("Invalid line range") unless valid_range?(b, e)
[b, e]
end
|
[
"def",
"range",
"(",
"input",
")",
"return",
"auto_range",
"(",
"@match",
"[",
"1",
"]",
"||",
"\"+\"",
")",
"unless",
"input",
"b",
",",
"e",
"=",
"parse_range",
"(",
"input",
")",
"raise",
"(",
"\"Invalid line range\"",
")",
"unless",
"valid_range?",
"(",
"b",
",",
"e",
")",
"[",
"b",
",",
"e",
"]",
"end"
] |
Line range to be printed by `list`.
If <input> is set, range is parsed from it.
Otherwise it's automatically chosen.
|
[
"Line",
"range",
"to",
"be",
"printed",
"by",
"list",
"."
] |
bf41a63858a648baa7fb621600d6451786d1572a
|
https://github.com/deivid-rodriguez/byebug/blob/bf41a63858a648baa7fb621600d6451786d1572a/lib/byebug/commands/list.rb#L60-L67
|
11,250
|
deivid-rodriguez/byebug
|
lib/byebug/commands/list.rb
|
Byebug.ListCommand.auto_range
|
def auto_range(direction)
prev_line = processor.prev_line
if direction == "=" || prev_line.nil?
source_file_formatter.range_around(frame.line)
else
source_file_formatter.range_from(move(prev_line, size, direction))
end
end
|
ruby
|
def auto_range(direction)
prev_line = processor.prev_line
if direction == "=" || prev_line.nil?
source_file_formatter.range_around(frame.line)
else
source_file_formatter.range_from(move(prev_line, size, direction))
end
end
|
[
"def",
"auto_range",
"(",
"direction",
")",
"prev_line",
"=",
"processor",
".",
"prev_line",
"if",
"direction",
"==",
"\"=\"",
"||",
"prev_line",
".",
"nil?",
"source_file_formatter",
".",
"range_around",
"(",
"frame",
".",
"line",
")",
"else",
"source_file_formatter",
".",
"range_from",
"(",
"move",
"(",
"prev_line",
",",
"size",
",",
"direction",
")",
")",
"end",
"end"
] |
Set line range to be printed by list
@return first line number to list
@return last line number to list
|
[
"Set",
"line",
"range",
"to",
"be",
"printed",
"by",
"list"
] |
bf41a63858a648baa7fb621600d6451786d1572a
|
https://github.com/deivid-rodriguez/byebug/blob/bf41a63858a648baa7fb621600d6451786d1572a/lib/byebug/commands/list.rb#L79-L87
|
11,251
|
deivid-rodriguez/byebug
|
lib/byebug/commands/list.rb
|
Byebug.ListCommand.display_lines
|
def display_lines(min, max)
puts "\n[#{min}, #{max}] in #{frame.file}"
puts source_file_formatter.lines(min, max).join
end
|
ruby
|
def display_lines(min, max)
puts "\n[#{min}, #{max}] in #{frame.file}"
puts source_file_formatter.lines(min, max).join
end
|
[
"def",
"display_lines",
"(",
"min",
",",
"max",
")",
"puts",
"\"\\n[#{min}, #{max}] in #{frame.file}\"",
"puts",
"source_file_formatter",
".",
"lines",
"(",
"min",
",",
"max",
")",
".",
"join",
"end"
] |
Show a range of lines in the current file.
@param min [Integer] Lower bound
@param max [Integer] Upper bound
|
[
"Show",
"a",
"range",
"of",
"lines",
"in",
"the",
"current",
"file",
"."
] |
bf41a63858a648baa7fb621600d6451786d1572a
|
https://github.com/deivid-rodriguez/byebug/blob/bf41a63858a648baa7fb621600d6451786d1572a/lib/byebug/commands/list.rb#L115-L119
|
11,252
|
deivid-rodriguez/byebug
|
lib/byebug/runner.rb
|
Byebug.Runner.run
|
def run
Byebug.mode = :standalone
option_parser.order!($ARGV)
return if non_script_option? || error_in_script?
$PROGRAM_NAME = program
Byebug.run_init_script if init_script
loop do
debug_program
break if quit
ControlProcessor.new(nil, interface).process_commands
end
end
|
ruby
|
def run
Byebug.mode = :standalone
option_parser.order!($ARGV)
return if non_script_option? || error_in_script?
$PROGRAM_NAME = program
Byebug.run_init_script if init_script
loop do
debug_program
break if quit
ControlProcessor.new(nil, interface).process_commands
end
end
|
[
"def",
"run",
"Byebug",
".",
"mode",
"=",
":standalone",
"option_parser",
".",
"order!",
"(",
"$ARGV",
")",
"return",
"if",
"non_script_option?",
"||",
"error_in_script?",
"$PROGRAM_NAME",
"=",
"program",
"Byebug",
".",
"run_init_script",
"if",
"init_script",
"loop",
"do",
"debug_program",
"break",
"if",
"quit",
"ControlProcessor",
".",
"new",
"(",
"nil",
",",
"interface",
")",
".",
"process_commands",
"end",
"end"
] |
Starts byebug to debug a program.
|
[
"Starts",
"byebug",
"to",
"debug",
"a",
"program",
"."
] |
bf41a63858a648baa7fb621600d6451786d1572a
|
https://github.com/deivid-rodriguez/byebug/blob/bf41a63858a648baa7fb621600d6451786d1572a/lib/byebug/runner.rb#L92-L109
|
11,253
|
deivid-rodriguez/byebug
|
lib/byebug/runner.rb
|
Byebug.Runner.option_parser
|
def option_parser
@option_parser ||= OptionParser.new(banner, 25) do |opts|
opts.banner = banner
OptionSetter.new(self, opts).setup
end
end
|
ruby
|
def option_parser
@option_parser ||= OptionParser.new(banner, 25) do |opts|
opts.banner = banner
OptionSetter.new(self, opts).setup
end
end
|
[
"def",
"option_parser",
"@option_parser",
"||=",
"OptionParser",
".",
"new",
"(",
"banner",
",",
"25",
")",
"do",
"|",
"opts",
"|",
"opts",
".",
"banner",
"=",
"banner",
"OptionSetter",
".",
"new",
"(",
"self",
",",
"opts",
")",
".",
"setup",
"end",
"end"
] |
Processes options passed from the command line.
|
[
"Processes",
"options",
"passed",
"from",
"the",
"command",
"line",
"."
] |
bf41a63858a648baa7fb621600d6451786d1572a
|
https://github.com/deivid-rodriguez/byebug/blob/bf41a63858a648baa7fb621600d6451786d1572a/lib/byebug/runner.rb#L118-L124
|
11,254
|
deivid-rodriguez/byebug
|
lib/byebug/interface.rb
|
Byebug.Interface.read_input
|
def read_input(prompt, save_hist = true)
line = prepare_input(prompt)
return unless line
history.push(line) if save_hist
command_queue.concat(split_commands(line))
command_queue.shift
end
|
ruby
|
def read_input(prompt, save_hist = true)
line = prepare_input(prompt)
return unless line
history.push(line) if save_hist
command_queue.concat(split_commands(line))
command_queue.shift
end
|
[
"def",
"read_input",
"(",
"prompt",
",",
"save_hist",
"=",
"true",
")",
"line",
"=",
"prepare_input",
"(",
"prompt",
")",
"return",
"unless",
"line",
"history",
".",
"push",
"(",
"line",
")",
"if",
"save_hist",
"command_queue",
".",
"concat",
"(",
"split_commands",
"(",
"line",
")",
")",
"command_queue",
".",
"shift",
"end"
] |
Reads a new line from the interface's input stream, parses it into
commands and saves it to history.
@return [String] Representing something to be run by the debugger.
|
[
"Reads",
"a",
"new",
"line",
"from",
"the",
"interface",
"s",
"input",
"stream",
"parses",
"it",
"into",
"commands",
"and",
"saves",
"it",
"to",
"history",
"."
] |
bf41a63858a648baa7fb621600d6451786d1572a
|
https://github.com/deivid-rodriguez/byebug/blob/bf41a63858a648baa7fb621600d6451786d1572a/lib/byebug/interface.rb#L54-L62
|
11,255
|
licensee/licensee
|
lib/licensee/license.rb
|
Licensee.License.raw_content
|
def raw_content
return if pseudo_license?
unless File.exist?(path)
raise Licensee::InvalidLicense, "'#{key}' is not a valid license key"
end
@raw_content ||= File.read(path, encoding: 'utf-8')
end
|
ruby
|
def raw_content
return if pseudo_license?
unless File.exist?(path)
raise Licensee::InvalidLicense, "'#{key}' is not a valid license key"
end
@raw_content ||= File.read(path, encoding: 'utf-8')
end
|
[
"def",
"raw_content",
"return",
"if",
"pseudo_license?",
"unless",
"File",
".",
"exist?",
"(",
"path",
")",
"raise",
"Licensee",
"::",
"InvalidLicense",
",",
"\"'#{key}' is not a valid license key\"",
"end",
"@raw_content",
"||=",
"File",
".",
"read",
"(",
"path",
",",
"encoding",
":",
"'utf-8'",
")",
"end"
] |
Raw content of license file, including YAML front matter
|
[
"Raw",
"content",
"of",
"license",
"file",
"including",
"YAML",
"front",
"matter"
] |
e181f73f529f9cefa91096817a9c13b9e1608599
|
https://github.com/licensee/licensee/blob/e181f73f529f9cefa91096817a9c13b9e1608599/lib/licensee/license.rb#L247-L254
|
11,256
|
licensee/licensee
|
lib/licensee/content_helper.rb
|
Licensee.ContentHelper.similarity
|
def similarity(other)
overlap = (wordset & other.wordset).size
total = wordset.size + other.wordset.size
100.0 * (overlap * 2.0 / total)
end
|
ruby
|
def similarity(other)
overlap = (wordset & other.wordset).size
total = wordset.size + other.wordset.size
100.0 * (overlap * 2.0 / total)
end
|
[
"def",
"similarity",
"(",
"other",
")",
"overlap",
"=",
"(",
"wordset",
"&",
"other",
".",
"wordset",
")",
".",
"size",
"total",
"=",
"wordset",
".",
"size",
"+",
"other",
".",
"wordset",
".",
"size",
"100.0",
"*",
"(",
"overlap",
"*",
"2.0",
"/",
"total",
")",
"end"
] |
Given another license or project file, calculates the similarity
as a percentage of words in common
|
[
"Given",
"another",
"license",
"or",
"project",
"file",
"calculates",
"the",
"similarity",
"as",
"a",
"percentage",
"of",
"words",
"in",
"common"
] |
e181f73f529f9cefa91096817a9c13b9e1608599
|
https://github.com/licensee/licensee/blob/e181f73f529f9cefa91096817a9c13b9e1608599/lib/licensee/content_helper.rb#L117-L121
|
11,257
|
licensee/licensee
|
lib/licensee/content_helper.rb
|
Licensee.ContentHelper.content_without_title_and_version
|
def content_without_title_and_version
@content_without_title_and_version ||= begin
@_content = nil
ops = %i[html hrs comments markdown_headings title version]
ops.each { |op| strip(op) }
_content
end
end
|
ruby
|
def content_without_title_and_version
@content_without_title_and_version ||= begin
@_content = nil
ops = %i[html hrs comments markdown_headings title version]
ops.each { |op| strip(op) }
_content
end
end
|
[
"def",
"content_without_title_and_version",
"@content_without_title_and_version",
"||=",
"begin",
"@_content",
"=",
"nil",
"ops",
"=",
"%i[",
"html",
"hrs",
"comments",
"markdown_headings",
"title",
"version",
"]",
"ops",
".",
"each",
"{",
"|",
"op",
"|",
"strip",
"(",
"op",
")",
"}",
"_content",
"end",
"end"
] |
Content with the title and version removed
The first time should normally be the attribution line
Used to dry up `content_normalized` but we need the case sensitive
content with attribution first to detect attribuion in LicenseFile
|
[
"Content",
"with",
"the",
"title",
"and",
"version",
"removed",
"The",
"first",
"time",
"should",
"normally",
"be",
"the",
"attribution",
"line",
"Used",
"to",
"dry",
"up",
"content_normalized",
"but",
"we",
"need",
"the",
"case",
"sensitive",
"content",
"with",
"attribution",
"first",
"to",
"detect",
"attribuion",
"in",
"LicenseFile"
] |
e181f73f529f9cefa91096817a9c13b9e1608599
|
https://github.com/licensee/licensee/blob/e181f73f529f9cefa91096817a9c13b9e1608599/lib/licensee/content_helper.rb#L132-L139
|
11,258
|
lynndylanhurley/devise_token_auth
|
app/controllers/devise_token_auth/passwords_controller.rb
|
DeviseTokenAuth.PasswordsController.edit
|
def edit
# if a user is not found, return nil
@resource = resource_class.with_reset_password_token(resource_params[:reset_password_token])
if @resource && @resource.reset_password_period_valid?
client_id, token = @resource.create_token
# ensure that user is confirmed
@resource.skip_confirmation! if confirmable_enabled? && !@resource.confirmed_at
# allow user to change password once without current_password
@resource.allow_password_change = true if recoverable_enabled?
@resource.save!
yield @resource if block_given?
redirect_header_options = { reset_password: true }
redirect_headers = build_redirect_headers(token,
client_id,
redirect_header_options)
redirect_to(@resource.build_auth_url(@redirect_url,
redirect_headers))
else
render_edit_error
end
end
|
ruby
|
def edit
# if a user is not found, return nil
@resource = resource_class.with_reset_password_token(resource_params[:reset_password_token])
if @resource && @resource.reset_password_period_valid?
client_id, token = @resource.create_token
# ensure that user is confirmed
@resource.skip_confirmation! if confirmable_enabled? && !@resource.confirmed_at
# allow user to change password once without current_password
@resource.allow_password_change = true if recoverable_enabled?
@resource.save!
yield @resource if block_given?
redirect_header_options = { reset_password: true }
redirect_headers = build_redirect_headers(token,
client_id,
redirect_header_options)
redirect_to(@resource.build_auth_url(@redirect_url,
redirect_headers))
else
render_edit_error
end
end
|
[
"def",
"edit",
"# if a user is not found, return nil",
"@resource",
"=",
"resource_class",
".",
"with_reset_password_token",
"(",
"resource_params",
"[",
":reset_password_token",
"]",
")",
"if",
"@resource",
"&&",
"@resource",
".",
"reset_password_period_valid?",
"client_id",
",",
"token",
"=",
"@resource",
".",
"create_token",
"# ensure that user is confirmed",
"@resource",
".",
"skip_confirmation!",
"if",
"confirmable_enabled?",
"&&",
"!",
"@resource",
".",
"confirmed_at",
"# allow user to change password once without current_password",
"@resource",
".",
"allow_password_change",
"=",
"true",
"if",
"recoverable_enabled?",
"@resource",
".",
"save!",
"yield",
"@resource",
"if",
"block_given?",
"redirect_header_options",
"=",
"{",
"reset_password",
":",
"true",
"}",
"redirect_headers",
"=",
"build_redirect_headers",
"(",
"token",
",",
"client_id",
",",
"redirect_header_options",
")",
"redirect_to",
"(",
"@resource",
".",
"build_auth_url",
"(",
"@redirect_url",
",",
"redirect_headers",
")",
")",
"else",
"render_edit_error",
"end",
"end"
] |
this is where users arrive after visiting the password reset confirmation link
|
[
"this",
"is",
"where",
"users",
"arrive",
"after",
"visiting",
"the",
"password",
"reset",
"confirmation",
"link"
] |
0727ac77e5d1cf8c065faa81ca6ddbba9cc0fe44
|
https://github.com/lynndylanhurley/devise_token_auth/blob/0727ac77e5d1cf8c065faa81ca6ddbba9cc0fe44/app/controllers/devise_token_auth/passwords_controller.rb#L37-L63
|
11,259
|
lynndylanhurley/devise_token_auth
|
app/controllers/devise_token_auth/unlocks_controller.rb
|
DeviseTokenAuth.UnlocksController.create
|
def create
return render_create_error_missing_email unless resource_params[:email]
@email = get_case_insensitive_field_from_resource_params(:email)
@resource = find_resource(:email, @email)
if @resource
yield @resource if block_given?
@resource.send_unlock_instructions(
email: @email,
provider: 'email',
client_config: params[:config_name]
)
if @resource.errors.empty?
return render_create_success
else
render_create_error @resource.errors
end
else
render_not_found_error
end
end
|
ruby
|
def create
return render_create_error_missing_email unless resource_params[:email]
@email = get_case_insensitive_field_from_resource_params(:email)
@resource = find_resource(:email, @email)
if @resource
yield @resource if block_given?
@resource.send_unlock_instructions(
email: @email,
provider: 'email',
client_config: params[:config_name]
)
if @resource.errors.empty?
return render_create_success
else
render_create_error @resource.errors
end
else
render_not_found_error
end
end
|
[
"def",
"create",
"return",
"render_create_error_missing_email",
"unless",
"resource_params",
"[",
":email",
"]",
"@email",
"=",
"get_case_insensitive_field_from_resource_params",
"(",
":email",
")",
"@resource",
"=",
"find_resource",
"(",
":email",
",",
"@email",
")",
"if",
"@resource",
"yield",
"@resource",
"if",
"block_given?",
"@resource",
".",
"send_unlock_instructions",
"(",
"email",
":",
"@email",
",",
"provider",
":",
"'email'",
",",
"client_config",
":",
"params",
"[",
":config_name",
"]",
")",
"if",
"@resource",
".",
"errors",
".",
"empty?",
"return",
"render_create_success",
"else",
"render_create_error",
"@resource",
".",
"errors",
"end",
"else",
"render_not_found_error",
"end",
"end"
] |
this action is responsible for generating unlock tokens and
sending emails
|
[
"this",
"action",
"is",
"responsible",
"for",
"generating",
"unlock",
"tokens",
"and",
"sending",
"emails"
] |
0727ac77e5d1cf8c065faa81ca6ddbba9cc0fe44
|
https://github.com/lynndylanhurley/devise_token_auth/blob/0727ac77e5d1cf8c065faa81ca6ddbba9cc0fe44/app/controllers/devise_token_auth/unlocks_controller.rb#L9-L32
|
11,260
|
lynndylanhurley/devise_token_auth
|
app/controllers/devise_token_auth/omniauth_callbacks_controller.rb
|
DeviseTokenAuth.OmniauthCallbacksController.redirect_callbacks
|
def redirect_callbacks
# derive target redirect route from 'resource_class' param, which was set
# before authentication.
devise_mapping = get_devise_mapping
redirect_route = get_redirect_route(devise_mapping)
# preserve omniauth info for success route. ignore 'extra' in twitter
# auth response to avoid CookieOverflow.
session['dta.omniauth.auth'] = request.env['omniauth.auth'].except('extra')
session['dta.omniauth.params'] = request.env['omniauth.params']
redirect_to redirect_route
end
|
ruby
|
def redirect_callbacks
# derive target redirect route from 'resource_class' param, which was set
# before authentication.
devise_mapping = get_devise_mapping
redirect_route = get_redirect_route(devise_mapping)
# preserve omniauth info for success route. ignore 'extra' in twitter
# auth response to avoid CookieOverflow.
session['dta.omniauth.auth'] = request.env['omniauth.auth'].except('extra')
session['dta.omniauth.params'] = request.env['omniauth.params']
redirect_to redirect_route
end
|
[
"def",
"redirect_callbacks",
"# derive target redirect route from 'resource_class' param, which was set",
"# before authentication.",
"devise_mapping",
"=",
"get_devise_mapping",
"redirect_route",
"=",
"get_redirect_route",
"(",
"devise_mapping",
")",
"# preserve omniauth info for success route. ignore 'extra' in twitter",
"# auth response to avoid CookieOverflow.",
"session",
"[",
"'dta.omniauth.auth'",
"]",
"=",
"request",
".",
"env",
"[",
"'omniauth.auth'",
"]",
".",
"except",
"(",
"'extra'",
")",
"session",
"[",
"'dta.omniauth.params'",
"]",
"=",
"request",
".",
"env",
"[",
"'omniauth.params'",
"]",
"redirect_to",
"redirect_route",
"end"
] |
intermediary route for successful omniauth authentication. omniauth does
not support multiple models, so we must resort to this terrible hack.
|
[
"intermediary",
"route",
"for",
"successful",
"omniauth",
"authentication",
".",
"omniauth",
"does",
"not",
"support",
"multiple",
"models",
"so",
"we",
"must",
"resort",
"to",
"this",
"terrible",
"hack",
"."
] |
0727ac77e5d1cf8c065faa81ca6ddbba9cc0fe44
|
https://github.com/lynndylanhurley/devise_token_auth/blob/0727ac77e5d1cf8c065faa81ca6ddbba9cc0fe44/app/controllers/devise_token_auth/omniauth_callbacks_controller.rb#L11-L24
|
11,261
|
lynndylanhurley/devise_token_auth
|
app/controllers/devise_token_auth/omniauth_callbacks_controller.rb
|
DeviseTokenAuth.OmniauthCallbacksController.omniauth_params
|
def omniauth_params
unless defined?(@_omniauth_params)
if request.env['omniauth.params'] && request.env['omniauth.params'].any?
@_omniauth_params = request.env['omniauth.params']
elsif session['dta.omniauth.params'] && session['dta.omniauth.params'].any?
@_omniauth_params ||= session.delete('dta.omniauth.params')
@_omniauth_params
elsif params['omniauth_window_type']
@_omniauth_params = params.slice('omniauth_window_type', 'auth_origin_url', 'resource_class', 'origin')
else
@_omniauth_params = {}
end
end
@_omniauth_params
end
|
ruby
|
def omniauth_params
unless defined?(@_omniauth_params)
if request.env['omniauth.params'] && request.env['omniauth.params'].any?
@_omniauth_params = request.env['omniauth.params']
elsif session['dta.omniauth.params'] && session['dta.omniauth.params'].any?
@_omniauth_params ||= session.delete('dta.omniauth.params')
@_omniauth_params
elsif params['omniauth_window_type']
@_omniauth_params = params.slice('omniauth_window_type', 'auth_origin_url', 'resource_class', 'origin')
else
@_omniauth_params = {}
end
end
@_omniauth_params
end
|
[
"def",
"omniauth_params",
"unless",
"defined?",
"(",
"@_omniauth_params",
")",
"if",
"request",
".",
"env",
"[",
"'omniauth.params'",
"]",
"&&",
"request",
".",
"env",
"[",
"'omniauth.params'",
"]",
".",
"any?",
"@_omniauth_params",
"=",
"request",
".",
"env",
"[",
"'omniauth.params'",
"]",
"elsif",
"session",
"[",
"'dta.omniauth.params'",
"]",
"&&",
"session",
"[",
"'dta.omniauth.params'",
"]",
".",
"any?",
"@_omniauth_params",
"||=",
"session",
".",
"delete",
"(",
"'dta.omniauth.params'",
")",
"@_omniauth_params",
"elsif",
"params",
"[",
"'omniauth_window_type'",
"]",
"@_omniauth_params",
"=",
"params",
".",
"slice",
"(",
"'omniauth_window_type'",
",",
"'auth_origin_url'",
",",
"'resource_class'",
",",
"'origin'",
")",
"else",
"@_omniauth_params",
"=",
"{",
"}",
"end",
"end",
"@_omniauth_params",
"end"
] |
this will be determined differently depending on the action that calls
it. redirect_callbacks is called upon returning from successful omniauth
authentication, and the target params live in an omniauth-specific
request.env variable. this variable is then persisted thru the redirect
using our own dta.omniauth.params session var. the omniauth_success
method will access that session var and then destroy it immediately
after use. In the failure case, finally, the omniauth params
are added as query params in our monkey patch to OmniAuth in engine.rb
|
[
"this",
"will",
"be",
"determined",
"differently",
"depending",
"on",
"the",
"action",
"that",
"calls",
"it",
".",
"redirect_callbacks",
"is",
"called",
"upon",
"returning",
"from",
"successful",
"omniauth",
"authentication",
"and",
"the",
"target",
"params",
"live",
"in",
"an",
"omniauth",
"-",
"specific",
"request",
".",
"env",
"variable",
".",
"this",
"variable",
"is",
"then",
"persisted",
"thru",
"the",
"redirect",
"using",
"our",
"own",
"dta",
".",
"omniauth",
".",
"params",
"session",
"var",
".",
"the",
"omniauth_success",
"method",
"will",
"access",
"that",
"session",
"var",
"and",
"then",
"destroy",
"it",
"immediately",
"after",
"use",
".",
"In",
"the",
"failure",
"case",
"finally",
"the",
"omniauth",
"params",
"are",
"added",
"as",
"query",
"params",
"in",
"our",
"monkey",
"patch",
"to",
"OmniAuth",
"in",
"engine",
".",
"rb"
] |
0727ac77e5d1cf8c065faa81ca6ddbba9cc0fe44
|
https://github.com/lynndylanhurley/devise_token_auth/blob/0727ac77e5d1cf8c065faa81ca6ddbba9cc0fe44/app/controllers/devise_token_auth/omniauth_callbacks_controller.rb#L88-L103
|
11,262
|
lynndylanhurley/devise_token_auth
|
app/controllers/devise_token_auth/omniauth_callbacks_controller.rb
|
DeviseTokenAuth.OmniauthCallbacksController.assign_provider_attrs
|
def assign_provider_attrs(user, auth_hash)
attrs = auth_hash['info'].slice(*user.attribute_names)
user.assign_attributes(attrs)
end
|
ruby
|
def assign_provider_attrs(user, auth_hash)
attrs = auth_hash['info'].slice(*user.attribute_names)
user.assign_attributes(attrs)
end
|
[
"def",
"assign_provider_attrs",
"(",
"user",
",",
"auth_hash",
")",
"attrs",
"=",
"auth_hash",
"[",
"'info'",
"]",
".",
"slice",
"(",
"user",
".",
"attribute_names",
")",
"user",
".",
"assign_attributes",
"(",
"attrs",
")",
"end"
] |
break out provider attribute assignment for easy method extension
|
[
"break",
"out",
"provider",
"attribute",
"assignment",
"for",
"easy",
"method",
"extension"
] |
0727ac77e5d1cf8c065faa81ca6ddbba9cc0fe44
|
https://github.com/lynndylanhurley/devise_token_auth/blob/0727ac77e5d1cf8c065faa81ca6ddbba9cc0fe44/app/controllers/devise_token_auth/omniauth_callbacks_controller.rb#L106-L109
|
11,263
|
lynndylanhurley/devise_token_auth
|
app/controllers/devise_token_auth/omniauth_callbacks_controller.rb
|
DeviseTokenAuth.OmniauthCallbacksController.whitelisted_params
|
def whitelisted_params
whitelist = params_for_resource(:sign_up)
whitelist.inject({}) do |coll, key|
param = omniauth_params[key.to_s]
coll[key] = param if param
coll
end
end
|
ruby
|
def whitelisted_params
whitelist = params_for_resource(:sign_up)
whitelist.inject({}) do |coll, key|
param = omniauth_params[key.to_s]
coll[key] = param if param
coll
end
end
|
[
"def",
"whitelisted_params",
"whitelist",
"=",
"params_for_resource",
"(",
":sign_up",
")",
"whitelist",
".",
"inject",
"(",
"{",
"}",
")",
"do",
"|",
"coll",
",",
"key",
"|",
"param",
"=",
"omniauth_params",
"[",
"key",
".",
"to_s",
"]",
"coll",
"[",
"key",
"]",
"=",
"param",
"if",
"param",
"coll",
"end",
"end"
] |
derive allowed params from the standard devise parameter sanitizer
|
[
"derive",
"allowed",
"params",
"from",
"the",
"standard",
"devise",
"parameter",
"sanitizer"
] |
0727ac77e5d1cf8c065faa81ca6ddbba9cc0fe44
|
https://github.com/lynndylanhurley/devise_token_auth/blob/0727ac77e5d1cf8c065faa81ca6ddbba9cc0fe44/app/controllers/devise_token_auth/omniauth_callbacks_controller.rb#L112-L120
|
11,264
|
danger/danger
|
lib/danger/ci_source/teamcity.rb
|
Danger.TeamCity.bitbucket_pr_from_env
|
def bitbucket_pr_from_env(env)
branch_name = env["BITBUCKET_BRANCH_NAME"]
repo_slug = env["BITBUCKET_REPO_SLUG"]
begin
Danger::RequestSources::BitbucketCloudAPI.new(repo_slug, nil, branch_name, env).pull_request_id
rescue
raise "Failed to find a pull request for branch \"#{branch_name}\" on Bitbucket."
end
end
|
ruby
|
def bitbucket_pr_from_env(env)
branch_name = env["BITBUCKET_BRANCH_NAME"]
repo_slug = env["BITBUCKET_REPO_SLUG"]
begin
Danger::RequestSources::BitbucketCloudAPI.new(repo_slug, nil, branch_name, env).pull_request_id
rescue
raise "Failed to find a pull request for branch \"#{branch_name}\" on Bitbucket."
end
end
|
[
"def",
"bitbucket_pr_from_env",
"(",
"env",
")",
"branch_name",
"=",
"env",
"[",
"\"BITBUCKET_BRANCH_NAME\"",
"]",
"repo_slug",
"=",
"env",
"[",
"\"BITBUCKET_REPO_SLUG\"",
"]",
"begin",
"Danger",
"::",
"RequestSources",
"::",
"BitbucketCloudAPI",
".",
"new",
"(",
"repo_slug",
",",
"nil",
",",
"branch_name",
",",
"env",
")",
".",
"pull_request_id",
"rescue",
"raise",
"\"Failed to find a pull request for branch \\\"#{branch_name}\\\" on Bitbucket.\"",
"end",
"end"
] |
This is a little hacky, because Bitbucket doesn't provide us a PR id
|
[
"This",
"is",
"a",
"little",
"hacky",
"because",
"Bitbucket",
"doesn",
"t",
"provide",
"us",
"a",
"PR",
"id"
] |
0d6d09f2d949c287fe75202d947374042b0679f4
|
https://github.com/danger/danger/blob/0d6d09f2d949c287fe75202d947374042b0679f4/lib/danger/ci_source/teamcity.rb#L149-L157
|
11,265
|
danger/danger
|
lib/danger/plugin_support/gems_resolver.rb
|
Danger.GemsResolver.paths
|
def paths
relative_paths = gem_names.flat_map do |plugin|
Dir.glob("vendor/gems/ruby/*/gems/#{plugin}*/lib/**/**/**/**.rb")
end
relative_paths.map { |path| File.join(dir, path) }
end
|
ruby
|
def paths
relative_paths = gem_names.flat_map do |plugin|
Dir.glob("vendor/gems/ruby/*/gems/#{plugin}*/lib/**/**/**/**.rb")
end
relative_paths.map { |path| File.join(dir, path) }
end
|
[
"def",
"paths",
"relative_paths",
"=",
"gem_names",
".",
"flat_map",
"do",
"|",
"plugin",
"|",
"Dir",
".",
"glob",
"(",
"\"vendor/gems/ruby/*/gems/#{plugin}*/lib/**/**/**/**.rb\"",
")",
"end",
"relative_paths",
".",
"map",
"{",
"|",
"path",
"|",
"File",
".",
"join",
"(",
"dir",
",",
"path",
")",
"}",
"end"
] |
The paths are relative to dir.
|
[
"The",
"paths",
"are",
"relative",
"to",
"dir",
"."
] |
0d6d09f2d949c287fe75202d947374042b0679f4
|
https://github.com/danger/danger/blob/0d6d09f2d949c287fe75202d947374042b0679f4/lib/danger/plugin_support/gems_resolver.rb#L45-L51
|
11,266
|
danger/danger
|
lib/danger/danger_core/executor.rb
|
Danger.Executor.validate_pr!
|
def validate_pr!(cork, fail_if_no_pr)
unless EnvironmentManager.pr?(system_env)
ci_name = EnvironmentManager.local_ci_source(system_env).name.split("::").last
msg = "Not a #{ci_name} Pull Request - skipping `danger` run. "
# circle won't run danger properly if the commit is pushed and build runs before the PR exists
# https://danger.systems/guides/troubleshooting.html#circle-ci-doesnt-run-my-build-consistently
# the best solution is to enable `fail_if_no_pr`, and then re-run the job once the PR is up
if ci_name == "CircleCI"
msg << "If you only created the PR recently, try re-running your workflow."
end
cork.puts msg.strip.yellow
exit(fail_if_no_pr ? 1 : 0)
end
end
|
ruby
|
def validate_pr!(cork, fail_if_no_pr)
unless EnvironmentManager.pr?(system_env)
ci_name = EnvironmentManager.local_ci_source(system_env).name.split("::").last
msg = "Not a #{ci_name} Pull Request - skipping `danger` run. "
# circle won't run danger properly if the commit is pushed and build runs before the PR exists
# https://danger.systems/guides/troubleshooting.html#circle-ci-doesnt-run-my-build-consistently
# the best solution is to enable `fail_if_no_pr`, and then re-run the job once the PR is up
if ci_name == "CircleCI"
msg << "If you only created the PR recently, try re-running your workflow."
end
cork.puts msg.strip.yellow
exit(fail_if_no_pr ? 1 : 0)
end
end
|
[
"def",
"validate_pr!",
"(",
"cork",
",",
"fail_if_no_pr",
")",
"unless",
"EnvironmentManager",
".",
"pr?",
"(",
"system_env",
")",
"ci_name",
"=",
"EnvironmentManager",
".",
"local_ci_source",
"(",
"system_env",
")",
".",
"name",
".",
"split",
"(",
"\"::\"",
")",
".",
"last",
"msg",
"=",
"\"Not a #{ci_name} Pull Request - skipping `danger` run. \"",
"# circle won't run danger properly if the commit is pushed and build runs before the PR exists",
"# https://danger.systems/guides/troubleshooting.html#circle-ci-doesnt-run-my-build-consistently",
"# the best solution is to enable `fail_if_no_pr`, and then re-run the job once the PR is up",
"if",
"ci_name",
"==",
"\"CircleCI\"",
"msg",
"<<",
"\"If you only created the PR recently, try re-running your workflow.\"",
"end",
"cork",
".",
"puts",
"msg",
".",
"strip",
".",
"yellow",
"exit",
"(",
"fail_if_no_pr",
"?",
"1",
":",
"0",
")",
"end",
"end"
] |
Could we determine that the CI source is inside a PR?
|
[
"Could",
"we",
"determine",
"that",
"the",
"CI",
"source",
"is",
"inside",
"a",
"PR?"
] |
0d6d09f2d949c287fe75202d947374042b0679f4
|
https://github.com/danger/danger/blob/0d6d09f2d949c287fe75202d947374042b0679f4/lib/danger/danger_core/executor.rb#L62-L77
|
11,267
|
danger/danger
|
lib/danger/plugin_support/plugin_linter.rb
|
Danger.PluginLinter.print_summary
|
def print_summary(ui)
# Print whether it passed/failed at the top
if failed?
ui.puts "\n[!] Failed\n".red
else
ui.notice "Passed"
end
# A generic proc to handle the similarities between
# errors and warnings.
do_rules = proc do |name, rules|
unless rules.empty?
ui.puts ""
ui.section(name.bold) do
rules.each do |rule|
title = rule.title.bold + " - #{rule.object_applied_to}"
subtitles = [rule.description, link(rule.ref)]
subtitles += [rule.metadata[:files].join(":")] if rule.metadata[:files]
ui.labeled(title, subtitles)
ui.puts ""
end
end
end
end
# Run the rules
do_rules.call("Errors".red, errors)
do_rules.call("Warnings".yellow, warnings)
end
|
ruby
|
def print_summary(ui)
# Print whether it passed/failed at the top
if failed?
ui.puts "\n[!] Failed\n".red
else
ui.notice "Passed"
end
# A generic proc to handle the similarities between
# errors and warnings.
do_rules = proc do |name, rules|
unless rules.empty?
ui.puts ""
ui.section(name.bold) do
rules.each do |rule|
title = rule.title.bold + " - #{rule.object_applied_to}"
subtitles = [rule.description, link(rule.ref)]
subtitles += [rule.metadata[:files].join(":")] if rule.metadata[:files]
ui.labeled(title, subtitles)
ui.puts ""
end
end
end
end
# Run the rules
do_rules.call("Errors".red, errors)
do_rules.call("Warnings".yellow, warnings)
end
|
[
"def",
"print_summary",
"(",
"ui",
")",
"# Print whether it passed/failed at the top",
"if",
"failed?",
"ui",
".",
"puts",
"\"\\n[!] Failed\\n\"",
".",
"red",
"else",
"ui",
".",
"notice",
"\"Passed\"",
"end",
"# A generic proc to handle the similarities between",
"# errors and warnings.",
"do_rules",
"=",
"proc",
"do",
"|",
"name",
",",
"rules",
"|",
"unless",
"rules",
".",
"empty?",
"ui",
".",
"puts",
"\"\"",
"ui",
".",
"section",
"(",
"name",
".",
"bold",
")",
"do",
"rules",
".",
"each",
"do",
"|",
"rule",
"|",
"title",
"=",
"rule",
".",
"title",
".",
"bold",
"+",
"\" - #{rule.object_applied_to}\"",
"subtitles",
"=",
"[",
"rule",
".",
"description",
",",
"link",
"(",
"rule",
".",
"ref",
")",
"]",
"subtitles",
"+=",
"[",
"rule",
".",
"metadata",
"[",
":files",
"]",
".",
"join",
"(",
"\":\"",
")",
"]",
"if",
"rule",
".",
"metadata",
"[",
":files",
"]",
"ui",
".",
"labeled",
"(",
"title",
",",
"subtitles",
")",
"ui",
".",
"puts",
"\"\"",
"end",
"end",
"end",
"end",
"# Run the rules",
"do_rules",
".",
"call",
"(",
"\"Errors\"",
".",
"red",
",",
"errors",
")",
"do_rules",
".",
"call",
"(",
"\"Warnings\"",
".",
"yellow",
",",
"warnings",
")",
"end"
] |
Prints a summary of the errors and warnings.
|
[
"Prints",
"a",
"summary",
"of",
"the",
"errors",
"and",
"warnings",
"."
] |
0d6d09f2d949c287fe75202d947374042b0679f4
|
https://github.com/danger/danger/blob/0d6d09f2d949c287fe75202d947374042b0679f4/lib/danger/plugin_support/plugin_linter.rb#L59-L87
|
11,268
|
danger/danger
|
lib/danger/plugin_support/plugin_linter.rb
|
Danger.PluginLinter.class_rules
|
def class_rules
[
Rule.new(:error, 4..6, "Description Markdown", "Above your class you need documentation that covers the scope, and the usage of your plugin.", proc do |json|
json[:body_md] && json[:body_md].empty?
end),
Rule.new(:warning, 30, "Tags", "This plugin does not include `@tags tag1, tag2` and thus will be harder to find in search.", proc do |json|
json[:tags] && json[:tags].empty?
end),
Rule.new(:warning, 29, "References", "Ideally, you have a reference implementation of your plugin that you can show to people, add `@see org/repo` to have the site auto link it.", proc do |json|
json[:see] && json[:see].empty?
end),
Rule.new(:error, 8..27, "Examples", "You should include some examples of common use-cases for your plugin.", proc do |json|
json[:example_code] && json[:example_code].empty?
end)
]
end
|
ruby
|
def class_rules
[
Rule.new(:error, 4..6, "Description Markdown", "Above your class you need documentation that covers the scope, and the usage of your plugin.", proc do |json|
json[:body_md] && json[:body_md].empty?
end),
Rule.new(:warning, 30, "Tags", "This plugin does not include `@tags tag1, tag2` and thus will be harder to find in search.", proc do |json|
json[:tags] && json[:tags].empty?
end),
Rule.new(:warning, 29, "References", "Ideally, you have a reference implementation of your plugin that you can show to people, add `@see org/repo` to have the site auto link it.", proc do |json|
json[:see] && json[:see].empty?
end),
Rule.new(:error, 8..27, "Examples", "You should include some examples of common use-cases for your plugin.", proc do |json|
json[:example_code] && json[:example_code].empty?
end)
]
end
|
[
"def",
"class_rules",
"[",
"Rule",
".",
"new",
"(",
":error",
",",
"4",
"..",
"6",
",",
"\"Description Markdown\"",
",",
"\"Above your class you need documentation that covers the scope, and the usage of your plugin.\"",
",",
"proc",
"do",
"|",
"json",
"|",
"json",
"[",
":body_md",
"]",
"&&",
"json",
"[",
":body_md",
"]",
".",
"empty?",
"end",
")",
",",
"Rule",
".",
"new",
"(",
":warning",
",",
"30",
",",
"\"Tags\"",
",",
"\"This plugin does not include `@tags tag1, tag2` and thus will be harder to find in search.\"",
",",
"proc",
"do",
"|",
"json",
"|",
"json",
"[",
":tags",
"]",
"&&",
"json",
"[",
":tags",
"]",
".",
"empty?",
"end",
")",
",",
"Rule",
".",
"new",
"(",
":warning",
",",
"29",
",",
"\"References\"",
",",
"\"Ideally, you have a reference implementation of your plugin that you can show to people, add `@see org/repo` to have the site auto link it.\"",
",",
"proc",
"do",
"|",
"json",
"|",
"json",
"[",
":see",
"]",
"&&",
"json",
"[",
":see",
"]",
".",
"empty?",
"end",
")",
",",
"Rule",
".",
"new",
"(",
":error",
",",
"8",
"..",
"27",
",",
"\"Examples\"",
",",
"\"You should include some examples of common use-cases for your plugin.\"",
",",
"proc",
"do",
"|",
"json",
"|",
"json",
"[",
":example_code",
"]",
"&&",
"json",
"[",
":example_code",
"]",
".",
"empty?",
"end",
")",
"]",
"end"
] |
Rules that apply to a class
|
[
"Rules",
"that",
"apply",
"to",
"a",
"class"
] |
0d6d09f2d949c287fe75202d947374042b0679f4
|
https://github.com/danger/danger/blob/0d6d09f2d949c287fe75202d947374042b0679f4/lib/danger/plugin_support/plugin_linter.rb#L93-L108
|
11,269
|
danger/danger
|
lib/danger/plugin_support/plugin_linter.rb
|
Danger.PluginLinter.method_rules
|
def method_rules
[
Rule.new(:error, 40..41, "Description", "You should include a description for your method.", proc do |json|
json[:body_md] && json[:body_md].empty?
end),
Rule.new(:warning, 43..45, "Params", "You should give a 'type' for the param, yes, ruby is duck-typey but it's useful for newbies to the language, use `@param [Type] name`.", proc do |json|
json[:param_couplets] && json[:param_couplets].flat_map(&:values).include?(nil)
end),
Rule.new(:warning, 43..45, "Unknown Param", "You should give a 'type' for the param, yes, ruby is duck-typey but it's useful for newbies to the language, use `@param [Type] name`.", proc do |json|
json[:param_couplets] && json[:param_couplets].flat_map(&:values).include?("Unknown")
end),
Rule.new(:warning, 46, "Return Type", "If the function has no useful return value, use ` @return [void]` - this will be ignored by documentation generators.", proc do |json|
return_hash = json[:tags].find { |tag| tag[:name] == "return" }
!(return_hash && return_hash[:types] && !return_hash[:types].first.empty?)
end)
]
end
|
ruby
|
def method_rules
[
Rule.new(:error, 40..41, "Description", "You should include a description for your method.", proc do |json|
json[:body_md] && json[:body_md].empty?
end),
Rule.new(:warning, 43..45, "Params", "You should give a 'type' for the param, yes, ruby is duck-typey but it's useful for newbies to the language, use `@param [Type] name`.", proc do |json|
json[:param_couplets] && json[:param_couplets].flat_map(&:values).include?(nil)
end),
Rule.new(:warning, 43..45, "Unknown Param", "You should give a 'type' for the param, yes, ruby is duck-typey but it's useful for newbies to the language, use `@param [Type] name`.", proc do |json|
json[:param_couplets] && json[:param_couplets].flat_map(&:values).include?("Unknown")
end),
Rule.new(:warning, 46, "Return Type", "If the function has no useful return value, use ` @return [void]` - this will be ignored by documentation generators.", proc do |json|
return_hash = json[:tags].find { |tag| tag[:name] == "return" }
!(return_hash && return_hash[:types] && !return_hash[:types].first.empty?)
end)
]
end
|
[
"def",
"method_rules",
"[",
"Rule",
".",
"new",
"(",
":error",
",",
"40",
"..",
"41",
",",
"\"Description\"",
",",
"\"You should include a description for your method.\"",
",",
"proc",
"do",
"|",
"json",
"|",
"json",
"[",
":body_md",
"]",
"&&",
"json",
"[",
":body_md",
"]",
".",
"empty?",
"end",
")",
",",
"Rule",
".",
"new",
"(",
":warning",
",",
"43",
"..",
"45",
",",
"\"Params\"",
",",
"\"You should give a 'type' for the param, yes, ruby is duck-typey but it's useful for newbies to the language, use `@param [Type] name`.\"",
",",
"proc",
"do",
"|",
"json",
"|",
"json",
"[",
":param_couplets",
"]",
"&&",
"json",
"[",
":param_couplets",
"]",
".",
"flat_map",
"(",
":values",
")",
".",
"include?",
"(",
"nil",
")",
"end",
")",
",",
"Rule",
".",
"new",
"(",
":warning",
",",
"43",
"..",
"45",
",",
"\"Unknown Param\"",
",",
"\"You should give a 'type' for the param, yes, ruby is duck-typey but it's useful for newbies to the language, use `@param [Type] name`.\"",
",",
"proc",
"do",
"|",
"json",
"|",
"json",
"[",
":param_couplets",
"]",
"&&",
"json",
"[",
":param_couplets",
"]",
".",
"flat_map",
"(",
":values",
")",
".",
"include?",
"(",
"\"Unknown\"",
")",
"end",
")",
",",
"Rule",
".",
"new",
"(",
":warning",
",",
"46",
",",
"\"Return Type\"",
",",
"\"If the function has no useful return value, use ` @return [void]` - this will be ignored by documentation generators.\"",
",",
"proc",
"do",
"|",
"json",
"|",
"return_hash",
"=",
"json",
"[",
":tags",
"]",
".",
"find",
"{",
"|",
"tag",
"|",
"tag",
"[",
":name",
"]",
"==",
"\"return\"",
"}",
"!",
"(",
"return_hash",
"&&",
"return_hash",
"[",
":types",
"]",
"&&",
"!",
"return_hash",
"[",
":types",
"]",
".",
"first",
".",
"empty?",
")",
"end",
")",
"]",
"end"
] |
Rules that apply to individual methods, and attributes
|
[
"Rules",
"that",
"apply",
"to",
"individual",
"methods",
"and",
"attributes"
] |
0d6d09f2d949c287fe75202d947374042b0679f4
|
https://github.com/danger/danger/blob/0d6d09f2d949c287fe75202d947374042b0679f4/lib/danger/plugin_support/plugin_linter.rb#L112-L128
|
11,270
|
danger/danger
|
lib/danger/plugin_support/plugin_linter.rb
|
Danger.PluginLinter.link
|
def link(ref)
if ref.kind_of?(Range)
"@see - " + "https://github.com/dbgrandi/danger-prose/blob/v2.0.0/lib/danger_plugin.rb#L#{ref.min}#-L#{ref.max}".blue
elsif ref.kind_of?(Integer)
"@see - " + "https://github.com/dbgrandi/danger-prose/blob/v2.0.0/lib/danger_plugin.rb#L#{ref}".blue
else
"@see - " + "https://github.com/dbgrandi/danger-prose/blob/v2.0.0/lib/danger_plugin.rb".blue
end
end
|
ruby
|
def link(ref)
if ref.kind_of?(Range)
"@see - " + "https://github.com/dbgrandi/danger-prose/blob/v2.0.0/lib/danger_plugin.rb#L#{ref.min}#-L#{ref.max}".blue
elsif ref.kind_of?(Integer)
"@see - " + "https://github.com/dbgrandi/danger-prose/blob/v2.0.0/lib/danger_plugin.rb#L#{ref}".blue
else
"@see - " + "https://github.com/dbgrandi/danger-prose/blob/v2.0.0/lib/danger_plugin.rb".blue
end
end
|
[
"def",
"link",
"(",
"ref",
")",
"if",
"ref",
".",
"kind_of?",
"(",
"Range",
")",
"\"@see - \"",
"+",
"\"https://github.com/dbgrandi/danger-prose/blob/v2.0.0/lib/danger_plugin.rb#L#{ref.min}#-L#{ref.max}\"",
".",
"blue",
"elsif",
"ref",
".",
"kind_of?",
"(",
"Integer",
")",
"\"@see - \"",
"+",
"\"https://github.com/dbgrandi/danger-prose/blob/v2.0.0/lib/danger_plugin.rb#L#{ref}\"",
".",
"blue",
"else",
"\"@see - \"",
"+",
"\"https://github.com/dbgrandi/danger-prose/blob/v2.0.0/lib/danger_plugin.rb\"",
".",
"blue",
"end",
"end"
] |
Generates a link to see an example of said rule
|
[
"Generates",
"a",
"link",
"to",
"see",
"an",
"example",
"of",
"said",
"rule"
] |
0d6d09f2d949c287fe75202d947374042b0679f4
|
https://github.com/danger/danger/blob/0d6d09f2d949c287fe75202d947374042b0679f4/lib/danger/plugin_support/plugin_linter.rb#L132-L140
|
11,271
|
danger/danger
|
lib/danger/plugin_support/plugin_file_resolver.rb
|
Danger.PluginFileResolver.resolve
|
def resolve
if !refs.nil? and refs.select { |ref| File.file? ref }.any?
paths = refs.select { |ref| File.file? ref }.map { |path| File.expand_path(path) }
elsif refs and refs.kind_of? Array
paths, gems = GemsResolver.new(refs).call
else
paths = Dir.glob(File.join(".", "lib/**/*.rb")).map { |path| File.expand_path(path) }
end
{ paths: paths, gems: gems || [] }
end
|
ruby
|
def resolve
if !refs.nil? and refs.select { |ref| File.file? ref }.any?
paths = refs.select { |ref| File.file? ref }.map { |path| File.expand_path(path) }
elsif refs and refs.kind_of? Array
paths, gems = GemsResolver.new(refs).call
else
paths = Dir.glob(File.join(".", "lib/**/*.rb")).map { |path| File.expand_path(path) }
end
{ paths: paths, gems: gems || [] }
end
|
[
"def",
"resolve",
"if",
"!",
"refs",
".",
"nil?",
"and",
"refs",
".",
"select",
"{",
"|",
"ref",
"|",
"File",
".",
"file?",
"ref",
"}",
".",
"any?",
"paths",
"=",
"refs",
".",
"select",
"{",
"|",
"ref",
"|",
"File",
".",
"file?",
"ref",
"}",
".",
"map",
"{",
"|",
"path",
"|",
"File",
".",
"expand_path",
"(",
"path",
")",
"}",
"elsif",
"refs",
"and",
"refs",
".",
"kind_of?",
"Array",
"paths",
",",
"gems",
"=",
"GemsResolver",
".",
"new",
"(",
"refs",
")",
".",
"call",
"else",
"paths",
"=",
"Dir",
".",
"glob",
"(",
"File",
".",
"join",
"(",
"\".\"",
",",
"\"lib/**/*.rb\"",
")",
")",
".",
"map",
"{",
"|",
"path",
"|",
"File",
".",
"expand_path",
"(",
"path",
")",
"}",
"end",
"{",
"paths",
":",
"paths",
",",
"gems",
":",
"gems",
"||",
"[",
"]",
"}",
"end"
] |
Takes an array of files, gems or nothing, then resolves them into
paths that should be sent into the documentation parser
When given existing paths, map to absolute & existing paths
When given a list of gems, resolve for list of gems
When empty, imply you want to test the current lib folder as a plugin
|
[
"Takes",
"an",
"array",
"of",
"files",
"gems",
"or",
"nothing",
"then",
"resolves",
"them",
"into",
"paths",
"that",
"should",
"be",
"sent",
"into",
"the",
"documentation",
"parser",
"When",
"given",
"existing",
"paths",
"map",
"to",
"absolute",
"&",
"existing",
"paths",
"When",
"given",
"a",
"list",
"of",
"gems",
"resolve",
"for",
"list",
"of",
"gems",
"When",
"empty",
"imply",
"you",
"want",
"to",
"test",
"the",
"current",
"lib",
"folder",
"as",
"a",
"plugin"
] |
0d6d09f2d949c287fe75202d947374042b0679f4
|
https://github.com/danger/danger/blob/0d6d09f2d949c287fe75202d947374042b0679f4/lib/danger/plugin_support/plugin_file_resolver.rb#L14-L24
|
11,272
|
danger/danger
|
lib/danger/ci_source/circle_api.rb
|
Danger.CircleAPI.pull_request_url
|
def pull_request_url(env)
url = env["CI_PULL_REQUEST"]
if url.nil? && !env["CIRCLE_PROJECT_USERNAME"].nil? && !env["CIRCLE_PROJECT_REPONAME"].nil?
repo_slug = env["CIRCLE_PROJECT_USERNAME"] + "/" + env["CIRCLE_PROJECT_REPONAME"]
if !env["CIRCLE_PR_NUMBER"].nil?
host = env["DANGER_GITHUB_HOST"] || "github.com"
url = "https://" + host + "/" + repo_slug + "/pull/" + env["CIRCLE_PR_NUMBER"]
else
token = env["DANGER_CIRCLE_CI_API_TOKEN"]
url = fetch_pull_request_url(repo_slug, env["CIRCLE_BUILD_NUM"], token)
end
end
url
end
|
ruby
|
def pull_request_url(env)
url = env["CI_PULL_REQUEST"]
if url.nil? && !env["CIRCLE_PROJECT_USERNAME"].nil? && !env["CIRCLE_PROJECT_REPONAME"].nil?
repo_slug = env["CIRCLE_PROJECT_USERNAME"] + "/" + env["CIRCLE_PROJECT_REPONAME"]
if !env["CIRCLE_PR_NUMBER"].nil?
host = env["DANGER_GITHUB_HOST"] || "github.com"
url = "https://" + host + "/" + repo_slug + "/pull/" + env["CIRCLE_PR_NUMBER"]
else
token = env["DANGER_CIRCLE_CI_API_TOKEN"]
url = fetch_pull_request_url(repo_slug, env["CIRCLE_BUILD_NUM"], token)
end
end
url
end
|
[
"def",
"pull_request_url",
"(",
"env",
")",
"url",
"=",
"env",
"[",
"\"CI_PULL_REQUEST\"",
"]",
"if",
"url",
".",
"nil?",
"&&",
"!",
"env",
"[",
"\"CIRCLE_PROJECT_USERNAME\"",
"]",
".",
"nil?",
"&&",
"!",
"env",
"[",
"\"CIRCLE_PROJECT_REPONAME\"",
"]",
".",
"nil?",
"repo_slug",
"=",
"env",
"[",
"\"CIRCLE_PROJECT_USERNAME\"",
"]",
"+",
"\"/\"",
"+",
"env",
"[",
"\"CIRCLE_PROJECT_REPONAME\"",
"]",
"if",
"!",
"env",
"[",
"\"CIRCLE_PR_NUMBER\"",
"]",
".",
"nil?",
"host",
"=",
"env",
"[",
"\"DANGER_GITHUB_HOST\"",
"]",
"||",
"\"github.com\"",
"url",
"=",
"\"https://\"",
"+",
"host",
"+",
"\"/\"",
"+",
"repo_slug",
"+",
"\"/pull/\"",
"+",
"env",
"[",
"\"CIRCLE_PR_NUMBER\"",
"]",
"else",
"token",
"=",
"env",
"[",
"\"DANGER_CIRCLE_CI_API_TOKEN\"",
"]",
"url",
"=",
"fetch_pull_request_url",
"(",
"repo_slug",
",",
"env",
"[",
"\"CIRCLE_BUILD_NUM\"",
"]",
",",
"token",
")",
"end",
"end",
"url",
"end"
] |
Determine if there's a PR attached to this commit,
and return the url if so
|
[
"Determine",
"if",
"there",
"s",
"a",
"PR",
"attached",
"to",
"this",
"commit",
"and",
"return",
"the",
"url",
"if",
"so"
] |
0d6d09f2d949c287fe75202d947374042b0679f4
|
https://github.com/danger/danger/blob/0d6d09f2d949c287fe75202d947374042b0679f4/lib/danger/ci_source/circle_api.rb#L14-L28
|
11,273
|
danger/danger
|
lib/danger/ci_source/circle_api.rb
|
Danger.CircleAPI.fetch_pull_request_url
|
def fetch_pull_request_url(repo_slug, build_number, token)
build_json = fetch_build(repo_slug, build_number, token)
pull_requests = build_json[:pull_requests]
return nil unless pull_requests.first
pull_requests.first[:url]
end
|
ruby
|
def fetch_pull_request_url(repo_slug, build_number, token)
build_json = fetch_build(repo_slug, build_number, token)
pull_requests = build_json[:pull_requests]
return nil unless pull_requests.first
pull_requests.first[:url]
end
|
[
"def",
"fetch_pull_request_url",
"(",
"repo_slug",
",",
"build_number",
",",
"token",
")",
"build_json",
"=",
"fetch_build",
"(",
"repo_slug",
",",
"build_number",
",",
"token",
")",
"pull_requests",
"=",
"build_json",
"[",
":pull_requests",
"]",
"return",
"nil",
"unless",
"pull_requests",
".",
"first",
"pull_requests",
".",
"first",
"[",
":url",
"]",
"end"
] |
Ask the API if the commit is inside a PR
|
[
"Ask",
"the",
"API",
"if",
"the",
"commit",
"is",
"inside",
"a",
"PR"
] |
0d6d09f2d949c287fe75202d947374042b0679f4
|
https://github.com/danger/danger/blob/0d6d09f2d949c287fe75202d947374042b0679f4/lib/danger/ci_source/circle_api.rb#L35-L40
|
11,274
|
danger/danger
|
lib/danger/ci_source/circle_api.rb
|
Danger.CircleAPI.fetch_build
|
def fetch_build(repo_slug, build_number, token)
url = "project/#{repo_slug}/#{build_number}"
params = { "circle-token" => token }
response = client.get url, params, accept: "application/json"
json = JSON.parse(response.body, symbolize_names: true)
json
end
|
ruby
|
def fetch_build(repo_slug, build_number, token)
url = "project/#{repo_slug}/#{build_number}"
params = { "circle-token" => token }
response = client.get url, params, accept: "application/json"
json = JSON.parse(response.body, symbolize_names: true)
json
end
|
[
"def",
"fetch_build",
"(",
"repo_slug",
",",
"build_number",
",",
"token",
")",
"url",
"=",
"\"project/#{repo_slug}/#{build_number}\"",
"params",
"=",
"{",
"\"circle-token\"",
"=>",
"token",
"}",
"response",
"=",
"client",
".",
"get",
"url",
",",
"params",
",",
"accept",
":",
"\"application/json\"",
"json",
"=",
"JSON",
".",
"parse",
"(",
"response",
".",
"body",
",",
"symbolize_names",
":",
"true",
")",
"json",
"end"
] |
Make the API call, and parse the JSON
|
[
"Make",
"the",
"API",
"call",
"and",
"parse",
"the",
"JSON"
] |
0d6d09f2d949c287fe75202d947374042b0679f4
|
https://github.com/danger/danger/blob/0d6d09f2d949c287fe75202d947374042b0679f4/lib/danger/ci_source/circle_api.rb#L43-L49
|
11,275
|
danger/danger
|
lib/danger/danger_core/plugins/dangerfile_danger_plugin.rb
|
Danger.DangerfileDangerPlugin.validate_file_contains_plugin!
|
def validate_file_contains_plugin!(file)
plugin_count_was = Danger::Plugin.all_plugins.length
yield
if Danger::Plugin.all_plugins.length == plugin_count_was
raise("#{file} doesn't contain any valid danger plugins.")
end
end
|
ruby
|
def validate_file_contains_plugin!(file)
plugin_count_was = Danger::Plugin.all_plugins.length
yield
if Danger::Plugin.all_plugins.length == plugin_count_was
raise("#{file} doesn't contain any valid danger plugins.")
end
end
|
[
"def",
"validate_file_contains_plugin!",
"(",
"file",
")",
"plugin_count_was",
"=",
"Danger",
"::",
"Plugin",
".",
"all_plugins",
".",
"length",
"yield",
"if",
"Danger",
"::",
"Plugin",
".",
"all_plugins",
".",
"length",
"==",
"plugin_count_was",
"raise",
"(",
"\"#{file} doesn't contain any valid danger plugins.\"",
")",
"end",
"end"
] |
Raises an error when the given block does not register a plugin.
|
[
"Raises",
"an",
"error",
"when",
"the",
"given",
"block",
"does",
"not",
"register",
"a",
"plugin",
"."
] |
0d6d09f2d949c287fe75202d947374042b0679f4
|
https://github.com/danger/danger/blob/0d6d09f2d949c287fe75202d947374042b0679f4/lib/danger/danger_core/plugins/dangerfile_danger_plugin.rb#L220-L227
|
11,276
|
danger/danger
|
lib/danger/danger_core/dangerfile.rb
|
Danger.Dangerfile.print_known_info
|
def print_known_info
rows = []
rows += method_values_for_plugin_hashes(core_dsl_attributes)
rows << ["---", "---"]
rows += method_values_for_plugin_hashes(external_dsl_attributes)
rows << ["---", "---"]
rows << ["SCM", env.scm.class]
rows << ["Source", env.ci_source.class]
rows << ["Requests", env.request_source.class]
rows << ["Base Commit", env.meta_info_for_base]
rows << ["Head Commit", env.meta_info_for_head]
params = {}
params[:rows] = rows.each { |current| current[0] = current[0].yellow }
params[:title] = "Danger v#{Danger::VERSION}\nDSL Attributes".green
ui.section("Info:") do
ui.puts
table = Terminal::Table.new(params)
table.align_column(0, :right)
ui.puts table
ui.puts
end
end
|
ruby
|
def print_known_info
rows = []
rows += method_values_for_plugin_hashes(core_dsl_attributes)
rows << ["---", "---"]
rows += method_values_for_plugin_hashes(external_dsl_attributes)
rows << ["---", "---"]
rows << ["SCM", env.scm.class]
rows << ["Source", env.ci_source.class]
rows << ["Requests", env.request_source.class]
rows << ["Base Commit", env.meta_info_for_base]
rows << ["Head Commit", env.meta_info_for_head]
params = {}
params[:rows] = rows.each { |current| current[0] = current[0].yellow }
params[:title] = "Danger v#{Danger::VERSION}\nDSL Attributes".green
ui.section("Info:") do
ui.puts
table = Terminal::Table.new(params)
table.align_column(0, :right)
ui.puts table
ui.puts
end
end
|
[
"def",
"print_known_info",
"rows",
"=",
"[",
"]",
"rows",
"+=",
"method_values_for_plugin_hashes",
"(",
"core_dsl_attributes",
")",
"rows",
"<<",
"[",
"\"---\"",
",",
"\"---\"",
"]",
"rows",
"+=",
"method_values_for_plugin_hashes",
"(",
"external_dsl_attributes",
")",
"rows",
"<<",
"[",
"\"---\"",
",",
"\"---\"",
"]",
"rows",
"<<",
"[",
"\"SCM\"",
",",
"env",
".",
"scm",
".",
"class",
"]",
"rows",
"<<",
"[",
"\"Source\"",
",",
"env",
".",
"ci_source",
".",
"class",
"]",
"rows",
"<<",
"[",
"\"Requests\"",
",",
"env",
".",
"request_source",
".",
"class",
"]",
"rows",
"<<",
"[",
"\"Base Commit\"",
",",
"env",
".",
"meta_info_for_base",
"]",
"rows",
"<<",
"[",
"\"Head Commit\"",
",",
"env",
".",
"meta_info_for_head",
"]",
"params",
"=",
"{",
"}",
"params",
"[",
":rows",
"]",
"=",
"rows",
".",
"each",
"{",
"|",
"current",
"|",
"current",
"[",
"0",
"]",
"=",
"current",
"[",
"0",
"]",
".",
"yellow",
"}",
"params",
"[",
":title",
"]",
"=",
"\"Danger v#{Danger::VERSION}\\nDSL Attributes\"",
".",
"green",
"ui",
".",
"section",
"(",
"\"Info:\"",
")",
"do",
"ui",
".",
"puts",
"table",
"=",
"Terminal",
"::",
"Table",
".",
"new",
"(",
"params",
")",
"table",
".",
"align_column",
"(",
"0",
",",
":right",
")",
"ui",
".",
"puts",
"table",
"ui",
".",
"puts",
"end",
"end"
] |
Iterates through the DSL's attributes, and table's the output
|
[
"Iterates",
"through",
"the",
"DSL",
"s",
"attributes",
"and",
"table",
"s",
"the",
"output"
] |
0d6d09f2d949c287fe75202d947374042b0679f4
|
https://github.com/danger/danger/blob/0d6d09f2d949c287fe75202d947374042b0679f4/lib/danger/danger_core/dangerfile.rb#L147-L170
|
11,277
|
danger/danger
|
lib/danger/danger_core/standard_error.rb
|
Danger.DSLError.message
|
def message
@message ||= begin
description, stacktrace = parse.values_at(:description, :stacktrace)
msg = description
msg = msg.red if msg.respond_to?(:red)
msg << stacktrace if stacktrace
msg
end
end
|
ruby
|
def message
@message ||= begin
description, stacktrace = parse.values_at(:description, :stacktrace)
msg = description
msg = msg.red if msg.respond_to?(:red)
msg << stacktrace if stacktrace
msg
end
end
|
[
"def",
"message",
"@message",
"||=",
"begin",
"description",
",",
"stacktrace",
"=",
"parse",
".",
"values_at",
"(",
":description",
",",
":stacktrace",
")",
"msg",
"=",
"description",
"msg",
"=",
"msg",
".",
"red",
"if",
"msg",
".",
"respond_to?",
"(",
":red",
")",
"msg",
"<<",
"stacktrace",
"if",
"stacktrace",
"msg",
"end",
"end"
] |
The message of the exception reports the content of podspec for the
line that generated the original exception.
@example Output
Invalid podspec at `RestKit.podspec` - undefined method
`exclude_header_search_paths=' for #<Pod::Specification for
`RestKit/Network (0.9.3)`>
from spec-repos/master/RestKit/0.9.3/RestKit.podspec:36
-------------------------------------------
# because it would break: #import <CoreData/CoreData.h>
> ns.exclude_header_search_paths = 'Code/RestKit.h'
end
-------------------------------------------
@return [String] the message of the exception.
|
[
"The",
"message",
"of",
"the",
"exception",
"reports",
"the",
"content",
"of",
"podspec",
"for",
"the",
"line",
"that",
"generated",
"the",
"original",
"exception",
"."
] |
0d6d09f2d949c287fe75202d947374042b0679f4
|
https://github.com/danger/danger/blob/0d6d09f2d949c287fe75202d947374042b0679f4/lib/danger/danger_core/standard_error.rb#L63-L72
|
11,278
|
airbnb/synapse
|
lib/synapse.rb
|
Synapse.Synapse.run
|
def run
log.info "synapse: starting..."
statsd_increment('synapse.start')
# start all the watchers
statsd_time('synapse.watchers.start.time') do
@service_watchers.map do |watcher|
begin
watcher.start
statsd_increment("synapse.watcher.start", ['start_result:success', "watcher_name:#{watcher.name}"])
rescue Exception => e
statsd_increment("synapse.watcher.start", ['start_result:fail', "watcher_name:#{watcher.name}", "exception_name:#{e.class.name}", "exception_message:#{e.message}"])
raise e
end
end
end
statsd_time('synapse.main_loop.elapsed_time') do
# main loop
loops = 0
loop do
@service_watchers.each do |w|
alive = w.ping?
statsd_increment('synapse.watcher.ping.count', ["watcher_name:#{w.name}", "ping_result:#{alive ? "success" : "failure"}"])
raise "synapse: service watcher #{w.name} failed ping!" unless alive
end
if @config_updated
@config_updated = false
statsd_increment('synapse.config.update')
@config_generators.each do |config_generator|
log.info "synapse: configuring #{config_generator.name}"
begin
config_generator.update_config(@service_watchers)
rescue StandardError => e
statsd_increment("synapse.config.update_failed", ["config_name:#{config_generator.name}"])
log.error "synapse: update config failed for config #{config_generator.name} with exception #{e}"
raise e
end
end
end
sleep 1
@config_generators.each do |config_generator|
config_generator.tick(@service_watchers)
end
loops += 1
log.debug "synapse: still running at #{Time.now}" if (loops % 60) == 0
end
end
rescue StandardError => e
statsd_increment('synapse.stop', ['stop_avenue:abort', 'stop_location:main_loop', "exception_name:#{e.class.name}", "exception_message:#{e.message}"])
log.error "synapse: encountered unexpected exception #{e.inspect} in main thread"
raise e
ensure
log.warn "synapse: exiting; sending stop signal to all watchers"
# stop all the watchers
@service_watchers.map do |w|
begin
w.stop
statsd_increment("synapse.watcher.stop", ['stop_avenue:clean', 'stop_location:main_loop', "watcher_name:#{w.name}"])
rescue Exception => e
statsd_increment("synapse.watcher.stop", ['stop_avenue:exception', 'stop_location:main_loop', "watcher_name:#{w.name}", "exception_name:#{e.class.name}", "exception_message:#{e.message}"])
raise e
end
end
statsd_increment('synapse.stop', ['stop_avenue:clean', 'stop_location:main_loop'])
end
|
ruby
|
def run
log.info "synapse: starting..."
statsd_increment('synapse.start')
# start all the watchers
statsd_time('synapse.watchers.start.time') do
@service_watchers.map do |watcher|
begin
watcher.start
statsd_increment("synapse.watcher.start", ['start_result:success', "watcher_name:#{watcher.name}"])
rescue Exception => e
statsd_increment("synapse.watcher.start", ['start_result:fail', "watcher_name:#{watcher.name}", "exception_name:#{e.class.name}", "exception_message:#{e.message}"])
raise e
end
end
end
statsd_time('synapse.main_loop.elapsed_time') do
# main loop
loops = 0
loop do
@service_watchers.each do |w|
alive = w.ping?
statsd_increment('synapse.watcher.ping.count', ["watcher_name:#{w.name}", "ping_result:#{alive ? "success" : "failure"}"])
raise "synapse: service watcher #{w.name} failed ping!" unless alive
end
if @config_updated
@config_updated = false
statsd_increment('synapse.config.update')
@config_generators.each do |config_generator|
log.info "synapse: configuring #{config_generator.name}"
begin
config_generator.update_config(@service_watchers)
rescue StandardError => e
statsd_increment("synapse.config.update_failed", ["config_name:#{config_generator.name}"])
log.error "synapse: update config failed for config #{config_generator.name} with exception #{e}"
raise e
end
end
end
sleep 1
@config_generators.each do |config_generator|
config_generator.tick(@service_watchers)
end
loops += 1
log.debug "synapse: still running at #{Time.now}" if (loops % 60) == 0
end
end
rescue StandardError => e
statsd_increment('synapse.stop', ['stop_avenue:abort', 'stop_location:main_loop', "exception_name:#{e.class.name}", "exception_message:#{e.message}"])
log.error "synapse: encountered unexpected exception #{e.inspect} in main thread"
raise e
ensure
log.warn "synapse: exiting; sending stop signal to all watchers"
# stop all the watchers
@service_watchers.map do |w|
begin
w.stop
statsd_increment("synapse.watcher.stop", ['stop_avenue:clean', 'stop_location:main_loop', "watcher_name:#{w.name}"])
rescue Exception => e
statsd_increment("synapse.watcher.stop", ['stop_avenue:exception', 'stop_location:main_loop', "watcher_name:#{w.name}", "exception_name:#{e.class.name}", "exception_message:#{e.message}"])
raise e
end
end
statsd_increment('synapse.stop', ['stop_avenue:clean', 'stop_location:main_loop'])
end
|
[
"def",
"run",
"log",
".",
"info",
"\"synapse: starting...\"",
"statsd_increment",
"(",
"'synapse.start'",
")",
"# start all the watchers",
"statsd_time",
"(",
"'synapse.watchers.start.time'",
")",
"do",
"@service_watchers",
".",
"map",
"do",
"|",
"watcher",
"|",
"begin",
"watcher",
".",
"start",
"statsd_increment",
"(",
"\"synapse.watcher.start\"",
",",
"[",
"'start_result:success'",
",",
"\"watcher_name:#{watcher.name}\"",
"]",
")",
"rescue",
"Exception",
"=>",
"e",
"statsd_increment",
"(",
"\"synapse.watcher.start\"",
",",
"[",
"'start_result:fail'",
",",
"\"watcher_name:#{watcher.name}\"",
",",
"\"exception_name:#{e.class.name}\"",
",",
"\"exception_message:#{e.message}\"",
"]",
")",
"raise",
"e",
"end",
"end",
"end",
"statsd_time",
"(",
"'synapse.main_loop.elapsed_time'",
")",
"do",
"# main loop",
"loops",
"=",
"0",
"loop",
"do",
"@service_watchers",
".",
"each",
"do",
"|",
"w",
"|",
"alive",
"=",
"w",
".",
"ping?",
"statsd_increment",
"(",
"'synapse.watcher.ping.count'",
",",
"[",
"\"watcher_name:#{w.name}\"",
",",
"\"ping_result:#{alive ? \"success\" : \"failure\"}\"",
"]",
")",
"raise",
"\"synapse: service watcher #{w.name} failed ping!\"",
"unless",
"alive",
"end",
"if",
"@config_updated",
"@config_updated",
"=",
"false",
"statsd_increment",
"(",
"'synapse.config.update'",
")",
"@config_generators",
".",
"each",
"do",
"|",
"config_generator",
"|",
"log",
".",
"info",
"\"synapse: configuring #{config_generator.name}\"",
"begin",
"config_generator",
".",
"update_config",
"(",
"@service_watchers",
")",
"rescue",
"StandardError",
"=>",
"e",
"statsd_increment",
"(",
"\"synapse.config.update_failed\"",
",",
"[",
"\"config_name:#{config_generator.name}\"",
"]",
")",
"log",
".",
"error",
"\"synapse: update config failed for config #{config_generator.name} with exception #{e}\"",
"raise",
"e",
"end",
"end",
"end",
"sleep",
"1",
"@config_generators",
".",
"each",
"do",
"|",
"config_generator",
"|",
"config_generator",
".",
"tick",
"(",
"@service_watchers",
")",
"end",
"loops",
"+=",
"1",
"log",
".",
"debug",
"\"synapse: still running at #{Time.now}\"",
"if",
"(",
"loops",
"%",
"60",
")",
"==",
"0",
"end",
"end",
"rescue",
"StandardError",
"=>",
"e",
"statsd_increment",
"(",
"'synapse.stop'",
",",
"[",
"'stop_avenue:abort'",
",",
"'stop_location:main_loop'",
",",
"\"exception_name:#{e.class.name}\"",
",",
"\"exception_message:#{e.message}\"",
"]",
")",
"log",
".",
"error",
"\"synapse: encountered unexpected exception #{e.inspect} in main thread\"",
"raise",
"e",
"ensure",
"log",
".",
"warn",
"\"synapse: exiting; sending stop signal to all watchers\"",
"# stop all the watchers",
"@service_watchers",
".",
"map",
"do",
"|",
"w",
"|",
"begin",
"w",
".",
"stop",
"statsd_increment",
"(",
"\"synapse.watcher.stop\"",
",",
"[",
"'stop_avenue:clean'",
",",
"'stop_location:main_loop'",
",",
"\"watcher_name:#{w.name}\"",
"]",
")",
"rescue",
"Exception",
"=>",
"e",
"statsd_increment",
"(",
"\"synapse.watcher.stop\"",
",",
"[",
"'stop_avenue:exception'",
",",
"'stop_location:main_loop'",
",",
"\"watcher_name:#{w.name}\"",
",",
"\"exception_name:#{e.class.name}\"",
",",
"\"exception_message:#{e.message}\"",
"]",
")",
"raise",
"e",
"end",
"end",
"statsd_increment",
"(",
"'synapse.stop'",
",",
"[",
"'stop_avenue:clean'",
",",
"'stop_location:main_loop'",
"]",
")",
"end"
] |
start all the watchers and enable haproxy configuration
|
[
"start",
"all",
"the",
"watchers",
"and",
"enable",
"haproxy",
"configuration"
] |
8d1f38236db1fc5ae1b3bf141090dddde42ccdbc
|
https://github.com/airbnb/synapse/blob/8d1f38236db1fc5ae1b3bf141090dddde42ccdbc/lib/synapse.rb#L42-L112
|
11,279
|
ankane/ahoy
|
lib/ahoy/database_store.rb
|
Ahoy.DatabaseStore.visit_or_create
|
def visit_or_create(started_at: nil)
ahoy.track_visit(started_at: started_at) if !visit && Ahoy.server_side_visits
visit
end
|
ruby
|
def visit_or_create(started_at: nil)
ahoy.track_visit(started_at: started_at) if !visit && Ahoy.server_side_visits
visit
end
|
[
"def",
"visit_or_create",
"(",
"started_at",
":",
"nil",
")",
"ahoy",
".",
"track_visit",
"(",
"started_at",
":",
"started_at",
")",
"if",
"!",
"visit",
"&&",
"Ahoy",
".",
"server_side_visits",
"visit",
"end"
] |
if we don't have a visit, let's try to create one first
|
[
"if",
"we",
"don",
"t",
"have",
"a",
"visit",
"let",
"s",
"try",
"to",
"create",
"one",
"first"
] |
514e4f9aed4ff87be791e4d8b73b0f2788233ba8
|
https://github.com/ankane/ahoy/blob/514e4f9aed4ff87be791e4d8b73b0f2788233ba8/lib/ahoy/database_store.rb#L62-L65
|
11,280
|
ankane/ahoy
|
lib/ahoy/tracker.rb
|
Ahoy.Tracker.track
|
def track(name, properties = {}, options = {})
if exclude?
debug "Event excluded"
elsif missing_params?
debug "Missing required parameters"
else
data = {
visit_token: visit_token,
user_id: user.try(:id),
name: name.to_s,
properties: properties,
time: trusted_time(options[:time]),
event_id: options[:id] || generate_id
}.select { |_, v| v }
@store.track_event(data)
end
true
rescue => e
report_exception(e)
end
|
ruby
|
def track(name, properties = {}, options = {})
if exclude?
debug "Event excluded"
elsif missing_params?
debug "Missing required parameters"
else
data = {
visit_token: visit_token,
user_id: user.try(:id),
name: name.to_s,
properties: properties,
time: trusted_time(options[:time]),
event_id: options[:id] || generate_id
}.select { |_, v| v }
@store.track_event(data)
end
true
rescue => e
report_exception(e)
end
|
[
"def",
"track",
"(",
"name",
",",
"properties",
"=",
"{",
"}",
",",
"options",
"=",
"{",
"}",
")",
"if",
"exclude?",
"debug",
"\"Event excluded\"",
"elsif",
"missing_params?",
"debug",
"\"Missing required parameters\"",
"else",
"data",
"=",
"{",
"visit_token",
":",
"visit_token",
",",
"user_id",
":",
"user",
".",
"try",
"(",
":id",
")",
",",
"name",
":",
"name",
".",
"to_s",
",",
"properties",
":",
"properties",
",",
"time",
":",
"trusted_time",
"(",
"options",
"[",
":time",
"]",
")",
",",
"event_id",
":",
"options",
"[",
":id",
"]",
"||",
"generate_id",
"}",
".",
"select",
"{",
"|",
"_",
",",
"v",
"|",
"v",
"}",
"@store",
".",
"track_event",
"(",
"data",
")",
"end",
"true",
"rescue",
"=>",
"e",
"report_exception",
"(",
"e",
")",
"end"
] |
can't use keyword arguments here
|
[
"can",
"t",
"use",
"keyword",
"arguments",
"here"
] |
514e4f9aed4ff87be791e4d8b73b0f2788233ba8
|
https://github.com/ankane/ahoy/blob/514e4f9aed4ff87be791e4d8b73b0f2788233ba8/lib/ahoy/tracker.rb#L18-L38
|
11,281
|
activerecord-hackery/ransack
|
lib/ransack/adapters/active_record/ransack/constants.rb
|
Ransack.Constants.escape_wildcards
|
def escape_wildcards(unescaped)
case ActiveRecord::Base.connection.adapter_name
when "Mysql2".freeze, "PostgreSQL".freeze
# Necessary for PostgreSQL and MySQL
unescaped.to_s.gsub(/([\\%_.])/, '\\\\\\1')
else
unescaped
end
end
|
ruby
|
def escape_wildcards(unescaped)
case ActiveRecord::Base.connection.adapter_name
when "Mysql2".freeze, "PostgreSQL".freeze
# Necessary for PostgreSQL and MySQL
unescaped.to_s.gsub(/([\\%_.])/, '\\\\\\1')
else
unescaped
end
end
|
[
"def",
"escape_wildcards",
"(",
"unescaped",
")",
"case",
"ActiveRecord",
"::",
"Base",
".",
"connection",
".",
"adapter_name",
"when",
"\"Mysql2\"",
".",
"freeze",
",",
"\"PostgreSQL\"",
".",
"freeze",
"# Necessary for PostgreSQL and MySQL",
"unescaped",
".",
"to_s",
".",
"gsub",
"(",
"/",
"\\\\",
"/",
",",
"'\\\\\\\\\\\\1'",
")",
"else",
"unescaped",
"end",
"end"
] |
replace % \ to \% \\
|
[
"replace",
"%",
"\\",
"to",
"\\",
"%",
"\\\\"
] |
d44bfe6fe21ab374ceea9d060267d0d38b09ef28
|
https://github.com/activerecord-hackery/ransack/blob/d44bfe6fe21ab374ceea9d060267d0d38b09ef28/lib/ransack/adapters/active_record/ransack/constants.rb#L103-L111
|
11,282
|
aasm/aasm
|
lib/aasm/base.rb
|
AASM.Base.attribute_name
|
def attribute_name(column_name=nil)
if column_name
@state_machine.config.column = column_name.to_sym
else
@state_machine.config.column ||= :aasm_state
end
@state_machine.config.column
end
|
ruby
|
def attribute_name(column_name=nil)
if column_name
@state_machine.config.column = column_name.to_sym
else
@state_machine.config.column ||= :aasm_state
end
@state_machine.config.column
end
|
[
"def",
"attribute_name",
"(",
"column_name",
"=",
"nil",
")",
"if",
"column_name",
"@state_machine",
".",
"config",
".",
"column",
"=",
"column_name",
".",
"to_sym",
"else",
"@state_machine",
".",
"config",
".",
"column",
"||=",
":aasm_state",
"end",
"@state_machine",
".",
"config",
".",
"column",
"end"
] |
This method is both a getter and a setter
|
[
"This",
"method",
"is",
"both",
"a",
"getter",
"and",
"a",
"setter"
] |
6a1000b489c6b2e205a7b142478a4b4e207c3dbd
|
https://github.com/aasm/aasm/blob/6a1000b489c6b2e205a7b142478a4b4e207c3dbd/lib/aasm/base.rb#L68-L75
|
11,283
|
aasm/aasm
|
lib/aasm/localizer.rb
|
AASM.Localizer.i18n_klass
|
def i18n_klass(klass)
klass.model_name.respond_to?(:i18n_key) ? klass.model_name.i18n_key : klass.name.underscore
end
|
ruby
|
def i18n_klass(klass)
klass.model_name.respond_to?(:i18n_key) ? klass.model_name.i18n_key : klass.name.underscore
end
|
[
"def",
"i18n_klass",
"(",
"klass",
")",
"klass",
".",
"model_name",
".",
"respond_to?",
"(",
":i18n_key",
")",
"?",
"klass",
".",
"model_name",
".",
"i18n_key",
":",
"klass",
".",
"name",
".",
"underscore",
"end"
] |
added for rails < 3.0.3 compatibility
|
[
"added",
"for",
"rails",
"<",
"3",
".",
"0",
".",
"3",
"compatibility"
] |
6a1000b489c6b2e205a7b142478a4b4e207c3dbd
|
https://github.com/aasm/aasm/blob/6a1000b489c6b2e205a7b142478a4b4e207c3dbd/lib/aasm/localizer.rb#L44-L46
|
11,284
|
aasm/aasm
|
lib/aasm/aasm.rb
|
AASM.ClassMethods.aasm
|
def aasm(*args, &block)
if args[0].is_a?(Symbol) || args[0].is_a?(String)
# using custom name
state_machine_name = args[0].to_sym
options = args[1] || {}
else
# using the default state_machine_name
state_machine_name = :default
options = args[0] || {}
end
AASM::StateMachineStore.fetch(self, true).register(state_machine_name, AASM::StateMachine.new(state_machine_name))
# use a default despite the DSL configuration default.
# this is because configuration hasn't been setup for the AASM class but we are accessing a DSL option already for the class.
aasm_klass = options[:with_klass] || AASM::Base
raise ArgumentError, "The class #{aasm_klass} must inherit from AASM::Base!" unless aasm_klass.ancestors.include?(AASM::Base)
@aasm ||= Concurrent::Map.new
if @aasm[state_machine_name]
# make sure to use provided options
options.each do |key, value|
@aasm[state_machine_name].state_machine.config.send("#{key}=", value)
end
else
# create a new base
@aasm[state_machine_name] = aasm_klass.new(
self,
state_machine_name,
AASM::StateMachineStore.fetch(self, true).machine(state_machine_name),
options
)
end
@aasm[state_machine_name].instance_eval(&block) if block # new DSL
@aasm[state_machine_name]
end
|
ruby
|
def aasm(*args, &block)
if args[0].is_a?(Symbol) || args[0].is_a?(String)
# using custom name
state_machine_name = args[0].to_sym
options = args[1] || {}
else
# using the default state_machine_name
state_machine_name = :default
options = args[0] || {}
end
AASM::StateMachineStore.fetch(self, true).register(state_machine_name, AASM::StateMachine.new(state_machine_name))
# use a default despite the DSL configuration default.
# this is because configuration hasn't been setup for the AASM class but we are accessing a DSL option already for the class.
aasm_klass = options[:with_klass] || AASM::Base
raise ArgumentError, "The class #{aasm_klass} must inherit from AASM::Base!" unless aasm_klass.ancestors.include?(AASM::Base)
@aasm ||= Concurrent::Map.new
if @aasm[state_machine_name]
# make sure to use provided options
options.each do |key, value|
@aasm[state_machine_name].state_machine.config.send("#{key}=", value)
end
else
# create a new base
@aasm[state_machine_name] = aasm_klass.new(
self,
state_machine_name,
AASM::StateMachineStore.fetch(self, true).machine(state_machine_name),
options
)
end
@aasm[state_machine_name].instance_eval(&block) if block # new DSL
@aasm[state_machine_name]
end
|
[
"def",
"aasm",
"(",
"*",
"args",
",",
"&",
"block",
")",
"if",
"args",
"[",
"0",
"]",
".",
"is_a?",
"(",
"Symbol",
")",
"||",
"args",
"[",
"0",
"]",
".",
"is_a?",
"(",
"String",
")",
"# using custom name",
"state_machine_name",
"=",
"args",
"[",
"0",
"]",
".",
"to_sym",
"options",
"=",
"args",
"[",
"1",
"]",
"||",
"{",
"}",
"else",
"# using the default state_machine_name",
"state_machine_name",
"=",
":default",
"options",
"=",
"args",
"[",
"0",
"]",
"||",
"{",
"}",
"end",
"AASM",
"::",
"StateMachineStore",
".",
"fetch",
"(",
"self",
",",
"true",
")",
".",
"register",
"(",
"state_machine_name",
",",
"AASM",
"::",
"StateMachine",
".",
"new",
"(",
"state_machine_name",
")",
")",
"# use a default despite the DSL configuration default.",
"# this is because configuration hasn't been setup for the AASM class but we are accessing a DSL option already for the class.",
"aasm_klass",
"=",
"options",
"[",
":with_klass",
"]",
"||",
"AASM",
"::",
"Base",
"raise",
"ArgumentError",
",",
"\"The class #{aasm_klass} must inherit from AASM::Base!\"",
"unless",
"aasm_klass",
".",
"ancestors",
".",
"include?",
"(",
"AASM",
"::",
"Base",
")",
"@aasm",
"||=",
"Concurrent",
"::",
"Map",
".",
"new",
"if",
"@aasm",
"[",
"state_machine_name",
"]",
"# make sure to use provided options",
"options",
".",
"each",
"do",
"|",
"key",
",",
"value",
"|",
"@aasm",
"[",
"state_machine_name",
"]",
".",
"state_machine",
".",
"config",
".",
"send",
"(",
"\"#{key}=\"",
",",
"value",
")",
"end",
"else",
"# create a new base",
"@aasm",
"[",
"state_machine_name",
"]",
"=",
"aasm_klass",
".",
"new",
"(",
"self",
",",
"state_machine_name",
",",
"AASM",
"::",
"StateMachineStore",
".",
"fetch",
"(",
"self",
",",
"true",
")",
".",
"machine",
"(",
"state_machine_name",
")",
",",
"options",
")",
"end",
"@aasm",
"[",
"state_machine_name",
"]",
".",
"instance_eval",
"(",
"block",
")",
"if",
"block",
"# new DSL",
"@aasm",
"[",
"state_machine_name",
"]",
"end"
] |
this is the entry point for all state and event definitions
|
[
"this",
"is",
"the",
"entry",
"point",
"for",
"all",
"state",
"and",
"event",
"definitions"
] |
6a1000b489c6b2e205a7b142478a4b4e207c3dbd
|
https://github.com/aasm/aasm/blob/6a1000b489c6b2e205a7b142478a4b4e207c3dbd/lib/aasm/aasm.rb#L28-L64
|
11,285
|
aasm/aasm
|
lib/aasm/core/event.rb
|
AASM::Core.Event.may_fire?
|
def may_fire?(obj, to_state=::AASM::NO_VALUE, *args)
_fire(obj, {:test_only => true}, to_state, *args) # true indicates test firing
end
|
ruby
|
def may_fire?(obj, to_state=::AASM::NO_VALUE, *args)
_fire(obj, {:test_only => true}, to_state, *args) # true indicates test firing
end
|
[
"def",
"may_fire?",
"(",
"obj",
",",
"to_state",
"=",
"::",
"AASM",
"::",
"NO_VALUE",
",",
"*",
"args",
")",
"_fire",
"(",
"obj",
",",
"{",
":test_only",
"=>",
"true",
"}",
",",
"to_state",
",",
"args",
")",
"# true indicates test firing",
"end"
] |
a neutered version of fire - it doesn't actually fire the event, it just
executes the transition guards to determine if a transition is even
an option given current conditions.
|
[
"a",
"neutered",
"version",
"of",
"fire",
"-",
"it",
"doesn",
"t",
"actually",
"fire",
"the",
"event",
"it",
"just",
"executes",
"the",
"transition",
"guards",
"to",
"determine",
"if",
"a",
"transition",
"is",
"even",
"an",
"option",
"given",
"current",
"conditions",
"."
] |
6a1000b489c6b2e205a7b142478a4b4e207c3dbd
|
https://github.com/aasm/aasm/blob/6a1000b489c6b2e205a7b142478a4b4e207c3dbd/lib/aasm/core/event.rb#L45-L47
|
11,286
|
rocketjob/symmetric-encryption
|
lib/symmetric_encryption/config.rb
|
SymmetricEncryption.Config.config
|
def config
@config ||= begin
raise(ConfigError, "Cannot find config file: #{file_name}") unless File.exist?(file_name)
env_config = YAML.load(ERB.new(File.new(file_name).read).result)[env]
raise(ConfigError, "Cannot find environment: #{env} in config file: #{file_name}") unless env_config
env_config = self.class.send(:deep_symbolize_keys, env_config)
self.class.send(:migrate_old_formats!, env_config)
end
end
|
ruby
|
def config
@config ||= begin
raise(ConfigError, "Cannot find config file: #{file_name}") unless File.exist?(file_name)
env_config = YAML.load(ERB.new(File.new(file_name).read).result)[env]
raise(ConfigError, "Cannot find environment: #{env} in config file: #{file_name}") unless env_config
env_config = self.class.send(:deep_symbolize_keys, env_config)
self.class.send(:migrate_old_formats!, env_config)
end
end
|
[
"def",
"config",
"@config",
"||=",
"begin",
"raise",
"(",
"ConfigError",
",",
"\"Cannot find config file: #{file_name}\"",
")",
"unless",
"File",
".",
"exist?",
"(",
"file_name",
")",
"env_config",
"=",
"YAML",
".",
"load",
"(",
"ERB",
".",
"new",
"(",
"File",
".",
"new",
"(",
"file_name",
")",
".",
"read",
")",
".",
"result",
")",
"[",
"env",
"]",
"raise",
"(",
"ConfigError",
",",
"\"Cannot find environment: #{env} in config file: #{file_name}\"",
")",
"unless",
"env_config",
"env_config",
"=",
"self",
".",
"class",
".",
"send",
"(",
":deep_symbolize_keys",
",",
"env_config",
")",
"self",
".",
"class",
".",
"send",
"(",
":migrate_old_formats!",
",",
"env_config",
")",
"end",
"end"
] |
Load the Encryption Configuration from a YAML file.
See: `.load!` for parameters.
Returns [Hash] the configuration for the supplied environment.
|
[
"Load",
"the",
"Encryption",
"Configuration",
"from",
"a",
"YAML",
"file",
"."
] |
064ba8d57ffac44a3ed80f5e76fa1a54d660ff98
|
https://github.com/rocketjob/symmetric-encryption/blob/064ba8d57ffac44a3ed80f5e76fa1a54d660ff98/lib/symmetric_encryption/config.rb#L73-L83
|
11,287
|
rocketjob/symmetric-encryption
|
lib/symmetric_encryption/writer.rb
|
SymmetricEncryption.Writer.close
|
def close(close_child_stream = true)
return if closed?
if size.positive?
final = @stream_cipher.final
@ios.write(final) unless final.empty?
end
@ios.close if close_child_stream
@closed = true
end
|
ruby
|
def close(close_child_stream = true)
return if closed?
if size.positive?
final = @stream_cipher.final
@ios.write(final) unless final.empty?
end
@ios.close if close_child_stream
@closed = true
end
|
[
"def",
"close",
"(",
"close_child_stream",
"=",
"true",
")",
"return",
"if",
"closed?",
"if",
"size",
".",
"positive?",
"final",
"=",
"@stream_cipher",
".",
"final",
"@ios",
".",
"write",
"(",
"final",
")",
"unless",
"final",
".",
"empty?",
"end",
"@ios",
".",
"close",
"if",
"close_child_stream",
"@closed",
"=",
"true",
"end"
] |
Encrypt data before writing to the supplied stream
Close the IO Stream.
Notes:
* Flushes any unwritten data.
* Once an EncryptionWriter has been closed a new instance must be
created before writing again.
* Closes the passed in io stream or file.
* `close` must be called _before_ the supplied stream is closed.
It is recommended to call Symmetric::EncryptedStream.open
rather than creating an instance of Symmetric::Writer directly to
ensure that the encrypted stream is closed before the stream itself is closed.
|
[
"Encrypt",
"data",
"before",
"writing",
"to",
"the",
"supplied",
"stream",
"Close",
"the",
"IO",
"Stream",
"."
] |
064ba8d57ffac44a3ed80f5e76fa1a54d660ff98
|
https://github.com/rocketjob/symmetric-encryption/blob/064ba8d57ffac44a3ed80f5e76fa1a54d660ff98/lib/symmetric_encryption/writer.rb#L143-L152
|
11,288
|
rocketjob/symmetric-encryption
|
lib/symmetric_encryption/cipher.rb
|
SymmetricEncryption.Cipher.encrypt
|
def encrypt(str, random_iv: SymmetricEncryption.randomize_iv?, compress: false, header: always_add_header)
return if str.nil?
str = str.to_s
return str if str.empty?
encrypted = binary_encrypt(str, random_iv: random_iv, compress: compress, header: header)
encode(encrypted)
end
|
ruby
|
def encrypt(str, random_iv: SymmetricEncryption.randomize_iv?, compress: false, header: always_add_header)
return if str.nil?
str = str.to_s
return str if str.empty?
encrypted = binary_encrypt(str, random_iv: random_iv, compress: compress, header: header)
encode(encrypted)
end
|
[
"def",
"encrypt",
"(",
"str",
",",
"random_iv",
":",
"SymmetricEncryption",
".",
"randomize_iv?",
",",
"compress",
":",
"false",
",",
"header",
":",
"always_add_header",
")",
"return",
"if",
"str",
".",
"nil?",
"str",
"=",
"str",
".",
"to_s",
"return",
"str",
"if",
"str",
".",
"empty?",
"encrypted",
"=",
"binary_encrypt",
"(",
"str",
",",
"random_iv",
":",
"random_iv",
",",
"compress",
":",
"compress",
",",
"header",
":",
"header",
")",
"encode",
"(",
"encrypted",
")",
"end"
] |
Encrypt and then encode a string
Returns data encrypted and then encoded according to the encoding setting
of this cipher
Returns nil if str is nil
Returns "" str is empty
Parameters
str [String]
String to be encrypted. If str is not a string, #to_s will be called on it
to convert it to a string
random_iv [true|false]
Whether the encypted value should use a random IV every time the
field is encrypted.
Notes:
* Setting random_iv to true will result in a different encrypted output for
the same input string.
* It is recommended to set this to true, except if it will be used as a lookup key.
* Only set to true if the field will never be used as a lookup key, since
the encrypted value needs to be same every time in this case.
* When random_iv is true it adds the random IV string to the header.
Default: false
Highly Recommended where feasible: true
compress [true|false]
Whether to compress str before encryption.
Default: false
Notes:
* Should only be used for large strings since compression overhead and
the overhead of adding the encryption header may exceed any benefits of
compression
|
[
"Encrypt",
"and",
"then",
"encode",
"a",
"string"
] |
064ba8d57ffac44a3ed80f5e76fa1a54d660ff98
|
https://github.com/rocketjob/symmetric-encryption/blob/064ba8d57ffac44a3ed80f5e76fa1a54d660ff98/lib/symmetric_encryption/cipher.rb#L134-L142
|
11,289
|
rocketjob/symmetric-encryption
|
lib/symmetric_encryption/cipher.rb
|
SymmetricEncryption.Cipher.decrypt
|
def decrypt(str)
decoded = decode(str)
return unless decoded
return decoded if decoded.empty?
decrypted = binary_decrypt(decoded)
# Try to force result to UTF-8 encoding, but if it is not valid, force it back to Binary
decrypted.force_encoding(SymmetricEncryption::BINARY_ENCODING) unless decrypted.force_encoding(SymmetricEncryption::UTF8_ENCODING).valid_encoding?
decrypted
end
|
ruby
|
def decrypt(str)
decoded = decode(str)
return unless decoded
return decoded if decoded.empty?
decrypted = binary_decrypt(decoded)
# Try to force result to UTF-8 encoding, but if it is not valid, force it back to Binary
decrypted.force_encoding(SymmetricEncryption::BINARY_ENCODING) unless decrypted.force_encoding(SymmetricEncryption::UTF8_ENCODING).valid_encoding?
decrypted
end
|
[
"def",
"decrypt",
"(",
"str",
")",
"decoded",
"=",
"decode",
"(",
"str",
")",
"return",
"unless",
"decoded",
"return",
"decoded",
"if",
"decoded",
".",
"empty?",
"decrypted",
"=",
"binary_decrypt",
"(",
"decoded",
")",
"# Try to force result to UTF-8 encoding, but if it is not valid, force it back to Binary",
"decrypted",
".",
"force_encoding",
"(",
"SymmetricEncryption",
"::",
"BINARY_ENCODING",
")",
"unless",
"decrypted",
".",
"force_encoding",
"(",
"SymmetricEncryption",
"::",
"UTF8_ENCODING",
")",
".",
"valid_encoding?",
"decrypted",
"end"
] |
Decode and Decrypt string
Returns a decrypted string after decoding it first according to the
encoding setting of this cipher
Returns nil if encrypted_string is nil
Returns '' if encrypted_string == ''
Parameters
encrypted_string [String]
Binary encrypted string to decrypt
Reads the header if present for key, iv, cipher_name and compression
encrypted_string must be in raw binary form when calling this method
Creates a new OpenSSL::Cipher with every call so that this call
is thread-safe and can be called concurrently by multiple threads with
the same instance of Cipher
|
[
"Decode",
"and",
"Decrypt",
"string",
"Returns",
"a",
"decrypted",
"string",
"after",
"decoding",
"it",
"first",
"according",
"to",
"the",
"encoding",
"setting",
"of",
"this",
"cipher",
"Returns",
"nil",
"if",
"encrypted_string",
"is",
"nil",
"Returns",
"if",
"encrypted_string",
"=="
] |
064ba8d57ffac44a3ed80f5e76fa1a54d660ff98
|
https://github.com/rocketjob/symmetric-encryption/blob/064ba8d57ffac44a3ed80f5e76fa1a54d660ff98/lib/symmetric_encryption/cipher.rb#L161-L173
|
11,290
|
rocketjob/symmetric-encryption
|
lib/symmetric_encryption/cipher.rb
|
SymmetricEncryption.Cipher.binary_encrypt
|
def binary_encrypt(str, random_iv: SymmetricEncryption.randomize_iv?, compress: false, header: always_add_header)
return if str.nil?
string = str.to_s
return string if string.empty?
# Header required when adding a random_iv or compressing
header = Header.new(version: version, compress: compress) if header || random_iv || compress
# Creates a new OpenSSL::Cipher with every call so that this call is thread-safe.
openssl_cipher = ::OpenSSL::Cipher.new(cipher_name)
openssl_cipher.encrypt
openssl_cipher.key = @key
result =
if header
if random_iv
openssl_cipher.iv = header.iv = openssl_cipher.random_iv
elsif iv
openssl_cipher.iv = iv
end
header.to_s + openssl_cipher.update(compress ? Zlib::Deflate.deflate(string) : string)
else
openssl_cipher.iv = iv if iv
openssl_cipher.update(string)
end
result << openssl_cipher.final
end
|
ruby
|
def binary_encrypt(str, random_iv: SymmetricEncryption.randomize_iv?, compress: false, header: always_add_header)
return if str.nil?
string = str.to_s
return string if string.empty?
# Header required when adding a random_iv or compressing
header = Header.new(version: version, compress: compress) if header || random_iv || compress
# Creates a new OpenSSL::Cipher with every call so that this call is thread-safe.
openssl_cipher = ::OpenSSL::Cipher.new(cipher_name)
openssl_cipher.encrypt
openssl_cipher.key = @key
result =
if header
if random_iv
openssl_cipher.iv = header.iv = openssl_cipher.random_iv
elsif iv
openssl_cipher.iv = iv
end
header.to_s + openssl_cipher.update(compress ? Zlib::Deflate.deflate(string) : string)
else
openssl_cipher.iv = iv if iv
openssl_cipher.update(string)
end
result << openssl_cipher.final
end
|
[
"def",
"binary_encrypt",
"(",
"str",
",",
"random_iv",
":",
"SymmetricEncryption",
".",
"randomize_iv?",
",",
"compress",
":",
"false",
",",
"header",
":",
"always_add_header",
")",
"return",
"if",
"str",
".",
"nil?",
"string",
"=",
"str",
".",
"to_s",
"return",
"string",
"if",
"string",
".",
"empty?",
"# Header required when adding a random_iv or compressing",
"header",
"=",
"Header",
".",
"new",
"(",
"version",
":",
"version",
",",
"compress",
":",
"compress",
")",
"if",
"header",
"||",
"random_iv",
"||",
"compress",
"# Creates a new OpenSSL::Cipher with every call so that this call is thread-safe.",
"openssl_cipher",
"=",
"::",
"OpenSSL",
"::",
"Cipher",
".",
"new",
"(",
"cipher_name",
")",
"openssl_cipher",
".",
"encrypt",
"openssl_cipher",
".",
"key",
"=",
"@key",
"result",
"=",
"if",
"header",
"if",
"random_iv",
"openssl_cipher",
".",
"iv",
"=",
"header",
".",
"iv",
"=",
"openssl_cipher",
".",
"random_iv",
"elsif",
"iv",
"openssl_cipher",
".",
"iv",
"=",
"iv",
"end",
"header",
".",
"to_s",
"+",
"openssl_cipher",
".",
"update",
"(",
"compress",
"?",
"Zlib",
"::",
"Deflate",
".",
"deflate",
"(",
"string",
")",
":",
"string",
")",
"else",
"openssl_cipher",
".",
"iv",
"=",
"iv",
"if",
"iv",
"openssl_cipher",
".",
"update",
"(",
"string",
")",
"end",
"result",
"<<",
"openssl_cipher",
".",
"final",
"end"
] |
Advanced use only
Returns a Binary encrypted string without applying Base64, or any other encoding.
str [String]
String to be encrypted. If str is not a string, #to_s will be called on it
to convert it to a string
random_iv [true|false]
Whether the encypted value should use a random IV every time the
field is encrypted.
Notes:
* Setting random_iv to true will result in a different encrypted output for
the same input string.
* It is recommended to set this to true, except if it will be used as a lookup key.
* Only set to true if the field will never be used as a lookup key, since
the encrypted value needs to be same every time in this case.
* When random_iv is true it adds the random IV string to the header.
Default: false
Highly Recommended where feasible: true
compress [true|false]
Whether to compress str before encryption.
Default: false
Notes:
* Should only be used for large strings since compression overhead and
the overhead of adding the encryption header may exceed any benefits of
compression
header [true|false]
Whether to add a header to the encrypted string.
Default: `always_add_header`
See #encrypt to encrypt and encode the result as a string.
|
[
"Advanced",
"use",
"only"
] |
064ba8d57ffac44a3ed80f5e76fa1a54d660ff98
|
https://github.com/rocketjob/symmetric-encryption/blob/064ba8d57ffac44a3ed80f5e76fa1a54d660ff98/lib/symmetric_encryption/cipher.rb#L249-L276
|
11,291
|
rocketjob/symmetric-encryption
|
lib/symmetric_encryption/header.rb
|
SymmetricEncryption.Header.read_string
|
def read_string(buffer, offset)
# TODO: Length check
# Exception when
# - offset exceeds length of buffer
# byteslice truncates when too long, but returns nil when start is beyond end of buffer
len = buffer.byteslice(offset, 2).unpack('v').first
offset += 2
out = buffer.byteslice(offset, len)
[out, offset + len]
end
|
ruby
|
def read_string(buffer, offset)
# TODO: Length check
# Exception when
# - offset exceeds length of buffer
# byteslice truncates when too long, but returns nil when start is beyond end of buffer
len = buffer.byteslice(offset, 2).unpack('v').first
offset += 2
out = buffer.byteslice(offset, len)
[out, offset + len]
end
|
[
"def",
"read_string",
"(",
"buffer",
",",
"offset",
")",
"# TODO: Length check",
"# Exception when",
"# - offset exceeds length of buffer",
"# byteslice truncates when too long, but returns nil when start is beyond end of buffer",
"len",
"=",
"buffer",
".",
"byteslice",
"(",
"offset",
",",
"2",
")",
".",
"unpack",
"(",
"'v'",
")",
".",
"first",
"offset",
"+=",
"2",
"out",
"=",
"buffer",
".",
"byteslice",
"(",
"offset",
",",
"len",
")",
"[",
"out",
",",
"offset",
"+",
"len",
"]",
"end"
] |
Extracts a string from the supplied buffer.
The buffer starts with a 2 byte length indicator in little endian format.
Parameters
buffer [String]
offset [Integer]
Start position within the buffer.
Returns [string, offset]
string [String]
The string copied from the buffer.
offset [Integer]
The new offset within the buffer.
|
[
"Extracts",
"a",
"string",
"from",
"the",
"supplied",
"buffer",
".",
"The",
"buffer",
"starts",
"with",
"a",
"2",
"byte",
"length",
"indicator",
"in",
"little",
"endian",
"format",
"."
] |
064ba8d57ffac44a3ed80f5e76fa1a54d660ff98
|
https://github.com/rocketjob/symmetric-encryption/blob/064ba8d57ffac44a3ed80f5e76fa1a54d660ff98/lib/symmetric_encryption/header.rb#L256-L265
|
11,292
|
rocketjob/symmetric-encryption
|
lib/symmetric_encryption/reader.rb
|
SymmetricEncryption.Reader.gets
|
def gets(sep_string, length = nil)
return read(length) if sep_string.nil?
# Read more data until we get the sep_string
while (index = @read_buffer.index(sep_string)).nil? && !@ios.eof?
break if length && @read_buffer.length >= length
read_block
end
index ||= -1
data = @read_buffer.slice!(0..index)
@pos += data.length
return nil if data.empty? && eof?
data
end
|
ruby
|
def gets(sep_string, length = nil)
return read(length) if sep_string.nil?
# Read more data until we get the sep_string
while (index = @read_buffer.index(sep_string)).nil? && !@ios.eof?
break if length && @read_buffer.length >= length
read_block
end
index ||= -1
data = @read_buffer.slice!(0..index)
@pos += data.length
return nil if data.empty? && eof?
data
end
|
[
"def",
"gets",
"(",
"sep_string",
",",
"length",
"=",
"nil",
")",
"return",
"read",
"(",
"length",
")",
"if",
"sep_string",
".",
"nil?",
"# Read more data until we get the sep_string",
"while",
"(",
"index",
"=",
"@read_buffer",
".",
"index",
"(",
"sep_string",
")",
")",
".",
"nil?",
"&&",
"!",
"@ios",
".",
"eof?",
"break",
"if",
"length",
"&&",
"@read_buffer",
".",
"length",
">=",
"length",
"read_block",
"end",
"index",
"||=",
"-",
"1",
"data",
"=",
"@read_buffer",
".",
"slice!",
"(",
"0",
"..",
"index",
")",
"@pos",
"+=",
"data",
".",
"length",
"return",
"nil",
"if",
"data",
".",
"empty?",
"&&",
"eof?",
"data",
"end"
] |
Reads a single decrypted line from the file up to and including the optional sep_string.
A sep_string of nil reads the entire contents of the file
Returns nil on eof
The stream must be opened for reading or an IOError will be raised.
|
[
"Reads",
"a",
"single",
"decrypted",
"line",
"from",
"the",
"file",
"up",
"to",
"and",
"including",
"the",
"optional",
"sep_string",
".",
"A",
"sep_string",
"of",
"nil",
"reads",
"the",
"entire",
"contents",
"of",
"the",
"file",
"Returns",
"nil",
"on",
"eof",
"The",
"stream",
"must",
"be",
"opened",
"for",
"reading",
"or",
"an",
"IOError",
"will",
"be",
"raised",
"."
] |
064ba8d57ffac44a3ed80f5e76fa1a54d660ff98
|
https://github.com/rocketjob/symmetric-encryption/blob/064ba8d57ffac44a3ed80f5e76fa1a54d660ff98/lib/symmetric_encryption/reader.rb#L219-L234
|
11,293
|
rocketjob/symmetric-encryption
|
lib/symmetric_encryption/reader.rb
|
SymmetricEncryption.Reader.read_header
|
def read_header
@pos = 0
# Read first block and check for the header
buf = @ios.read(@buffer_size, @output_buffer ||= ''.b)
# Use cipher specified in header, or global cipher if it has no header
iv, key, cipher_name, cipher = nil
header = Header.new
if header.parse!(buf)
@header_present = true
@compressed = header.compressed?
@version = header.version
cipher = header.cipher
cipher_name = header.cipher_name || cipher.cipher_name
key = header.key
iv = header.iv
else
@header_present = false
@compressed = nil
cipher = SymmetricEncryption.cipher(@version)
cipher_name = cipher.cipher_name
end
@stream_cipher = ::OpenSSL::Cipher.new(cipher_name)
@stream_cipher.decrypt
@stream_cipher.key = key || cipher.send(:key)
@stream_cipher.iv = iv || cipher.iv
decrypt(buf)
end
|
ruby
|
def read_header
@pos = 0
# Read first block and check for the header
buf = @ios.read(@buffer_size, @output_buffer ||= ''.b)
# Use cipher specified in header, or global cipher if it has no header
iv, key, cipher_name, cipher = nil
header = Header.new
if header.parse!(buf)
@header_present = true
@compressed = header.compressed?
@version = header.version
cipher = header.cipher
cipher_name = header.cipher_name || cipher.cipher_name
key = header.key
iv = header.iv
else
@header_present = false
@compressed = nil
cipher = SymmetricEncryption.cipher(@version)
cipher_name = cipher.cipher_name
end
@stream_cipher = ::OpenSSL::Cipher.new(cipher_name)
@stream_cipher.decrypt
@stream_cipher.key = key || cipher.send(:key)
@stream_cipher.iv = iv || cipher.iv
decrypt(buf)
end
|
[
"def",
"read_header",
"@pos",
"=",
"0",
"# Read first block and check for the header",
"buf",
"=",
"@ios",
".",
"read",
"(",
"@buffer_size",
",",
"@output_buffer",
"||=",
"''",
".",
"b",
")",
"# Use cipher specified in header, or global cipher if it has no header",
"iv",
",",
"key",
",",
"cipher_name",
",",
"cipher",
"=",
"nil",
"header",
"=",
"Header",
".",
"new",
"if",
"header",
".",
"parse!",
"(",
"buf",
")",
"@header_present",
"=",
"true",
"@compressed",
"=",
"header",
".",
"compressed?",
"@version",
"=",
"header",
".",
"version",
"cipher",
"=",
"header",
".",
"cipher",
"cipher_name",
"=",
"header",
".",
"cipher_name",
"||",
"cipher",
".",
"cipher_name",
"key",
"=",
"header",
".",
"key",
"iv",
"=",
"header",
".",
"iv",
"else",
"@header_present",
"=",
"false",
"@compressed",
"=",
"nil",
"cipher",
"=",
"SymmetricEncryption",
".",
"cipher",
"(",
"@version",
")",
"cipher_name",
"=",
"cipher",
".",
"cipher_name",
"end",
"@stream_cipher",
"=",
"::",
"OpenSSL",
"::",
"Cipher",
".",
"new",
"(",
"cipher_name",
")",
"@stream_cipher",
".",
"decrypt",
"@stream_cipher",
".",
"key",
"=",
"key",
"||",
"cipher",
".",
"send",
"(",
":key",
")",
"@stream_cipher",
".",
"iv",
"=",
"iv",
"||",
"cipher",
".",
"iv",
"decrypt",
"(",
"buf",
")",
"end"
] |
Read the header from the file if present
|
[
"Read",
"the",
"header",
"from",
"the",
"file",
"if",
"present"
] |
064ba8d57ffac44a3ed80f5e76fa1a54d660ff98
|
https://github.com/rocketjob/symmetric-encryption/blob/064ba8d57ffac44a3ed80f5e76fa1a54d660ff98/lib/symmetric_encryption/reader.rb#L309-L339
|
11,294
|
braintree/braintree_ruby
|
lib/braintree/resource_collection.rb
|
Braintree.ResourceCollection.each
|
def each(&block)
@ids.each_slice(@page_size) do |page_of_ids|
resources = @paging_block.call(page_of_ids)
resources.each(&block)
end
end
|
ruby
|
def each(&block)
@ids.each_slice(@page_size) do |page_of_ids|
resources = @paging_block.call(page_of_ids)
resources.each(&block)
end
end
|
[
"def",
"each",
"(",
"&",
"block",
")",
"@ids",
".",
"each_slice",
"(",
"@page_size",
")",
"do",
"|",
"page_of_ids",
"|",
"resources",
"=",
"@paging_block",
".",
"call",
"(",
"page_of_ids",
")",
"resources",
".",
"each",
"(",
"block",
")",
"end",
"end"
] |
Yields each item
|
[
"Yields",
"each",
"item"
] |
6e56c7099ea55bcdc4073cbea60b2688cef69663
|
https://github.com/braintree/braintree_ruby/blob/6e56c7099ea55bcdc4073cbea60b2688cef69663/lib/braintree/resource_collection.rb#L14-L19
|
11,295
|
collectiveidea/audited
|
lib/audited/audit.rb
|
Audited.Audit.revision
|
def revision
clazz = auditable_type.constantize
(clazz.find_by_id(auditable_id) || clazz.new).tap do |m|
self.class.assign_revision_attributes(m, self.class.reconstruct_attributes(ancestors).merge(audit_version: version))
end
end
|
ruby
|
def revision
clazz = auditable_type.constantize
(clazz.find_by_id(auditable_id) || clazz.new).tap do |m|
self.class.assign_revision_attributes(m, self.class.reconstruct_attributes(ancestors).merge(audit_version: version))
end
end
|
[
"def",
"revision",
"clazz",
"=",
"auditable_type",
".",
"constantize",
"(",
"clazz",
".",
"find_by_id",
"(",
"auditable_id",
")",
"||",
"clazz",
".",
"new",
")",
".",
"tap",
"do",
"|",
"m",
"|",
"self",
".",
"class",
".",
"assign_revision_attributes",
"(",
"m",
",",
"self",
".",
"class",
".",
"reconstruct_attributes",
"(",
"ancestors",
")",
".",
"merge",
"(",
"audit_version",
":",
"version",
")",
")",
"end",
"end"
] |
Return an instance of what the object looked like at this revision. If
the object has been destroyed, this will be a new record.
|
[
"Return",
"an",
"instance",
"of",
"what",
"the",
"object",
"looked",
"like",
"at",
"this",
"revision",
".",
"If",
"the",
"object",
"has",
"been",
"destroyed",
"this",
"will",
"be",
"a",
"new",
"record",
"."
] |
af5d51b45368eabb0e727d064faf29f4af6e1458
|
https://github.com/collectiveidea/audited/blob/af5d51b45368eabb0e727d064faf29f4af6e1458/lib/audited/audit.rb#L65-L70
|
11,296
|
collectiveidea/audited
|
lib/audited/audit.rb
|
Audited.Audit.new_attributes
|
def new_attributes
(audited_changes || {}).inject({}.with_indifferent_access) do |attrs, (attr, values)|
attrs[attr] = values.is_a?(Array) ? values.last : values
attrs
end
end
|
ruby
|
def new_attributes
(audited_changes || {}).inject({}.with_indifferent_access) do |attrs, (attr, values)|
attrs[attr] = values.is_a?(Array) ? values.last : values
attrs
end
end
|
[
"def",
"new_attributes",
"(",
"audited_changes",
"||",
"{",
"}",
")",
".",
"inject",
"(",
"{",
"}",
".",
"with_indifferent_access",
")",
"do",
"|",
"attrs",
",",
"(",
"attr",
",",
"values",
")",
"|",
"attrs",
"[",
"attr",
"]",
"=",
"values",
".",
"is_a?",
"(",
"Array",
")",
"?",
"values",
".",
"last",
":",
"values",
"attrs",
"end",
"end"
] |
Returns a hash of the changed attributes with the new values
|
[
"Returns",
"a",
"hash",
"of",
"the",
"changed",
"attributes",
"with",
"the",
"new",
"values"
] |
af5d51b45368eabb0e727d064faf29f4af6e1458
|
https://github.com/collectiveidea/audited/blob/af5d51b45368eabb0e727d064faf29f4af6e1458/lib/audited/audit.rb#L73-L78
|
11,297
|
collectiveidea/audited
|
lib/audited/audit.rb
|
Audited.Audit.old_attributes
|
def old_attributes
(audited_changes || {}).inject({}.with_indifferent_access) do |attrs, (attr, values)|
attrs[attr] = Array(values).first
attrs
end
end
|
ruby
|
def old_attributes
(audited_changes || {}).inject({}.with_indifferent_access) do |attrs, (attr, values)|
attrs[attr] = Array(values).first
attrs
end
end
|
[
"def",
"old_attributes",
"(",
"audited_changes",
"||",
"{",
"}",
")",
".",
"inject",
"(",
"{",
"}",
".",
"with_indifferent_access",
")",
"do",
"|",
"attrs",
",",
"(",
"attr",
",",
"values",
")",
"|",
"attrs",
"[",
"attr",
"]",
"=",
"Array",
"(",
"values",
")",
".",
"first",
"attrs",
"end",
"end"
] |
Returns a hash of the changed attributes with the old values
|
[
"Returns",
"a",
"hash",
"of",
"the",
"changed",
"attributes",
"with",
"the",
"old",
"values"
] |
af5d51b45368eabb0e727d064faf29f4af6e1458
|
https://github.com/collectiveidea/audited/blob/af5d51b45368eabb0e727d064faf29f4af6e1458/lib/audited/audit.rb#L81-L87
|
11,298
|
collectiveidea/audited
|
lib/audited/audit.rb
|
Audited.Audit.undo
|
def undo
case action
when 'create'
# destroys a newly created record
auditable.destroy!
when 'destroy'
# creates a new record with the destroyed record attributes
auditable_type.constantize.create!(audited_changes)
when 'update'
# changes back attributes
auditable.update_attributes!(audited_changes.transform_values(&:first))
else
raise StandardError, "invalid action given #{action}"
end
end
|
ruby
|
def undo
case action
when 'create'
# destroys a newly created record
auditable.destroy!
when 'destroy'
# creates a new record with the destroyed record attributes
auditable_type.constantize.create!(audited_changes)
when 'update'
# changes back attributes
auditable.update_attributes!(audited_changes.transform_values(&:first))
else
raise StandardError, "invalid action given #{action}"
end
end
|
[
"def",
"undo",
"case",
"action",
"when",
"'create'",
"# destroys a newly created record",
"auditable",
".",
"destroy!",
"when",
"'destroy'",
"# creates a new record with the destroyed record attributes",
"auditable_type",
".",
"constantize",
".",
"create!",
"(",
"audited_changes",
")",
"when",
"'update'",
"# changes back attributes",
"auditable",
".",
"update_attributes!",
"(",
"audited_changes",
".",
"transform_values",
"(",
":first",
")",
")",
"else",
"raise",
"StandardError",
",",
"\"invalid action given #{action}\"",
"end",
"end"
] |
Allows user to undo changes
|
[
"Allows",
"user",
"to",
"undo",
"changes"
] |
af5d51b45368eabb0e727d064faf29f4af6e1458
|
https://github.com/collectiveidea/audited/blob/af5d51b45368eabb0e727d064faf29f4af6e1458/lib/audited/audit.rb#L90-L104
|
11,299
|
collectiveidea/audited
|
lib/audited/audit.rb
|
Audited.Audit.user_as_string=
|
def user_as_string=(user)
# reset both either way
self.user_as_model = self.username = nil
user.is_a?(::ActiveRecord::Base) ?
self.user_as_model = user :
self.username = user
end
|
ruby
|
def user_as_string=(user)
# reset both either way
self.user_as_model = self.username = nil
user.is_a?(::ActiveRecord::Base) ?
self.user_as_model = user :
self.username = user
end
|
[
"def",
"user_as_string",
"=",
"(",
"user",
")",
"# reset both either way",
"self",
".",
"user_as_model",
"=",
"self",
".",
"username",
"=",
"nil",
"user",
".",
"is_a?",
"(",
"::",
"ActiveRecord",
"::",
"Base",
")",
"?",
"self",
".",
"user_as_model",
"=",
"user",
":",
"self",
".",
"username",
"=",
"user",
"end"
] |
Allows user to be set to either a string or an ActiveRecord object
@private
|
[
"Allows",
"user",
"to",
"be",
"set",
"to",
"either",
"a",
"string",
"or",
"an",
"ActiveRecord",
"object"
] |
af5d51b45368eabb0e727d064faf29f4af6e1458
|
https://github.com/collectiveidea/audited/blob/af5d51b45368eabb0e727d064faf29f4af6e1458/lib/audited/audit.rb#L108-L114
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.