repo
stringlengths 5
58
| path
stringlengths 9
168
| func_name
stringlengths 9
130
| original_string
stringlengths 66
10.5k
| language
stringclasses 1
value | code
stringlengths 66
10.5k
| code_tokens
sequence | docstring
stringlengths 8
16k
| docstring_tokens
sequence | sha
stringlengths 40
40
| url
stringlengths 94
266
| partition
stringclasses 1
value |
---|---|---|---|---|---|---|---|---|---|---|---|
colszowka/simplecov | lib/simplecov/configuration.rb | SimpleCov.Configuration.at_exit | def at_exit(&block)
return proc {} unless running || block_given?
@at_exit = block if block_given?
@at_exit ||= proc { SimpleCov.result.format! }
end | ruby | def at_exit(&block)
return proc {} unless running || block_given?
@at_exit = block if block_given?
@at_exit ||= proc { SimpleCov.result.format! }
end | [
"def",
"at_exit",
"(",
"&",
"block",
")",
"return",
"proc",
"{",
"}",
"unless",
"running",
"||",
"block_given?",
"@at_exit",
"=",
"block",
"if",
"block_given?",
"@at_exit",
"||=",
"proc",
"{",
"SimpleCov",
".",
"result",
".",
"format!",
"}",
"end"
] | Gets or sets the behavior to process coverage results.
By default, it will call SimpleCov.result.format!
Configure with:
SimpleCov.at_exit do
puts "Coverage done"
SimpleCov.result.format!
end | [
"Gets",
"or",
"sets",
"the",
"behavior",
"to",
"process",
"coverage",
"results",
"."
] | 8f6978a2513f10c4dd8d7dd7eed666fe3f2b55c2 | https://github.com/colszowka/simplecov/blob/8f6978a2513f10c4dd8d7dd7eed666fe3f2b55c2/lib/simplecov/configuration.rb#L179-L183 | train |
colszowka/simplecov | lib/simplecov/configuration.rb | SimpleCov.Configuration.project_name | def project_name(new_name = nil)
return @project_name if defined?(@project_name) && @project_name && new_name.nil?
@project_name = new_name if new_name.is_a?(String)
@project_name ||= File.basename(root.split("/").last).capitalize.tr("_", " ")
end | ruby | def project_name(new_name = nil)
return @project_name if defined?(@project_name) && @project_name && new_name.nil?
@project_name = new_name if new_name.is_a?(String)
@project_name ||= File.basename(root.split("/").last).capitalize.tr("_", " ")
end | [
"def",
"project_name",
"(",
"new_name",
"=",
"nil",
")",
"return",
"@project_name",
"if",
"defined?",
"(",
"@project_name",
")",
"&&",
"@project_name",
"&&",
"new_name",
".",
"nil?",
"@project_name",
"=",
"new_name",
"if",
"new_name",
".",
"is_a?",
"(",
"String",
")",
"@project_name",
"||=",
"File",
".",
"basename",
"(",
"root",
".",
"split",
"(",
"\"/\"",
")",
".",
"last",
")",
".",
"capitalize",
".",
"tr",
"(",
"\"_\"",
",",
"\" \"",
")",
"end"
] | Returns the project name - currently assuming the last dirname in
the SimpleCov.root is this. | [
"Returns",
"the",
"project",
"name",
"-",
"currently",
"assuming",
"the",
"last",
"dirname",
"in",
"the",
"SimpleCov",
".",
"root",
"is",
"this",
"."
] | 8f6978a2513f10c4dd8d7dd7eed666fe3f2b55c2 | https://github.com/colszowka/simplecov/blob/8f6978a2513f10c4dd8d7dd7eed666fe3f2b55c2/lib/simplecov/configuration.rb#L189-L193 | train |
colszowka/simplecov | lib/simplecov/configuration.rb | SimpleCov.Configuration.parse_filter | def parse_filter(filter_argument = nil, &filter_proc)
filter = filter_argument || filter_proc
if filter
SimpleCov::Filter.build_filter(filter)
else
raise ArgumentError, "Please specify either a filter or a block to filter with"
end
end | ruby | def parse_filter(filter_argument = nil, &filter_proc)
filter = filter_argument || filter_proc
if filter
SimpleCov::Filter.build_filter(filter)
else
raise ArgumentError, "Please specify either a filter or a block to filter with"
end
end | [
"def",
"parse_filter",
"(",
"filter_argument",
"=",
"nil",
",",
"&",
"filter_proc",
")",
"filter",
"=",
"filter_argument",
"||",
"filter_proc",
"if",
"filter",
"SimpleCov",
"::",
"Filter",
".",
"build_filter",
"(",
"filter",
")",
"else",
"raise",
"ArgumentError",
",",
"\"Please specify either a filter or a block to filter with\"",
"end",
"end"
] | The actual filter processor. Not meant for direct use | [
"The",
"actual",
"filter",
"processor",
".",
"Not",
"meant",
"for",
"direct",
"use"
] | 8f6978a2513f10c4dd8d7dd7eed666fe3f2b55c2 | https://github.com/colszowka/simplecov/blob/8f6978a2513f10c4dd8d7dd7eed666fe3f2b55c2/lib/simplecov/configuration.rb#L295-L303 | train |
colszowka/simplecov | lib/simplecov/raw_coverage.rb | SimpleCov.RawCoverage.merge_resultsets | def merge_resultsets(result1, result2)
(result1.keys | result2.keys).each_with_object({}) do |filename, merged|
file1 = result1[filename]
file2 = result2[filename]
merged[filename] = merge_file_coverage(file1, file2)
end
end | ruby | def merge_resultsets(result1, result2)
(result1.keys | result2.keys).each_with_object({}) do |filename, merged|
file1 = result1[filename]
file2 = result2[filename]
merged[filename] = merge_file_coverage(file1, file2)
end
end | [
"def",
"merge_resultsets",
"(",
"result1",
",",
"result2",
")",
"(",
"result1",
".",
"keys",
"|",
"result2",
".",
"keys",
")",
".",
"each_with_object",
"(",
"{",
"}",
")",
"do",
"|",
"filename",
",",
"merged",
"|",
"file1",
"=",
"result1",
"[",
"filename",
"]",
"file2",
"=",
"result2",
"[",
"filename",
"]",
"merged",
"[",
"filename",
"]",
"=",
"merge_file_coverage",
"(",
"file1",
",",
"file2",
")",
"end",
"end"
] | Merges two Coverage.result hashes | [
"Merges",
"two",
"Coverage",
".",
"result",
"hashes"
] | 8f6978a2513f10c4dd8d7dd7eed666fe3f2b55c2 | https://github.com/colszowka/simplecov/blob/8f6978a2513f10c4dd8d7dd7eed666fe3f2b55c2/lib/simplecov/raw_coverage.rb#L15-L21 | train |
colszowka/simplecov | lib/simplecov/profiles.rb | SimpleCov.Profiles.load | def load(name)
name = name.to_sym
raise "Could not find SimpleCov Profile called '#{name}'" unless key?(name)
SimpleCov.configure(&self[name])
end | ruby | def load(name)
name = name.to_sym
raise "Could not find SimpleCov Profile called '#{name}'" unless key?(name)
SimpleCov.configure(&self[name])
end | [
"def",
"load",
"(",
"name",
")",
"name",
"=",
"name",
".",
"to_sym",
"raise",
"\"Could not find SimpleCov Profile called '#{name}'\"",
"unless",
"key?",
"(",
"name",
")",
"SimpleCov",
".",
"configure",
"(",
"self",
"[",
"name",
"]",
")",
"end"
] | Applies the profile of given name on SimpleCov.configure | [
"Applies",
"the",
"profile",
"of",
"given",
"name",
"on",
"SimpleCov",
".",
"configure"
] | 8f6978a2513f10c4dd8d7dd7eed666fe3f2b55c2 | https://github.com/colszowka/simplecov/blob/8f6978a2513f10c4dd8d7dd7eed666fe3f2b55c2/lib/simplecov/profiles.rb#L27-L31 | train |
troessner/reek | lib/reek/documentation_link.rb | Reek.DocumentationLink.build | def build(subject)
Kernel.format(HELP_LINK_TEMPLATE, version: Version::STRING, item: name_to_param(subject))
end | ruby | def build(subject)
Kernel.format(HELP_LINK_TEMPLATE, version: Version::STRING, item: name_to_param(subject))
end | [
"def",
"build",
"(",
"subject",
")",
"Kernel",
".",
"format",
"(",
"HELP_LINK_TEMPLATE",
",",
"version",
":",
"Version",
"::",
"STRING",
",",
"item",
":",
"name_to_param",
"(",
"subject",
")",
")",
"end"
] | Build link to the documentation about the given subject for the current
version of Reek. The subject can be either a smell type like
'FeatureEnvy' or a general subject like 'Rake Task'.
@param subject [String]
@return [String] the full URL for the relevant documentation | [
"Build",
"link",
"to",
"the",
"documentation",
"about",
"the",
"given",
"subject",
"for",
"the",
"current",
"version",
"of",
"Reek",
".",
"The",
"subject",
"can",
"be",
"either",
"a",
"smell",
"type",
"like",
"FeatureEnvy",
"or",
"a",
"general",
"subject",
"like",
"Rake",
"Task",
"."
] | 8c6b5c0c6228a6981ab48543457889f9ea984054 | https://github.com/troessner/reek/blob/8c6b5c0c6228a6981ab48543457889f9ea984054/lib/reek/documentation_link.rb#L16-L18 | train |
troessner/reek | samples/smelly_source/inline.rb | Inline.C.load_cache | def load_cache
begin
file = File.join("inline", File.basename(so_name))
if require file then
dir = Inline.directory
warn "WAR\NING: #{dir} exists but is not being used" if test ?d, dir and $VERBOSE
return true
end
rescue LoadError
end
return false
end | ruby | def load_cache
begin
file = File.join("inline", File.basename(so_name))
if require file then
dir = Inline.directory
warn "WAR\NING: #{dir} exists but is not being used" if test ?d, dir and $VERBOSE
return true
end
rescue LoadError
end
return false
end | [
"def",
"load_cache",
"begin",
"file",
"=",
"File",
".",
"join",
"(",
"\"inline\"",
",",
"File",
".",
"basename",
"(",
"so_name",
")",
")",
"if",
"require",
"file",
"then",
"dir",
"=",
"Inline",
".",
"directory",
"warn",
"\"WAR\\NING: #{dir} exists but is not being used\"",
"if",
"test",
"?d",
",",
"dir",
"and",
"$VERBOSE",
"return",
"true",
"end",
"rescue",
"LoadError",
"end",
"return",
"false",
"end"
] | Attempts to load pre-generated code returning true if it succeeds. | [
"Attempts",
"to",
"load",
"pre",
"-",
"generated",
"code",
"returning",
"true",
"if",
"it",
"succeeds",
"."
] | 8c6b5c0c6228a6981ab48543457889f9ea984054 | https://github.com/troessner/reek/blob/8c6b5c0c6228a6981ab48543457889f9ea984054/samples/smelly_source/inline.rb#L315-L326 | train |
troessner/reek | samples/smelly_source/inline.rb | Inline.C.add_type_converter | def add_type_converter(type, r2c, c2r)
warn "WAR\NING: overridding #{type} on #{caller[0]}" if @@type_map.has_key? type
@@type_map[type] = [r2c, c2r]
end | ruby | def add_type_converter(type, r2c, c2r)
warn "WAR\NING: overridding #{type} on #{caller[0]}" if @@type_map.has_key? type
@@type_map[type] = [r2c, c2r]
end | [
"def",
"add_type_converter",
"(",
"type",
",",
"r2c",
",",
"c2r",
")",
"warn",
"\"WAR\\NING: overridding #{type} on #{caller[0]}\"",
"if",
"@@type_map",
".",
"has_key?",
"type",
"@@type_map",
"[",
"type",
"]",
"=",
"[",
"r2c",
",",
"c2r",
"]",
"end"
] | Registers C type-casts +r2c+ and +c2r+ for +type+. | [
"Registers",
"C",
"type",
"-",
"casts",
"+",
"r2c",
"+",
"and",
"+",
"c2r",
"+",
"for",
"+",
"type",
"+",
"."
] | 8c6b5c0c6228a6981ab48543457889f9ea984054 | https://github.com/troessner/reek/blob/8c6b5c0c6228a6981ab48543457889f9ea984054/samples/smelly_source/inline.rb#L520-L523 | train |
troessner/reek | samples/smelly_source/inline.rb | Inline.C.c | def c src, options = {}
options = {
:expand_types => true,
}.merge options
self.generate src, options
end | ruby | def c src, options = {}
options = {
:expand_types => true,
}.merge options
self.generate src, options
end | [
"def",
"c",
"src",
",",
"options",
"=",
"{",
"}",
"options",
"=",
"{",
":expand_types",
"=>",
"true",
",",
"}",
".",
"merge",
"options",
"self",
".",
"generate",
"src",
",",
"options",
"end"
] | Adds a C function to the source, including performing automatic
type conversion to arguments and the return value. The Ruby
method name can be overridden by providing method_name. Unknown
type conversions can be extended by using +add_type_converter+. | [
"Adds",
"a",
"C",
"function",
"to",
"the",
"source",
"including",
"performing",
"automatic",
"type",
"conversion",
"to",
"arguments",
"and",
"the",
"return",
"value",
".",
"The",
"Ruby",
"method",
"name",
"can",
"be",
"overridden",
"by",
"providing",
"method_name",
".",
"Unknown",
"type",
"conversions",
"can",
"be",
"extended",
"by",
"using",
"+",
"add_type_converter",
"+",
"."
] | 8c6b5c0c6228a6981ab48543457889f9ea984054 | https://github.com/troessner/reek/blob/8c6b5c0c6228a6981ab48543457889f9ea984054/samples/smelly_source/inline.rb#L575-L580 | train |
troessner/reek | samples/smelly_source/inline.rb | Inline.C.c_singleton | def c_singleton src, options = {}
options = {
:expand_types => true,
:singleton => true,
}.merge options
self.generate src, options
end | ruby | def c_singleton src, options = {}
options = {
:expand_types => true,
:singleton => true,
}.merge options
self.generate src, options
end | [
"def",
"c_singleton",
"src",
",",
"options",
"=",
"{",
"}",
"options",
"=",
"{",
":expand_types",
"=>",
"true",
",",
":singleton",
"=>",
"true",
",",
"}",
".",
"merge",
"options",
"self",
".",
"generate",
"src",
",",
"options",
"end"
] | Same as +c+, but adds a class function. | [
"Same",
"as",
"+",
"c",
"+",
"but",
"adds",
"a",
"class",
"function",
"."
] | 8c6b5c0c6228a6981ab48543457889f9ea984054 | https://github.com/troessner/reek/blob/8c6b5c0c6228a6981ab48543457889f9ea984054/samples/smelly_source/inline.rb#L585-L591 | train |
troessner/reek | samples/smelly_source/inline.rb | Inline.C.c_raw_singleton | def c_raw_singleton src, options = {}
options = {
:singleton => true,
}.merge options
self.generate src, options
end | ruby | def c_raw_singleton src, options = {}
options = {
:singleton => true,
}.merge options
self.generate src, options
end | [
"def",
"c_raw_singleton",
"src",
",",
"options",
"=",
"{",
"}",
"options",
"=",
"{",
":singleton",
"=>",
"true",
",",
"}",
".",
"merge",
"options",
"self",
".",
"generate",
"src",
",",
"options",
"end"
] | Same as +c_raw+, but adds a class function. | [
"Same",
"as",
"+",
"c_raw",
"+",
"but",
"adds",
"a",
"class",
"function",
"."
] | 8c6b5c0c6228a6981ab48543457889f9ea984054 | https://github.com/troessner/reek/blob/8c6b5c0c6228a6981ab48543457889f9ea984054/samples/smelly_source/inline.rb#L606-L611 | train |
troessner/reek | lib/reek/spec.rb | Reek.Spec.reek_of | def reek_of(smell_type,
smell_details = {},
configuration = Configuration::AppConfiguration.default)
ShouldReekOf.new(smell_type, smell_details, configuration)
end | ruby | def reek_of(smell_type,
smell_details = {},
configuration = Configuration::AppConfiguration.default)
ShouldReekOf.new(smell_type, smell_details, configuration)
end | [
"def",
"reek_of",
"(",
"smell_type",
",",
"smell_details",
"=",
"{",
"}",
",",
"configuration",
"=",
"Configuration",
"::",
"AppConfiguration",
".",
"default",
")",
"ShouldReekOf",
".",
"new",
"(",
"smell_type",
",",
"smell_details",
",",
"configuration",
")",
"end"
] | Checks the target source code for instances of "smell type"
and returns true only if it can find one of them that matches.
You can pass the smell type you want to check for as String or as Symbol:
- :UtilityFunction
- "UtilityFunction"
It is recommended to pass this as a symbol like :UtilityFunction. However we don't
enforce this.
Additionally you can be more specific and pass in "smell_details" you
want to check for as well e.g. "name" or "count" (see the examples below).
The parameters you can check for are depending on the smell you are checking for.
For instance "count" doesn't make sense everywhere whereas "name" does in most cases.
If you pass in a parameter that doesn't exist (e.g. you make a typo like "namme") Reek will
raise an ArgumentError to give you a hint that you passed something that doesn't make
much sense.
@param smell_type [Symbol, String] The "smell type" to check for.
@param smell_details [Hash] A hash containing "smell warning" parameters
@example Without smell_details
reek_of(:FeatureEnvy)
reek_of(:UtilityFunction)
@example With smell_details
reek_of(:UncommunicativeParameterName, name: 'x2')
reek_of(:DataClump, count: 3)
@example From a real spec
expect(src).to reek_of(:DuplicateMethodCall, name: '@other.thing')
@public
@quality :reek:UtilityFunction | [
"Checks",
"the",
"target",
"source",
"code",
"for",
"instances",
"of",
"smell",
"type",
"and",
"returns",
"true",
"only",
"if",
"it",
"can",
"find",
"one",
"of",
"them",
"that",
"matches",
"."
] | 8c6b5c0c6228a6981ab48543457889f9ea984054 | https://github.com/troessner/reek/blob/8c6b5c0c6228a6981ab48543457889f9ea984054/lib/reek/spec.rb#L88-L92 | train |
troessner/reek | lib/reek/spec.rb | Reek.Spec.reek_only_of | def reek_only_of(smell_type, configuration = Configuration::AppConfiguration.default)
ShouldReekOnlyOf.new(smell_type, configuration)
end | ruby | def reek_only_of(smell_type, configuration = Configuration::AppConfiguration.default)
ShouldReekOnlyOf.new(smell_type, configuration)
end | [
"def",
"reek_only_of",
"(",
"smell_type",
",",
"configuration",
"=",
"Configuration",
"::",
"AppConfiguration",
".",
"default",
")",
"ShouldReekOnlyOf",
".",
"new",
"(",
"smell_type",
",",
"configuration",
")",
"end"
] | See the documentaton for "reek_of".
Notable differences to reek_of:
1.) "reek_of" doesn't mind if there are other smells of a different type.
"reek_only_of" will fail in that case.
2.) "reek_only_of" doesn't support the additional smell_details hash.
@param smell_type [Symbol, String] The "smell type" to check for.
@public
@quality :reek:UtilityFunction | [
"See",
"the",
"documentaton",
"for",
"reek_of",
"."
] | 8c6b5c0c6228a6981ab48543457889f9ea984054 | https://github.com/troessner/reek/blob/8c6b5c0c6228a6981ab48543457889f9ea984054/lib/reek/spec.rb#L107-L109 | train |
troessner/reek | lib/reek/context_builder.rb | Reek.ContextBuilder.build | def build(exp, parent_exp = nil)
context_processor = "process_#{exp.type}"
if context_processor_exists?(context_processor)
send(context_processor, exp, parent_exp)
else
process exp
end
current_context
end | ruby | def build(exp, parent_exp = nil)
context_processor = "process_#{exp.type}"
if context_processor_exists?(context_processor)
send(context_processor, exp, parent_exp)
else
process exp
end
current_context
end | [
"def",
"build",
"(",
"exp",
",",
"parent_exp",
"=",
"nil",
")",
"context_processor",
"=",
"\"process_#{exp.type}\"",
"if",
"context_processor_exists?",
"(",
"context_processor",
")",
"send",
"(",
"context_processor",
",",
"exp",
",",
"parent_exp",
")",
"else",
"process",
"exp",
"end",
"current_context",
"end"
] | Processes the given AST, memoizes it and returns a tree of nested
contexts.
For example this ruby code:
class Car; def drive; end; end
would get compiled into this AST:
(class
(const nil :Car) nil
(def :drive
(args) nil))
Processing this AST would result in a context tree where each node
contains the outer context, the AST and the child contexts. The top
node is always Reek::Context::RootContext. Using the example above,
the tree would look like this:
RootContext -> children: 1 ModuleContext -> children: 1 MethodContext
@return [Reek::Context::RootContext] tree of nested contexts | [
"Processes",
"the",
"given",
"AST",
"memoizes",
"it",
"and",
"returns",
"a",
"tree",
"of",
"nested",
"contexts",
"."
] | 8c6b5c0c6228a6981ab48543457889f9ea984054 | https://github.com/troessner/reek/blob/8c6b5c0c6228a6981ab48543457889f9ea984054/lib/reek/context_builder.rb#L62-L70 | train |
troessner/reek | lib/reek/context_builder.rb | Reek.ContextBuilder.process | def process(exp)
exp.children.grep(AST::Node).each { |child| build(child, exp) }
end | ruby | def process(exp)
exp.children.grep(AST::Node).each { |child| build(child, exp) }
end | [
"def",
"process",
"(",
"exp",
")",
"exp",
".",
"children",
".",
"grep",
"(",
"AST",
"::",
"Node",
")",
".",
"each",
"{",
"|",
"child",
"|",
"build",
"(",
"child",
",",
"exp",
")",
"}",
"end"
] | Handles every node for which we have no context_processor. | [
"Handles",
"every",
"node",
"for",
"which",
"we",
"have",
"no",
"context_processor",
"."
] | 8c6b5c0c6228a6981ab48543457889f9ea984054 | https://github.com/troessner/reek/blob/8c6b5c0c6228a6981ab48543457889f9ea984054/lib/reek/context_builder.rb#L74-L76 | train |
troessner/reek | lib/reek/context_builder.rb | Reek.ContextBuilder.process_def | def process_def(exp, parent)
inside_new_context(current_context.method_context_class, exp, parent) do
increase_statement_count_by(exp.body)
process(exp)
end
end | ruby | def process_def(exp, parent)
inside_new_context(current_context.method_context_class, exp, parent) do
increase_statement_count_by(exp.body)
process(exp)
end
end | [
"def",
"process_def",
"(",
"exp",
",",
"parent",
")",
"inside_new_context",
"(",
"current_context",
".",
"method_context_class",
",",
"exp",
",",
"parent",
")",
"do",
"increase_statement_count_by",
"(",
"exp",
".",
"body",
")",
"process",
"(",
"exp",
")",
"end",
"end"
] | Handles `def` nodes.
An input example that would trigger this method would be:
def call_me; foo = 2; bar = 5; end
Given the above example we would count 2 statements overall. | [
"Handles",
"def",
"nodes",
"."
] | 8c6b5c0c6228a6981ab48543457889f9ea984054 | https://github.com/troessner/reek/blob/8c6b5c0c6228a6981ab48543457889f9ea984054/lib/reek/context_builder.rb#L123-L128 | train |
troessner/reek | lib/reek/context_builder.rb | Reek.ContextBuilder.process_send | def process_send(exp, _parent)
process(exp)
case current_context
when Context::ModuleContext
handle_send_for_modules exp
when Context::MethodContext
handle_send_for_methods exp
end
end | ruby | def process_send(exp, _parent)
process(exp)
case current_context
when Context::ModuleContext
handle_send_for_modules exp
when Context::MethodContext
handle_send_for_methods exp
end
end | [
"def",
"process_send",
"(",
"exp",
",",
"_parent",
")",
"process",
"(",
"exp",
")",
"case",
"current_context",
"when",
"Context",
"::",
"ModuleContext",
"handle_send_for_modules",
"exp",
"when",
"Context",
"::",
"MethodContext",
"handle_send_for_methods",
"exp",
"end",
"end"
] | Handles `send` nodes a.k.a. method calls.
An input example that would trigger this method would be:
call_me()
Besides checking if it's a visibility modifier or an attribute writer
we also record to what the method call is referring to
which we later use for smell detectors like FeatureEnvy. | [
"Handles",
"send",
"nodes",
"a",
".",
"k",
".",
"a",
".",
"method",
"calls",
"."
] | 8c6b5c0c6228a6981ab48543457889f9ea984054 | https://github.com/troessner/reek/blob/8c6b5c0c6228a6981ab48543457889f9ea984054/lib/reek/context_builder.rb#L155-L163 | train |
troessner/reek | lib/reek/context_builder.rb | Reek.ContextBuilder.process_if | def process_if(exp, _parent)
children = exp.children
increase_statement_count_by(children[1])
increase_statement_count_by(children[2])
decrease_statement_count
process(exp)
end | ruby | def process_if(exp, _parent)
children = exp.children
increase_statement_count_by(children[1])
increase_statement_count_by(children[2])
decrease_statement_count
process(exp)
end | [
"def",
"process_if",
"(",
"exp",
",",
"_parent",
")",
"children",
"=",
"exp",
".",
"children",
"increase_statement_count_by",
"(",
"children",
"[",
"1",
"]",
")",
"increase_statement_count_by",
"(",
"children",
"[",
"2",
"]",
")",
"decrease_statement_count",
"process",
"(",
"exp",
")",
"end"
] | Handles `if` nodes.
An input example that would trigger this method would be:
if a > 5 && b < 3
puts 'bingo'
else
3
end
Counts the `if` body as one statement and the `else` body as another statement.
At the end we subtract one statement because the surrounding context was already counted
as one (e.g. via `process_def`).
`children[1]` refers to the `if` body (so `puts 'bingo'` from above) and
`children[2]` to the `else` body (so `3` from above), which might be nil. | [
"Handles",
"if",
"nodes",
"."
] | 8c6b5c0c6228a6981ab48543457889f9ea984054 | https://github.com/troessner/reek/blob/8c6b5c0c6228a6981ab48543457889f9ea984054/lib/reek/context_builder.rb#L312-L318 | train |
troessner/reek | lib/reek/context_builder.rb | Reek.ContextBuilder.process_rescue | def process_rescue(exp, _parent)
increase_statement_count_by(exp.children.first)
decrease_statement_count
process(exp)
end | ruby | def process_rescue(exp, _parent)
increase_statement_count_by(exp.children.first)
decrease_statement_count
process(exp)
end | [
"def",
"process_rescue",
"(",
"exp",
",",
"_parent",
")",
"increase_statement_count_by",
"(",
"exp",
".",
"children",
".",
"first",
")",
"decrease_statement_count",
"process",
"(",
"exp",
")",
"end"
] | Handles `rescue` nodes.
An input example that would trigger this method would be:
def simple
raise ArgumentError, 'raising...'
rescue => e
puts 'rescued!'
end
Counts everything before the `rescue` body as one statement.
At the end we subtract one statement because the surrounding context was already counted
as one (e.g. via `process_def`).
`exp.children.first` below refers to everything before the actual `rescue`
which would be the
raise ArgumentError, 'raising...'
in the example above.
`exp` would be the whole method body wrapped under a `rescue` node.
See `process_resbody` for additional reference. | [
"Handles",
"rescue",
"nodes",
"."
] | 8c6b5c0c6228a6981ab48543457889f9ea984054 | https://github.com/troessner/reek/blob/8c6b5c0c6228a6981ab48543457889f9ea984054/lib/reek/context_builder.rb#L388-L392 | train |
troessner/reek | lib/reek/context_builder.rb | Reek.ContextBuilder.inside_new_context | def inside_new_context(klass, *args)
new_context = append_new_context(klass, *args)
orig, self.current_context = current_context, new_context
yield
self.current_context = orig
end | ruby | def inside_new_context(klass, *args)
new_context = append_new_context(klass, *args)
orig, self.current_context = current_context, new_context
yield
self.current_context = orig
end | [
"def",
"inside_new_context",
"(",
"klass",
",",
"*",
"args",
")",
"new_context",
"=",
"append_new_context",
"(",
"klass",
",",
"args",
")",
"orig",
",",
"self",
".",
"current_context",
"=",
"current_context",
",",
"new_context",
"yield",
"self",
".",
"current_context",
"=",
"orig",
"end"
] | Stores a reference to the current context, creates a nested new one,
yields to the given block and then restores the previous context.
@param klass [Context::*Context] context class
@param args arguments for the class initializer
@yield block | [
"Stores",
"a",
"reference",
"to",
"the",
"current",
"context",
"creates",
"a",
"nested",
"new",
"one",
"yields",
"to",
"the",
"given",
"block",
"and",
"then",
"restores",
"the",
"previous",
"context",
"."
] | 8c6b5c0c6228a6981ab48543457889f9ea984054 | https://github.com/troessner/reek/blob/8c6b5c0c6228a6981ab48543457889f9ea984054/lib/reek/context_builder.rb#L489-L495 | train |
troessner/reek | lib/reek/context_builder.rb | Reek.ContextBuilder.append_new_context | def append_new_context(klass, *args)
klass.new(*args).tap do |new_context|
new_context.register_with_parent(current_context)
end
end | ruby | def append_new_context(klass, *args)
klass.new(*args).tap do |new_context|
new_context.register_with_parent(current_context)
end
end | [
"def",
"append_new_context",
"(",
"klass",
",",
"*",
"args",
")",
"klass",
".",
"new",
"(",
"args",
")",
".",
"tap",
"do",
"|",
"new_context",
"|",
"new_context",
".",
"register_with_parent",
"(",
"current_context",
")",
"end",
"end"
] | Appends a new child context to the current context but does not change
the current context.
@param klass [Context::*Context] context class
@param args arguments for the class initializer
@return [Context::*Context] the context that was appended | [
"Appends",
"a",
"new",
"child",
"context",
"to",
"the",
"current",
"context",
"but",
"does",
"not",
"change",
"the",
"current",
"context",
"."
] | 8c6b5c0c6228a6981ab48543457889f9ea984054 | https://github.com/troessner/reek/blob/8c6b5c0c6228a6981ab48543457889f9ea984054/lib/reek/context_builder.rb#L505-L509 | train |
troessner/reek | lib/reek/smell_configuration.rb | Reek.SmellConfiguration.value | def value(key, context)
overrides_for(context).each { |conf| return conf[key] if conf.key?(key) }
options.fetch(key)
end | ruby | def value(key, context)
overrides_for(context).each { |conf| return conf[key] if conf.key?(key) }
options.fetch(key)
end | [
"def",
"value",
"(",
"key",
",",
"context",
")",
"overrides_for",
"(",
"context",
")",
".",
"each",
"{",
"|",
"conf",
"|",
"return",
"conf",
"[",
"key",
"]",
"if",
"conf",
".",
"key?",
"(",
"key",
")",
"}",
"options",
".",
"fetch",
"(",
"key",
")",
"end"
] | Retrieves the value, if any, for the given +key+ in the given +context+.
Raises an error if neither the context nor this config have a value for
the key. | [
"Retrieves",
"the",
"value",
"if",
"any",
"for",
"the",
"given",
"+",
"key",
"+",
"in",
"the",
"given",
"+",
"context",
"+",
"."
] | 8c6b5c0c6228a6981ab48543457889f9ea984054 | https://github.com/troessner/reek/blob/8c6b5c0c6228a6981ab48543457889f9ea984054/lib/reek/smell_configuration.rb#L37-L40 | train |
troessner/reek | lib/reek/smell_configuration.rb | Reek.Overrides.for_context | def for_context(context)
contexts = hash.keys.select { |ckey| context.matches?([ckey]) }
contexts.map { |exc| hash[exc] }
end | ruby | def for_context(context)
contexts = hash.keys.select { |ckey| context.matches?([ckey]) }
contexts.map { |exc| hash[exc] }
end | [
"def",
"for_context",
"(",
"context",
")",
"contexts",
"=",
"hash",
".",
"keys",
".",
"select",
"{",
"|",
"ckey",
"|",
"context",
".",
"matches?",
"(",
"[",
"ckey",
"]",
")",
"}",
"contexts",
".",
"map",
"{",
"|",
"exc",
"|",
"hash",
"[",
"exc",
"]",
"}",
"end"
] | Find any overrides that match the supplied context | [
"Find",
"any",
"overrides",
"that",
"match",
"the",
"supplied",
"context"
] | 8c6b5c0c6228a6981ab48543457889f9ea984054 | https://github.com/troessner/reek/blob/8c6b5c0c6228a6981ab48543457889f9ea984054/lib/reek/smell_configuration.rb#L56-L59 | train |
troessner/reek | lib/reek/tree_dresser.rb | Reek.TreeDresser.dress | def dress(sexp, comment_map)
return sexp unless sexp.is_a? ::Parser::AST::Node
type = sexp.type
children = sexp.children.map { |child| dress(child, comment_map) }
comments = comment_map[sexp]
klass_map.klass_for(type).new(type, children,
location: sexp.loc, comments: comments)
end | ruby | def dress(sexp, comment_map)
return sexp unless sexp.is_a? ::Parser::AST::Node
type = sexp.type
children = sexp.children.map { |child| dress(child, comment_map) }
comments = comment_map[sexp]
klass_map.klass_for(type).new(type, children,
location: sexp.loc, comments: comments)
end | [
"def",
"dress",
"(",
"sexp",
",",
"comment_map",
")",
"return",
"sexp",
"unless",
"sexp",
".",
"is_a?",
"::",
"Parser",
"::",
"AST",
"::",
"Node",
"type",
"=",
"sexp",
".",
"type",
"children",
"=",
"sexp",
".",
"children",
".",
"map",
"{",
"|",
"child",
"|",
"dress",
"(",
"child",
",",
"comment_map",
")",
"}",
"comments",
"=",
"comment_map",
"[",
"sexp",
"]",
"klass_map",
".",
"klass_for",
"(",
"type",
")",
".",
"new",
"(",
"type",
",",
"children",
",",
"location",
":",
"sexp",
".",
"loc",
",",
"comments",
":",
"comments",
")",
"end"
] | Recursively enhance an AST with type-dependent mixins, and comments.
See {file:docs/How-reek-works-internally.md} for the big picture of how this works.
Example:
This
class Klazz; def meth(argument); argument.call_me; end; end
corresponds to this sexp:
(class
(const nil :Klazz) nil
(def :meth
(args
(arg :argument))
(send
(lvar :argument) :call_me)))
where every node is of type Parser::AST::Node.
Passing this into `dress` will return the exact same structure, but this
time the nodes will contain type-dependent mixins, e.g. this:
(const nil :Klazz)
will be of type Reek::AST::Node with Reek::AST::SexpExtensions::ConstNode mixed in.
@param sexp [Parser::AST::Node] the given sexp
@param comment_map [Hash] see the documentation for SourceCode#syntax_tree
@return an instance of Reek::AST::Node with type-dependent sexp extensions mixed in.
@quality :reek:FeatureEnvy
@quality :reek:TooManyStatements { max_statements: 6 } | [
"Recursively",
"enhance",
"an",
"AST",
"with",
"type",
"-",
"dependent",
"mixins",
"and",
"comments",
"."
] | 8c6b5c0c6228a6981ab48543457889f9ea984054 | https://github.com/troessner/reek/blob/8c6b5c0c6228a6981ab48543457889f9ea984054/lib/reek/tree_dresser.rb#L42-L50 | train |
uken/fluent-plugin-elasticsearch | lib/fluent/plugin/out_elasticsearch.rb | Fluent::Plugin.ElasticsearchOutput.append_record_to_messages | def append_record_to_messages(op, meta, header, record, msgs)
case op
when UPDATE_OP, UPSERT_OP
if meta.has_key?(ID_FIELD)
header[UPDATE_OP] = meta
msgs << @dump_proc.call(header) << BODY_DELIMITER
msgs << @dump_proc.call(update_body(record, op)) << BODY_DELIMITER
return true
end
when CREATE_OP
if meta.has_key?(ID_FIELD)
header[CREATE_OP] = meta
msgs << @dump_proc.call(header) << BODY_DELIMITER
msgs << @dump_proc.call(record) << BODY_DELIMITER
return true
end
when INDEX_OP
header[INDEX_OP] = meta
msgs << @dump_proc.call(header) << BODY_DELIMITER
msgs << @dump_proc.call(record) << BODY_DELIMITER
return true
end
return false
end | ruby | def append_record_to_messages(op, meta, header, record, msgs)
case op
when UPDATE_OP, UPSERT_OP
if meta.has_key?(ID_FIELD)
header[UPDATE_OP] = meta
msgs << @dump_proc.call(header) << BODY_DELIMITER
msgs << @dump_proc.call(update_body(record, op)) << BODY_DELIMITER
return true
end
when CREATE_OP
if meta.has_key?(ID_FIELD)
header[CREATE_OP] = meta
msgs << @dump_proc.call(header) << BODY_DELIMITER
msgs << @dump_proc.call(record) << BODY_DELIMITER
return true
end
when INDEX_OP
header[INDEX_OP] = meta
msgs << @dump_proc.call(header) << BODY_DELIMITER
msgs << @dump_proc.call(record) << BODY_DELIMITER
return true
end
return false
end | [
"def",
"append_record_to_messages",
"(",
"op",
",",
"meta",
",",
"header",
",",
"record",
",",
"msgs",
")",
"case",
"op",
"when",
"UPDATE_OP",
",",
"UPSERT_OP",
"if",
"meta",
".",
"has_key?",
"(",
"ID_FIELD",
")",
"header",
"[",
"UPDATE_OP",
"]",
"=",
"meta",
"msgs",
"<<",
"@dump_proc",
".",
"call",
"(",
"header",
")",
"<<",
"BODY_DELIMITER",
"msgs",
"<<",
"@dump_proc",
".",
"call",
"(",
"update_body",
"(",
"record",
",",
"op",
")",
")",
"<<",
"BODY_DELIMITER",
"return",
"true",
"end",
"when",
"CREATE_OP",
"if",
"meta",
".",
"has_key?",
"(",
"ID_FIELD",
")",
"header",
"[",
"CREATE_OP",
"]",
"=",
"meta",
"msgs",
"<<",
"@dump_proc",
".",
"call",
"(",
"header",
")",
"<<",
"BODY_DELIMITER",
"msgs",
"<<",
"@dump_proc",
".",
"call",
"(",
"record",
")",
"<<",
"BODY_DELIMITER",
"return",
"true",
"end",
"when",
"INDEX_OP",
"header",
"[",
"INDEX_OP",
"]",
"=",
"meta",
"msgs",
"<<",
"@dump_proc",
".",
"call",
"(",
"header",
")",
"<<",
"BODY_DELIMITER",
"msgs",
"<<",
"@dump_proc",
".",
"call",
"(",
"record",
")",
"<<",
"BODY_DELIMITER",
"return",
"true",
"end",
"return",
"false",
"end"
] | append_record_to_messages adds a record to the bulk message
payload to be submitted to Elasticsearch. Records that do
not include '_id' field are skipped when 'write_operation'
is configured for 'create' or 'update'
returns 'true' if record was appended to the bulk message
and 'false' otherwise | [
"append_record_to_messages",
"adds",
"a",
"record",
"to",
"the",
"bulk",
"message",
"payload",
"to",
"be",
"submitted",
"to",
"Elasticsearch",
".",
"Records",
"that",
"do",
"not",
"include",
"_id",
"field",
"are",
"skipped",
"when",
"write_operation",
"is",
"configured",
"for",
"create",
"or",
"update"
] | 9f9e51ddd012acb36c7f9d7a16e00970004098bc | https://github.com/uken/fluent-plugin-elasticsearch/blob/9f9e51ddd012acb36c7f9d7a16e00970004098bc/lib/fluent/plugin/out_elasticsearch.rb#L492-L515 | train |
uken/fluent-plugin-elasticsearch | lib/fluent/plugin/out_elasticsearch.rb | Fluent::Plugin.ElasticsearchOutput.send_bulk | def send_bulk(data, tag, chunk, bulk_message_count, extracted_values, info)
begin
log.on_trace { log.trace "bulk request: #{data}" }
response = client(info.host).bulk body: data, index: info.index
log.on_trace { log.trace "bulk response: #{response}" }
if response['errors']
error = Fluent::Plugin::ElasticsearchErrorHandler.new(self)
error.handle_error(response, tag, chunk, bulk_message_count, extracted_values)
end
rescue RetryStreamError => e
emit_tag = @retry_tag ? @retry_tag : tag
router.emit_stream(emit_tag, e.retry_stream)
rescue => e
ignore = @ignore_exception_classes.any? { |clazz| e.class <= clazz }
log.warn "Exception ignored in tag #{tag}: #{e.class.name} #{e.message}" if ignore
@_es = nil if @reconnect_on_error
@_es_info = nil if @reconnect_on_error
raise UnrecoverableRequestFailure if ignore && @exception_backup
# FIXME: identify unrecoverable errors and raise UnrecoverableRequestFailure instead
raise RecoverableRequestFailure, "could not push logs to Elasticsearch cluster (#{connection_options_description(info.host)}): #{e.message}" unless ignore
end
end | ruby | def send_bulk(data, tag, chunk, bulk_message_count, extracted_values, info)
begin
log.on_trace { log.trace "bulk request: #{data}" }
response = client(info.host).bulk body: data, index: info.index
log.on_trace { log.trace "bulk response: #{response}" }
if response['errors']
error = Fluent::Plugin::ElasticsearchErrorHandler.new(self)
error.handle_error(response, tag, chunk, bulk_message_count, extracted_values)
end
rescue RetryStreamError => e
emit_tag = @retry_tag ? @retry_tag : tag
router.emit_stream(emit_tag, e.retry_stream)
rescue => e
ignore = @ignore_exception_classes.any? { |clazz| e.class <= clazz }
log.warn "Exception ignored in tag #{tag}: #{e.class.name} #{e.message}" if ignore
@_es = nil if @reconnect_on_error
@_es_info = nil if @reconnect_on_error
raise UnrecoverableRequestFailure if ignore && @exception_backup
# FIXME: identify unrecoverable errors and raise UnrecoverableRequestFailure instead
raise RecoverableRequestFailure, "could not push logs to Elasticsearch cluster (#{connection_options_description(info.host)}): #{e.message}" unless ignore
end
end | [
"def",
"send_bulk",
"(",
"data",
",",
"tag",
",",
"chunk",
",",
"bulk_message_count",
",",
"extracted_values",
",",
"info",
")",
"begin",
"log",
".",
"on_trace",
"{",
"log",
".",
"trace",
"\"bulk request: #{data}\"",
"}",
"response",
"=",
"client",
"(",
"info",
".",
"host",
")",
".",
"bulk",
"body",
":",
"data",
",",
"index",
":",
"info",
".",
"index",
"log",
".",
"on_trace",
"{",
"log",
".",
"trace",
"\"bulk response: #{response}\"",
"}",
"if",
"response",
"[",
"'errors'",
"]",
"error",
"=",
"Fluent",
"::",
"Plugin",
"::",
"ElasticsearchErrorHandler",
".",
"new",
"(",
"self",
")",
"error",
".",
"handle_error",
"(",
"response",
",",
"tag",
",",
"chunk",
",",
"bulk_message_count",
",",
"extracted_values",
")",
"end",
"rescue",
"RetryStreamError",
"=>",
"e",
"emit_tag",
"=",
"@retry_tag",
"?",
"@retry_tag",
":",
"tag",
"router",
".",
"emit_stream",
"(",
"emit_tag",
",",
"e",
".",
"retry_stream",
")",
"rescue",
"=>",
"e",
"ignore",
"=",
"@ignore_exception_classes",
".",
"any?",
"{",
"|",
"clazz",
"|",
"e",
".",
"class",
"<=",
"clazz",
"}",
"log",
".",
"warn",
"\"Exception ignored in tag #{tag}: #{e.class.name} #{e.message}\"",
"if",
"ignore",
"@_es",
"=",
"nil",
"if",
"@reconnect_on_error",
"@_es_info",
"=",
"nil",
"if",
"@reconnect_on_error",
"raise",
"UnrecoverableRequestFailure",
"if",
"ignore",
"&&",
"@exception_backup",
"# FIXME: identify unrecoverable errors and raise UnrecoverableRequestFailure instead",
"raise",
"RecoverableRequestFailure",
",",
"\"could not push logs to Elasticsearch cluster (#{connection_options_description(info.host)}): #{e.message}\"",
"unless",
"ignore",
"end",
"end"
] | send_bulk given a specific bulk request, the original tag,
chunk, and bulk_message_count | [
"send_bulk",
"given",
"a",
"specific",
"bulk",
"request",
"the",
"original",
"tag",
"chunk",
"and",
"bulk_message_count"
] | 9f9e51ddd012acb36c7f9d7a16e00970004098bc | https://github.com/uken/fluent-plugin-elasticsearch/blob/9f9e51ddd012acb36c7f9d7a16e00970004098bc/lib/fluent/plugin/out_elasticsearch.rb#L709-L736 | train |
plataformatec/responders | lib/responders/controller_method.rb | Responders.ControllerMethod.responders | def responders(*responders)
self.responder = responders.inject(Class.new(responder)) do |klass, responder|
responder = case responder
when Module
responder
when String, Symbol
Responders.const_get("#{responder.to_s.camelize}Responder")
else
raise "responder has to be a string, a symbol or a module"
end
klass.send(:include, responder)
klass
end
end | ruby | def responders(*responders)
self.responder = responders.inject(Class.new(responder)) do |klass, responder|
responder = case responder
when Module
responder
when String, Symbol
Responders.const_get("#{responder.to_s.camelize}Responder")
else
raise "responder has to be a string, a symbol or a module"
end
klass.send(:include, responder)
klass
end
end | [
"def",
"responders",
"(",
"*",
"responders",
")",
"self",
".",
"responder",
"=",
"responders",
".",
"inject",
"(",
"Class",
".",
"new",
"(",
"responder",
")",
")",
"do",
"|",
"klass",
",",
"responder",
"|",
"responder",
"=",
"case",
"responder",
"when",
"Module",
"responder",
"when",
"String",
",",
"Symbol",
"Responders",
".",
"const_get",
"(",
"\"#{responder.to_s.camelize}Responder\"",
")",
"else",
"raise",
"\"responder has to be a string, a symbol or a module\"",
"end",
"klass",
".",
"send",
"(",
":include",
",",
"responder",
")",
"klass",
"end",
"end"
] | Adds the given responders to the current controller's responder, allowing you to cherry-pick
which responders you want per controller.
class InvitationsController < ApplicationController
responders :flash, :http_cache
end
Takes symbols and strings and translates them to VariableResponder (eg. :flash becomes FlashResponder).
Also allows passing in the responders modules in directly, so you could do:
responders FlashResponder, HttpCacheResponder
Or a mix of both methods:
responders :flash, MyCustomResponder | [
"Adds",
"the",
"given",
"responders",
"to",
"the",
"current",
"controller",
"s",
"responder",
"allowing",
"you",
"to",
"cherry",
"-",
"pick",
"which",
"responders",
"you",
"want",
"per",
"controller",
"."
] | a1a2706091d4ffcbbe387407ddfc5671a59ad842 | https://github.com/plataformatec/responders/blob/a1a2706091d4ffcbbe387407ddfc5671a59ad842/lib/responders/controller_method.rb#L19-L33 | train |
plataformatec/responders | lib/action_controller/respond_with.rb | ActionController.RespondWith.respond_with | def respond_with(*resources, &block)
if self.class.mimes_for_respond_to.empty?
raise "In order to use respond_with, first you need to declare the " \
"formats your controller responds to in the class level."
end
mimes = collect_mimes_from_class_level
collector = ActionController::MimeResponds::Collector.new(mimes, request.variant)
block.call(collector) if block_given?
if format = collector.negotiate_format(request)
_process_format(format)
options = resources.size == 1 ? {} : resources.extract_options!
options = options.clone
options[:default_response] = collector.response
(options.delete(:responder) || self.class.responder).call(self, resources, options)
else
raise ActionController::UnknownFormat
end
end | ruby | def respond_with(*resources, &block)
if self.class.mimes_for_respond_to.empty?
raise "In order to use respond_with, first you need to declare the " \
"formats your controller responds to in the class level."
end
mimes = collect_mimes_from_class_level
collector = ActionController::MimeResponds::Collector.new(mimes, request.variant)
block.call(collector) if block_given?
if format = collector.negotiate_format(request)
_process_format(format)
options = resources.size == 1 ? {} : resources.extract_options!
options = options.clone
options[:default_response] = collector.response
(options.delete(:responder) || self.class.responder).call(self, resources, options)
else
raise ActionController::UnknownFormat
end
end | [
"def",
"respond_with",
"(",
"*",
"resources",
",",
"&",
"block",
")",
"if",
"self",
".",
"class",
".",
"mimes_for_respond_to",
".",
"empty?",
"raise",
"\"In order to use respond_with, first you need to declare the \"",
"\"formats your controller responds to in the class level.\"",
"end",
"mimes",
"=",
"collect_mimes_from_class_level",
"collector",
"=",
"ActionController",
"::",
"MimeResponds",
"::",
"Collector",
".",
"new",
"(",
"mimes",
",",
"request",
".",
"variant",
")",
"block",
".",
"call",
"(",
"collector",
")",
"if",
"block_given?",
"if",
"format",
"=",
"collector",
".",
"negotiate_format",
"(",
"request",
")",
"_process_format",
"(",
"format",
")",
"options",
"=",
"resources",
".",
"size",
"==",
"1",
"?",
"{",
"}",
":",
"resources",
".",
"extract_options!",
"options",
"=",
"options",
".",
"clone",
"options",
"[",
":default_response",
"]",
"=",
"collector",
".",
"response",
"(",
"options",
".",
"delete",
"(",
":responder",
")",
"||",
"self",
".",
"class",
".",
"responder",
")",
".",
"call",
"(",
"self",
",",
"resources",
",",
"options",
")",
"else",
"raise",
"ActionController",
"::",
"UnknownFormat",
"end",
"end"
] | For a given controller action, respond_with generates an appropriate
response based on the mime-type requested by the client.
If the method is called with just a resource, as in this example -
class PeopleController < ApplicationController
respond_to :html, :xml, :json
def index
@people = Person.all
respond_with @people
end
end
then the mime-type of the response is typically selected based on the
request's Accept header and the set of available formats declared
by previous calls to the controller's class method +respond_to+. Alternatively
the mime-type can be selected by explicitly setting <tt>request.format</tt> in
the controller.
If an acceptable format is not identified, the application returns a
'406 - not acceptable' status. Otherwise, the default response is to render
a template named after the current action and the selected format,
e.g. <tt>index.html.erb</tt>. If no template is available, the behavior
depends on the selected format:
* for an html response - if the request method is +get+, an exception
is raised but for other requests such as +post+ the response
depends on whether the resource has any validation errors (i.e.
assuming that an attempt has been made to save the resource,
e.g. by a +create+ action) -
1. If there are no errors, i.e. the resource
was saved successfully, the response +redirect+'s to the resource
i.e. its +show+ action.
2. If there are validation errors, the response
renders a default action, which is <tt>:new</tt> for a
+post+ request or <tt>:edit</tt> for +patch+ or +put+.
Thus an example like this -
respond_to :html, :xml
def create
@user = User.new(params[:user])
flash[:notice] = 'User was successfully created.' if @user.save
respond_with(@user)
end
is equivalent, in the absence of <tt>create.html.erb</tt>, to -
def create
@user = User.new(params[:user])
respond_to do |format|
if @user.save
flash[:notice] = 'User was successfully created.'
format.html { redirect_to(@user) }
format.xml { render xml: @user }
else
format.html { render action: "new" }
format.xml { render xml: @user }
end
end
end
* for a JavaScript request - if the template isn't found, an exception is
raised.
* for other requests - i.e. data formats such as xml, json, csv etc, if
the resource passed to +respond_with+ responds to <code>to_<format></code>,
the method attempts to render the resource in the requested format
directly, e.g. for an xml request, the response is equivalent to calling
<code>render xml: resource</code>.
=== Nested resources
As outlined above, the +resources+ argument passed to +respond_with+
can play two roles. It can be used to generate the redirect url
for successful html requests (e.g. for +create+ actions when
no template exists), while for formats other than html and JavaScript
it is the object that gets rendered, by being converted directly to the
required format (again assuming no template exists).
For redirecting successful html requests, +respond_with+ also supports
the use of nested resources, which are supplied in the same way as
in <code>form_for</code> and <code>polymorphic_url</code>. For example -
def create
@project = Project.find(params[:project_id])
@task = @project.comments.build(params[:task])
flash[:notice] = 'Task was successfully created.' if @task.save
respond_with(@project, @task)
end
This would cause +respond_with+ to redirect to <code>project_task_url</code>
instead of <code>task_url</code>. For request formats other than html or
JavaScript, if multiple resources are passed in this way, it is the last
one specified that is rendered.
=== Customizing response behavior
Like +respond_to+, +respond_with+ may also be called with a block that
can be used to overwrite any of the default responses, e.g. -
def create
@user = User.new(params[:user])
flash[:notice] = "User was successfully created." if @user.save
respond_with(@user) do |format|
format.html { render }
end
end
The argument passed to the block is an ActionController::MimeResponds::Collector
object which stores the responses for the formats defined within the
block. Note that formats with responses defined explicitly in this way
do not have to first be declared using the class method +respond_to+.
Also, a hash passed to +respond_with+ immediately after the specified
resource(s) is interpreted as a set of options relevant to all
formats. Any option accepted by +render+ can be used, e.g.
respond_with @people, status: 200
However, note that these options are ignored after an unsuccessful attempt
to save a resource, e.g. when automatically rendering <tt>:new</tt>
after a post request.
Three additional options are relevant specifically to +respond_with+ -
1. <tt>:location</tt> - overwrites the default redirect location used after
a successful html +post+ request.
2. <tt>:action</tt> - overwrites the default render action used after an
unsuccessful html +post+ request.
3. <tt>:render</tt> - allows to pass any options directly to the <tt>:render<tt/>
call after unsuccessful html +post+ request. Usefull if for example you
need to render a template which is outside of controller's path or you
want to override the default http <tt>:status</tt> code, e.g.
respond_with(resource, render: { template: 'path/to/template', status: 422 }) | [
"For",
"a",
"given",
"controller",
"action",
"respond_with",
"generates",
"an",
"appropriate",
"response",
"based",
"on",
"the",
"mime",
"-",
"type",
"requested",
"by",
"the",
"client",
"."
] | a1a2706091d4ffcbbe387407ddfc5671a59ad842 | https://github.com/plataformatec/responders/blob/a1a2706091d4ffcbbe387407ddfc5671a59ad842/lib/action_controller/respond_with.rb#L196-L215 | train |
plataformatec/responders | lib/action_controller/respond_with.rb | ActionController.RespondWith.collect_mimes_from_class_level | def collect_mimes_from_class_level #:nodoc:
action = action_name.to_sym
self.class.mimes_for_respond_to.keys.select do |mime|
config = self.class.mimes_for_respond_to[mime]
if config[:except]
!config[:except].include?(action)
elsif config[:only]
config[:only].include?(action)
else
true
end
end
end | ruby | def collect_mimes_from_class_level #:nodoc:
action = action_name.to_sym
self.class.mimes_for_respond_to.keys.select do |mime|
config = self.class.mimes_for_respond_to[mime]
if config[:except]
!config[:except].include?(action)
elsif config[:only]
config[:only].include?(action)
else
true
end
end
end | [
"def",
"collect_mimes_from_class_level",
"#:nodoc:",
"action",
"=",
"action_name",
".",
"to_sym",
"self",
".",
"class",
".",
"mimes_for_respond_to",
".",
"keys",
".",
"select",
"do",
"|",
"mime",
"|",
"config",
"=",
"self",
".",
"class",
".",
"mimes_for_respond_to",
"[",
"mime",
"]",
"if",
"config",
"[",
":except",
"]",
"!",
"config",
"[",
":except",
"]",
".",
"include?",
"(",
"action",
")",
"elsif",
"config",
"[",
":only",
"]",
"config",
"[",
":only",
"]",
".",
"include?",
"(",
"action",
")",
"else",
"true",
"end",
"end",
"end"
] | Collect mimes declared in the class method respond_to valid for the
current action. | [
"Collect",
"mimes",
"declared",
"in",
"the",
"class",
"method",
"respond_to",
"valid",
"for",
"the",
"current",
"action",
"."
] | a1a2706091d4ffcbbe387407ddfc5671a59ad842 | https://github.com/plataformatec/responders/blob/a1a2706091d4ffcbbe387407ddfc5671a59ad842/lib/action_controller/respond_with.rb#L240-L254 | train |
algolia/algoliasearch-rails | lib/algoliasearch-rails.rb | AlgoliaSearch.ClassMethods.algolia_reindex | def algolia_reindex(batch_size = AlgoliaSearch::IndexSettings::DEFAULT_BATCH_SIZE, synchronous = false)
return if algolia_without_auto_index_scope
algolia_configurations.each do |options, settings|
next if algolia_indexing_disabled?(options)
next if options[:slave] || options[:replica]
# fetch the master settings
master_index = algolia_ensure_init(options, settings)
master_settings = master_index.get_settings rescue {} # if master doesn't exist yet
master_settings.merge!(JSON.parse(settings.to_settings.to_json)) # convert symbols to strings
# remove the replicas of the temporary index
master_settings.delete :slaves
master_settings.delete 'slaves'
master_settings.delete :replicas
master_settings.delete 'replicas'
# init temporary index
index_name = algolia_index_name(options)
tmp_options = options.merge({ :index_name => "#{index_name}.tmp" })
tmp_options.delete(:per_environment) # already included in the temporary index_name
tmp_settings = settings.dup
tmp_index = algolia_ensure_init(tmp_options, tmp_settings, master_settings)
algolia_find_in_batches(batch_size) do |group|
if algolia_conditional_index?(tmp_options)
# select only indexable objects
group = group.select { |o| algolia_indexable?(o, tmp_options) }
end
objects = group.map { |o| tmp_settings.get_attributes(o).merge 'objectID' => algolia_object_id_of(o, tmp_options) }
tmp_index.save_objects(objects)
end
move_task = SafeIndex.move_index(tmp_index.name, index_name)
master_index.wait_task(move_task["taskID"]) if synchronous || options[:synchronous]
end
nil
end | ruby | def algolia_reindex(batch_size = AlgoliaSearch::IndexSettings::DEFAULT_BATCH_SIZE, synchronous = false)
return if algolia_without_auto_index_scope
algolia_configurations.each do |options, settings|
next if algolia_indexing_disabled?(options)
next if options[:slave] || options[:replica]
# fetch the master settings
master_index = algolia_ensure_init(options, settings)
master_settings = master_index.get_settings rescue {} # if master doesn't exist yet
master_settings.merge!(JSON.parse(settings.to_settings.to_json)) # convert symbols to strings
# remove the replicas of the temporary index
master_settings.delete :slaves
master_settings.delete 'slaves'
master_settings.delete :replicas
master_settings.delete 'replicas'
# init temporary index
index_name = algolia_index_name(options)
tmp_options = options.merge({ :index_name => "#{index_name}.tmp" })
tmp_options.delete(:per_environment) # already included in the temporary index_name
tmp_settings = settings.dup
tmp_index = algolia_ensure_init(tmp_options, tmp_settings, master_settings)
algolia_find_in_batches(batch_size) do |group|
if algolia_conditional_index?(tmp_options)
# select only indexable objects
group = group.select { |o| algolia_indexable?(o, tmp_options) }
end
objects = group.map { |o| tmp_settings.get_attributes(o).merge 'objectID' => algolia_object_id_of(o, tmp_options) }
tmp_index.save_objects(objects)
end
move_task = SafeIndex.move_index(tmp_index.name, index_name)
master_index.wait_task(move_task["taskID"]) if synchronous || options[:synchronous]
end
nil
end | [
"def",
"algolia_reindex",
"(",
"batch_size",
"=",
"AlgoliaSearch",
"::",
"IndexSettings",
"::",
"DEFAULT_BATCH_SIZE",
",",
"synchronous",
"=",
"false",
")",
"return",
"if",
"algolia_without_auto_index_scope",
"algolia_configurations",
".",
"each",
"do",
"|",
"options",
",",
"settings",
"|",
"next",
"if",
"algolia_indexing_disabled?",
"(",
"options",
")",
"next",
"if",
"options",
"[",
":slave",
"]",
"||",
"options",
"[",
":replica",
"]",
"# fetch the master settings",
"master_index",
"=",
"algolia_ensure_init",
"(",
"options",
",",
"settings",
")",
"master_settings",
"=",
"master_index",
".",
"get_settings",
"rescue",
"{",
"}",
"# if master doesn't exist yet",
"master_settings",
".",
"merge!",
"(",
"JSON",
".",
"parse",
"(",
"settings",
".",
"to_settings",
".",
"to_json",
")",
")",
"# convert symbols to strings",
"# remove the replicas of the temporary index",
"master_settings",
".",
"delete",
":slaves",
"master_settings",
".",
"delete",
"'slaves'",
"master_settings",
".",
"delete",
":replicas",
"master_settings",
".",
"delete",
"'replicas'",
"# init temporary index",
"index_name",
"=",
"algolia_index_name",
"(",
"options",
")",
"tmp_options",
"=",
"options",
".",
"merge",
"(",
"{",
":index_name",
"=>",
"\"#{index_name}.tmp\"",
"}",
")",
"tmp_options",
".",
"delete",
"(",
":per_environment",
")",
"# already included in the temporary index_name",
"tmp_settings",
"=",
"settings",
".",
"dup",
"tmp_index",
"=",
"algolia_ensure_init",
"(",
"tmp_options",
",",
"tmp_settings",
",",
"master_settings",
")",
"algolia_find_in_batches",
"(",
"batch_size",
")",
"do",
"|",
"group",
"|",
"if",
"algolia_conditional_index?",
"(",
"tmp_options",
")",
"# select only indexable objects",
"group",
"=",
"group",
".",
"select",
"{",
"|",
"o",
"|",
"algolia_indexable?",
"(",
"o",
",",
"tmp_options",
")",
"}",
"end",
"objects",
"=",
"group",
".",
"map",
"{",
"|",
"o",
"|",
"tmp_settings",
".",
"get_attributes",
"(",
"o",
")",
".",
"merge",
"'objectID'",
"=>",
"algolia_object_id_of",
"(",
"o",
",",
"tmp_options",
")",
"}",
"tmp_index",
".",
"save_objects",
"(",
"objects",
")",
"end",
"move_task",
"=",
"SafeIndex",
".",
"move_index",
"(",
"tmp_index",
".",
"name",
",",
"index_name",
")",
"master_index",
".",
"wait_task",
"(",
"move_task",
"[",
"\"taskID\"",
"]",
")",
"if",
"synchronous",
"||",
"options",
"[",
":synchronous",
"]",
"end",
"nil",
"end"
] | reindex whole database using a extra temporary index + move operation | [
"reindex",
"whole",
"database",
"using",
"a",
"extra",
"temporary",
"index",
"+",
"move",
"operation"
] | 360e47d733476e6611d9874cf89e57942b7f2939 | https://github.com/algolia/algoliasearch-rails/blob/360e47d733476e6611d9874cf89e57942b7f2939/lib/algoliasearch-rails.rb#L540-L577 | train |
algolia/algoliasearch-rails | lib/algoliasearch-rails.rb | AlgoliaSearch.SafeIndex.get_settings | def get_settings(*args)
SafeIndex.log_or_throw(:get_settings, @raise_on_failure) do
begin
@index.get_settings(*args)
rescue Algolia::AlgoliaError => e
return {} if e.code == 404 # not fatal
raise e
end
end
end | ruby | def get_settings(*args)
SafeIndex.log_or_throw(:get_settings, @raise_on_failure) do
begin
@index.get_settings(*args)
rescue Algolia::AlgoliaError => e
return {} if e.code == 404 # not fatal
raise e
end
end
end | [
"def",
"get_settings",
"(",
"*",
"args",
")",
"SafeIndex",
".",
"log_or_throw",
"(",
":get_settings",
",",
"@raise_on_failure",
")",
"do",
"begin",
"@index",
".",
"get_settings",
"(",
"args",
")",
"rescue",
"Algolia",
"::",
"AlgoliaError",
"=>",
"e",
"return",
"{",
"}",
"if",
"e",
".",
"code",
"==",
"404",
"# not fatal",
"raise",
"e",
"end",
"end",
"end"
] | special handling of get_settings to avoid raising errors on 404 | [
"special",
"handling",
"of",
"get_settings",
"to",
"avoid",
"raising",
"errors",
"on",
"404"
] | 360e47d733476e6611d9874cf89e57942b7f2939 | https://github.com/algolia/algoliasearch-rails/blob/360e47d733476e6611d9874cf89e57942b7f2939/lib/algoliasearch-rails.rb#L328-L337 | train |
jhund/filterrific | lib/filterrific/param_set.rb | Filterrific.ParamSet.define_and_assign_attr_accessors_for_each_filter | def define_and_assign_attr_accessors_for_each_filter(fp)
model_class.filterrific_available_filters.each do |filter_name|
self.class.send(:attr_accessor, filter_name)
v = fp[filter_name]
self.send("#{ filter_name }=", v) if v.present?
end
end | ruby | def define_and_assign_attr_accessors_for_each_filter(fp)
model_class.filterrific_available_filters.each do |filter_name|
self.class.send(:attr_accessor, filter_name)
v = fp[filter_name]
self.send("#{ filter_name }=", v) if v.present?
end
end | [
"def",
"define_and_assign_attr_accessors_for_each_filter",
"(",
"fp",
")",
"model_class",
".",
"filterrific_available_filters",
".",
"each",
"do",
"|",
"filter_name",
"|",
"self",
".",
"class",
".",
"send",
"(",
":attr_accessor",
",",
"filter_name",
")",
"v",
"=",
"fp",
"[",
"filter_name",
"]",
"self",
".",
"send",
"(",
"\"#{ filter_name }=\"",
",",
"v",
")",
"if",
"v",
".",
"present?",
"end",
"end"
] | Defines attr accessors for each available_filter on self and assigns
values based on fp.
@param fp [Hash] filterrific_params with stringified keys | [
"Defines",
"attr",
"accessors",
"for",
"each",
"available_filter",
"on",
"self",
"and",
"assigns",
"values",
"based",
"on",
"fp",
"."
] | 811edc57d3e2a3e538c1f0e9554e0909be052881 | https://github.com/jhund/filterrific/blob/811edc57d3e2a3e538c1f0e9554e0909be052881/lib/filterrific/param_set.rb#L120-L126 | train |
jhund/filterrific | lib/filterrific/action_controller_extension.rb | Filterrific.ActionControllerExtension.compute_filterrific_params | def compute_filterrific_params(model_class, filterrific_params, opts, persistence_id)
opts = { "sanitize_params" => true }.merge(opts.stringify_keys)
r = (
filterrific_params.presence || # start with passed in params
(persistence_id && session[persistence_id].presence) || # then try session persisted params if persistence_id is present
opts['default_filter_params'] || # then use passed in opts
model_class.filterrific_default_filter_params # finally use model_class defaults
).stringify_keys
r.slice!(*opts['available_filters'].map(&:to_s)) if opts['available_filters']
# Sanitize params to prevent reflected XSS attack
if opts["sanitize_params"]
r.each { |k,v| r[k] = sanitize_filterrific_param(r[k]) }
end
r
end | ruby | def compute_filterrific_params(model_class, filterrific_params, opts, persistence_id)
opts = { "sanitize_params" => true }.merge(opts.stringify_keys)
r = (
filterrific_params.presence || # start with passed in params
(persistence_id && session[persistence_id].presence) || # then try session persisted params if persistence_id is present
opts['default_filter_params'] || # then use passed in opts
model_class.filterrific_default_filter_params # finally use model_class defaults
).stringify_keys
r.slice!(*opts['available_filters'].map(&:to_s)) if opts['available_filters']
# Sanitize params to prevent reflected XSS attack
if opts["sanitize_params"]
r.each { |k,v| r[k] = sanitize_filterrific_param(r[k]) }
end
r
end | [
"def",
"compute_filterrific_params",
"(",
"model_class",
",",
"filterrific_params",
",",
"opts",
",",
"persistence_id",
")",
"opts",
"=",
"{",
"\"sanitize_params\"",
"=>",
"true",
"}",
".",
"merge",
"(",
"opts",
".",
"stringify_keys",
")",
"r",
"=",
"(",
"filterrific_params",
".",
"presence",
"||",
"# start with passed in params",
"(",
"persistence_id",
"&&",
"session",
"[",
"persistence_id",
"]",
".",
"presence",
")",
"||",
"# then try session persisted params if persistence_id is present",
"opts",
"[",
"'default_filter_params'",
"]",
"||",
"# then use passed in opts",
"model_class",
".",
"filterrific_default_filter_params",
"# finally use model_class defaults",
")",
".",
"stringify_keys",
"r",
".",
"slice!",
"(",
"opts",
"[",
"'available_filters'",
"]",
".",
"map",
"(",
":to_s",
")",
")",
"if",
"opts",
"[",
"'available_filters'",
"]",
"# Sanitize params to prevent reflected XSS attack",
"if",
"opts",
"[",
"\"sanitize_params\"",
"]",
"r",
".",
"each",
"{",
"|",
"k",
",",
"v",
"|",
"r",
"[",
"k",
"]",
"=",
"sanitize_filterrific_param",
"(",
"r",
"[",
"k",
"]",
")",
"}",
"end",
"r",
"end"
] | Computes filterrific params using a number of strategies. Limits params
to 'available_filters' if given via opts.
@param model_class [ActiveRecord::Base]
@param filterrific_params [ActionController::Params, Hash]
@param opts [Hash]
@option opts [Boolean, optional] "sanitize_params"
if true, sanitizes all filterrific params to prevent reflected (or stored) XSS attacks.
Defaults to true.
@param persistence_id [String, nil] | [
"Computes",
"filterrific",
"params",
"using",
"a",
"number",
"of",
"strategies",
".",
"Limits",
"params",
"to",
"available_filters",
"if",
"given",
"via",
"opts",
"."
] | 811edc57d3e2a3e538c1f0e9554e0909be052881 | https://github.com/jhund/filterrific/blob/811edc57d3e2a3e538c1f0e9554e0909be052881/lib/filterrific/action_controller_extension.rb#L70-L84 | train |
jhund/filterrific | lib/filterrific/action_view_extension.rb | Filterrific.ActionViewExtension.form_for_filterrific | def form_for_filterrific(record, options = {}, &block)
options[:as] ||= :filterrific
options[:html] ||= {}
options[:html][:method] ||= :get
options[:html][:id] ||= :filterrific_filter
options[:url] ||= url_for(
:controller => controller.controller_name,
:action => controller.action_name
)
form_for(record, options, &block)
end | ruby | def form_for_filterrific(record, options = {}, &block)
options[:as] ||= :filterrific
options[:html] ||= {}
options[:html][:method] ||= :get
options[:html][:id] ||= :filterrific_filter
options[:url] ||= url_for(
:controller => controller.controller_name,
:action => controller.action_name
)
form_for(record, options, &block)
end | [
"def",
"form_for_filterrific",
"(",
"record",
",",
"options",
"=",
"{",
"}",
",",
"&",
"block",
")",
"options",
"[",
":as",
"]",
"||=",
":filterrific",
"options",
"[",
":html",
"]",
"||=",
"{",
"}",
"options",
"[",
":html",
"]",
"[",
":method",
"]",
"||=",
":get",
"options",
"[",
":html",
"]",
"[",
":id",
"]",
"||=",
":filterrific_filter",
"options",
"[",
":url",
"]",
"||=",
"url_for",
"(",
":controller",
"=>",
"controller",
".",
"controller_name",
",",
":action",
"=>",
"controller",
".",
"action_name",
")",
"form_for",
"(",
"record",
",",
"options",
",",
"block",
")",
"end"
] | Sets all options on form_for to defaults that work with Filterrific
@param record [Filterrific] the @filterrific object
@param options [Hash] standard options for form_for
@param block [Proc] the form body | [
"Sets",
"all",
"options",
"on",
"form_for",
"to",
"defaults",
"that",
"work",
"with",
"Filterrific"
] | 811edc57d3e2a3e538c1f0e9554e0909be052881 | https://github.com/jhund/filterrific/blob/811edc57d3e2a3e538c1f0e9554e0909be052881/lib/filterrific/action_view_extension.rb#L14-L24 | train |
jhund/filterrific | lib/filterrific/action_view_extension.rb | Filterrific.ActionViewExtension.filterrific_sorting_link_reverse_order | def filterrific_sorting_link_reverse_order(filterrific, new_sort_key, opts)
# current sort column, toggle search_direction
new_sort_direction = 'asc' == opts[:current_sort_direction] ? 'desc' : 'asc'
new_sorting = safe_join([new_sort_key, new_sort_direction], '_')
css_classes = safe_join([
opts[:active_column_class],
opts[:html_attrs].delete(:class)
].compact, ' ')
new_filterrific_params = filterrific.to_hash
.with_indifferent_access
.merge(opts[:sorting_scope_name] => new_sorting)
url_for_attrs = opts[:url_for_attrs].merge(:filterrific => new_filterrific_params)
link_to(
safe_join([opts[:label], opts[:current_sort_direction_indicator]], ' '),
url_for(url_for_attrs),
opts[:html_attrs].reverse_merge(:class => css_classes, :method => :get, :remote => true)
)
end | ruby | def filterrific_sorting_link_reverse_order(filterrific, new_sort_key, opts)
# current sort column, toggle search_direction
new_sort_direction = 'asc' == opts[:current_sort_direction] ? 'desc' : 'asc'
new_sorting = safe_join([new_sort_key, new_sort_direction], '_')
css_classes = safe_join([
opts[:active_column_class],
opts[:html_attrs].delete(:class)
].compact, ' ')
new_filterrific_params = filterrific.to_hash
.with_indifferent_access
.merge(opts[:sorting_scope_name] => new_sorting)
url_for_attrs = opts[:url_for_attrs].merge(:filterrific => new_filterrific_params)
link_to(
safe_join([opts[:label], opts[:current_sort_direction_indicator]], ' '),
url_for(url_for_attrs),
opts[:html_attrs].reverse_merge(:class => css_classes, :method => :get, :remote => true)
)
end | [
"def",
"filterrific_sorting_link_reverse_order",
"(",
"filterrific",
",",
"new_sort_key",
",",
"opts",
")",
"# current sort column, toggle search_direction",
"new_sort_direction",
"=",
"'asc'",
"==",
"opts",
"[",
":current_sort_direction",
"]",
"?",
"'desc'",
":",
"'asc'",
"new_sorting",
"=",
"safe_join",
"(",
"[",
"new_sort_key",
",",
"new_sort_direction",
"]",
",",
"'_'",
")",
"css_classes",
"=",
"safe_join",
"(",
"[",
"opts",
"[",
":active_column_class",
"]",
",",
"opts",
"[",
":html_attrs",
"]",
".",
"delete",
"(",
":class",
")",
"]",
".",
"compact",
",",
"' '",
")",
"new_filterrific_params",
"=",
"filterrific",
".",
"to_hash",
".",
"with_indifferent_access",
".",
"merge",
"(",
"opts",
"[",
":sorting_scope_name",
"]",
"=>",
"new_sorting",
")",
"url_for_attrs",
"=",
"opts",
"[",
":url_for_attrs",
"]",
".",
"merge",
"(",
":filterrific",
"=>",
"new_filterrific_params",
")",
"link_to",
"(",
"safe_join",
"(",
"[",
"opts",
"[",
":label",
"]",
",",
"opts",
"[",
":current_sort_direction_indicator",
"]",
"]",
",",
"' '",
")",
",",
"url_for",
"(",
"url_for_attrs",
")",
",",
"opts",
"[",
":html_attrs",
"]",
".",
"reverse_merge",
"(",
":class",
"=>",
"css_classes",
",",
":method",
"=>",
":get",
",",
":remote",
"=>",
"true",
")",
")",
"end"
] | Renders HTML to reverse sort order on currently sorted column.
@param filterrific [Filterrific::ParamSet]
@param new_sort_key [String]
@param opts [Hash]
@return [String] an HTML fragment | [
"Renders",
"HTML",
"to",
"reverse",
"sort",
"order",
"on",
"currently",
"sorted",
"column",
"."
] | 811edc57d3e2a3e538c1f0e9554e0909be052881 | https://github.com/jhund/filterrific/blob/811edc57d3e2a3e538c1f0e9554e0909be052881/lib/filterrific/action_view_extension.rb#L102-L119 | train |
dotless-de/vagrant-vbguest | lib/vagrant-vbguest/config.rb | VagrantVbguest.Config.to_hash | def to_hash
{
:installer => installer,
:installer_arguments => installer_arguments,
:iso_path => iso_path,
:iso_upload_path => iso_upload_path,
:iso_mount_point => iso_mount_point,
:auto_update => auto_update,
:auto_reboot => auto_reboot,
:no_install => no_install,
:no_remote => no_remote,
:yes => yes
}
end | ruby | def to_hash
{
:installer => installer,
:installer_arguments => installer_arguments,
:iso_path => iso_path,
:iso_upload_path => iso_upload_path,
:iso_mount_point => iso_mount_point,
:auto_update => auto_update,
:auto_reboot => auto_reboot,
:no_install => no_install,
:no_remote => no_remote,
:yes => yes
}
end | [
"def",
"to_hash",
"{",
":installer",
"=>",
"installer",
",",
":installer_arguments",
"=>",
"installer_arguments",
",",
":iso_path",
"=>",
"iso_path",
",",
":iso_upload_path",
"=>",
"iso_upload_path",
",",
":iso_mount_point",
"=>",
"iso_mount_point",
",",
":auto_update",
"=>",
"auto_update",
",",
":auto_reboot",
"=>",
"auto_reboot",
",",
":no_install",
"=>",
"no_install",
",",
":no_remote",
"=>",
"no_remote",
",",
":yes",
"=>",
"yes",
"}",
"end"
] | explicit hash, to get symbols in hash keys | [
"explicit",
"hash",
"to",
"get",
"symbols",
"in",
"hash",
"keys"
] | 934fd22864c811c951c020cfcfc5c2ef9d79d5ef | https://github.com/dotless-de/vagrant-vbguest/blob/934fd22864c811c951c020cfcfc5c2ef9d79d5ef/lib/vagrant-vbguest/config.rb#L42-L55 | train |
dotless-de/vagrant-vbguest | lib/vagrant-vbguest/command.rb | VagrantVbguest.Command.execute_on_vm | def execute_on_vm(vm, options)
check_runable_on(vm)
options = options.clone
_method = options.delete(:_method)
_rebootable = options.delete(:_rebootable)
options = vm.config.vbguest.to_hash.merge(options)
machine = VagrantVbguest::Machine.new(vm, options)
status = machine.state
vm.env.ui.send((:ok == status ? :success : :warn), I18n.t("vagrant_vbguest.status.#{status}", machine.info))
if _method != :status
machine.send(_method)
end
reboot!(vm, options) if _rebootable && machine.reboot?
rescue VagrantVbguest::Installer::NoInstallerFoundError => e
vm.env.ui.error e.message
end | ruby | def execute_on_vm(vm, options)
check_runable_on(vm)
options = options.clone
_method = options.delete(:_method)
_rebootable = options.delete(:_rebootable)
options = vm.config.vbguest.to_hash.merge(options)
machine = VagrantVbguest::Machine.new(vm, options)
status = machine.state
vm.env.ui.send((:ok == status ? :success : :warn), I18n.t("vagrant_vbguest.status.#{status}", machine.info))
if _method != :status
machine.send(_method)
end
reboot!(vm, options) if _rebootable && machine.reboot?
rescue VagrantVbguest::Installer::NoInstallerFoundError => e
vm.env.ui.error e.message
end | [
"def",
"execute_on_vm",
"(",
"vm",
",",
"options",
")",
"check_runable_on",
"(",
"vm",
")",
"options",
"=",
"options",
".",
"clone",
"_method",
"=",
"options",
".",
"delete",
"(",
":_method",
")",
"_rebootable",
"=",
"options",
".",
"delete",
"(",
":_rebootable",
")",
"options",
"=",
"vm",
".",
"config",
".",
"vbguest",
".",
"to_hash",
".",
"merge",
"(",
"options",
")",
"machine",
"=",
"VagrantVbguest",
"::",
"Machine",
".",
"new",
"(",
"vm",
",",
"options",
")",
"status",
"=",
"machine",
".",
"state",
"vm",
".",
"env",
".",
"ui",
".",
"send",
"(",
"(",
":ok",
"==",
"status",
"?",
":success",
":",
":warn",
")",
",",
"I18n",
".",
"t",
"(",
"\"vagrant_vbguest.status.#{status}\"",
",",
"machine",
".",
"info",
")",
")",
"if",
"_method",
"!=",
":status",
"machine",
".",
"send",
"(",
"_method",
")",
"end",
"reboot!",
"(",
"vm",
",",
"options",
")",
"if",
"_rebootable",
"&&",
"machine",
".",
"reboot?",
"rescue",
"VagrantVbguest",
"::",
"Installer",
"::",
"NoInstallerFoundError",
"=>",
"e",
"vm",
".",
"env",
".",
"ui",
".",
"error",
"e",
".",
"message",
"end"
] | Executes a task on a specific VM.
@param vm [Vagrant::VM]
@param options [Hash] Parsed options from the command line | [
"Executes",
"a",
"task",
"on",
"a",
"specific",
"VM",
"."
] | 934fd22864c811c951c020cfcfc5c2ef9d79d5ef | https://github.com/dotless-de/vagrant-vbguest/blob/934fd22864c811c951c020cfcfc5c2ef9d79d5ef/lib/vagrant-vbguest/command.rb#L87-L106 | train |
nathanvda/cocoon | lib/cocoon/view_helpers.rb | Cocoon.ViewHelpers.link_to_add_association | def link_to_add_association(*args, &block)
if block_given?
link_to_add_association(capture(&block), *args)
elsif args.first.respond_to?(:object)
association = args.second
name = I18n.translate("cocoon.#{association}.add", default: I18n.translate('cocoon.defaults.add'))
link_to_add_association(name, *args)
else
name, f, association, html_options = *args
html_options ||= {}
render_options = html_options.delete(:render_options)
render_options ||= {}
override_partial = html_options.delete(:partial)
wrap_object = html_options.delete(:wrap_object)
force_non_association_create = html_options.delete(:force_non_association_create) || false
form_parameter_name = html_options.delete(:form_name) || 'f'
count = html_options.delete(:count).to_i
html_options[:class] = [html_options[:class], "add_fields"].compact.join(' ')
html_options[:'data-association'] = association.to_s.singularize
html_options[:'data-associations'] = association.to_s.pluralize
new_object = create_object(f, association, force_non_association_create)
new_object = wrap_object.call(new_object) if wrap_object.respond_to?(:call)
html_options[:'data-association-insertion-template'] = CGI.escapeHTML(render_association(association, f, new_object, form_parameter_name, render_options, override_partial).to_str).html_safe
html_options[:'data-count'] = count if count > 0
link_to(name, '#', html_options)
end
end | ruby | def link_to_add_association(*args, &block)
if block_given?
link_to_add_association(capture(&block), *args)
elsif args.first.respond_to?(:object)
association = args.second
name = I18n.translate("cocoon.#{association}.add", default: I18n.translate('cocoon.defaults.add'))
link_to_add_association(name, *args)
else
name, f, association, html_options = *args
html_options ||= {}
render_options = html_options.delete(:render_options)
render_options ||= {}
override_partial = html_options.delete(:partial)
wrap_object = html_options.delete(:wrap_object)
force_non_association_create = html_options.delete(:force_non_association_create) || false
form_parameter_name = html_options.delete(:form_name) || 'f'
count = html_options.delete(:count).to_i
html_options[:class] = [html_options[:class], "add_fields"].compact.join(' ')
html_options[:'data-association'] = association.to_s.singularize
html_options[:'data-associations'] = association.to_s.pluralize
new_object = create_object(f, association, force_non_association_create)
new_object = wrap_object.call(new_object) if wrap_object.respond_to?(:call)
html_options[:'data-association-insertion-template'] = CGI.escapeHTML(render_association(association, f, new_object, form_parameter_name, render_options, override_partial).to_str).html_safe
html_options[:'data-count'] = count if count > 0
link_to(name, '#', html_options)
end
end | [
"def",
"link_to_add_association",
"(",
"*",
"args",
",",
"&",
"block",
")",
"if",
"block_given?",
"link_to_add_association",
"(",
"capture",
"(",
"block",
")",
",",
"args",
")",
"elsif",
"args",
".",
"first",
".",
"respond_to?",
"(",
":object",
")",
"association",
"=",
"args",
".",
"second",
"name",
"=",
"I18n",
".",
"translate",
"(",
"\"cocoon.#{association}.add\"",
",",
"default",
":",
"I18n",
".",
"translate",
"(",
"'cocoon.defaults.add'",
")",
")",
"link_to_add_association",
"(",
"name",
",",
"args",
")",
"else",
"name",
",",
"f",
",",
"association",
",",
"html_options",
"=",
"args",
"html_options",
"||=",
"{",
"}",
"render_options",
"=",
"html_options",
".",
"delete",
"(",
":render_options",
")",
"render_options",
"||=",
"{",
"}",
"override_partial",
"=",
"html_options",
".",
"delete",
"(",
":partial",
")",
"wrap_object",
"=",
"html_options",
".",
"delete",
"(",
":wrap_object",
")",
"force_non_association_create",
"=",
"html_options",
".",
"delete",
"(",
":force_non_association_create",
")",
"||",
"false",
"form_parameter_name",
"=",
"html_options",
".",
"delete",
"(",
":form_name",
")",
"||",
"'f'",
"count",
"=",
"html_options",
".",
"delete",
"(",
":count",
")",
".",
"to_i",
"html_options",
"[",
":class",
"]",
"=",
"[",
"html_options",
"[",
":class",
"]",
",",
"\"add_fields\"",
"]",
".",
"compact",
".",
"join",
"(",
"' '",
")",
"html_options",
"[",
":'",
"'",
"]",
"=",
"association",
".",
"to_s",
".",
"singularize",
"html_options",
"[",
":'",
"'",
"]",
"=",
"association",
".",
"to_s",
".",
"pluralize",
"new_object",
"=",
"create_object",
"(",
"f",
",",
"association",
",",
"force_non_association_create",
")",
"new_object",
"=",
"wrap_object",
".",
"call",
"(",
"new_object",
")",
"if",
"wrap_object",
".",
"respond_to?",
"(",
":call",
")",
"html_options",
"[",
":'",
"'",
"]",
"=",
"CGI",
".",
"escapeHTML",
"(",
"render_association",
"(",
"association",
",",
"f",
",",
"new_object",
",",
"form_parameter_name",
",",
"render_options",
",",
"override_partial",
")",
".",
"to_str",
")",
".",
"html_safe",
"html_options",
"[",
":'",
"'",
"]",
"=",
"count",
"if",
"count",
">",
"0",
"link_to",
"(",
"name",
",",
"'#'",
",",
"html_options",
")",
"end",
"end"
] | shows a link that will allow to dynamically add a new associated object.
- *name* : the text to show in the link
- *f* : the form this should come in (the formtastic form)
- *association* : the associated objects, e.g. :tasks, this should be the name of the <tt>has_many</tt> relation.
- *html_options*: html options to be passed to <tt>link_to</tt> (see <tt>link_to</tt>)
- *:render_options* : options passed to `simple_fields_for, semantic_fields_for or fields_for`
- *:locals* : the locals hash in the :render_options is handed to the partial
- *:partial* : explicitly override the default partial name
- *:wrap_object* : a proc that will allow to wrap your object, especially suited when using
decorators, or if you want special initialisation
- *:form_name* : the parameter for the form in the nested form partial. Default `f`.
- *:count* : Count of how many objects will be added on a single click. Default `1`.
- *&block*: see <tt>link_to</tt> | [
"shows",
"a",
"link",
"that",
"will",
"allow",
"to",
"dynamically",
"add",
"a",
"new",
"associated",
"object",
"."
] | ec18c446a5475aa4959c699c797ee0fe9b0c9136 | https://github.com/nathanvda/cocoon/blob/ec18c446a5475aa4959c699c797ee0fe9b0c9136/lib/cocoon/view_helpers.rb#L71-L104 | train |
getsentry/raven-ruby | lib/raven/instance.rb | Raven.Instance.capture | def capture(options = {})
if block_given?
begin
yield
rescue Error
raise # Don't capture Raven errors
rescue Exception => e
capture_type(e, options)
raise
end
else
install_at_exit_hook(options)
end
end | ruby | def capture(options = {})
if block_given?
begin
yield
rescue Error
raise # Don't capture Raven errors
rescue Exception => e
capture_type(e, options)
raise
end
else
install_at_exit_hook(options)
end
end | [
"def",
"capture",
"(",
"options",
"=",
"{",
"}",
")",
"if",
"block_given?",
"begin",
"yield",
"rescue",
"Error",
"raise",
"# Don't capture Raven errors",
"rescue",
"Exception",
"=>",
"e",
"capture_type",
"(",
"e",
",",
"options",
")",
"raise",
"end",
"else",
"install_at_exit_hook",
"(",
"options",
")",
"end",
"end"
] | Capture and process any exceptions from the given block.
@example
Raven.capture do
MyApp.run
end | [
"Capture",
"and",
"process",
"any",
"exceptions",
"from",
"the",
"given",
"block",
"."
] | 729c22f9284939695f14822683bff1a0b72502bd | https://github.com/getsentry/raven-ruby/blob/729c22f9284939695f14822683bff1a0b72502bd/lib/raven/instance.rb#L90-L103 | train |
getsentry/raven-ruby | lib/raven/instance.rb | Raven.Instance.annotate_exception | def annotate_exception(exc, options = {})
notes = (exc.instance_variable_defined?(:@__raven_context) && exc.instance_variable_get(:@__raven_context)) || {}
Raven::Utils::DeepMergeHash.deep_merge!(notes, options)
exc.instance_variable_set(:@__raven_context, notes)
exc
end | ruby | def annotate_exception(exc, options = {})
notes = (exc.instance_variable_defined?(:@__raven_context) && exc.instance_variable_get(:@__raven_context)) || {}
Raven::Utils::DeepMergeHash.deep_merge!(notes, options)
exc.instance_variable_set(:@__raven_context, notes)
exc
end | [
"def",
"annotate_exception",
"(",
"exc",
",",
"options",
"=",
"{",
"}",
")",
"notes",
"=",
"(",
"exc",
".",
"instance_variable_defined?",
"(",
":@__raven_context",
")",
"&&",
"exc",
".",
"instance_variable_get",
"(",
":@__raven_context",
")",
")",
"||",
"{",
"}",
"Raven",
"::",
"Utils",
"::",
"DeepMergeHash",
".",
"deep_merge!",
"(",
"notes",
",",
"options",
")",
"exc",
".",
"instance_variable_set",
"(",
":@__raven_context",
",",
"notes",
")",
"exc",
"end"
] | Provides extra context to the exception prior to it being handled by
Raven. An exception can have multiple annotations, which are merged
together.
The options (annotation) is treated the same as the ``options``
parameter to ``capture_exception`` or ``Event.from_exception``, and
can contain the same ``:user``, ``:tags``, etc. options as these
methods.
These will be merged with the ``options`` parameter to
``Event.from_exception`` at the top of execution.
@example
begin
raise "Hello"
rescue => exc
Raven.annotate_exception(exc, :user => { 'id' => 1,
'email' => '[email protected]' })
end | [
"Provides",
"extra",
"context",
"to",
"the",
"exception",
"prior",
"to",
"it",
"being",
"handled",
"by",
"Raven",
".",
"An",
"exception",
"can",
"have",
"multiple",
"annotations",
"which",
"are",
"merged",
"together",
"."
] | 729c22f9284939695f14822683bff1a0b72502bd | https://github.com/getsentry/raven-ruby/blob/729c22f9284939695f14822683bff1a0b72502bd/lib/raven/instance.rb#L159-L164 | train |
getsentry/raven-ruby | lib/raven/integrations/sidekiq.rb | Raven.SidekiqErrorHandler.filter_context | def filter_context(context)
case context
when Array
context.map { |arg| filter_context(arg) }
when Hash
Hash[context.map { |key, value| filter_context_hash(key, value) }]
else
format_globalid(context)
end
end | ruby | def filter_context(context)
case context
when Array
context.map { |arg| filter_context(arg) }
when Hash
Hash[context.map { |key, value| filter_context_hash(key, value) }]
else
format_globalid(context)
end
end | [
"def",
"filter_context",
"(",
"context",
")",
"case",
"context",
"when",
"Array",
"context",
".",
"map",
"{",
"|",
"arg",
"|",
"filter_context",
"(",
"arg",
")",
"}",
"when",
"Hash",
"Hash",
"[",
"context",
".",
"map",
"{",
"|",
"key",
",",
"value",
"|",
"filter_context_hash",
"(",
"key",
",",
"value",
")",
"}",
"]",
"else",
"format_globalid",
"(",
"context",
")",
"end",
"end"
] | Once an ActiveJob is queued, ActiveRecord references get serialized into
some internal reserved keys, such as _aj_globalid.
The problem is, if this job in turn gets queued back into ActiveJob with
these magic reserved keys, ActiveJob will throw up and error. We want to
capture these and mutate the keys so we can sanely report it. | [
"Once",
"an",
"ActiveJob",
"is",
"queued",
"ActiveRecord",
"references",
"get",
"serialized",
"into",
"some",
"internal",
"reserved",
"keys",
"such",
"as",
"_aj_globalid",
"."
] | 729c22f9284939695f14822683bff1a0b72502bd | https://github.com/getsentry/raven-ruby/blob/729c22f9284939695f14822683bff1a0b72502bd/lib/raven/integrations/sidekiq.rb#L39-L48 | train |
chef/ohai | lib/ohai/system.rb | Ohai.System.run_plugins | def run_plugins(safe = false, attribute_filter = nil)
begin
@provides_map.all_plugins(attribute_filter).each do |plugin|
@runner.run_plugin(plugin)
end
rescue Ohai::Exceptions::AttributeNotFound, Ohai::Exceptions::DependencyCycle => e
logger.error("Encountered error while running plugins: #{e.inspect}")
raise
end
critical_failed = Ohai::Config.ohai[:critical_plugins] & @runner.failed_plugins
unless critical_failed.empty?
msg = "The following Ohai plugins marked as critical failed: #{critical_failed}"
if @cli
logger.error(msg)
exit(true)
else
raise Ohai::Exceptions::CriticalPluginFailure, "#{msg}. Failing Chef run."
end
end
# Freeze all strings.
freeze_strings!
end | ruby | def run_plugins(safe = false, attribute_filter = nil)
begin
@provides_map.all_plugins(attribute_filter).each do |plugin|
@runner.run_plugin(plugin)
end
rescue Ohai::Exceptions::AttributeNotFound, Ohai::Exceptions::DependencyCycle => e
logger.error("Encountered error while running plugins: #{e.inspect}")
raise
end
critical_failed = Ohai::Config.ohai[:critical_plugins] & @runner.failed_plugins
unless critical_failed.empty?
msg = "The following Ohai plugins marked as critical failed: #{critical_failed}"
if @cli
logger.error(msg)
exit(true)
else
raise Ohai::Exceptions::CriticalPluginFailure, "#{msg}. Failing Chef run."
end
end
# Freeze all strings.
freeze_strings!
end | [
"def",
"run_plugins",
"(",
"safe",
"=",
"false",
",",
"attribute_filter",
"=",
"nil",
")",
"begin",
"@provides_map",
".",
"all_plugins",
"(",
"attribute_filter",
")",
".",
"each",
"do",
"|",
"plugin",
"|",
"@runner",
".",
"run_plugin",
"(",
"plugin",
")",
"end",
"rescue",
"Ohai",
"::",
"Exceptions",
"::",
"AttributeNotFound",
",",
"Ohai",
"::",
"Exceptions",
"::",
"DependencyCycle",
"=>",
"e",
"logger",
".",
"error",
"(",
"\"Encountered error while running plugins: #{e.inspect}\"",
")",
"raise",
"end",
"critical_failed",
"=",
"Ohai",
"::",
"Config",
".",
"ohai",
"[",
":critical_plugins",
"]",
"&",
"@runner",
".",
"failed_plugins",
"unless",
"critical_failed",
".",
"empty?",
"msg",
"=",
"\"The following Ohai plugins marked as critical failed: #{critical_failed}\"",
"if",
"@cli",
"logger",
".",
"error",
"(",
"msg",
")",
"exit",
"(",
"true",
")",
"else",
"raise",
"Ohai",
"::",
"Exceptions",
"::",
"CriticalPluginFailure",
",",
"\"#{msg}. Failing Chef run.\"",
"end",
"end",
"# Freeze all strings.",
"freeze_strings!",
"end"
] | run all plugins or those that match the attribute filter is provided
@param safe [Boolean]
@param [Array<String>] attribute_filter the attributes to run. All will be run if not specified
@return [Mash] | [
"run",
"all",
"plugins",
"or",
"those",
"that",
"match",
"the",
"attribute",
"filter",
"is",
"provided"
] | 8d66449940f04237586b2f928231c6b26e2cc19a | https://github.com/chef/ohai/blob/8d66449940f04237586b2f928231c6b26e2cc19a/lib/ohai/system.rb#L109-L131 | train |
chef/ohai | lib/ohai/system.rb | Ohai.System.json_pretty_print | def json_pretty_print(item = nil)
FFI_Yajl::Encoder.new(pretty: true, validate_utf8: false).encode(item || @data)
end | ruby | def json_pretty_print(item = nil)
FFI_Yajl::Encoder.new(pretty: true, validate_utf8: false).encode(item || @data)
end | [
"def",
"json_pretty_print",
"(",
"item",
"=",
"nil",
")",
"FFI_Yajl",
"::",
"Encoder",
".",
"new",
"(",
"pretty",
":",
"true",
",",
"validate_utf8",
":",
"false",
")",
".",
"encode",
"(",
"item",
"||",
"@data",
")",
"end"
] | Pretty Print this object as JSON | [
"Pretty",
"Print",
"this",
"object",
"as",
"JSON"
] | 8d66449940f04237586b2f928231c6b26e2cc19a | https://github.com/chef/ohai/blob/8d66449940f04237586b2f928231c6b26e2cc19a/lib/ohai/system.rb#L152-L154 | train |
chef/ohai | lib/ohai/provides_map.rb | Ohai.ProvidesMap.find_providers_for | def find_providers_for(attributes)
plugins = []
attributes.each do |attribute|
attrs = select_subtree(@map, attribute)
raise Ohai::Exceptions::AttributeNotFound, "No such attribute: \'#{attribute}\'" unless attrs
raise Ohai::Exceptions::ProviderNotFound, "Cannot find plugin providing attribute: \'#{attribute}\'" unless attrs[:_plugins]
plugins += attrs[:_plugins]
end
plugins.uniq
end | ruby | def find_providers_for(attributes)
plugins = []
attributes.each do |attribute|
attrs = select_subtree(@map, attribute)
raise Ohai::Exceptions::AttributeNotFound, "No such attribute: \'#{attribute}\'" unless attrs
raise Ohai::Exceptions::ProviderNotFound, "Cannot find plugin providing attribute: \'#{attribute}\'" unless attrs[:_plugins]
plugins += attrs[:_plugins]
end
plugins.uniq
end | [
"def",
"find_providers_for",
"(",
"attributes",
")",
"plugins",
"=",
"[",
"]",
"attributes",
".",
"each",
"do",
"|",
"attribute",
"|",
"attrs",
"=",
"select_subtree",
"(",
"@map",
",",
"attribute",
")",
"raise",
"Ohai",
"::",
"Exceptions",
"::",
"AttributeNotFound",
",",
"\"No such attribute: \\'#{attribute}\\'\"",
"unless",
"attrs",
"raise",
"Ohai",
"::",
"Exceptions",
"::",
"ProviderNotFound",
",",
"\"Cannot find plugin providing attribute: \\'#{attribute}\\'\"",
"unless",
"attrs",
"[",
":_plugins",
"]",
"plugins",
"+=",
"attrs",
"[",
":_plugins",
"]",
"end",
"plugins",
".",
"uniq",
"end"
] | gather plugins providing exactly the attributes listed | [
"gather",
"plugins",
"providing",
"exactly",
"the",
"attributes",
"listed"
] | 8d66449940f04237586b2f928231c6b26e2cc19a | https://github.com/chef/ohai/blob/8d66449940f04237586b2f928231c6b26e2cc19a/lib/ohai/provides_map.rb#L52-L61 | train |
chef/ohai | lib/ohai/provides_map.rb | Ohai.ProvidesMap.deep_find_providers_for | def deep_find_providers_for(attributes)
plugins = []
attributes.each do |attribute|
attrs = select_subtree(@map, attribute)
unless attrs
attrs = select_closest_subtree(@map, attribute)
unless attrs
raise Ohai::Exceptions::AttributeNotFound, "No such attribute: \'#{attribute}\'"
end
end
collect_plugins_in(attrs, plugins)
end
plugins.uniq
end | ruby | def deep_find_providers_for(attributes)
plugins = []
attributes.each do |attribute|
attrs = select_subtree(@map, attribute)
unless attrs
attrs = select_closest_subtree(@map, attribute)
unless attrs
raise Ohai::Exceptions::AttributeNotFound, "No such attribute: \'#{attribute}\'"
end
end
collect_plugins_in(attrs, plugins)
end
plugins.uniq
end | [
"def",
"deep_find_providers_for",
"(",
"attributes",
")",
"plugins",
"=",
"[",
"]",
"attributes",
".",
"each",
"do",
"|",
"attribute",
"|",
"attrs",
"=",
"select_subtree",
"(",
"@map",
",",
"attribute",
")",
"unless",
"attrs",
"attrs",
"=",
"select_closest_subtree",
"(",
"@map",
",",
"attribute",
")",
"unless",
"attrs",
"raise",
"Ohai",
"::",
"Exceptions",
"::",
"AttributeNotFound",
",",
"\"No such attribute: \\'#{attribute}\\'\"",
"end",
"end",
"collect_plugins_in",
"(",
"attrs",
",",
"plugins",
")",
"end",
"plugins",
".",
"uniq",
"end"
] | This function is used to fetch the plugins for the attributes specified
in the CLI options to Ohai.
It first attempts to find the plugins for the attributes
or the sub attributes given.
If it can't find any, it looks for plugins that might
provide the parents of a given attribute and returns the
first parent found. | [
"This",
"function",
"is",
"used",
"to",
"fetch",
"the",
"plugins",
"for",
"the",
"attributes",
"specified",
"in",
"the",
"CLI",
"options",
"to",
"Ohai",
".",
"It",
"first",
"attempts",
"to",
"find",
"the",
"plugins",
"for",
"the",
"attributes",
"or",
"the",
"sub",
"attributes",
"given",
".",
"If",
"it",
"can",
"t",
"find",
"any",
"it",
"looks",
"for",
"plugins",
"that",
"might",
"provide",
"the",
"parents",
"of",
"a",
"given",
"attribute",
"and",
"returns",
"the",
"first",
"parent",
"found",
"."
] | 8d66449940f04237586b2f928231c6b26e2cc19a | https://github.com/chef/ohai/blob/8d66449940f04237586b2f928231c6b26e2cc19a/lib/ohai/provides_map.rb#L70-L87 | train |
chef/ohai | lib/ohai/provides_map.rb | Ohai.ProvidesMap.find_closest_providers_for | def find_closest_providers_for(attributes)
plugins = []
attributes.each do |attribute|
parts = normalize_and_validate(attribute)
raise Ohai::Exceptions::AttributeNotFound, "No such attribute: \'#{attribute}\'" unless @map[parts[0]]
attrs = select_closest_subtree(@map, attribute)
raise Ohai::Exceptions::ProviderNotFound, "Cannot find plugin providing attribute: \'#{attribute}\'" unless attrs
plugins += attrs[:_plugins]
end
plugins.uniq
end | ruby | def find_closest_providers_for(attributes)
plugins = []
attributes.each do |attribute|
parts = normalize_and_validate(attribute)
raise Ohai::Exceptions::AttributeNotFound, "No such attribute: \'#{attribute}\'" unless @map[parts[0]]
attrs = select_closest_subtree(@map, attribute)
raise Ohai::Exceptions::ProviderNotFound, "Cannot find plugin providing attribute: \'#{attribute}\'" unless attrs
plugins += attrs[:_plugins]
end
plugins.uniq
end | [
"def",
"find_closest_providers_for",
"(",
"attributes",
")",
"plugins",
"=",
"[",
"]",
"attributes",
".",
"each",
"do",
"|",
"attribute",
"|",
"parts",
"=",
"normalize_and_validate",
"(",
"attribute",
")",
"raise",
"Ohai",
"::",
"Exceptions",
"::",
"AttributeNotFound",
",",
"\"No such attribute: \\'#{attribute}\\'\"",
"unless",
"@map",
"[",
"parts",
"[",
"0",
"]",
"]",
"attrs",
"=",
"select_closest_subtree",
"(",
"@map",
",",
"attribute",
")",
"raise",
"Ohai",
"::",
"Exceptions",
"::",
"ProviderNotFound",
",",
"\"Cannot find plugin providing attribute: \\'#{attribute}\\'\"",
"unless",
"attrs",
"plugins",
"+=",
"attrs",
"[",
":_plugins",
"]",
"end",
"plugins",
".",
"uniq",
"end"
] | This function is used to fetch the plugins from
'depends "languages"' statements in plugins.
It gathers plugins providing each of the attributes listed, or the
plugins providing the closest parent attribute | [
"This",
"function",
"is",
"used",
"to",
"fetch",
"the",
"plugins",
"from",
"depends",
"languages",
"statements",
"in",
"plugins",
".",
"It",
"gathers",
"plugins",
"providing",
"each",
"of",
"the",
"attributes",
"listed",
"or",
"the",
"plugins",
"providing",
"the",
"closest",
"parent",
"attribute"
] | 8d66449940f04237586b2f928231c6b26e2cc19a | https://github.com/chef/ohai/blob/8d66449940f04237586b2f928231c6b26e2cc19a/lib/ohai/provides_map.rb#L93-L103 | train |
chef/ohai | lib/ohai/provides_map.rb | Ohai.ProvidesMap.collect_plugins_in | def collect_plugins_in(provides_map, collected)
provides_map.each_key do |plugin|
if plugin.eql?("_plugins")
collected.concat(provides_map[plugin])
else
collect_plugins_in(provides_map[plugin], collected)
end
end
collected
end | ruby | def collect_plugins_in(provides_map, collected)
provides_map.each_key do |plugin|
if plugin.eql?("_plugins")
collected.concat(provides_map[plugin])
else
collect_plugins_in(provides_map[plugin], collected)
end
end
collected
end | [
"def",
"collect_plugins_in",
"(",
"provides_map",
",",
"collected",
")",
"provides_map",
".",
"each_key",
"do",
"|",
"plugin",
"|",
"if",
"plugin",
".",
"eql?",
"(",
"\"_plugins\"",
")",
"collected",
".",
"concat",
"(",
"provides_map",
"[",
"plugin",
"]",
")",
"else",
"collect_plugins_in",
"(",
"provides_map",
"[",
"plugin",
"]",
",",
"collected",
")",
"end",
"end",
"collected",
"end"
] | Takes a section of the map, recursively searches for a `_plugins` key
to find all the plugins in that section of the map. If given the whole
map, it will find all of the plugins that have at least one provided
attribute. | [
"Takes",
"a",
"section",
"of",
"the",
"map",
"recursively",
"searches",
"for",
"a",
"_plugins",
"key",
"to",
"find",
"all",
"the",
"plugins",
"in",
"that",
"section",
"of",
"the",
"map",
".",
"If",
"given",
"the",
"whole",
"map",
"it",
"will",
"find",
"all",
"of",
"the",
"plugins",
"that",
"have",
"at",
"least",
"one",
"provided",
"attribute",
"."
] | 8d66449940f04237586b2f928231c6b26e2cc19a | https://github.com/chef/ohai/blob/8d66449940f04237586b2f928231c6b26e2cc19a/lib/ohai/provides_map.rb#L173-L182 | train |
chef/ohai | lib/ohai/loader.rb | Ohai.Loader.plugin_files_by_dir | def plugin_files_by_dir(plugin_dir = Ohai.config[:plugin_path])
Array(plugin_dir).map do |path|
if Dir.exist?(path)
Ohai::Log.trace("Searching for Ohai plugins in #{path}")
escaped = ChefConfig::PathHelper.escape_glob_dir(path)
Dir[File.join(escaped, "**", "*.rb")]
else
Ohai::Log.debug("The plugin path #{path} does not exist. Skipping...")
[]
end
end.flatten
end | ruby | def plugin_files_by_dir(plugin_dir = Ohai.config[:plugin_path])
Array(plugin_dir).map do |path|
if Dir.exist?(path)
Ohai::Log.trace("Searching for Ohai plugins in #{path}")
escaped = ChefConfig::PathHelper.escape_glob_dir(path)
Dir[File.join(escaped, "**", "*.rb")]
else
Ohai::Log.debug("The plugin path #{path} does not exist. Skipping...")
[]
end
end.flatten
end | [
"def",
"plugin_files_by_dir",
"(",
"plugin_dir",
"=",
"Ohai",
".",
"config",
"[",
":plugin_path",
"]",
")",
"Array",
"(",
"plugin_dir",
")",
".",
"map",
"do",
"|",
"path",
"|",
"if",
"Dir",
".",
"exist?",
"(",
"path",
")",
"Ohai",
"::",
"Log",
".",
"trace",
"(",
"\"Searching for Ohai plugins in #{path}\"",
")",
"escaped",
"=",
"ChefConfig",
"::",
"PathHelper",
".",
"escape_glob_dir",
"(",
"path",
")",
"Dir",
"[",
"File",
".",
"join",
"(",
"escaped",
",",
"\"**\"",
",",
"\"*.rb\"",
")",
"]",
"else",
"Ohai",
"::",
"Log",
".",
"debug",
"(",
"\"The plugin path #{path} does not exist. Skipping...\"",
")",
"[",
"]",
"end",
"end",
".",
"flatten",
"end"
] | Searches all plugin paths and returns an Array of file paths to plugins
@param dir [Array, String] directory/directories to load plugins from
@return [Array<String>] | [
"Searches",
"all",
"plugin",
"paths",
"and",
"returns",
"an",
"Array",
"of",
"file",
"paths",
"to",
"plugins"
] | 8d66449940f04237586b2f928231c6b26e2cc19a | https://github.com/chef/ohai/blob/8d66449940f04237586b2f928231c6b26e2cc19a/lib/ohai/loader.rb#L43-L55 | train |
chef/ohai | lib/ohai/loader.rb | Ohai.Loader.load_additional | def load_additional(from)
from = [ Ohai.config[:plugin_path], from].flatten
plugin_files_by_dir(from).collect do |plugin_file|
logger.trace "Loading additional plugin: #{plugin_file}"
plugin = load_plugin_class(plugin_file)
load_v7_plugin(plugin)
end
end | ruby | def load_additional(from)
from = [ Ohai.config[:plugin_path], from].flatten
plugin_files_by_dir(from).collect do |plugin_file|
logger.trace "Loading additional plugin: #{plugin_file}"
plugin = load_plugin_class(plugin_file)
load_v7_plugin(plugin)
end
end | [
"def",
"load_additional",
"(",
"from",
")",
"from",
"=",
"[",
"Ohai",
".",
"config",
"[",
":plugin_path",
"]",
",",
"from",
"]",
".",
"flatten",
"plugin_files_by_dir",
"(",
"from",
")",
".",
"collect",
"do",
"|",
"plugin_file",
"|",
"logger",
".",
"trace",
"\"Loading additional plugin: #{plugin_file}\"",
"plugin",
"=",
"load_plugin_class",
"(",
"plugin_file",
")",
"load_v7_plugin",
"(",
"plugin",
")",
"end",
"end"
] | load additional plugins classes from a given directory
@param from [String] path to a directory with additional plugins to load | [
"load",
"additional",
"plugins",
"classes",
"from",
"a",
"given",
"directory"
] | 8d66449940f04237586b2f928231c6b26e2cc19a | https://github.com/chef/ohai/blob/8d66449940f04237586b2f928231c6b26e2cc19a/lib/ohai/loader.rb#L70-L77 | train |
chef/ohai | lib/ohai/loader.rb | Ohai.Loader.load_plugin | def load_plugin(plugin_path)
plugin_class = load_plugin_class(plugin_path)
return nil unless plugin_class.kind_of?(Class)
if plugin_class < Ohai::DSL::Plugin::VersionVII
load_v7_plugin(plugin_class)
else
raise Exceptions::IllegalPluginDefinition, "cannot create plugin of type #{plugin_class}"
end
end | ruby | def load_plugin(plugin_path)
plugin_class = load_plugin_class(plugin_path)
return nil unless plugin_class.kind_of?(Class)
if plugin_class < Ohai::DSL::Plugin::VersionVII
load_v7_plugin(plugin_class)
else
raise Exceptions::IllegalPluginDefinition, "cannot create plugin of type #{plugin_class}"
end
end | [
"def",
"load_plugin",
"(",
"plugin_path",
")",
"plugin_class",
"=",
"load_plugin_class",
"(",
"plugin_path",
")",
"return",
"nil",
"unless",
"plugin_class",
".",
"kind_of?",
"(",
"Class",
")",
"if",
"plugin_class",
"<",
"Ohai",
"::",
"DSL",
"::",
"Plugin",
"::",
"VersionVII",
"load_v7_plugin",
"(",
"plugin_class",
")",
"else",
"raise",
"Exceptions",
"::",
"IllegalPluginDefinition",
",",
"\"cannot create plugin of type #{plugin_class}\"",
"end",
"end"
] | Load a specified file as an ohai plugin and creates an instance of it.
Not used by ohai itself, but is used in the specs to load plugins for testing
@private
@param plugin_path [String] | [
"Load",
"a",
"specified",
"file",
"as",
"an",
"ohai",
"plugin",
"and",
"creates",
"an",
"instance",
"of",
"it",
".",
"Not",
"used",
"by",
"ohai",
"itself",
"but",
"is",
"used",
"in",
"the",
"specs",
"to",
"load",
"plugins",
"for",
"testing"
] | 8d66449940f04237586b2f928231c6b26e2cc19a | https://github.com/chef/ohai/blob/8d66449940f04237586b2f928231c6b26e2cc19a/lib/ohai/loader.rb#L84-L92 | train |
chef/ohai | lib/ohai/runner.rb | Ohai.Runner.get_cycle | def get_cycle(plugins, cycle_start)
cycle = plugins.drop_while { |plugin| !plugin.eql?(cycle_start) }
names = []
cycle.each { |plugin| names << plugin.name }
names
end | ruby | def get_cycle(plugins, cycle_start)
cycle = plugins.drop_while { |plugin| !plugin.eql?(cycle_start) }
names = []
cycle.each { |plugin| names << plugin.name }
names
end | [
"def",
"get_cycle",
"(",
"plugins",
",",
"cycle_start",
")",
"cycle",
"=",
"plugins",
".",
"drop_while",
"{",
"|",
"plugin",
"|",
"!",
"plugin",
".",
"eql?",
"(",
"cycle_start",
")",
"}",
"names",
"=",
"[",
"]",
"cycle",
".",
"each",
"{",
"|",
"plugin",
"|",
"names",
"<<",
"plugin",
".",
"name",
"}",
"names",
"end"
] | Given a list of plugins and the first plugin in the cycle,
returns the list of plugin source files responsible for the
cycle. Does not include plugins that aren't a part of the cycle | [
"Given",
"a",
"list",
"of",
"plugins",
"and",
"the",
"first",
"plugin",
"in",
"the",
"cycle",
"returns",
"the",
"list",
"of",
"plugin",
"source",
"files",
"responsible",
"for",
"the",
"cycle",
".",
"Does",
"not",
"include",
"plugins",
"that",
"aren",
"t",
"a",
"part",
"of",
"the",
"cycle"
] | 8d66449940f04237586b2f928231c6b26e2cc19a | https://github.com/chef/ohai/blob/8d66449940f04237586b2f928231c6b26e2cc19a/lib/ohai/runner.rb#L104-L109 | train |
ruby2d/ruby2d | lib/ruby2d/triangle.rb | Ruby2D.Triangle.contains? | def contains?(x, y)
self_area = triangle_area(@x1, @y1, @x2, @y2, @x3, @y3)
questioned_area =
triangle_area(@x1, @y1, @x2, @y2, x, y) +
triangle_area(@x2, @y2, @x3, @y3, x, y) +
triangle_area(@x3, @y3, @x1, @y1, x, y)
questioned_area <= self_area
end | ruby | def contains?(x, y)
self_area = triangle_area(@x1, @y1, @x2, @y2, @x3, @y3)
questioned_area =
triangle_area(@x1, @y1, @x2, @y2, x, y) +
triangle_area(@x2, @y2, @x3, @y3, x, y) +
triangle_area(@x3, @y3, @x1, @y1, x, y)
questioned_area <= self_area
end | [
"def",
"contains?",
"(",
"x",
",",
"y",
")",
"self_area",
"=",
"triangle_area",
"(",
"@x1",
",",
"@y1",
",",
"@x2",
",",
"@y2",
",",
"@x3",
",",
"@y3",
")",
"questioned_area",
"=",
"triangle_area",
"(",
"@x1",
",",
"@y1",
",",
"@x2",
",",
"@y2",
",",
"x",
",",
"y",
")",
"+",
"triangle_area",
"(",
"@x2",
",",
"@y2",
",",
"@x3",
",",
"@y3",
",",
"x",
",",
"y",
")",
"+",
"triangle_area",
"(",
"@x3",
",",
"@y3",
",",
"@x1",
",",
"@y1",
",",
"x",
",",
"y",
")",
"questioned_area",
"<=",
"self_area",
"end"
] | A point is inside a triangle if the area of 3 triangles, constructed from
triangle sides and the given point, is equal to the area of triangle. | [
"A",
"point",
"is",
"inside",
"a",
"triangle",
"if",
"the",
"area",
"of",
"3",
"triangles",
"constructed",
"from",
"triangle",
"sides",
"and",
"the",
"given",
"point",
"is",
"equal",
"to",
"the",
"area",
"of",
"triangle",
"."
] | 43ce9805a7ae8b82b7ab8c50bf6d4c845d395dc4 | https://github.com/ruby2d/ruby2d/blob/43ce9805a7ae8b82b7ab8c50bf6d4c845d395dc4/lib/ruby2d/triangle.rb#L31-L39 | train |
ruby2d/ruby2d | lib/ruby2d/sprite.rb | Ruby2D.Sprite.play | def play(opts = {}, &done_proc)
animation = opts[:animation]
loop = opts[:loop]
flip = opts[:flip]
if !@playing || (animation != @playing_animation && animation != nil) || flip != @flip
@playing = true
@playing_animation = animation || :default
frames = @animations[@playing_animation]
flip_sprite(flip)
@done_proc = done_proc
case frames
# When animation is a range, play through frames horizontally
when Range
@first_frame = frames.first || @defaults[:frame]
@current_frame = frames.first || @defaults[:frame]
@last_frame = frames.last
# When array...
when Array
@first_frame = 0
@current_frame = 0
@last_frame = frames.length - 1
end
# Set looping
@loop = loop == true || @defaults[:loop] ? true : false
set_frame
restart_time
end
end | ruby | def play(opts = {}, &done_proc)
animation = opts[:animation]
loop = opts[:loop]
flip = opts[:flip]
if !@playing || (animation != @playing_animation && animation != nil) || flip != @flip
@playing = true
@playing_animation = animation || :default
frames = @animations[@playing_animation]
flip_sprite(flip)
@done_proc = done_proc
case frames
# When animation is a range, play through frames horizontally
when Range
@first_frame = frames.first || @defaults[:frame]
@current_frame = frames.first || @defaults[:frame]
@last_frame = frames.last
# When array...
when Array
@first_frame = 0
@current_frame = 0
@last_frame = frames.length - 1
end
# Set looping
@loop = loop == true || @defaults[:loop] ? true : false
set_frame
restart_time
end
end | [
"def",
"play",
"(",
"opts",
"=",
"{",
"}",
",",
"&",
"done_proc",
")",
"animation",
"=",
"opts",
"[",
":animation",
"]",
"loop",
"=",
"opts",
"[",
":loop",
"]",
"flip",
"=",
"opts",
"[",
":flip",
"]",
"if",
"!",
"@playing",
"||",
"(",
"animation",
"!=",
"@playing_animation",
"&&",
"animation",
"!=",
"nil",
")",
"||",
"flip",
"!=",
"@flip",
"@playing",
"=",
"true",
"@playing_animation",
"=",
"animation",
"||",
":default",
"frames",
"=",
"@animations",
"[",
"@playing_animation",
"]",
"flip_sprite",
"(",
"flip",
")",
"@done_proc",
"=",
"done_proc",
"case",
"frames",
"# When animation is a range, play through frames horizontally",
"when",
"Range",
"@first_frame",
"=",
"frames",
".",
"first",
"||",
"@defaults",
"[",
":frame",
"]",
"@current_frame",
"=",
"frames",
".",
"first",
"||",
"@defaults",
"[",
":frame",
"]",
"@last_frame",
"=",
"frames",
".",
"last",
"# When array...",
"when",
"Array",
"@first_frame",
"=",
"0",
"@current_frame",
"=",
"0",
"@last_frame",
"=",
"frames",
".",
"length",
"-",
"1",
"end",
"# Set looping",
"@loop",
"=",
"loop",
"==",
"true",
"||",
"@defaults",
"[",
":loop",
"]",
"?",
"true",
":",
"false",
"set_frame",
"restart_time",
"end",
"end"
] | Play an animation | [
"Play",
"an",
"animation"
] | 43ce9805a7ae8b82b7ab8c50bf6d4c845d395dc4 | https://github.com/ruby2d/ruby2d/blob/43ce9805a7ae8b82b7ab8c50bf6d4c845d395dc4/lib/ruby2d/sprite.rb#L111-L144 | train |
ruby2d/ruby2d | lib/ruby2d/sprite.rb | Ruby2D.Sprite.set_frame | def set_frame
frames = @animations[@playing_animation]
case frames
when Range
reset_clipping_rect
@clip_x = @current_frame * @clip_width
when Array
f = frames[@current_frame]
@clip_x = f[:x] || @defaults[:clip_x]
@clip_y = f[:y] || @defaults[:clip_y]
@clip_width = f[:width] || @defaults[:clip_width]
@clip_height = f[:height] || @defaults[:clip_height]
@frame_time = f[:time] || @defaults[:frame_time]
end
end | ruby | def set_frame
frames = @animations[@playing_animation]
case frames
when Range
reset_clipping_rect
@clip_x = @current_frame * @clip_width
when Array
f = frames[@current_frame]
@clip_x = f[:x] || @defaults[:clip_x]
@clip_y = f[:y] || @defaults[:clip_y]
@clip_width = f[:width] || @defaults[:clip_width]
@clip_height = f[:height] || @defaults[:clip_height]
@frame_time = f[:time] || @defaults[:frame_time]
end
end | [
"def",
"set_frame",
"frames",
"=",
"@animations",
"[",
"@playing_animation",
"]",
"case",
"frames",
"when",
"Range",
"reset_clipping_rect",
"@clip_x",
"=",
"@current_frame",
"*",
"@clip_width",
"when",
"Array",
"f",
"=",
"frames",
"[",
"@current_frame",
"]",
"@clip_x",
"=",
"f",
"[",
":x",
"]",
"||",
"@defaults",
"[",
":clip_x",
"]",
"@clip_y",
"=",
"f",
"[",
":y",
"]",
"||",
"@defaults",
"[",
":clip_y",
"]",
"@clip_width",
"=",
"f",
"[",
":width",
"]",
"||",
"@defaults",
"[",
":clip_width",
"]",
"@clip_height",
"=",
"f",
"[",
":height",
"]",
"||",
"@defaults",
"[",
":clip_height",
"]",
"@frame_time",
"=",
"f",
"[",
":time",
"]",
"||",
"@defaults",
"[",
":frame_time",
"]",
"end",
"end"
] | Set the position of the clipping retangle based on the current frame | [
"Set",
"the",
"position",
"of",
"the",
"clipping",
"retangle",
"based",
"on",
"the",
"current",
"frame"
] | 43ce9805a7ae8b82b7ab8c50bf6d4c845d395dc4 | https://github.com/ruby2d/ruby2d/blob/43ce9805a7ae8b82b7ab8c50bf6d4c845d395dc4/lib/ruby2d/sprite.rb#L198-L212 | train |
ruby2d/ruby2d | lib/ruby2d/line.rb | Ruby2D.Line.points_distance | def points_distance(x1, y1, x2, y2)
Math.sqrt((x1 - x2) ** 2 + (y1 - y2) ** 2)
end | ruby | def points_distance(x1, y1, x2, y2)
Math.sqrt((x1 - x2) ** 2 + (y1 - y2) ** 2)
end | [
"def",
"points_distance",
"(",
"x1",
",",
"y1",
",",
"x2",
",",
"y2",
")",
"Math",
".",
"sqrt",
"(",
"(",
"x1",
"-",
"x2",
")",
"**",
"2",
"+",
"(",
"y1",
"-",
"y2",
")",
"**",
"2",
")",
"end"
] | Calculate the distance between two points | [
"Calculate",
"the",
"distance",
"between",
"two",
"points"
] | 43ce9805a7ae8b82b7ab8c50bf6d4c845d395dc4 | https://github.com/ruby2d/ruby2d/blob/43ce9805a7ae8b82b7ab8c50bf6d4c845d395dc4/lib/ruby2d/line.rb#L44-L46 | train |
ruby2d/ruby2d | lib/ruby2d/window.rb | Ruby2D.Window.set | def set(opts)
# Store new window attributes, or ignore if nil
@title = opts[:title] || @title
if Color.is_valid? opts[:background]
@background = Color.new(opts[:background])
end
@icon = opts[:icon] || @icon
@width = opts[:width] || @width
@height = opts[:height] || @height
@fps_cap = opts[:fps_cap] || @fps_cap
@viewport_width = opts[:viewport_width] || @viewport_width
@viewport_height = opts[:viewport_height] || @viewport_height
@resizable = opts[:resizable] || @resizable
@borderless = opts[:borderless] || @borderless
@fullscreen = opts[:fullscreen] || @fullscreen
@highdpi = opts[:highdpi] || @highdpi
unless opts[:diagnostics].nil?
@diagnostics = opts[:diagnostics]
ext_diagnostics(@diagnostics)
end
end | ruby | def set(opts)
# Store new window attributes, or ignore if nil
@title = opts[:title] || @title
if Color.is_valid? opts[:background]
@background = Color.new(opts[:background])
end
@icon = opts[:icon] || @icon
@width = opts[:width] || @width
@height = opts[:height] || @height
@fps_cap = opts[:fps_cap] || @fps_cap
@viewport_width = opts[:viewport_width] || @viewport_width
@viewport_height = opts[:viewport_height] || @viewport_height
@resizable = opts[:resizable] || @resizable
@borderless = opts[:borderless] || @borderless
@fullscreen = opts[:fullscreen] || @fullscreen
@highdpi = opts[:highdpi] || @highdpi
unless opts[:diagnostics].nil?
@diagnostics = opts[:diagnostics]
ext_diagnostics(@diagnostics)
end
end | [
"def",
"set",
"(",
"opts",
")",
"# Store new window attributes, or ignore if nil",
"@title",
"=",
"opts",
"[",
":title",
"]",
"||",
"@title",
"if",
"Color",
".",
"is_valid?",
"opts",
"[",
":background",
"]",
"@background",
"=",
"Color",
".",
"new",
"(",
"opts",
"[",
":background",
"]",
")",
"end",
"@icon",
"=",
"opts",
"[",
":icon",
"]",
"||",
"@icon",
"@width",
"=",
"opts",
"[",
":width",
"]",
"||",
"@width",
"@height",
"=",
"opts",
"[",
":height",
"]",
"||",
"@height",
"@fps_cap",
"=",
"opts",
"[",
":fps_cap",
"]",
"||",
"@fps_cap",
"@viewport_width",
"=",
"opts",
"[",
":viewport_width",
"]",
"||",
"@viewport_width",
"@viewport_height",
"=",
"opts",
"[",
":viewport_height",
"]",
"||",
"@viewport_height",
"@resizable",
"=",
"opts",
"[",
":resizable",
"]",
"||",
"@resizable",
"@borderless",
"=",
"opts",
"[",
":borderless",
"]",
"||",
"@borderless",
"@fullscreen",
"=",
"opts",
"[",
":fullscreen",
"]",
"||",
"@fullscreen",
"@highdpi",
"=",
"opts",
"[",
":highdpi",
"]",
"||",
"@highdpi",
"unless",
"opts",
"[",
":diagnostics",
"]",
".",
"nil?",
"@diagnostics",
"=",
"opts",
"[",
":diagnostics",
"]",
"ext_diagnostics",
"(",
"@diagnostics",
")",
"end",
"end"
] | Set a window attribute | [
"Set",
"a",
"window",
"attribute"
] | 43ce9805a7ae8b82b7ab8c50bf6d4c845d395dc4 | https://github.com/ruby2d/ruby2d/blob/43ce9805a7ae8b82b7ab8c50bf6d4c845d395dc4/lib/ruby2d/window.rb#L195-L215 | train |
ruby2d/ruby2d | lib/ruby2d/window.rb | Ruby2D.Window.add | def add(o)
case o
when nil
raise Error, "Cannot add '#{o.class}' to window!"
when Array
o.each { |x| add_object(x) }
else
add_object(o)
end
end | ruby | def add(o)
case o
when nil
raise Error, "Cannot add '#{o.class}' to window!"
when Array
o.each { |x| add_object(x) }
else
add_object(o)
end
end | [
"def",
"add",
"(",
"o",
")",
"case",
"o",
"when",
"nil",
"raise",
"Error",
",",
"\"Cannot add '#{o.class}' to window!\"",
"when",
"Array",
"o",
".",
"each",
"{",
"|",
"x",
"|",
"add_object",
"(",
"x",
")",
"}",
"else",
"add_object",
"(",
"o",
")",
"end",
"end"
] | Add an object to the window | [
"Add",
"an",
"object",
"to",
"the",
"window"
] | 43ce9805a7ae8b82b7ab8c50bf6d4c845d395dc4 | https://github.com/ruby2d/ruby2d/blob/43ce9805a7ae8b82b7ab8c50bf6d4c845d395dc4/lib/ruby2d/window.rb#L218-L227 | train |
ruby2d/ruby2d | lib/ruby2d/window.rb | Ruby2D.Window.remove | def remove(o)
if o == nil
raise Error, "Cannot remove '#{o.class}' from window!"
end
if i = @objects.index(o)
@objects.delete_at(i)
true
else
false
end
end | ruby | def remove(o)
if o == nil
raise Error, "Cannot remove '#{o.class}' from window!"
end
if i = @objects.index(o)
@objects.delete_at(i)
true
else
false
end
end | [
"def",
"remove",
"(",
"o",
")",
"if",
"o",
"==",
"nil",
"raise",
"Error",
",",
"\"Cannot remove '#{o.class}' from window!\"",
"end",
"if",
"i",
"=",
"@objects",
".",
"index",
"(",
"o",
")",
"@objects",
".",
"delete_at",
"(",
"i",
")",
"true",
"else",
"false",
"end",
"end"
] | Remove an object from the window | [
"Remove",
"an",
"object",
"from",
"the",
"window"
] | 43ce9805a7ae8b82b7ab8c50bf6d4c845d395dc4 | https://github.com/ruby2d/ruby2d/blob/43ce9805a7ae8b82b7ab8c50bf6d4c845d395dc4/lib/ruby2d/window.rb#L230-L241 | train |
ruby2d/ruby2d | lib/ruby2d/window.rb | Ruby2D.Window.on | def on(event, &proc)
unless @events.has_key? event
raise Error, "`#{event}` is not a valid event type"
end
event_id = new_event_key
@events[event][event_id] = proc
EventDescriptor.new(event, event_id)
end | ruby | def on(event, &proc)
unless @events.has_key? event
raise Error, "`#{event}` is not a valid event type"
end
event_id = new_event_key
@events[event][event_id] = proc
EventDescriptor.new(event, event_id)
end | [
"def",
"on",
"(",
"event",
",",
"&",
"proc",
")",
"unless",
"@events",
".",
"has_key?",
"event",
"raise",
"Error",
",",
"\"`#{event}` is not a valid event type\"",
"end",
"event_id",
"=",
"new_event_key",
"@events",
"[",
"event",
"]",
"[",
"event_id",
"]",
"=",
"proc",
"EventDescriptor",
".",
"new",
"(",
"event",
",",
"event_id",
")",
"end"
] | Set an event handler | [
"Set",
"an",
"event",
"handler"
] | 43ce9805a7ae8b82b7ab8c50bf6d4c845d395dc4 | https://github.com/ruby2d/ruby2d/blob/43ce9805a7ae8b82b7ab8c50bf6d4c845d395dc4/lib/ruby2d/window.rb#L260-L267 | train |
ruby2d/ruby2d | lib/ruby2d/window.rb | Ruby2D.Window.key_callback | def key_callback(type, key)
key = key.downcase
# All key events
@events[:key].each do |id, e|
e.call(KeyEvent.new(type, key))
end
case type
# When key is pressed, fired once
when :down
@events[:key_down].each do |id, e|
e.call(KeyEvent.new(type, key))
end
# When key is being held down, fired every frame
when :held
@events[:key_held].each do |id, e|
e.call(KeyEvent.new(type, key))
end
# When key released, fired once
when :up
@events[:key_up].each do |id, e|
e.call(KeyEvent.new(type, key))
end
end
end | ruby | def key_callback(type, key)
key = key.downcase
# All key events
@events[:key].each do |id, e|
e.call(KeyEvent.new(type, key))
end
case type
# When key is pressed, fired once
when :down
@events[:key_down].each do |id, e|
e.call(KeyEvent.new(type, key))
end
# When key is being held down, fired every frame
when :held
@events[:key_held].each do |id, e|
e.call(KeyEvent.new(type, key))
end
# When key released, fired once
when :up
@events[:key_up].each do |id, e|
e.call(KeyEvent.new(type, key))
end
end
end | [
"def",
"key_callback",
"(",
"type",
",",
"key",
")",
"key",
"=",
"key",
".",
"downcase",
"# All key events",
"@events",
"[",
":key",
"]",
".",
"each",
"do",
"|",
"id",
",",
"e",
"|",
"e",
".",
"call",
"(",
"KeyEvent",
".",
"new",
"(",
"type",
",",
"key",
")",
")",
"end",
"case",
"type",
"# When key is pressed, fired once",
"when",
":down",
"@events",
"[",
":key_down",
"]",
".",
"each",
"do",
"|",
"id",
",",
"e",
"|",
"e",
".",
"call",
"(",
"KeyEvent",
".",
"new",
"(",
"type",
",",
"key",
")",
")",
"end",
"# When key is being held down, fired every frame",
"when",
":held",
"@events",
"[",
":key_held",
"]",
".",
"each",
"do",
"|",
"id",
",",
"e",
"|",
"e",
".",
"call",
"(",
"KeyEvent",
".",
"new",
"(",
"type",
",",
"key",
")",
")",
"end",
"# When key released, fired once",
"when",
":up",
"@events",
"[",
":key_up",
"]",
".",
"each",
"do",
"|",
"id",
",",
"e",
"|",
"e",
".",
"call",
"(",
"KeyEvent",
".",
"new",
"(",
"type",
",",
"key",
")",
")",
"end",
"end",
"end"
] | Key callback method, called by the native and web extentions | [
"Key",
"callback",
"method",
"called",
"by",
"the",
"native",
"and",
"web",
"extentions"
] | 43ce9805a7ae8b82b7ab8c50bf6d4c845d395dc4 | https://github.com/ruby2d/ruby2d/blob/43ce9805a7ae8b82b7ab8c50bf6d4c845d395dc4/lib/ruby2d/window.rb#L275-L300 | train |
ruby2d/ruby2d | lib/ruby2d/window.rb | Ruby2D.Window.mouse_callback | def mouse_callback(type, button, direction, x, y, delta_x, delta_y)
# All mouse events
@events[:mouse].each do |id, e|
e.call(MouseEvent.new(type, button, direction, x, y, delta_x, delta_y))
end
case type
# When mouse button pressed
when :down
@events[:mouse_down].each do |id, e|
e.call(MouseEvent.new(type, button, nil, x, y, nil, nil))
end
# When mouse button released
when :up
@events[:mouse_up].each do |id, e|
e.call(MouseEvent.new(type, button, nil, x, y, nil, nil))
end
# When mouse motion / movement
when :scroll
@events[:mouse_scroll].each do |id, e|
e.call(MouseEvent.new(type, nil, direction, nil, nil, delta_x, delta_y))
end
# When mouse scrolling, wheel or trackpad
when :move
@events[:mouse_move].each do |id, e|
e.call(MouseEvent.new(type, nil, nil, x, y, delta_x, delta_y))
end
end
end | ruby | def mouse_callback(type, button, direction, x, y, delta_x, delta_y)
# All mouse events
@events[:mouse].each do |id, e|
e.call(MouseEvent.new(type, button, direction, x, y, delta_x, delta_y))
end
case type
# When mouse button pressed
when :down
@events[:mouse_down].each do |id, e|
e.call(MouseEvent.new(type, button, nil, x, y, nil, nil))
end
# When mouse button released
when :up
@events[:mouse_up].each do |id, e|
e.call(MouseEvent.new(type, button, nil, x, y, nil, nil))
end
# When mouse motion / movement
when :scroll
@events[:mouse_scroll].each do |id, e|
e.call(MouseEvent.new(type, nil, direction, nil, nil, delta_x, delta_y))
end
# When mouse scrolling, wheel or trackpad
when :move
@events[:mouse_move].each do |id, e|
e.call(MouseEvent.new(type, nil, nil, x, y, delta_x, delta_y))
end
end
end | [
"def",
"mouse_callback",
"(",
"type",
",",
"button",
",",
"direction",
",",
"x",
",",
"y",
",",
"delta_x",
",",
"delta_y",
")",
"# All mouse events",
"@events",
"[",
":mouse",
"]",
".",
"each",
"do",
"|",
"id",
",",
"e",
"|",
"e",
".",
"call",
"(",
"MouseEvent",
".",
"new",
"(",
"type",
",",
"button",
",",
"direction",
",",
"x",
",",
"y",
",",
"delta_x",
",",
"delta_y",
")",
")",
"end",
"case",
"type",
"# When mouse button pressed",
"when",
":down",
"@events",
"[",
":mouse_down",
"]",
".",
"each",
"do",
"|",
"id",
",",
"e",
"|",
"e",
".",
"call",
"(",
"MouseEvent",
".",
"new",
"(",
"type",
",",
"button",
",",
"nil",
",",
"x",
",",
"y",
",",
"nil",
",",
"nil",
")",
")",
"end",
"# When mouse button released",
"when",
":up",
"@events",
"[",
":mouse_up",
"]",
".",
"each",
"do",
"|",
"id",
",",
"e",
"|",
"e",
".",
"call",
"(",
"MouseEvent",
".",
"new",
"(",
"type",
",",
"button",
",",
"nil",
",",
"x",
",",
"y",
",",
"nil",
",",
"nil",
")",
")",
"end",
"# When mouse motion / movement",
"when",
":scroll",
"@events",
"[",
":mouse_scroll",
"]",
".",
"each",
"do",
"|",
"id",
",",
"e",
"|",
"e",
".",
"call",
"(",
"MouseEvent",
".",
"new",
"(",
"type",
",",
"nil",
",",
"direction",
",",
"nil",
",",
"nil",
",",
"delta_x",
",",
"delta_y",
")",
")",
"end",
"# When mouse scrolling, wheel or trackpad",
"when",
":move",
"@events",
"[",
":mouse_move",
"]",
".",
"each",
"do",
"|",
"id",
",",
"e",
"|",
"e",
".",
"call",
"(",
"MouseEvent",
".",
"new",
"(",
"type",
",",
"nil",
",",
"nil",
",",
"x",
",",
"y",
",",
"delta_x",
",",
"delta_y",
")",
")",
"end",
"end",
"end"
] | Mouse callback method, called by the native and web extentions | [
"Mouse",
"callback",
"method",
"called",
"by",
"the",
"native",
"and",
"web",
"extentions"
] | 43ce9805a7ae8b82b7ab8c50bf6d4c845d395dc4 | https://github.com/ruby2d/ruby2d/blob/43ce9805a7ae8b82b7ab8c50bf6d4c845d395dc4/lib/ruby2d/window.rb#L303-L331 | train |
ruby2d/ruby2d | lib/ruby2d/window.rb | Ruby2D.Window.controller_callback | def controller_callback(which, type, axis, value, button)
# All controller events
@events[:controller].each do |id, e|
e.call(ControllerEvent.new(which, type, axis, value, button))
end
case type
# When controller axis motion, like analog sticks
when :axis
@events[:controller_axis].each do |id, e|
e.call(ControllerAxisEvent.new(which, axis, value))
end
# When controller button is pressed
when :button_down
@events[:controller_button_down].each do |id, e|
e.call(ControllerButtonEvent.new(which, button))
end
# When controller button is released
when :button_up
@events[:controller_button_up].each do |id, e|
e.call(ControllerButtonEvent.new(which, button))
end
end
end | ruby | def controller_callback(which, type, axis, value, button)
# All controller events
@events[:controller].each do |id, e|
e.call(ControllerEvent.new(which, type, axis, value, button))
end
case type
# When controller axis motion, like analog sticks
when :axis
@events[:controller_axis].each do |id, e|
e.call(ControllerAxisEvent.new(which, axis, value))
end
# When controller button is pressed
when :button_down
@events[:controller_button_down].each do |id, e|
e.call(ControllerButtonEvent.new(which, button))
end
# When controller button is released
when :button_up
@events[:controller_button_up].each do |id, e|
e.call(ControllerButtonEvent.new(which, button))
end
end
end | [
"def",
"controller_callback",
"(",
"which",
",",
"type",
",",
"axis",
",",
"value",
",",
"button",
")",
"# All controller events",
"@events",
"[",
":controller",
"]",
".",
"each",
"do",
"|",
"id",
",",
"e",
"|",
"e",
".",
"call",
"(",
"ControllerEvent",
".",
"new",
"(",
"which",
",",
"type",
",",
"axis",
",",
"value",
",",
"button",
")",
")",
"end",
"case",
"type",
"# When controller axis motion, like analog sticks",
"when",
":axis",
"@events",
"[",
":controller_axis",
"]",
".",
"each",
"do",
"|",
"id",
",",
"e",
"|",
"e",
".",
"call",
"(",
"ControllerAxisEvent",
".",
"new",
"(",
"which",
",",
"axis",
",",
"value",
")",
")",
"end",
"# When controller button is pressed",
"when",
":button_down",
"@events",
"[",
":controller_button_down",
"]",
".",
"each",
"do",
"|",
"id",
",",
"e",
"|",
"e",
".",
"call",
"(",
"ControllerButtonEvent",
".",
"new",
"(",
"which",
",",
"button",
")",
")",
"end",
"# When controller button is released",
"when",
":button_up",
"@events",
"[",
":controller_button_up",
"]",
".",
"each",
"do",
"|",
"id",
",",
"e",
"|",
"e",
".",
"call",
"(",
"ControllerButtonEvent",
".",
"new",
"(",
"which",
",",
"button",
")",
")",
"end",
"end",
"end"
] | Controller callback method, called by the native and web extentions | [
"Controller",
"callback",
"method",
"called",
"by",
"the",
"native",
"and",
"web",
"extentions"
] | 43ce9805a7ae8b82b7ab8c50bf6d4c845d395dc4 | https://github.com/ruby2d/ruby2d/blob/43ce9805a7ae8b82b7ab8c50bf6d4c845d395dc4/lib/ruby2d/window.rb#L341-L364 | train |
ruby2d/ruby2d | lib/ruby2d/window.rb | Ruby2D.Window.update_callback | def update_callback
@update_proc.call
# Accept and eval commands if in console mode
if @console
if STDIN.ready?
cmd = STDIN.gets
begin
res = eval(cmd, TOPLEVEL_BINDING)
STDOUT.puts "=> #{res.inspect}"
STDOUT.flush
rescue SyntaxError => se
STDOUT.puts se
STDOUT.flush
rescue Exception => e
STDOUT.puts e
STDOUT.flush
end
end
end
end | ruby | def update_callback
@update_proc.call
# Accept and eval commands if in console mode
if @console
if STDIN.ready?
cmd = STDIN.gets
begin
res = eval(cmd, TOPLEVEL_BINDING)
STDOUT.puts "=> #{res.inspect}"
STDOUT.flush
rescue SyntaxError => se
STDOUT.puts se
STDOUT.flush
rescue Exception => e
STDOUT.puts e
STDOUT.flush
end
end
end
end | [
"def",
"update_callback",
"@update_proc",
".",
"call",
"# Accept and eval commands if in console mode",
"if",
"@console",
"if",
"STDIN",
".",
"ready?",
"cmd",
"=",
"STDIN",
".",
"gets",
"begin",
"res",
"=",
"eval",
"(",
"cmd",
",",
"TOPLEVEL_BINDING",
")",
"STDOUT",
".",
"puts",
"\"=> #{res.inspect}\"",
"STDOUT",
".",
"flush",
"rescue",
"SyntaxError",
"=>",
"se",
"STDOUT",
".",
"puts",
"se",
"STDOUT",
".",
"flush",
"rescue",
"Exception",
"=>",
"e",
"STDOUT",
".",
"puts",
"e",
"STDOUT",
".",
"flush",
"end",
"end",
"end",
"end"
] | Update callback method, called by the native and web extentions | [
"Update",
"callback",
"method",
"called",
"by",
"the",
"native",
"and",
"web",
"extentions"
] | 43ce9805a7ae8b82b7ab8c50bf6d4c845d395dc4 | https://github.com/ruby2d/ruby2d/blob/43ce9805a7ae8b82b7ab8c50bf6d4c845d395dc4/lib/ruby2d/window.rb#L367-L388 | train |
ruby2d/ruby2d | lib/ruby2d/window.rb | Ruby2D.Window.add_object | def add_object(o)
if [email protected]?(o)
index = @objects.index do |object|
object.z > o.z
end
if index
@objects.insert(index, o)
else
@objects.push(o)
end
true
else
false
end
end | ruby | def add_object(o)
if [email protected]?(o)
index = @objects.index do |object|
object.z > o.z
end
if index
@objects.insert(index, o)
else
@objects.push(o)
end
true
else
false
end
end | [
"def",
"add_object",
"(",
"o",
")",
"if",
"!",
"@objects",
".",
"include?",
"(",
"o",
")",
"index",
"=",
"@objects",
".",
"index",
"do",
"|",
"object",
"|",
"object",
".",
"z",
">",
"o",
".",
"z",
"end",
"if",
"index",
"@objects",
".",
"insert",
"(",
"index",
",",
"o",
")",
"else",
"@objects",
".",
"push",
"(",
"o",
")",
"end",
"true",
"else",
"false",
"end",
"end"
] | An an object to the window, used by the public `add` method | [
"An",
"an",
"object",
"to",
"the",
"window",
"used",
"by",
"the",
"public",
"add",
"method"
] | 43ce9805a7ae8b82b7ab8c50bf6d4c845d395dc4 | https://github.com/ruby2d/ruby2d/blob/43ce9805a7ae8b82b7ab8c50bf6d4c845d395dc4/lib/ruby2d/window.rb#L419-L433 | train |
scenic-views/scenic | lib/scenic/statements.rb | Scenic.Statements.create_view | def create_view(name, version: nil, sql_definition: nil, materialized: false)
if version.present? && sql_definition.present?
raise(
ArgumentError,
"sql_definition and version cannot both be set",
)
end
if version.blank? && sql_definition.blank?
version = 1
end
sql_definition ||= definition(name, version)
if materialized
Scenic.database.create_materialized_view(
name,
sql_definition,
no_data: no_data(materialized),
)
else
Scenic.database.create_view(name, sql_definition)
end
end | ruby | def create_view(name, version: nil, sql_definition: nil, materialized: false)
if version.present? && sql_definition.present?
raise(
ArgumentError,
"sql_definition and version cannot both be set",
)
end
if version.blank? && sql_definition.blank?
version = 1
end
sql_definition ||= definition(name, version)
if materialized
Scenic.database.create_materialized_view(
name,
sql_definition,
no_data: no_data(materialized),
)
else
Scenic.database.create_view(name, sql_definition)
end
end | [
"def",
"create_view",
"(",
"name",
",",
"version",
":",
"nil",
",",
"sql_definition",
":",
"nil",
",",
"materialized",
":",
"false",
")",
"if",
"version",
".",
"present?",
"&&",
"sql_definition",
".",
"present?",
"raise",
"(",
"ArgumentError",
",",
"\"sql_definition and version cannot both be set\"",
",",
")",
"end",
"if",
"version",
".",
"blank?",
"&&",
"sql_definition",
".",
"blank?",
"version",
"=",
"1",
"end",
"sql_definition",
"||=",
"definition",
"(",
"name",
",",
"version",
")",
"if",
"materialized",
"Scenic",
".",
"database",
".",
"create_materialized_view",
"(",
"name",
",",
"sql_definition",
",",
"no_data",
":",
"no_data",
"(",
"materialized",
")",
",",
")",
"else",
"Scenic",
".",
"database",
".",
"create_view",
"(",
"name",
",",
"sql_definition",
")",
"end",
"end"
] | Create a new database view.
@param name [String, Symbol] The name of the database view.
@param version [Fixnum] The version number of the view, used to find the
definition file in `db/views`. This defaults to `1` if not provided.
@param sql_definition [String] The SQL query for the view schema. An error
will be raised if `sql_definition` and `version` are both set,
as they are mutually exclusive.
@param materialized [Boolean, Hash] Set to true to create a materialized
view. Set to { no_data: true } to create materialized view without
loading data. Defaults to false.
@return The database response from executing the create statement.
@example Create from `db/views/searches_v02.sql`
create_view(:searches, version: 2)
@example Create from provided SQL string
create_view(:active_users, sql_definition: <<-SQL)
SELECT * FROM users WHERE users.active = 't'
SQL | [
"Create",
"a",
"new",
"database",
"view",
"."
] | cc6adbde2bded9c895c41025d371c4c0f34c9253 | https://github.com/scenic-views/scenic/blob/cc6adbde2bded9c895c41025d371c4c0f34c9253/lib/scenic/statements.rb#L25-L48 | train |
scenic-views/scenic | lib/scenic/statements.rb | Scenic.Statements.drop_view | def drop_view(name, revert_to_version: nil, materialized: false)
if materialized
Scenic.database.drop_materialized_view(name)
else
Scenic.database.drop_view(name)
end
end | ruby | def drop_view(name, revert_to_version: nil, materialized: false)
if materialized
Scenic.database.drop_materialized_view(name)
else
Scenic.database.drop_view(name)
end
end | [
"def",
"drop_view",
"(",
"name",
",",
"revert_to_version",
":",
"nil",
",",
"materialized",
":",
"false",
")",
"if",
"materialized",
"Scenic",
".",
"database",
".",
"drop_materialized_view",
"(",
"name",
")",
"else",
"Scenic",
".",
"database",
".",
"drop_view",
"(",
"name",
")",
"end",
"end"
] | Drop a database view by name.
@param name [String, Symbol] The name of the database view.
@param revert_to_version [Fixnum] Used to reverse the `drop_view` command
on `rake db:rollback`. The provided version will be passed as the
`version` argument to {#create_view}.
@param materialized [Boolean] Set to true if dropping a meterialized view.
defaults to false.
@return The database response from executing the drop statement.
@example Drop a view, rolling back to version 3 on rollback
drop_view(:users_who_recently_logged_in, revert_to_version: 3) | [
"Drop",
"a",
"database",
"view",
"by",
"name",
"."
] | cc6adbde2bded9c895c41025d371c4c0f34c9253 | https://github.com/scenic-views/scenic/blob/cc6adbde2bded9c895c41025d371c4c0f34c9253/lib/scenic/statements.rb#L63-L69 | train |
scenic-views/scenic | lib/scenic/statements.rb | Scenic.Statements.update_view | def update_view(name, version: nil, sql_definition: nil, revert_to_version: nil, materialized: false)
if version.blank? && sql_definition.blank?
raise(
ArgumentError,
"sql_definition or version must be specified",
)
end
if version.present? && sql_definition.present?
raise(
ArgumentError,
"sql_definition and version cannot both be set",
)
end
sql_definition ||= definition(name, version)
if materialized
Scenic.database.update_materialized_view(
name,
sql_definition,
no_data: no_data(materialized),
)
else
Scenic.database.update_view(name, sql_definition)
end
end | ruby | def update_view(name, version: nil, sql_definition: nil, revert_to_version: nil, materialized: false)
if version.blank? && sql_definition.blank?
raise(
ArgumentError,
"sql_definition or version must be specified",
)
end
if version.present? && sql_definition.present?
raise(
ArgumentError,
"sql_definition and version cannot both be set",
)
end
sql_definition ||= definition(name, version)
if materialized
Scenic.database.update_materialized_view(
name,
sql_definition,
no_data: no_data(materialized),
)
else
Scenic.database.update_view(name, sql_definition)
end
end | [
"def",
"update_view",
"(",
"name",
",",
"version",
":",
"nil",
",",
"sql_definition",
":",
"nil",
",",
"revert_to_version",
":",
"nil",
",",
"materialized",
":",
"false",
")",
"if",
"version",
".",
"blank?",
"&&",
"sql_definition",
".",
"blank?",
"raise",
"(",
"ArgumentError",
",",
"\"sql_definition or version must be specified\"",
",",
")",
"end",
"if",
"version",
".",
"present?",
"&&",
"sql_definition",
".",
"present?",
"raise",
"(",
"ArgumentError",
",",
"\"sql_definition and version cannot both be set\"",
",",
")",
"end",
"sql_definition",
"||=",
"definition",
"(",
"name",
",",
"version",
")",
"if",
"materialized",
"Scenic",
".",
"database",
".",
"update_materialized_view",
"(",
"name",
",",
"sql_definition",
",",
"no_data",
":",
"no_data",
"(",
"materialized",
")",
",",
")",
"else",
"Scenic",
".",
"database",
".",
"update_view",
"(",
"name",
",",
"sql_definition",
")",
"end",
"end"
] | Update a database view to a new version.
The existing view is dropped and recreated using the supplied `version`
parameter.
@param name [String, Symbol] The name of the database view.
@param version [Fixnum] The version number of the view.
@param sql_definition [String] The SQL query for the view schema. An error
will be raised if `sql_definition` and `version` are both set,
as they are mutually exclusive.
@param revert_to_version [Fixnum] The version number to rollback to on
`rake db rollback`
@param materialized [Boolean, Hash] True if updating a materialized view.
Set to { no_data: true } to update materialized view without loading
data. Defaults to false.
@return The database response from executing the create statement.
@example
update_view :engagement_reports, version: 3, revert_to_version: 2 | [
"Update",
"a",
"database",
"view",
"to",
"a",
"new",
"version",
"."
] | cc6adbde2bded9c895c41025d371c4c0f34c9253 | https://github.com/scenic-views/scenic/blob/cc6adbde2bded9c895c41025d371c4c0f34c9253/lib/scenic/statements.rb#L91-L117 | train |
scenic-views/scenic | lib/scenic/statements.rb | Scenic.Statements.replace_view | def replace_view(name, version: nil, revert_to_version: nil, materialized: false)
if version.blank?
raise ArgumentError, "version is required"
end
if materialized
raise ArgumentError, "Cannot replace materialized views"
end
sql_definition = definition(name, version)
Scenic.database.replace_view(name, sql_definition)
end | ruby | def replace_view(name, version: nil, revert_to_version: nil, materialized: false)
if version.blank?
raise ArgumentError, "version is required"
end
if materialized
raise ArgumentError, "Cannot replace materialized views"
end
sql_definition = definition(name, version)
Scenic.database.replace_view(name, sql_definition)
end | [
"def",
"replace_view",
"(",
"name",
",",
"version",
":",
"nil",
",",
"revert_to_version",
":",
"nil",
",",
"materialized",
":",
"false",
")",
"if",
"version",
".",
"blank?",
"raise",
"ArgumentError",
",",
"\"version is required\"",
"end",
"if",
"materialized",
"raise",
"ArgumentError",
",",
"\"Cannot replace materialized views\"",
"end",
"sql_definition",
"=",
"definition",
"(",
"name",
",",
"version",
")",
"Scenic",
".",
"database",
".",
"replace_view",
"(",
"name",
",",
"sql_definition",
")",
"end"
] | Update a database view to a new version using `CREATE OR REPLACE VIEW`.
The existing view is replaced using the supplied `version`
parameter.
Does not work with materialized views due to lack of database support.
@param name [String, Symbol] The name of the database view.
@param version [Fixnum] The version number of the view.
@param revert_to_version [Fixnum] The version number to rollback to on
`rake db rollback`
@return The database response from executing the create statement.
@example
replace_view :engagement_reports, version: 3, revert_to_version: 2 | [
"Update",
"a",
"database",
"view",
"to",
"a",
"new",
"version",
"using",
"CREATE",
"OR",
"REPLACE",
"VIEW",
"."
] | cc6adbde2bded9c895c41025d371c4c0f34c9253 | https://github.com/scenic-views/scenic/blob/cc6adbde2bded9c895c41025d371c4c0f34c9253/lib/scenic/statements.rb#L135-L147 | train |
RailsEventStore/rails_event_store | ruby_event_store/lib/ruby_event_store/event.rb | RubyEventStore.Event.to_h | def to_h
{
event_id: event_id,
metadata: metadata.to_h,
data: data,
type: type,
}
end | ruby | def to_h
{
event_id: event_id,
metadata: metadata.to_h,
data: data,
type: type,
}
end | [
"def",
"to_h",
"{",
"event_id",
":",
"event_id",
",",
"metadata",
":",
"metadata",
".",
"to_h",
",",
"data",
":",
"data",
",",
"type",
":",
"type",
",",
"}",
"end"
] | Returns a hash representation of the event.
Metadata is converted to hash as well
@return [Hash] with :event_id, :metadata, :data, :type keys | [
"Returns",
"a",
"hash",
"representation",
"of",
"the",
"event",
"."
] | 3ee4f3148499794154ee6fec74ccf6d4670d85ac | https://github.com/RailsEventStore/rails_event_store/blob/3ee4f3148499794154ee6fec74ccf6d4670d85ac/ruby_event_store/lib/ruby_event_store/event.rb#L40-L47 | train |
RailsEventStore/rails_event_store | ruby_event_store/lib/ruby_event_store/client.rb | RubyEventStore.Client.publish | def publish(events, stream_name: GLOBAL_STREAM, expected_version: :any)
enriched_events = enrich_events_metadata(events)
serialized_events = serialize_events(enriched_events)
append_to_stream_serialized_events(serialized_events, stream_name: stream_name, expected_version: expected_version)
enriched_events.zip(serialized_events) do |event, serialized_event|
with_metadata(
correlation_id: event.metadata[:correlation_id] || event.event_id,
causation_id: event.event_id,
) do
broker.(event, serialized_event)
end
end
self
end | ruby | def publish(events, stream_name: GLOBAL_STREAM, expected_version: :any)
enriched_events = enrich_events_metadata(events)
serialized_events = serialize_events(enriched_events)
append_to_stream_serialized_events(serialized_events, stream_name: stream_name, expected_version: expected_version)
enriched_events.zip(serialized_events) do |event, serialized_event|
with_metadata(
correlation_id: event.metadata[:correlation_id] || event.event_id,
causation_id: event.event_id,
) do
broker.(event, serialized_event)
end
end
self
end | [
"def",
"publish",
"(",
"events",
",",
"stream_name",
":",
"GLOBAL_STREAM",
",",
"expected_version",
":",
":any",
")",
"enriched_events",
"=",
"enrich_events_metadata",
"(",
"events",
")",
"serialized_events",
"=",
"serialize_events",
"(",
"enriched_events",
")",
"append_to_stream_serialized_events",
"(",
"serialized_events",
",",
"stream_name",
":",
"stream_name",
",",
"expected_version",
":",
"expected_version",
")",
"enriched_events",
".",
"zip",
"(",
"serialized_events",
")",
"do",
"|",
"event",
",",
"serialized_event",
"|",
"with_metadata",
"(",
"correlation_id",
":",
"event",
".",
"metadata",
"[",
":correlation_id",
"]",
"||",
"event",
".",
"event_id",
",",
"causation_id",
":",
"event",
".",
"event_id",
",",
")",
"do",
"broker",
".",
"(",
"event",
",",
"serialized_event",
")",
"end",
"end",
"self",
"end"
] | Persists events and notifies subscribed handlers about them
@param events [Array<Event, Proto>, Event, Proto] event(s)
@param stream_name [String] name of the stream for persisting events.
@param expected_version [:any, :auto, :none, Integer] controls optimistic locking strategy. {http://railseventstore.org/docs/expected_version/ Read more}
@return [self] | [
"Persists",
"events",
"and",
"notifies",
"subscribed",
"handlers",
"about",
"them"
] | 3ee4f3148499794154ee6fec74ccf6d4670d85ac | https://github.com/RailsEventStore/rails_event_store/blob/3ee4f3148499794154ee6fec74ccf6d4670d85ac/ruby_event_store/lib/ruby_event_store/client.rb#L25-L38 | train |
twitter/secure_headers | lib/secure_headers/middleware.rb | SecureHeaders.Middleware.call | def call(env)
req = Rack::Request.new(env)
status, headers, response = @app.call(env)
config = SecureHeaders.config_for(req)
flag_cookies!(headers, override_secure(env, config.cookies)) unless config.cookies == OPT_OUT
headers.merge!(SecureHeaders.header_hash_for(req))
[status, headers, response]
end | ruby | def call(env)
req = Rack::Request.new(env)
status, headers, response = @app.call(env)
config = SecureHeaders.config_for(req)
flag_cookies!(headers, override_secure(env, config.cookies)) unless config.cookies == OPT_OUT
headers.merge!(SecureHeaders.header_hash_for(req))
[status, headers, response]
end | [
"def",
"call",
"(",
"env",
")",
"req",
"=",
"Rack",
"::",
"Request",
".",
"new",
"(",
"env",
")",
"status",
",",
"headers",
",",
"response",
"=",
"@app",
".",
"call",
"(",
"env",
")",
"config",
"=",
"SecureHeaders",
".",
"config_for",
"(",
"req",
")",
"flag_cookies!",
"(",
"headers",
",",
"override_secure",
"(",
"env",
",",
"config",
".",
"cookies",
")",
")",
"unless",
"config",
".",
"cookies",
"==",
"OPT_OUT",
"headers",
".",
"merge!",
"(",
"SecureHeaders",
".",
"header_hash_for",
"(",
"req",
")",
")",
"[",
"status",
",",
"headers",
",",
"response",
"]",
"end"
] | merges the hash of headers into the current header set. | [
"merges",
"the",
"hash",
"of",
"headers",
"into",
"the",
"current",
"header",
"set",
"."
] | 543e6712aadae08f1653ed973e6b6204f7eac26a | https://github.com/twitter/secure_headers/blob/543e6712aadae08f1653ed973e6b6204f7eac26a/lib/secure_headers/middleware.rb#L9-L17 | train |
twitter/secure_headers | lib/secure_headers/middleware.rb | SecureHeaders.Middleware.override_secure | def override_secure(env, config = {})
if scheme(env) != "https" && config != OPT_OUT
config[:secure] = OPT_OUT
end
config
end | ruby | def override_secure(env, config = {})
if scheme(env) != "https" && config != OPT_OUT
config[:secure] = OPT_OUT
end
config
end | [
"def",
"override_secure",
"(",
"env",
",",
"config",
"=",
"{",
"}",
")",
"if",
"scheme",
"(",
"env",
")",
"!=",
"\"https\"",
"&&",
"config",
"!=",
"OPT_OUT",
"config",
"[",
":secure",
"]",
"=",
"OPT_OUT",
"end",
"config",
"end"
] | disable Secure cookies for non-https requests | [
"disable",
"Secure",
"cookies",
"for",
"non",
"-",
"https",
"requests"
] | 543e6712aadae08f1653ed973e6b6204f7eac26a | https://github.com/twitter/secure_headers/blob/543e6712aadae08f1653ed973e6b6204f7eac26a/lib/secure_headers/middleware.rb#L34-L40 | train |
twitter/secure_headers | lib/secure_headers/utils/cookies_config.rb | SecureHeaders.CookiesConfig.validate_samesite_boolean_config! | def validate_samesite_boolean_config!
if config[:samesite].key?(:lax) && config[:samesite][:lax].is_a?(TrueClass) && config[:samesite].key?(:strict)
raise CookiesConfigError.new("samesite cookie config is invalid, combination use of booleans and Hash to configure lax and strict enforcement is not permitted.")
elsif config[:samesite].key?(:strict) && config[:samesite][:strict].is_a?(TrueClass) && config[:samesite].key?(:lax)
raise CookiesConfigError.new("samesite cookie config is invalid, combination use of booleans and Hash to configure lax and strict enforcement is not permitted.")
end
end | ruby | def validate_samesite_boolean_config!
if config[:samesite].key?(:lax) && config[:samesite][:lax].is_a?(TrueClass) && config[:samesite].key?(:strict)
raise CookiesConfigError.new("samesite cookie config is invalid, combination use of booleans and Hash to configure lax and strict enforcement is not permitted.")
elsif config[:samesite].key?(:strict) && config[:samesite][:strict].is_a?(TrueClass) && config[:samesite].key?(:lax)
raise CookiesConfigError.new("samesite cookie config is invalid, combination use of booleans and Hash to configure lax and strict enforcement is not permitted.")
end
end | [
"def",
"validate_samesite_boolean_config!",
"if",
"config",
"[",
":samesite",
"]",
".",
"key?",
"(",
":lax",
")",
"&&",
"config",
"[",
":samesite",
"]",
"[",
":lax",
"]",
".",
"is_a?",
"(",
"TrueClass",
")",
"&&",
"config",
"[",
":samesite",
"]",
".",
"key?",
"(",
":strict",
")",
"raise",
"CookiesConfigError",
".",
"new",
"(",
"\"samesite cookie config is invalid, combination use of booleans and Hash to configure lax and strict enforcement is not permitted.\"",
")",
"elsif",
"config",
"[",
":samesite",
"]",
".",
"key?",
"(",
":strict",
")",
"&&",
"config",
"[",
":samesite",
"]",
"[",
":strict",
"]",
".",
"is_a?",
"(",
"TrueClass",
")",
"&&",
"config",
"[",
":samesite",
"]",
".",
"key?",
"(",
":lax",
")",
"raise",
"CookiesConfigError",
".",
"new",
"(",
"\"samesite cookie config is invalid, combination use of booleans and Hash to configure lax and strict enforcement is not permitted.\"",
")",
"end",
"end"
] | when configuring with booleans, only one enforcement is permitted | [
"when",
"configuring",
"with",
"booleans",
"only",
"one",
"enforcement",
"is",
"permitted"
] | 543e6712aadae08f1653ed973e6b6204f7eac26a | https://github.com/twitter/secure_headers/blob/543e6712aadae08f1653ed973e6b6204f7eac26a/lib/secure_headers/utils/cookies_config.rb#L45-L51 | train |
twitter/secure_headers | lib/secure_headers/utils/cookies_config.rb | SecureHeaders.CookiesConfig.validate_exclusive_use_of_hash_constraints! | def validate_exclusive_use_of_hash_constraints!(conf, attribute)
return unless is_hash?(conf)
if conf.key?(:only) && conf.key?(:except)
raise CookiesConfigError.new("#{attribute} cookie config is invalid, simultaneous use of conditional arguments `only` and `except` is not permitted.")
end
end | ruby | def validate_exclusive_use_of_hash_constraints!(conf, attribute)
return unless is_hash?(conf)
if conf.key?(:only) && conf.key?(:except)
raise CookiesConfigError.new("#{attribute} cookie config is invalid, simultaneous use of conditional arguments `only` and `except` is not permitted.")
end
end | [
"def",
"validate_exclusive_use_of_hash_constraints!",
"(",
"conf",
",",
"attribute",
")",
"return",
"unless",
"is_hash?",
"(",
"conf",
")",
"if",
"conf",
".",
"key?",
"(",
":only",
")",
"&&",
"conf",
".",
"key?",
"(",
":except",
")",
"raise",
"CookiesConfigError",
".",
"new",
"(",
"\"#{attribute} cookie config is invalid, simultaneous use of conditional arguments `only` and `except` is not permitted.\"",
")",
"end",
"end"
] | validate exclusive use of only or except but not both at the same time | [
"validate",
"exclusive",
"use",
"of",
"only",
"or",
"except",
"but",
"not",
"both",
"at",
"the",
"same",
"time"
] | 543e6712aadae08f1653ed973e6b6204f7eac26a | https://github.com/twitter/secure_headers/blob/543e6712aadae08f1653ed973e6b6204f7eac26a/lib/secure_headers/utils/cookies_config.rb#L73-L78 | train |
twitter/secure_headers | lib/secure_headers/utils/cookies_config.rb | SecureHeaders.CookiesConfig.validate_exclusive_use_of_samesite_enforcement! | def validate_exclusive_use_of_samesite_enforcement!(attribute)
if (intersection = (config[:samesite][:lax].fetch(attribute, []) & config[:samesite][:strict].fetch(attribute, []))).any?
raise CookiesConfigError.new("samesite cookie config is invalid, cookie(s) #{intersection.join(', ')} cannot be enforced as lax and strict")
end
end | ruby | def validate_exclusive_use_of_samesite_enforcement!(attribute)
if (intersection = (config[:samesite][:lax].fetch(attribute, []) & config[:samesite][:strict].fetch(attribute, []))).any?
raise CookiesConfigError.new("samesite cookie config is invalid, cookie(s) #{intersection.join(', ')} cannot be enforced as lax and strict")
end
end | [
"def",
"validate_exclusive_use_of_samesite_enforcement!",
"(",
"attribute",
")",
"if",
"(",
"intersection",
"=",
"(",
"config",
"[",
":samesite",
"]",
"[",
":lax",
"]",
".",
"fetch",
"(",
"attribute",
",",
"[",
"]",
")",
"&",
"config",
"[",
":samesite",
"]",
"[",
":strict",
"]",
".",
"fetch",
"(",
"attribute",
",",
"[",
"]",
")",
")",
")",
".",
"any?",
"raise",
"CookiesConfigError",
".",
"new",
"(",
"\"samesite cookie config is invalid, cookie(s) #{intersection.join(', ')} cannot be enforced as lax and strict\"",
")",
"end",
"end"
] | validate exclusivity of only and except members within strict and lax | [
"validate",
"exclusivity",
"of",
"only",
"and",
"except",
"members",
"within",
"strict",
"and",
"lax"
] | 543e6712aadae08f1653ed973e6b6204f7eac26a | https://github.com/twitter/secure_headers/blob/543e6712aadae08f1653ed973e6b6204f7eac26a/lib/secure_headers/utils/cookies_config.rb#L81-L85 | train |
twitter/secure_headers | lib/secure_headers/headers/content_security_policy.rb | SecureHeaders.ContentSecurityPolicy.reject_all_values_if_none | def reject_all_values_if_none(source_list)
if source_list.length > 1
source_list.reject { |value| value == NONE }
else
source_list
end
end | ruby | def reject_all_values_if_none(source_list)
if source_list.length > 1
source_list.reject { |value| value == NONE }
else
source_list
end
end | [
"def",
"reject_all_values_if_none",
"(",
"source_list",
")",
"if",
"source_list",
".",
"length",
">",
"1",
"source_list",
".",
"reject",
"{",
"|",
"value",
"|",
"value",
"==",
"NONE",
"}",
"else",
"source_list",
"end",
"end"
] | Discard any 'none' values if more directives are supplied since none may override values. | [
"Discard",
"any",
"none",
"values",
"if",
"more",
"directives",
"are",
"supplied",
"since",
"none",
"may",
"override",
"values",
"."
] | 543e6712aadae08f1653ed973e6b6204f7eac26a | https://github.com/twitter/secure_headers/blob/543e6712aadae08f1653ed973e6b6204f7eac26a/lib/secure_headers/headers/content_security_policy.rb#L137-L143 | train |
twitter/secure_headers | lib/secure_headers/headers/content_security_policy.rb | SecureHeaders.ContentSecurityPolicy.dedup_source_list | def dedup_source_list(sources)
sources = sources.uniq
wild_sources = sources.select { |source| source =~ STAR_REGEXP }
if wild_sources.any?
sources.reject do |source|
!wild_sources.include?(source) &&
wild_sources.any? { |pattern| File.fnmatch(pattern, source) }
end
else
sources
end
end | ruby | def dedup_source_list(sources)
sources = sources.uniq
wild_sources = sources.select { |source| source =~ STAR_REGEXP }
if wild_sources.any?
sources.reject do |source|
!wild_sources.include?(source) &&
wild_sources.any? { |pattern| File.fnmatch(pattern, source) }
end
else
sources
end
end | [
"def",
"dedup_source_list",
"(",
"sources",
")",
"sources",
"=",
"sources",
".",
"uniq",
"wild_sources",
"=",
"sources",
".",
"select",
"{",
"|",
"source",
"|",
"source",
"=~",
"STAR_REGEXP",
"}",
"if",
"wild_sources",
".",
"any?",
"sources",
".",
"reject",
"do",
"|",
"source",
"|",
"!",
"wild_sources",
".",
"include?",
"(",
"source",
")",
"&&",
"wild_sources",
".",
"any?",
"{",
"|",
"pattern",
"|",
"File",
".",
"fnmatch",
"(",
"pattern",
",",
"source",
")",
"}",
"end",
"else",
"sources",
"end",
"end"
] | Removes duplicates and sources that already match an existing wild card.
e.g. *.github.com asdf.github.com becomes *.github.com | [
"Removes",
"duplicates",
"and",
"sources",
"that",
"already",
"match",
"an",
"existing",
"wild",
"card",
"."
] | 543e6712aadae08f1653ed973e6b6204f7eac26a | https://github.com/twitter/secure_headers/blob/543e6712aadae08f1653ed973e6b6204f7eac26a/lib/secure_headers/headers/content_security_policy.rb#L148-L160 | train |
ambethia/recaptcha | lib/recaptcha/client_helper.rb | Recaptcha.ClientHelper.invisible_recaptcha_tags | def invisible_recaptcha_tags(options = {})
options = {callback: 'invisibleRecaptchaSubmit', ui: :button}.merge options
text = options.delete(:text)
html, tag_attributes = Recaptcha::ClientHelper.recaptcha_components(options)
html << recaptcha_default_callback(options) if recaptcha_default_callback_required?(options)
case options[:ui]
when :button
html << %(<button type="submit" #{tag_attributes}>#{text}</button>\n)
when :invisible
html << %(<div data-size="invisible" #{tag_attributes}></div>\n)
when :input
html << %(<input type="submit" #{tag_attributes} value="#{text}"/>\n)
else
raise(RecaptchaError, "ReCAPTCHA ui `#{options[:ui]}` is not valid.")
end
html.respond_to?(:html_safe) ? html.html_safe : html
end | ruby | def invisible_recaptcha_tags(options = {})
options = {callback: 'invisibleRecaptchaSubmit', ui: :button}.merge options
text = options.delete(:text)
html, tag_attributes = Recaptcha::ClientHelper.recaptcha_components(options)
html << recaptcha_default_callback(options) if recaptcha_default_callback_required?(options)
case options[:ui]
when :button
html << %(<button type="submit" #{tag_attributes}>#{text}</button>\n)
when :invisible
html << %(<div data-size="invisible" #{tag_attributes}></div>\n)
when :input
html << %(<input type="submit" #{tag_attributes} value="#{text}"/>\n)
else
raise(RecaptchaError, "ReCAPTCHA ui `#{options[:ui]}` is not valid.")
end
html.respond_to?(:html_safe) ? html.html_safe : html
end | [
"def",
"invisible_recaptcha_tags",
"(",
"options",
"=",
"{",
"}",
")",
"options",
"=",
"{",
"callback",
":",
"'invisibleRecaptchaSubmit'",
",",
"ui",
":",
":button",
"}",
".",
"merge",
"options",
"text",
"=",
"options",
".",
"delete",
"(",
":text",
")",
"html",
",",
"tag_attributes",
"=",
"Recaptcha",
"::",
"ClientHelper",
".",
"recaptcha_components",
"(",
"options",
")",
"html",
"<<",
"recaptcha_default_callback",
"(",
"options",
")",
"if",
"recaptcha_default_callback_required?",
"(",
"options",
")",
"case",
"options",
"[",
":ui",
"]",
"when",
":button",
"html",
"<<",
"%(<button type=\"submit\" #{tag_attributes}>#{text}</button>\\n)",
"when",
":invisible",
"html",
"<<",
"%(<div data-size=\"invisible\" #{tag_attributes}></div>\\n)",
"when",
":input",
"html",
"<<",
"%(<input type=\"submit\" #{tag_attributes} value=\"#{text}\"/>\\n)",
"else",
"raise",
"(",
"RecaptchaError",
",",
"\"ReCAPTCHA ui `#{options[:ui]}` is not valid.\"",
")",
"end",
"html",
".",
"respond_to?",
"(",
":html_safe",
")",
"?",
"html",
".",
"html_safe",
":",
"html",
"end"
] | Invisible reCAPTCHA implementation | [
"Invisible",
"reCAPTCHA",
"implementation"
] | fcac97960ce29ebd7473315d9ffe89dccce6615e | https://github.com/ambethia/recaptcha/blob/fcac97960ce29ebd7473315d9ffe89dccce6615e/lib/recaptcha/client_helper.rb#L51-L67 | train |
ambethia/recaptcha | lib/recaptcha/verify.rb | Recaptcha.Verify.verify_recaptcha | def verify_recaptcha(options = {})
options = {model: options} unless options.is_a? Hash
return true if Recaptcha::Verify.skip?(options[:env])
model = options[:model]
attribute = options[:attribute] || :base
recaptcha_response = options[:response] || params['g-recaptcha-response'].to_s
begin
verified = if recaptcha_response.empty? || recaptcha_response.length > G_RESPONSE_LIMIT
false
else
recaptcha_verify_via_api_call(request, recaptcha_response, options)
end
if verified
flash.delete(:recaptcha_error) if recaptcha_flash_supported? && !model
true
else
recaptcha_error(
model,
attribute,
options[:message],
"recaptcha.errors.verification_failed",
"reCAPTCHA verification failed, please try again."
)
false
end
rescue Timeout::Error
if Recaptcha.configuration.handle_timeouts_gracefully
recaptcha_error(
model,
attribute,
options[:message],
"recaptcha.errors.recaptcha_unreachable",
"Oops, we failed to validate your reCAPTCHA response. Please try again."
)
false
else
raise RecaptchaError, "Recaptcha unreachable."
end
rescue StandardError => e
raise RecaptchaError, e.message, e.backtrace
end
end | ruby | def verify_recaptcha(options = {})
options = {model: options} unless options.is_a? Hash
return true if Recaptcha::Verify.skip?(options[:env])
model = options[:model]
attribute = options[:attribute] || :base
recaptcha_response = options[:response] || params['g-recaptcha-response'].to_s
begin
verified = if recaptcha_response.empty? || recaptcha_response.length > G_RESPONSE_LIMIT
false
else
recaptcha_verify_via_api_call(request, recaptcha_response, options)
end
if verified
flash.delete(:recaptcha_error) if recaptcha_flash_supported? && !model
true
else
recaptcha_error(
model,
attribute,
options[:message],
"recaptcha.errors.verification_failed",
"reCAPTCHA verification failed, please try again."
)
false
end
rescue Timeout::Error
if Recaptcha.configuration.handle_timeouts_gracefully
recaptcha_error(
model,
attribute,
options[:message],
"recaptcha.errors.recaptcha_unreachable",
"Oops, we failed to validate your reCAPTCHA response. Please try again."
)
false
else
raise RecaptchaError, "Recaptcha unreachable."
end
rescue StandardError => e
raise RecaptchaError, e.message, e.backtrace
end
end | [
"def",
"verify_recaptcha",
"(",
"options",
"=",
"{",
"}",
")",
"options",
"=",
"{",
"model",
":",
"options",
"}",
"unless",
"options",
".",
"is_a?",
"Hash",
"return",
"true",
"if",
"Recaptcha",
"::",
"Verify",
".",
"skip?",
"(",
"options",
"[",
":env",
"]",
")",
"model",
"=",
"options",
"[",
":model",
"]",
"attribute",
"=",
"options",
"[",
":attribute",
"]",
"||",
":base",
"recaptcha_response",
"=",
"options",
"[",
":response",
"]",
"||",
"params",
"[",
"'g-recaptcha-response'",
"]",
".",
"to_s",
"begin",
"verified",
"=",
"if",
"recaptcha_response",
".",
"empty?",
"||",
"recaptcha_response",
".",
"length",
">",
"G_RESPONSE_LIMIT",
"false",
"else",
"recaptcha_verify_via_api_call",
"(",
"request",
",",
"recaptcha_response",
",",
"options",
")",
"end",
"if",
"verified",
"flash",
".",
"delete",
"(",
":recaptcha_error",
")",
"if",
"recaptcha_flash_supported?",
"&&",
"!",
"model",
"true",
"else",
"recaptcha_error",
"(",
"model",
",",
"attribute",
",",
"options",
"[",
":message",
"]",
",",
"\"recaptcha.errors.verification_failed\"",
",",
"\"reCAPTCHA verification failed, please try again.\"",
")",
"false",
"end",
"rescue",
"Timeout",
"::",
"Error",
"if",
"Recaptcha",
".",
"configuration",
".",
"handle_timeouts_gracefully",
"recaptcha_error",
"(",
"model",
",",
"attribute",
",",
"options",
"[",
":message",
"]",
",",
"\"recaptcha.errors.recaptcha_unreachable\"",
",",
"\"Oops, we failed to validate your reCAPTCHA response. Please try again.\"",
")",
"false",
"else",
"raise",
"RecaptchaError",
",",
"\"Recaptcha unreachable.\"",
"end",
"rescue",
"StandardError",
"=>",
"e",
"raise",
"RecaptchaError",
",",
"e",
".",
"message",
",",
"e",
".",
"backtrace",
"end",
"end"
] | Your private API can be specified in the +options+ hash or preferably
using the Configuration. | [
"Your",
"private",
"API",
"can",
"be",
"specified",
"in",
"the",
"+",
"options",
"+",
"hash",
"or",
"preferably",
"using",
"the",
"Configuration",
"."
] | fcac97960ce29ebd7473315d9ffe89dccce6615e | https://github.com/ambethia/recaptcha/blob/fcac97960ce29ebd7473315d9ffe89dccce6615e/lib/recaptcha/verify.rb#L10-L54 | train |
sds/haml-lint | lib/haml_lint/configuration.rb | HamlLint.Configuration.for_linter | def for_linter(linter)
linter_name =
case linter
when Class
linter.name.split('::').last
when HamlLint::Linter
linter.name
end
@hash['linters'].fetch(linter_name, {}).dup.freeze
end | ruby | def for_linter(linter)
linter_name =
case linter
when Class
linter.name.split('::').last
when HamlLint::Linter
linter.name
end
@hash['linters'].fetch(linter_name, {}).dup.freeze
end | [
"def",
"for_linter",
"(",
"linter",
")",
"linter_name",
"=",
"case",
"linter",
"when",
"Class",
"linter",
".",
"name",
".",
"split",
"(",
"'::'",
")",
".",
"last",
"when",
"HamlLint",
"::",
"Linter",
"linter",
".",
"name",
"end",
"@hash",
"[",
"'linters'",
"]",
".",
"fetch",
"(",
"linter_name",
",",
"{",
"}",
")",
".",
"dup",
".",
"freeze",
"end"
] | Compares this configuration with another.
@param other [HamlLint::Configuration]
@return [true,false] whether the given configuration is equivalent
Returns a non-modifiable configuration for the specified linter.
@param linter [HamlLint::Linter,Class] | [
"Compares",
"this",
"configuration",
"with",
"another",
"."
] | 024c773667e54cf88db938c2b368977005d70ee8 | https://github.com/sds/haml-lint/blob/024c773667e54cf88db938c2b368977005d70ee8/lib/haml_lint/configuration.rb#L43-L53 | train |
sds/haml-lint | lib/haml_lint/configuration.rb | HamlLint.Configuration.smart_merge | def smart_merge(parent, child)
parent.merge(child) do |_key, old, new|
case old
when Hash
smart_merge(old, new)
else
new
end
end
end | ruby | def smart_merge(parent, child)
parent.merge(child) do |_key, old, new|
case old
when Hash
smart_merge(old, new)
else
new
end
end
end | [
"def",
"smart_merge",
"(",
"parent",
",",
"child",
")",
"parent",
".",
"merge",
"(",
"child",
")",
"do",
"|",
"_key",
",",
"old",
",",
"new",
"|",
"case",
"old",
"when",
"Hash",
"smart_merge",
"(",
"old",
",",
"new",
")",
"else",
"new",
"end",
"end",
"end"
] | Merge two hashes such that nested hashes are merged rather than replaced.
@param parent [Hash]
@param child [Hash]
@return [Hash] | [
"Merge",
"two",
"hashes",
"such",
"that",
"nested",
"hashes",
"are",
"merged",
"rather",
"than",
"replaced",
"."
] | 024c773667e54cf88db938c2b368977005d70ee8 | https://github.com/sds/haml-lint/blob/024c773667e54cf88db938c2b368977005d70ee8/lib/haml_lint/configuration.rb#L71-L80 | train |
sds/haml-lint | lib/haml_lint/reporter/disabled_config_reporter.rb | HamlLint.Reporter::DisabledConfigReporter.display_report | def display_report(report)
super
File.write(ConfigurationLoader::AUTO_GENERATED_FILE, config_file_contents)
log.log "Created #{ConfigurationLoader::AUTO_GENERATED_FILE}."
log.log "Run `haml-lint --config #{ConfigurationLoader::AUTO_GENERATED_FILE}`" \
", or add `inherits_from: #{ConfigurationLoader::AUTO_GENERATED_FILE}` in a " \
'.haml-lint.yml file.'
end | ruby | def display_report(report)
super
File.write(ConfigurationLoader::AUTO_GENERATED_FILE, config_file_contents)
log.log "Created #{ConfigurationLoader::AUTO_GENERATED_FILE}."
log.log "Run `haml-lint --config #{ConfigurationLoader::AUTO_GENERATED_FILE}`" \
", or add `inherits_from: #{ConfigurationLoader::AUTO_GENERATED_FILE}` in a " \
'.haml-lint.yml file.'
end | [
"def",
"display_report",
"(",
"report",
")",
"super",
"File",
".",
"write",
"(",
"ConfigurationLoader",
"::",
"AUTO_GENERATED_FILE",
",",
"config_file_contents",
")",
"log",
".",
"log",
"\"Created #{ConfigurationLoader::AUTO_GENERATED_FILE}.\"",
"log",
".",
"log",
"\"Run `haml-lint --config #{ConfigurationLoader::AUTO_GENERATED_FILE}`\"",
"\", or add `inherits_from: #{ConfigurationLoader::AUTO_GENERATED_FILE}` in a \"",
"'.haml-lint.yml file.'",
"end"
] | Prints the standard progress reporter output and writes the new config file.
@param report [HamlLint::Report]
@return [void] | [
"Prints",
"the",
"standard",
"progress",
"reporter",
"output",
"and",
"writes",
"the",
"new",
"config",
"file",
"."
] | 024c773667e54cf88db938c2b368977005d70ee8 | https://github.com/sds/haml-lint/blob/024c773667e54cf88db938c2b368977005d70ee8/lib/haml_lint/reporter/disabled_config_reporter.rb#L56-L64 | train |
sds/haml-lint | lib/haml_lint/reporter/disabled_config_reporter.rb | HamlLint.Reporter::DisabledConfigReporter.finished_file | def finished_file(file, lints)
super
if lints.any?
lints.each do |lint|
linters_with_lints[lint.linter.name] |= [lint.filename]
linters_lint_count[lint.linter.name] += 1
end
end
end | ruby | def finished_file(file, lints)
super
if lints.any?
lints.each do |lint|
linters_with_lints[lint.linter.name] |= [lint.filename]
linters_lint_count[lint.linter.name] += 1
end
end
end | [
"def",
"finished_file",
"(",
"file",
",",
"lints",
")",
"super",
"if",
"lints",
".",
"any?",
"lints",
".",
"each",
"do",
"|",
"lint",
"|",
"linters_with_lints",
"[",
"lint",
".",
"linter",
".",
"name",
"]",
"|=",
"[",
"lint",
".",
"filename",
"]",
"linters_lint_count",
"[",
"lint",
".",
"linter",
".",
"name",
"]",
"+=",
"1",
"end",
"end",
"end"
] | Prints the standard progress report marks and tracks files with lint.
@param file [String]
@param lints [Array<HamlLint::Lint>]
@return [void] | [
"Prints",
"the",
"standard",
"progress",
"report",
"marks",
"and",
"tracks",
"files",
"with",
"lint",
"."
] | 024c773667e54cf88db938c2b368977005d70ee8 | https://github.com/sds/haml-lint/blob/024c773667e54cf88db938c2b368977005d70ee8/lib/haml_lint/reporter/disabled_config_reporter.rb#L71-L80 | train |
sds/haml-lint | lib/haml_lint/reporter/disabled_config_reporter.rb | HamlLint.Reporter::DisabledConfigReporter.config_file_contents | def config_file_contents
output = []
output << HEADING
output << 'linters:' if linters_with_lints.any?
linters_with_lints.each do |linter, files|
output << generate_config_for_linter(linter, files)
end
output.join("\n\n")
end | ruby | def config_file_contents
output = []
output << HEADING
output << 'linters:' if linters_with_lints.any?
linters_with_lints.each do |linter, files|
output << generate_config_for_linter(linter, files)
end
output.join("\n\n")
end | [
"def",
"config_file_contents",
"output",
"=",
"[",
"]",
"output",
"<<",
"HEADING",
"output",
"<<",
"'linters:'",
"if",
"linters_with_lints",
".",
"any?",
"linters_with_lints",
".",
"each",
"do",
"|",
"linter",
",",
"files",
"|",
"output",
"<<",
"generate_config_for_linter",
"(",
"linter",
",",
"files",
")",
"end",
"output",
".",
"join",
"(",
"\"\\n\\n\"",
")",
"end"
] | The contents of the generated configuration file based on captured lint.
@return [String] a Yaml-formatted configuration file's contents | [
"The",
"contents",
"of",
"the",
"generated",
"configuration",
"file",
"based",
"on",
"captured",
"lint",
"."
] | 024c773667e54cf88db938c2b368977005d70ee8 | https://github.com/sds/haml-lint/blob/024c773667e54cf88db938c2b368977005d70ee8/lib/haml_lint/reporter/disabled_config_reporter.rb#L87-L95 | train |
sds/haml-lint | lib/haml_lint/reporter/disabled_config_reporter.rb | HamlLint.Reporter::DisabledConfigReporter.generate_config_for_linter | def generate_config_for_linter(linter, files)
[].tap do |output|
output << " # Offense count: #{linters_lint_count[linter]}"
output << " #{linter}:"
# disable the linter when there are many files with offenses.
# exclude the affected files otherwise.
if files.count > exclude_limit
output << ' enabled: false'
else
output << ' exclude:'
files.each do |filename|
output << %{ - "#{filename}"}
end
end
end.join("\n")
end | ruby | def generate_config_for_linter(linter, files)
[].tap do |output|
output << " # Offense count: #{linters_lint_count[linter]}"
output << " #{linter}:"
# disable the linter when there are many files with offenses.
# exclude the affected files otherwise.
if files.count > exclude_limit
output << ' enabled: false'
else
output << ' exclude:'
files.each do |filename|
output << %{ - "#{filename}"}
end
end
end.join("\n")
end | [
"def",
"generate_config_for_linter",
"(",
"linter",
",",
"files",
")",
"[",
"]",
".",
"tap",
"do",
"|",
"output",
"|",
"output",
"<<",
"\" # Offense count: #{linters_lint_count[linter]}\"",
"output",
"<<",
"\" #{linter}:\"",
"# disable the linter when there are many files with offenses.",
"# exclude the affected files otherwise.",
"if",
"files",
".",
"count",
">",
"exclude_limit",
"output",
"<<",
"' enabled: false'",
"else",
"output",
"<<",
"' exclude:'",
"files",
".",
"each",
"do",
"|",
"filename",
"|",
"output",
"<<",
"%{ - \"#{filename}\"}",
"end",
"end",
"end",
".",
"join",
"(",
"\"\\n\"",
")",
"end"
] | Constructs the configuration for excluding a linter in some files.
@param linter [String] the name of the linter to exclude
@param files [Array<String>] the files in which the linter is excluded
@return [String] a Yaml-formatted configuration | [
"Constructs",
"the",
"configuration",
"for",
"excluding",
"a",
"linter",
"in",
"some",
"files",
"."
] | 024c773667e54cf88db938c2b368977005d70ee8 | https://github.com/sds/haml-lint/blob/024c773667e54cf88db938c2b368977005d70ee8/lib/haml_lint/reporter/disabled_config_reporter.rb#L102-L117 | train |
sds/haml-lint | lib/haml_lint/options.rb | HamlLint.Options.load_reporter_class | def load_reporter_class(reporter_name)
HamlLint::Reporter.const_get("#{reporter_name}Reporter")
rescue NameError
raise HamlLint::Exceptions::InvalidCLIOption,
"#{reporter_name}Reporter does not exist"
end | ruby | def load_reporter_class(reporter_name)
HamlLint::Reporter.const_get("#{reporter_name}Reporter")
rescue NameError
raise HamlLint::Exceptions::InvalidCLIOption,
"#{reporter_name}Reporter does not exist"
end | [
"def",
"load_reporter_class",
"(",
"reporter_name",
")",
"HamlLint",
"::",
"Reporter",
".",
"const_get",
"(",
"\"#{reporter_name}Reporter\"",
")",
"rescue",
"NameError",
"raise",
"HamlLint",
"::",
"Exceptions",
"::",
"InvalidCLIOption",
",",
"\"#{reporter_name}Reporter does not exist\"",
"end"
] | Returns the class of the specified Reporter.
@param reporter_name [String]
@raise [HamlLint::Exceptions::InvalidCLIOption] if reporter doesn't exist
@return [Class] | [
"Returns",
"the",
"class",
"of",
"the",
"specified",
"Reporter",
"."
] | 024c773667e54cf88db938c2b368977005d70ee8 | https://github.com/sds/haml-lint/blob/024c773667e54cf88db938c2b368977005d70ee8/lib/haml_lint/options.rb#L79-L84 | train |
sds/haml-lint | lib/haml_lint/linter/instance_variables.rb | HamlLint.Linter::InstanceVariables.visit_root | def visit_root(node)
@enabled = matcher.match(File.basename(node.file)) ? true : false
end | ruby | def visit_root(node)
@enabled = matcher.match(File.basename(node.file)) ? true : false
end | [
"def",
"visit_root",
"(",
"node",
")",
"@enabled",
"=",
"matcher",
".",
"match",
"(",
"File",
".",
"basename",
"(",
"node",
".",
"file",
")",
")",
"?",
"true",
":",
"false",
"end"
] | Enables the linter if the tree is for the right file type.
@param [HamlLint::Tree::RootNode] the root of a syntax tree
@return [true, false] whether the linter is enabled for the tree | [
"Enables",
"the",
"linter",
"if",
"the",
"tree",
"is",
"for",
"the",
"right",
"file",
"type",
"."
] | 024c773667e54cf88db938c2b368977005d70ee8 | https://github.com/sds/haml-lint/blob/024c773667e54cf88db938c2b368977005d70ee8/lib/haml_lint/linter/instance_variables.rb#L12-L14 | train |
sds/haml-lint | lib/haml_lint/linter/instance_variables.rb | HamlLint.Linter::InstanceVariables.visit_tag | def visit_tag(node)
return unless enabled?
visit_script(node) ||
if node.parsed_attributes.contains_instance_variables?
record_lint(node, "Avoid using instance variables in #{file_types} views")
end
end | ruby | def visit_tag(node)
return unless enabled?
visit_script(node) ||
if node.parsed_attributes.contains_instance_variables?
record_lint(node, "Avoid using instance variables in #{file_types} views")
end
end | [
"def",
"visit_tag",
"(",
"node",
")",
"return",
"unless",
"enabled?",
"visit_script",
"(",
"node",
")",
"||",
"if",
"node",
".",
"parsed_attributes",
".",
"contains_instance_variables?",
"record_lint",
"(",
"node",
",",
"\"Avoid using instance variables in #{file_types} views\"",
")",
"end",
"end"
] | Checks for instance variables in tag nodes when the linter is enabled.
@param [HamlLint::Tree:TagNode]
@return [void] | [
"Checks",
"for",
"instance",
"variables",
"in",
"tag",
"nodes",
"when",
"the",
"linter",
"is",
"enabled",
"."
] | 024c773667e54cf88db938c2b368977005d70ee8 | https://github.com/sds/haml-lint/blob/024c773667e54cf88db938c2b368977005d70ee8/lib/haml_lint/linter/instance_variables.rb#L39-L46 | train |
sds/haml-lint | lib/haml_lint/runner.rb | HamlLint.Runner.run | def run(options = {})
@config = load_applicable_config(options)
@files = extract_applicable_files(config, options)
@linter_selector = HamlLint::LinterSelector.new(config, options)
@fail_fast = options.fetch(:fail_fast, false)
report(options)
end | ruby | def run(options = {})
@config = load_applicable_config(options)
@files = extract_applicable_files(config, options)
@linter_selector = HamlLint::LinterSelector.new(config, options)
@fail_fast = options.fetch(:fail_fast, false)
report(options)
end | [
"def",
"run",
"(",
"options",
"=",
"{",
"}",
")",
"@config",
"=",
"load_applicable_config",
"(",
"options",
")",
"@files",
"=",
"extract_applicable_files",
"(",
"config",
",",
"options",
")",
"@linter_selector",
"=",
"HamlLint",
"::",
"LinterSelector",
".",
"new",
"(",
"config",
",",
"options",
")",
"@fail_fast",
"=",
"options",
".",
"fetch",
"(",
":fail_fast",
",",
"false",
")",
"report",
"(",
"options",
")",
"end"
] | Runs the appropriate linters against the desired files given the specified
options.
@param [Hash] options
@option options :config_file [String] path of configuration file to load
@option options :config [HamlLint::Configuration] configuration to use
@option options :excluded_files [Array<String>]
@option options :included_linters [Array<String>]
@option options :excluded_linters [Array<String>]
@option options :fail_fast [true, false] flag for failing after first failure
@option options :fail_level
@option options :reporter [HamlLint::Reporter]
@return [HamlLint::Report] a summary of all lints found | [
"Runs",
"the",
"appropriate",
"linters",
"against",
"the",
"desired",
"files",
"given",
"the",
"specified",
"options",
"."
] | 024c773667e54cf88db938c2b368977005d70ee8 | https://github.com/sds/haml-lint/blob/024c773667e54cf88db938c2b368977005d70ee8/lib/haml_lint/runner.rb#L19-L26 | train |
sds/haml-lint | lib/haml_lint/runner.rb | HamlLint.Runner.collect_lints | def collect_lints(file, linter_selector, config)
begin
document = HamlLint::Document.new(File.read(file), file: file, config: config)
rescue HamlLint::Exceptions::ParseError => e
return [HamlLint::Lint.new(HamlLint::Linter::Syntax.new(config), file,
e.line, e.to_s, :error)]
end
linter_selector.linters_for_file(file).map do |linter|
linter.run(document)
end.flatten
end | ruby | def collect_lints(file, linter_selector, config)
begin
document = HamlLint::Document.new(File.read(file), file: file, config: config)
rescue HamlLint::Exceptions::ParseError => e
return [HamlLint::Lint.new(HamlLint::Linter::Syntax.new(config), file,
e.line, e.to_s, :error)]
end
linter_selector.linters_for_file(file).map do |linter|
linter.run(document)
end.flatten
end | [
"def",
"collect_lints",
"(",
"file",
",",
"linter_selector",
",",
"config",
")",
"begin",
"document",
"=",
"HamlLint",
"::",
"Document",
".",
"new",
"(",
"File",
".",
"read",
"(",
"file",
")",
",",
"file",
":",
"file",
",",
"config",
":",
"config",
")",
"rescue",
"HamlLint",
"::",
"Exceptions",
"::",
"ParseError",
"=>",
"e",
"return",
"[",
"HamlLint",
"::",
"Lint",
".",
"new",
"(",
"HamlLint",
"::",
"Linter",
"::",
"Syntax",
".",
"new",
"(",
"config",
")",
",",
"file",
",",
"e",
".",
"line",
",",
"e",
".",
"to_s",
",",
":error",
")",
"]",
"end",
"linter_selector",
".",
"linters_for_file",
"(",
"file",
")",
".",
"map",
"do",
"|",
"linter",
"|",
"linter",
".",
"run",
"(",
"document",
")",
"end",
".",
"flatten",
"end"
] | Runs all provided linters using the specified config against the given
file.
@param file [String] path to file to lint
@param linter_selector [HamlLint::LinterSelector]
@param config [HamlLint::Configuration] | [
"Runs",
"all",
"provided",
"linters",
"using",
"the",
"specified",
"config",
"against",
"the",
"given",
"file",
"."
] | 024c773667e54cf88db938c2b368977005d70ee8 | https://github.com/sds/haml-lint/blob/024c773667e54cf88db938c2b368977005d70ee8/lib/haml_lint/runner.rb#L80-L91 | train |
sds/haml-lint | lib/haml_lint/runner.rb | HamlLint.Runner.extract_applicable_files | def extract_applicable_files(config, options)
included_patterns = options[:files]
excluded_patterns = config['exclude']
excluded_patterns += options.fetch(:excluded_files, [])
HamlLint::FileFinder.new(config).find(included_patterns, excluded_patterns)
end | ruby | def extract_applicable_files(config, options)
included_patterns = options[:files]
excluded_patterns = config['exclude']
excluded_patterns += options.fetch(:excluded_files, [])
HamlLint::FileFinder.new(config).find(included_patterns, excluded_patterns)
end | [
"def",
"extract_applicable_files",
"(",
"config",
",",
"options",
")",
"included_patterns",
"=",
"options",
"[",
":files",
"]",
"excluded_patterns",
"=",
"config",
"[",
"'exclude'",
"]",
"excluded_patterns",
"+=",
"options",
".",
"fetch",
"(",
":excluded_files",
",",
"[",
"]",
")",
"HamlLint",
"::",
"FileFinder",
".",
"new",
"(",
"config",
")",
".",
"find",
"(",
"included_patterns",
",",
"excluded_patterns",
")",
"end"
] | Returns the list of files that should be linted given the specified
configuration and options.
@param config [HamlLint::Configuration]
@param options [Hash]
@return [Array<String>] | [
"Returns",
"the",
"list",
"of",
"files",
"that",
"should",
"be",
"linted",
"given",
"the",
"specified",
"configuration",
"and",
"options",
"."
] | 024c773667e54cf88db938c2b368977005d70ee8 | https://github.com/sds/haml-lint/blob/024c773667e54cf88db938c2b368977005d70ee8/lib/haml_lint/runner.rb#L99-L105 | train |
sds/haml-lint | lib/haml_lint/runner.rb | HamlLint.Runner.process_files | def process_files(report)
files.each do |file|
process_file(file, report)
break if report.failed? && fail_fast?
end
end | ruby | def process_files(report)
files.each do |file|
process_file(file, report)
break if report.failed? && fail_fast?
end
end | [
"def",
"process_files",
"(",
"report",
")",
"files",
".",
"each",
"do",
"|",
"file",
"|",
"process_file",
"(",
"file",
",",
"report",
")",
"break",
"if",
"report",
".",
"failed?",
"&&",
"fail_fast?",
"end",
"end"
] | Process the files and add them to the given report.
@param report [HamlLint::Report]
@return [void] | [
"Process",
"the",
"files",
"and",
"add",
"them",
"to",
"the",
"given",
"report",
"."
] | 024c773667e54cf88db938c2b368977005d70ee8 | https://github.com/sds/haml-lint/blob/024c773667e54cf88db938c2b368977005d70ee8/lib/haml_lint/runner.rb#L111-L116 | train |
sds/haml-lint | lib/haml_lint/runner.rb | HamlLint.Runner.process_file | def process_file(file, report)
lints = collect_lints(file, linter_selector, config)
lints.each { |lint| report.add_lint(lint) }
report.finish_file(file, lints)
end | ruby | def process_file(file, report)
lints = collect_lints(file, linter_selector, config)
lints.each { |lint| report.add_lint(lint) }
report.finish_file(file, lints)
end | [
"def",
"process_file",
"(",
"file",
",",
"report",
")",
"lints",
"=",
"collect_lints",
"(",
"file",
",",
"linter_selector",
",",
"config",
")",
"lints",
".",
"each",
"{",
"|",
"lint",
"|",
"report",
".",
"add_lint",
"(",
"lint",
")",
"}",
"report",
".",
"finish_file",
"(",
"file",
",",
"lints",
")",
"end"
] | Process a file and add it to the given report.
@param file [String] the name of the file to process
@param report [HamlLint::Report]
@return [void] | [
"Process",
"a",
"file",
"and",
"add",
"it",
"to",
"the",
"given",
"report",
"."
] | 024c773667e54cf88db938c2b368977005d70ee8 | https://github.com/sds/haml-lint/blob/024c773667e54cf88db938c2b368977005d70ee8/lib/haml_lint/runner.rb#L123-L127 | train |
sds/haml-lint | lib/haml_lint/runner.rb | HamlLint.Runner.report | def report(options)
report = HamlLint::Report.new(reporter: options[:reporter], fail_level: options[:fail_level])
report.start(@files)
process_files(report)
report
end | ruby | def report(options)
report = HamlLint::Report.new(reporter: options[:reporter], fail_level: options[:fail_level])
report.start(@files)
process_files(report)
report
end | [
"def",
"report",
"(",
"options",
")",
"report",
"=",
"HamlLint",
"::",
"Report",
".",
"new",
"(",
"reporter",
":",
"options",
"[",
":reporter",
"]",
",",
"fail_level",
":",
"options",
"[",
":fail_level",
"]",
")",
"report",
".",
"start",
"(",
"@files",
")",
"process_files",
"(",
"report",
")",
"report",
"end"
] | Generates a report based on the given options.
@param options [Hash]
@option options :reporter [HamlLint::Reporter] the reporter to report with
@return [HamlLint::Report] | [
"Generates",
"a",
"report",
"based",
"on",
"the",
"given",
"options",
"."
] | 024c773667e54cf88db938c2b368977005d70ee8 | https://github.com/sds/haml-lint/blob/024c773667e54cf88db938c2b368977005d70ee8/lib/haml_lint/runner.rb#L134-L139 | train |
sds/haml-lint | lib/haml_lint/file_finder.rb | HamlLint.FileFinder.find | def find(patterns, excluded_patterns)
excluded_patterns = excluded_patterns.map { |pattern| normalize_path(pattern) }
extract_files_from(patterns).reject do |file|
excluded_patterns.any? do |exclusion_glob|
HamlLint::Utils.any_glob_matches?(exclusion_glob, file)
end
end
end | ruby | def find(patterns, excluded_patterns)
excluded_patterns = excluded_patterns.map { |pattern| normalize_path(pattern) }
extract_files_from(patterns).reject do |file|
excluded_patterns.any? do |exclusion_glob|
HamlLint::Utils.any_glob_matches?(exclusion_glob, file)
end
end
end | [
"def",
"find",
"(",
"patterns",
",",
"excluded_patterns",
")",
"excluded_patterns",
"=",
"excluded_patterns",
".",
"map",
"{",
"|",
"pattern",
"|",
"normalize_path",
"(",
"pattern",
")",
"}",
"extract_files_from",
"(",
"patterns",
")",
".",
"reject",
"do",
"|",
"file",
"|",
"excluded_patterns",
".",
"any?",
"do",
"|",
"exclusion_glob",
"|",
"HamlLint",
"::",
"Utils",
".",
"any_glob_matches?",
"(",
"exclusion_glob",
",",
"file",
")",
"end",
"end",
"end"
] | Create a file finder using the specified configuration.
@param config [HamlLint::Configuration]
Return list of files to lint given the specified set of paths and glob
patterns.
@param patterns [Array<String>]
@param excluded_patterns [Array<String>]
@raise [HamlLint::Exceptions::InvalidFilePath]
@return [Array<String>] list of actual files | [
"Create",
"a",
"file",
"finder",
"using",
"the",
"specified",
"configuration",
"."
] | 024c773667e54cf88db938c2b368977005d70ee8 | https://github.com/sds/haml-lint/blob/024c773667e54cf88db938c2b368977005d70ee8/lib/haml_lint/file_finder.rb#L26-L34 | train |
sds/haml-lint | lib/haml_lint/file_finder.rb | HamlLint.FileFinder.extract_files_from | def extract_files_from(patterns) # rubocop:disable MethodLength
files = []
patterns.each do |pattern|
if File.file?(pattern)
files << pattern
else
begin
::Find.find(pattern) do |file|
files << file if haml_file?(file)
end
rescue ::Errno::ENOENT
# File didn't exist; it might be a file glob pattern
matches = ::Dir.glob(pattern)
if matches.any?
files += matches
else
# One of the paths specified does not exist; raise a more
# descriptive exception so we know which one
raise HamlLint::Exceptions::InvalidFilePath,
"File path '#{pattern}' does not exist"
end
end
end
end
files.uniq.sort.map { |file| normalize_path(file) }
end | ruby | def extract_files_from(patterns) # rubocop:disable MethodLength
files = []
patterns.each do |pattern|
if File.file?(pattern)
files << pattern
else
begin
::Find.find(pattern) do |file|
files << file if haml_file?(file)
end
rescue ::Errno::ENOENT
# File didn't exist; it might be a file glob pattern
matches = ::Dir.glob(pattern)
if matches.any?
files += matches
else
# One of the paths specified does not exist; raise a more
# descriptive exception so we know which one
raise HamlLint::Exceptions::InvalidFilePath,
"File path '#{pattern}' does not exist"
end
end
end
end
files.uniq.sort.map { |file| normalize_path(file) }
end | [
"def",
"extract_files_from",
"(",
"patterns",
")",
"# rubocop:disable MethodLength",
"files",
"=",
"[",
"]",
"patterns",
".",
"each",
"do",
"|",
"pattern",
"|",
"if",
"File",
".",
"file?",
"(",
"pattern",
")",
"files",
"<<",
"pattern",
"else",
"begin",
"::",
"Find",
".",
"find",
"(",
"pattern",
")",
"do",
"|",
"file",
"|",
"files",
"<<",
"file",
"if",
"haml_file?",
"(",
"file",
")",
"end",
"rescue",
"::",
"Errno",
"::",
"ENOENT",
"# File didn't exist; it might be a file glob pattern",
"matches",
"=",
"::",
"Dir",
".",
"glob",
"(",
"pattern",
")",
"if",
"matches",
".",
"any?",
"files",
"+=",
"matches",
"else",
"# One of the paths specified does not exist; raise a more",
"# descriptive exception so we know which one",
"raise",
"HamlLint",
"::",
"Exceptions",
"::",
"InvalidFilePath",
",",
"\"File path '#{pattern}' does not exist\"",
"end",
"end",
"end",
"end",
"files",
".",
"uniq",
".",
"sort",
".",
"map",
"{",
"|",
"file",
"|",
"normalize_path",
"(",
"file",
")",
"}",
"end"
] | Extract the list of matching files given the list of glob patterns, file
paths, and directories.
@param patterns [Array<String>]
@return [Array<String>] | [
"Extract",
"the",
"list",
"of",
"matching",
"files",
"given",
"the",
"list",
"of",
"glob",
"patterns",
"file",
"paths",
"and",
"directories",
"."
] | 024c773667e54cf88db938c2b368977005d70ee8 | https://github.com/sds/haml-lint/blob/024c773667e54cf88db938c2b368977005d70ee8/lib/haml_lint/file_finder.rb#L43-L70 | train |
sds/haml-lint | lib/haml_lint/file_finder.rb | HamlLint.FileFinder.haml_file? | def haml_file?(file)
return false unless ::FileTest.file?(file)
VALID_EXTENSIONS.include?(::File.extname(file))
end | ruby | def haml_file?(file)
return false unless ::FileTest.file?(file)
VALID_EXTENSIONS.include?(::File.extname(file))
end | [
"def",
"haml_file?",
"(",
"file",
")",
"return",
"false",
"unless",
"::",
"FileTest",
".",
"file?",
"(",
"file",
")",
"VALID_EXTENSIONS",
".",
"include?",
"(",
"::",
"File",
".",
"extname",
"(",
"file",
")",
")",
"end"
] | Whether the given file should be treated as a Haml file.
@param file [String]
@return [Boolean] | [
"Whether",
"the",
"given",
"file",
"should",
"be",
"treated",
"as",
"a",
"Haml",
"file",
"."
] | 024c773667e54cf88db938c2b368977005d70ee8 | https://github.com/sds/haml-lint/blob/024c773667e54cf88db938c2b368977005d70ee8/lib/haml_lint/file_finder.rb#L84-L88 | train |
sds/haml-lint | lib/haml_lint/linter/unnecessary_string_output.rb | HamlLint.Linter::UnnecessaryStringOutput.starts_with_reserved_character? | def starts_with_reserved_character?(stringish)
string = stringish.respond_to?(:children) ? stringish.children.first : stringish
string =~ %r{\A\s*[/#-=%~]}
end | ruby | def starts_with_reserved_character?(stringish)
string = stringish.respond_to?(:children) ? stringish.children.first : stringish
string =~ %r{\A\s*[/#-=%~]}
end | [
"def",
"starts_with_reserved_character?",
"(",
"stringish",
")",
"string",
"=",
"stringish",
".",
"respond_to?",
"(",
":children",
")",
"?",
"stringish",
".",
"children",
".",
"first",
":",
"stringish",
"string",
"=~",
"%r{",
"\\A",
"\\s",
"}",
"end"
] | Returns whether a string starts with a character that would otherwise be
given special treatment, thus making enclosing it in a string necessary. | [
"Returns",
"whether",
"a",
"string",
"starts",
"with",
"a",
"character",
"that",
"would",
"otherwise",
"be",
"given",
"special",
"treatment",
"thus",
"making",
"enclosing",
"it",
"in",
"a",
"string",
"necessary",
"."
] | 024c773667e54cf88db938c2b368977005d70ee8 | https://github.com/sds/haml-lint/blob/024c773667e54cf88db938c2b368977005d70ee8/lib/haml_lint/linter/unnecessary_string_output.rb#L44-L47 | train |
sds/haml-lint | lib/haml_lint/linter.rb | HamlLint.Linter.run | def run(document)
@document = document
@lints = []
visit(document.tree)
@lints
rescue Parser::SyntaxError => e
location = e.diagnostic.location
@lints <<
HamlLint::Lint.new(
HamlLint::Linter::Syntax.new(config),
document.file,
location.line,
e.to_s,
:error
)
end | ruby | def run(document)
@document = document
@lints = []
visit(document.tree)
@lints
rescue Parser::SyntaxError => e
location = e.diagnostic.location
@lints <<
HamlLint::Lint.new(
HamlLint::Linter::Syntax.new(config),
document.file,
location.line,
e.to_s,
:error
)
end | [
"def",
"run",
"(",
"document",
")",
"@document",
"=",
"document",
"@lints",
"=",
"[",
"]",
"visit",
"(",
"document",
".",
"tree",
")",
"@lints",
"rescue",
"Parser",
"::",
"SyntaxError",
"=>",
"e",
"location",
"=",
"e",
".",
"diagnostic",
".",
"location",
"@lints",
"<<",
"HamlLint",
"::",
"Lint",
".",
"new",
"(",
"HamlLint",
"::",
"Linter",
"::",
"Syntax",
".",
"new",
"(",
"config",
")",
",",
"document",
".",
"file",
",",
"location",
".",
"line",
",",
"e",
".",
"to_s",
",",
":error",
")",
"end"
] | Initializes a linter with the specified configuration.
@param config [Hash] configuration for this linter
Runs the linter against the given Haml document.
@param document [HamlLint::Document] | [
"Initializes",
"a",
"linter",
"with",
"the",
"specified",
"configuration",
"."
] | 024c773667e54cf88db938c2b368977005d70ee8 | https://github.com/sds/haml-lint/blob/024c773667e54cf88db938c2b368977005d70ee8/lib/haml_lint/linter.rb#L27-L42 | train |
sds/haml-lint | lib/haml_lint/linter.rb | HamlLint.Linter.inline_content_is_string? | def inline_content_is_string?(node)
tag_with_inline_content = tag_with_inline_text(node)
inline_content = inline_node_content(node)
index = tag_with_inline_content.rindex(inline_content) - 1
%w[' "].include?(tag_with_inline_content[index])
end | ruby | def inline_content_is_string?(node)
tag_with_inline_content = tag_with_inline_text(node)
inline_content = inline_node_content(node)
index = tag_with_inline_content.rindex(inline_content) - 1
%w[' "].include?(tag_with_inline_content[index])
end | [
"def",
"inline_content_is_string?",
"(",
"node",
")",
"tag_with_inline_content",
"=",
"tag_with_inline_text",
"(",
"node",
")",
"inline_content",
"=",
"inline_node_content",
"(",
"node",
")",
"index",
"=",
"tag_with_inline_content",
".",
"rindex",
"(",
"inline_content",
")",
"-",
"1",
"%w[",
"'",
"\"",
"]",
".",
"include?",
"(",
"tag_with_inline_content",
"[",
"index",
"]",
")",
"end"
] | Returns whether the inline content for a node is a string.
For example, the following node has a literal string:
%tag= "A literal #{string}"
whereas this one does not:
%tag A literal #{string}
@param node [HamlLint::Tree::Node]
@return [true,false] | [
"Returns",
"whether",
"the",
"inline",
"content",
"for",
"a",
"node",
"is",
"a",
"string",
"."
] | 024c773667e54cf88db938c2b368977005d70ee8 | https://github.com/sds/haml-lint/blob/024c773667e54cf88db938c2b368977005d70ee8/lib/haml_lint/linter.rb#L118-L125 | train |
Subsets and Splits