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 |
---|---|---|---|---|---|---|---|---|---|---|---|
fulldecent/structured-acceptance-test | implementations/ruby/lib/stat.rb | StatModule.Stat.summary_print | def summary_print(formatted = false)
errors = 0
warnings = 0
findings.each { |finding|
if finding.failure
errors += 1
else
warnings += 1
end
}
if errors == 0 && warnings == 0
result = "#{FORMATTING_CHECKMARK} PASSED with no warning".colorize(:green)
elsif errors == 0
result = "#{FORMATTING_WARNING} PASSED with #{warnings} warning".colorize(:yellow)
elsif warnings == 0
result = "#{FORMATTING_BALL} FAILED with #{errors} error".colorize(:red)
else
result = "#{FORMATTING_BALL} FAILED with #{errors} error and #{warnings} warning".colorize(:red)
end
if formatted
result
else
result[result.index(' ') + 1..result.length]
end
end | ruby | def summary_print(formatted = false)
errors = 0
warnings = 0
findings.each { |finding|
if finding.failure
errors += 1
else
warnings += 1
end
}
if errors == 0 && warnings == 0
result = "#{FORMATTING_CHECKMARK} PASSED with no warning".colorize(:green)
elsif errors == 0
result = "#{FORMATTING_WARNING} PASSED with #{warnings} warning".colorize(:yellow)
elsif warnings == 0
result = "#{FORMATTING_BALL} FAILED with #{errors} error".colorize(:red)
else
result = "#{FORMATTING_BALL} FAILED with #{errors} error and #{warnings} warning".colorize(:red)
end
if formatted
result
else
result[result.index(' ') + 1..result.length]
end
end | [
"def",
"summary_print",
"(",
"formatted",
"=",
"false",
")",
"errors",
"=",
"0",
"warnings",
"=",
"0",
"findings",
".",
"each",
"{",
"|",
"finding",
"|",
"if",
"finding",
".",
"failure",
"errors",
"+=",
"1",
"else",
"warnings",
"+=",
"1",
"end",
"}",
"if",
"errors",
"==",
"0",
"&&",
"warnings",
"==",
"0",
"result",
"=",
"\"#{FORMATTING_CHECKMARK} PASSED with no warning\"",
".",
"colorize",
"(",
":green",
")",
"elsif",
"errors",
"==",
"0",
"result",
"=",
"\"#{FORMATTING_WARNING} PASSED with #{warnings} warning\"",
".",
"colorize",
"(",
":yellow",
")",
"elsif",
"warnings",
"==",
"0",
"result",
"=",
"\"#{FORMATTING_BALL} FAILED with #{errors} error\"",
".",
"colorize",
"(",
":red",
")",
"else",
"result",
"=",
"\"#{FORMATTING_BALL} FAILED with #{errors} error and #{warnings} warning\"",
".",
"colorize",
"(",
":red",
")",
"end",
"if",
"formatted",
"result",
"else",
"result",
"[",
"result",
".",
"index",
"(",
"' '",
")",
"+",
"1",
"..",
"result",
".",
"length",
"]",
"end",
"end"
] | Get statistic information about findings
Params:
+formatted+:: indicate weather print boring or pretty colorful statistic | [
"Get",
"statistic",
"information",
"about",
"findings"
] | 9766f4863a8bcfdf6ac50a7aa36cce0314481118 | https://github.com/fulldecent/structured-acceptance-test/blob/9766f4863a8bcfdf6ac50a7aa36cce0314481118/implementations/ruby/lib/stat.rb#L126-L150 | train |
dennmart/wanikani-gem | lib/wanikani/user.rb | Wanikani.User.gravatar_url | def gravatar_url(options = {})
raise ArgumentError, "The size parameter must be an integer" if options[:size] && !options[:size].is_a?(Integer)
response = api_response("user-information")
hash = response["user_information"]["gravatar"]
return nil if hash.nil?
return build_gravatar_url(hash, options)
end | ruby | def gravatar_url(options = {})
raise ArgumentError, "The size parameter must be an integer" if options[:size] && !options[:size].is_a?(Integer)
response = api_response("user-information")
hash = response["user_information"]["gravatar"]
return nil if hash.nil?
return build_gravatar_url(hash, options)
end | [
"def",
"gravatar_url",
"(",
"options",
"=",
"{",
"}",
")",
"raise",
"ArgumentError",
",",
"\"The size parameter must be an integer\"",
"if",
"options",
"[",
":size",
"]",
"&&",
"!",
"options",
"[",
":size",
"]",
".",
"is_a?",
"(",
"Integer",
")",
"response",
"=",
"api_response",
"(",
"\"user-information\"",
")",
"hash",
"=",
"response",
"[",
"\"user_information\"",
"]",
"[",
"\"gravatar\"",
"]",
"return",
"nil",
"if",
"hash",
".",
"nil?",
"return",
"build_gravatar_url",
"(",
"hash",
",",
"options",
")",
"end"
] | Returns the Gravatar image URL using the Gravatar hash from the user's information.
@param options [Hash] optional settings for the gravatar URL.
@return [String, nil] the Gravatar URL, with the optional size parameter, nil if
the user information contains no Gravatar hash. | [
"Returns",
"the",
"Gravatar",
"image",
"URL",
"using",
"the",
"Gravatar",
"hash",
"from",
"the",
"user",
"s",
"information",
"."
] | 70f9e4289f758c9663c0ee4d1172acb711487df9 | https://github.com/dennmart/wanikani-gem/blob/70f9e4289f758c9663c0ee4d1172acb711487df9/lib/wanikani/user.rb#L27-L34 | train |
addagger/html_slicer | lib/html_slicer/helpers/action_view_extension.rb | HtmlSlicer.ActionViewExtension.slice | def slice(object, options = {}, &block)
slicer = HtmlSlicer::Helpers::Slicer.new self, object.options.reverse_merge(options).reverse_merge(:current_slice => object.current_slice, :slice_number => object.slice_number, :remote => false)
slicer.to_s
end | ruby | def slice(object, options = {}, &block)
slicer = HtmlSlicer::Helpers::Slicer.new self, object.options.reverse_merge(options).reverse_merge(:current_slice => object.current_slice, :slice_number => object.slice_number, :remote => false)
slicer.to_s
end | [
"def",
"slice",
"(",
"object",
",",
"options",
"=",
"{",
"}",
",",
"&",
"block",
")",
"slicer",
"=",
"HtmlSlicer",
"::",
"Helpers",
"::",
"Slicer",
".",
"new",
"self",
",",
"object",
".",
"options",
".",
"reverse_merge",
"(",
"options",
")",
".",
"reverse_merge",
"(",
":current_slice",
"=>",
"object",
".",
"current_slice",
",",
":slice_number",
"=>",
"object",
".",
"slice_number",
",",
":remote",
"=>",
"false",
")",
"slicer",
".",
"to_s",
"end"
] | A helper that renders the pagination links.
<%= slicer @article.paged %>
==== Options
* <tt>:window</tt> - The "inner window" size (4 by default).
* <tt>:outer_window</tt> - The "outer window" size (0 by default).
* <tt>:left</tt> - The "left outer window" size (0 by default).
* <tt>:right</tt> - The "right outer window" size (0 by default).
* <tt>:params</tt> - url_for parameters for the links (:controller, :action, etc.)
* <tt>:param_name</tt> - parameter name for slice number in the links. Accepts +symbol+, +string+, +array+.
* <tt>:remote</tt> - Ajax? (false by default)
* <tt>:ANY_OTHER_VALUES</tt> - Any other hash key & values would be directly passed into each tag as :locals value. | [
"A",
"helper",
"that",
"renders",
"the",
"pagination",
"links",
"."
] | bbe6ab55a0d0335621079c304af534959b518d8b | https://github.com/addagger/html_slicer/blob/bbe6ab55a0d0335621079c304af534959b518d8b/lib/html_slicer/helpers/action_view_extension.rb#L33-L36 | train |
holyshared/yaml-translator | lib/yaml-translator/locale.rb | YamlTranslator.Locale.save | def save(dir = Dir.pwd, options = {})
prefix = options[:prefix] if options.key?(:prefix)
write_file(File.join(dir, "#{prefix}#{lang}.yml"), options)
end | ruby | def save(dir = Dir.pwd, options = {})
prefix = options[:prefix] if options.key?(:prefix)
write_file(File.join(dir, "#{prefix}#{lang}.yml"), options)
end | [
"def",
"save",
"(",
"dir",
"=",
"Dir",
".",
"pwd",
",",
"options",
"=",
"{",
"}",
")",
"prefix",
"=",
"options",
"[",
":prefix",
"]",
"if",
"options",
".",
"key?",
"(",
":prefix",
")",
"write_file",
"(",
"File",
".",
"join",
"(",
"dir",
",",
"\"#{prefix}#{lang}.yml\"",
")",
",",
"options",
")",
"end"
] | Save the file
@param dir [String] Directory path to save the file
@param options [Hash] Options for saving
@return int | [
"Save",
"the",
"file"
] | f6e4497e1695a353534828b005638a6d5c625c07 | https://github.com/holyshared/yaml-translator/blob/f6e4497e1695a353534828b005638a6d5c625c07/lib/yaml-translator/locale.rb#L73-L76 | train |
holyshared/yaml-translator | lib/yaml-translator/locale.rb | YamlTranslator.Locale.compact_of | def compact_of(values = {}, path = KeyPath.new)
result = {}
values.each_with_index do |(i, v)|
path.move_to(i)
if v.is_a?(Hash)
result.merge!(compact_of(v, path))
else
result[path.to_s] = v
end
path.leave
end
result
end | ruby | def compact_of(values = {}, path = KeyPath.new)
result = {}
values.each_with_index do |(i, v)|
path.move_to(i)
if v.is_a?(Hash)
result.merge!(compact_of(v, path))
else
result[path.to_s] = v
end
path.leave
end
result
end | [
"def",
"compact_of",
"(",
"values",
"=",
"{",
"}",
",",
"path",
"=",
"KeyPath",
".",
"new",
")",
"result",
"=",
"{",
"}",
"values",
".",
"each_with_index",
"do",
"|",
"(",
"i",
",",
"v",
")",
"|",
"path",
".",
"move_to",
"(",
"i",
")",
"if",
"v",
".",
"is_a?",
"(",
"Hash",
")",
"result",
".",
"merge!",
"(",
"compact_of",
"(",
"v",
",",
"path",
")",
")",
"else",
"result",
"[",
"path",
".",
"to_s",
"]",
"=",
"v",
"end",
"path",
".",
"leave",
"end",
"result",
"end"
] | Covert to a flatten hash | [
"Covert",
"to",
"a",
"flatten",
"hash"
] | f6e4497e1695a353534828b005638a6d5c625c07 | https://github.com/holyshared/yaml-translator/blob/f6e4497e1695a353534828b005638a6d5c625c07/lib/yaml-translator/locale.rb#L98-L110 | train |
holyshared/yaml-translator | lib/yaml-translator/locale.rb | YamlTranslator.Locale.tree_of | def tree_of(values)
result = {}
current = result
values.each do |k, v|
keys = k.to_s.split('.')
last_key = keys.pop
keys.each do |ks|
current = if current.key?(ks)
current[ks]
else
current[ks] = {}
current[ks]
end
end
current[last_key] = v
current = result
end
result
end | ruby | def tree_of(values)
result = {}
current = result
values.each do |k, v|
keys = k.to_s.split('.')
last_key = keys.pop
keys.each do |ks|
current = if current.key?(ks)
current[ks]
else
current[ks] = {}
current[ks]
end
end
current[last_key] = v
current = result
end
result
end | [
"def",
"tree_of",
"(",
"values",
")",
"result",
"=",
"{",
"}",
"current",
"=",
"result",
"values",
".",
"each",
"do",
"|",
"k",
",",
"v",
"|",
"keys",
"=",
"k",
".",
"to_s",
".",
"split",
"(",
"'.'",
")",
"last_key",
"=",
"keys",
".",
"pop",
"keys",
".",
"each",
"do",
"|",
"ks",
"|",
"current",
"=",
"if",
"current",
".",
"key?",
"(",
"ks",
")",
"current",
"[",
"ks",
"]",
"else",
"current",
"[",
"ks",
"]",
"=",
"{",
"}",
"current",
"[",
"ks",
"]",
"end",
"end",
"current",
"[",
"last_key",
"]",
"=",
"v",
"current",
"=",
"result",
"end",
"result",
"end"
] | Returning the flattened structure to the tree structure
@param [Hash] values flatten Hash
@return [Hash] translated hash | [
"Returning",
"the",
"flattened",
"structure",
"to",
"the",
"tree",
"structure"
] | f6e4497e1695a353534828b005638a6d5c625c07 | https://github.com/holyshared/yaml-translator/blob/f6e4497e1695a353534828b005638a6d5c625c07/lib/yaml-translator/locale.rb#L116-L134 | train |
bterkuile/cmtool | app/helpers/cmtool/application_helper.rb | Cmtool.ApplicationHelper.collapsible_content | def collapsible_content(options = {}, &blk)
options = {title: options} if options.is_a?(String) # Single argument is title
content = capture(&blk) if blk.present?
content ||= options[:content]
options[:collapsed] = true unless options.has_key?(:collapsed)
classes = Array.wrap(options[:class]) | ["collapsible-container", options[:collapsed] ? 'collapsed' : nil]
title_tag = content_tag(:div, "<span></span>#{options[:title]}".html_safe, class: 'collapsible-title')
content_tag(:div, title_tag + content_tag(:div, content, class: 'collapsible-content'), class: classes)
end | ruby | def collapsible_content(options = {}, &blk)
options = {title: options} if options.is_a?(String) # Single argument is title
content = capture(&blk) if blk.present?
content ||= options[:content]
options[:collapsed] = true unless options.has_key?(:collapsed)
classes = Array.wrap(options[:class]) | ["collapsible-container", options[:collapsed] ? 'collapsed' : nil]
title_tag = content_tag(:div, "<span></span>#{options[:title]}".html_safe, class: 'collapsible-title')
content_tag(:div, title_tag + content_tag(:div, content, class: 'collapsible-content'), class: classes)
end | [
"def",
"collapsible_content",
"(",
"options",
"=",
"{",
"}",
",",
"&",
"blk",
")",
"options",
"=",
"{",
"title",
":",
"options",
"}",
"if",
"options",
".",
"is_a?",
"(",
"String",
")",
"content",
"=",
"capture",
"(",
"&",
"blk",
")",
"if",
"blk",
".",
"present?",
"content",
"||=",
"options",
"[",
":content",
"]",
"options",
"[",
":collapsed",
"]",
"=",
"true",
"unless",
"options",
".",
"has_key?",
"(",
":collapsed",
")",
"classes",
"=",
"Array",
".",
"wrap",
"(",
"options",
"[",
":class",
"]",
")",
"|",
"[",
"\"collapsible-container\"",
",",
"options",
"[",
":collapsed",
"]",
"?",
"'collapsed'",
":",
"nil",
"]",
"title_tag",
"=",
"content_tag",
"(",
":div",
",",
"\"<span></span>#{options[:title]}\"",
".",
"html_safe",
",",
"class",
":",
"'collapsible-title'",
")",
"content_tag",
"(",
":div",
",",
"title_tag",
"+",
"content_tag",
"(",
":div",
",",
"content",
",",
"class",
":",
"'collapsible-content'",
")",
",",
"class",
":",
"classes",
")",
"end"
] | This is a wrapper to create collapsible content. | [
"This",
"is",
"a",
"wrapper",
"to",
"create",
"collapsible",
"content",
"."
] | 3caf808e223233f19b29acde35429be75acd44e2 | https://github.com/bterkuile/cmtool/blob/3caf808e223233f19b29acde35429be75acd44e2/app/helpers/cmtool/application_helper.rb#L107-L115 | train |
praxis/praxis-blueprints | lib/praxis-blueprints/view.rb | Praxis.View.attribute | def attribute(name, **opts, &block)
raise AttributorException, "Attribute names must be symbols, got: #{name.inspect}" unless name.is_a? ::Symbol
attribute = schema.attributes.fetch(name) do
raise "Displaying :#{name} is not allowed in view :#{self.name} of #{schema}. This attribute does not exist in the mediatype"
end
if block_given?
type = attribute.type
@contents[name] = if type < Attributor::Collection
CollectionView.new(name, type.member_attribute.type, &block)
else
View.new(name, attribute, &block)
end
else
type = attribute.type
if type < Attributor::Collection
is_collection = true
type = type.member_attribute.type
end
if type < Praxis::Blueprint
view_name = opts[:view] || :default
view = type.views.fetch(view_name) do
raise "view with name '#{view_name.inspect}' is not defined in #{type}"
end
@contents[name] = if is_collection
Praxis::CollectionView.new(view_name, type, view)
else
view
end
else
@contents[name] = attribute # , opts]
end
end
end | ruby | def attribute(name, **opts, &block)
raise AttributorException, "Attribute names must be symbols, got: #{name.inspect}" unless name.is_a? ::Symbol
attribute = schema.attributes.fetch(name) do
raise "Displaying :#{name} is not allowed in view :#{self.name} of #{schema}. This attribute does not exist in the mediatype"
end
if block_given?
type = attribute.type
@contents[name] = if type < Attributor::Collection
CollectionView.new(name, type.member_attribute.type, &block)
else
View.new(name, attribute, &block)
end
else
type = attribute.type
if type < Attributor::Collection
is_collection = true
type = type.member_attribute.type
end
if type < Praxis::Blueprint
view_name = opts[:view] || :default
view = type.views.fetch(view_name) do
raise "view with name '#{view_name.inspect}' is not defined in #{type}"
end
@contents[name] = if is_collection
Praxis::CollectionView.new(view_name, type, view)
else
view
end
else
@contents[name] = attribute # , opts]
end
end
end | [
"def",
"attribute",
"(",
"name",
",",
"**",
"opts",
",",
"&",
"block",
")",
"raise",
"AttributorException",
",",
"\"Attribute names must be symbols, got: #{name.inspect}\"",
"unless",
"name",
".",
"is_a?",
"::",
"Symbol",
"attribute",
"=",
"schema",
".",
"attributes",
".",
"fetch",
"(",
"name",
")",
"do",
"raise",
"\"Displaying :#{name} is not allowed in view :#{self.name} of #{schema}. This attribute does not exist in the mediatype\"",
"end",
"if",
"block_given?",
"type",
"=",
"attribute",
".",
"type",
"@contents",
"[",
"name",
"]",
"=",
"if",
"type",
"<",
"Attributor",
"::",
"Collection",
"CollectionView",
".",
"new",
"(",
"name",
",",
"type",
".",
"member_attribute",
".",
"type",
",",
"&",
"block",
")",
"else",
"View",
".",
"new",
"(",
"name",
",",
"attribute",
",",
"&",
"block",
")",
"end",
"else",
"type",
"=",
"attribute",
".",
"type",
"if",
"type",
"<",
"Attributor",
"::",
"Collection",
"is_collection",
"=",
"true",
"type",
"=",
"type",
".",
"member_attribute",
".",
"type",
"end",
"if",
"type",
"<",
"Praxis",
"::",
"Blueprint",
"view_name",
"=",
"opts",
"[",
":view",
"]",
"||",
":default",
"view",
"=",
"type",
".",
"views",
".",
"fetch",
"(",
"view_name",
")",
"do",
"raise",
"\"view with name '#{view_name.inspect}' is not defined in #{type}\"",
"end",
"@contents",
"[",
"name",
"]",
"=",
"if",
"is_collection",
"Praxis",
"::",
"CollectionView",
".",
"new",
"(",
"view_name",
",",
"type",
",",
"view",
")",
"else",
"view",
"end",
"else",
"@contents",
"[",
"name",
"]",
"=",
"attribute",
"end",
"end",
"end"
] | Why did we need this again? | [
"Why",
"did",
"we",
"need",
"this",
"again?"
] | 57b9f9d81d313a7c7bf3e9eebb4b8153c3b48f1c | https://github.com/praxis/praxis-blueprints/blob/57b9f9d81d313a7c7bf3e9eebb4b8153c3b48f1c/lib/praxis-blueprints/view.rb#L40-L75 | train |
robertwahler/repo_manager | lib/repo_manager/assets/asset_configuration.rb | RepoManager.AssetConfiguration.save | def save(attrs=nil)
raise "a Hash of attributes to save must be specified" unless attrs && attrs.is_a?(Hash)
raise "folder must be set prior to saving attributes" unless folder
# merge attributes to asset that contains parent attributes
@asset.attributes.merge!(attrs)
# load contents of the user folder and merge in attributes passed to save
# so that we don't save parent attributes
contents = {}
if File.exists?(folder)
contents = load_contents(folder)
raise "expected contents to be a hash" unless contents.is_a?(Hash)
end
contents = contents.merge!(attrs)
write_contents(folder, contents)
end | ruby | def save(attrs=nil)
raise "a Hash of attributes to save must be specified" unless attrs && attrs.is_a?(Hash)
raise "folder must be set prior to saving attributes" unless folder
# merge attributes to asset that contains parent attributes
@asset.attributes.merge!(attrs)
# load contents of the user folder and merge in attributes passed to save
# so that we don't save parent attributes
contents = {}
if File.exists?(folder)
contents = load_contents(folder)
raise "expected contents to be a hash" unless contents.is_a?(Hash)
end
contents = contents.merge!(attrs)
write_contents(folder, contents)
end | [
"def",
"save",
"(",
"attrs",
"=",
"nil",
")",
"raise",
"\"a Hash of attributes to save must be specified\"",
"unless",
"attrs",
"&&",
"attrs",
".",
"is_a?",
"(",
"Hash",
")",
"raise",
"\"folder must be set prior to saving attributes\"",
"unless",
"folder",
"@asset",
".",
"attributes",
".",
"merge!",
"(",
"attrs",
")",
"contents",
"=",
"{",
"}",
"if",
"File",
".",
"exists?",
"(",
"folder",
")",
"contents",
"=",
"load_contents",
"(",
"folder",
")",
"raise",
"\"expected contents to be a hash\"",
"unless",
"contents",
".",
"is_a?",
"(",
"Hash",
")",
"end",
"contents",
"=",
"contents",
".",
"merge!",
"(",
"attrs",
")",
"write_contents",
"(",
"folder",
",",
"contents",
")",
"end"
] | Save specific attributes to an asset configuration file. Only the param
'attrs' and the current contents of the config file are saved. Parent
asset configurations are not saved. | [
"Save",
"specific",
"attributes",
"to",
"an",
"asset",
"configuration",
"file",
".",
"Only",
"the",
"param",
"attrs",
"and",
"the",
"current",
"contents",
"of",
"the",
"config",
"file",
"are",
"saved",
".",
"Parent",
"asset",
"configurations",
"are",
"not",
"saved",
"."
] | d945f1cb6ac48b5689b633fcc029fd77c6a02d09 | https://github.com/robertwahler/repo_manager/blob/d945f1cb6ac48b5689b633fcc029fd77c6a02d09/lib/repo_manager/assets/asset_configuration.rb#L45-L62 | train |
robertwahler/repo_manager | lib/repo_manager/assets/asset_configuration.rb | RepoManager.AssetConfiguration.load | def load(ds=nil)
@folder ||= ds
contents = load_contents(folder)
# if a global parent folder is defined, load it first
parent = contents.delete(:parent) || parent
if parent
parent_folder = File.join(parent)
unless Pathname.new(parent_folder).absolute?
base_folder = File.dirname(folder)
parent_folder = File.join(base_folder, parent_folder)
end
logger.debug "AssetConfiguration loading parent: #{parent_folder}"
parent_configuration = RepoManager::AssetConfiguration.new(asset)
begin
parent_configuration.load(parent_folder)
rescue Exception => e
logger.warn "AssetConfiguration parent configuration load failed on: '#{parent_folder}' with: '#{e.message}'"
end
end
# Load all attributes as hash 'attributes' so that merging
# and adding new attributes doesn't require code changes. Note
# that the 'parent' setting is not merged to attributes
@asset.attributes.merge!(contents)
@asset.create_accessors(@asset.attributes[:user_attributes])
@asset
end | ruby | def load(ds=nil)
@folder ||= ds
contents = load_contents(folder)
# if a global parent folder is defined, load it first
parent = contents.delete(:parent) || parent
if parent
parent_folder = File.join(parent)
unless Pathname.new(parent_folder).absolute?
base_folder = File.dirname(folder)
parent_folder = File.join(base_folder, parent_folder)
end
logger.debug "AssetConfiguration loading parent: #{parent_folder}"
parent_configuration = RepoManager::AssetConfiguration.new(asset)
begin
parent_configuration.load(parent_folder)
rescue Exception => e
logger.warn "AssetConfiguration parent configuration load failed on: '#{parent_folder}' with: '#{e.message}'"
end
end
# Load all attributes as hash 'attributes' so that merging
# and adding new attributes doesn't require code changes. Note
# that the 'parent' setting is not merged to attributes
@asset.attributes.merge!(contents)
@asset.create_accessors(@asset.attributes[:user_attributes])
@asset
end | [
"def",
"load",
"(",
"ds",
"=",
"nil",
")",
"@folder",
"||=",
"ds",
"contents",
"=",
"load_contents",
"(",
"folder",
")",
"parent",
"=",
"contents",
".",
"delete",
"(",
":parent",
")",
"||",
"parent",
"if",
"parent",
"parent_folder",
"=",
"File",
".",
"join",
"(",
"parent",
")",
"unless",
"Pathname",
".",
"new",
"(",
"parent_folder",
")",
".",
"absolute?",
"base_folder",
"=",
"File",
".",
"dirname",
"(",
"folder",
")",
"parent_folder",
"=",
"File",
".",
"join",
"(",
"base_folder",
",",
"parent_folder",
")",
"end",
"logger",
".",
"debug",
"\"AssetConfiguration loading parent: #{parent_folder}\"",
"parent_configuration",
"=",
"RepoManager",
"::",
"AssetConfiguration",
".",
"new",
"(",
"asset",
")",
"begin",
"parent_configuration",
".",
"load",
"(",
"parent_folder",
")",
"rescue",
"Exception",
"=>",
"e",
"logger",
".",
"warn",
"\"AssetConfiguration parent configuration load failed on: '#{parent_folder}' with: '#{e.message}'\"",
"end",
"end",
"@asset",
".",
"attributes",
".",
"merge!",
"(",
"contents",
")",
"@asset",
".",
"create_accessors",
"(",
"@asset",
".",
"attributes",
"[",
":user_attributes",
"]",
")",
"@asset",
"end"
] | load an asset from a configuration folder | [
"load",
"an",
"asset",
"from",
"a",
"configuration",
"folder"
] | d945f1cb6ac48b5689b633fcc029fd77c6a02d09 | https://github.com/robertwahler/repo_manager/blob/d945f1cb6ac48b5689b633fcc029fd77c6a02d09/lib/repo_manager/assets/asset_configuration.rb#L65-L95 | train |
robertwahler/repo_manager | lib/repo_manager/assets/asset_configuration.rb | RepoManager.AssetConfiguration.load_contents | def load_contents(asset_folder)
file = File.join(asset_folder, 'asset.conf')
if File.exists?(file)
contents = YAML.load(ERB.new(File.open(file, "rb").read).result(@asset.get_binding))
if contents && contents.is_a?(Hash)
contents.recursively_symbolize_keys!
else
{}
end
else
{}
end
end | ruby | def load_contents(asset_folder)
file = File.join(asset_folder, 'asset.conf')
if File.exists?(file)
contents = YAML.load(ERB.new(File.open(file, "rb").read).result(@asset.get_binding))
if contents && contents.is_a?(Hash)
contents.recursively_symbolize_keys!
else
{}
end
else
{}
end
end | [
"def",
"load_contents",
"(",
"asset_folder",
")",
"file",
"=",
"File",
".",
"join",
"(",
"asset_folder",
",",
"'asset.conf'",
")",
"if",
"File",
".",
"exists?",
"(",
"file",
")",
"contents",
"=",
"YAML",
".",
"load",
"(",
"ERB",
".",
"new",
"(",
"File",
".",
"open",
"(",
"file",
",",
"\"rb\"",
")",
".",
"read",
")",
".",
"result",
"(",
"@asset",
".",
"get_binding",
")",
")",
"if",
"contents",
"&&",
"contents",
".",
"is_a?",
"(",
"Hash",
")",
"contents",
".",
"recursively_symbolize_keys!",
"else",
"{",
"}",
"end",
"else",
"{",
"}",
"end",
"end"
] | load the raw contents from an asset_folder, ignore parents
@return [Hash] of the raw text contents | [
"load",
"the",
"raw",
"contents",
"from",
"an",
"asset_folder",
"ignore",
"parents"
] | d945f1cb6ac48b5689b633fcc029fd77c6a02d09 | https://github.com/robertwahler/repo_manager/blob/d945f1cb6ac48b5689b633fcc029fd77c6a02d09/lib/repo_manager/assets/asset_configuration.rb#L109-L121 | train |
robertwahler/repo_manager | lib/repo_manager/assets/asset_configuration.rb | RepoManager.AssetConfiguration.write_contents | def write_contents(asset_folder, contents)
contents.recursively_stringify_keys!
FileUtils.mkdir(asset_folder) unless File.exists?(asset_folder)
filename = File.join(asset_folder, 'asset.conf')
#TODO, use "wb" and write CRLF on Windows
File.open(filename, "w") do |f|
f.write(contents.to_conf)
end
end | ruby | def write_contents(asset_folder, contents)
contents.recursively_stringify_keys!
FileUtils.mkdir(asset_folder) unless File.exists?(asset_folder)
filename = File.join(asset_folder, 'asset.conf')
#TODO, use "wb" and write CRLF on Windows
File.open(filename, "w") do |f|
f.write(contents.to_conf)
end
end | [
"def",
"write_contents",
"(",
"asset_folder",
",",
"contents",
")",
"contents",
".",
"recursively_stringify_keys!",
"FileUtils",
".",
"mkdir",
"(",
"asset_folder",
")",
"unless",
"File",
".",
"exists?",
"(",
"asset_folder",
")",
"filename",
"=",
"File",
".",
"join",
"(",
"asset_folder",
",",
"'asset.conf'",
")",
"File",
".",
"open",
"(",
"filename",
",",
"\"w\"",
")",
"do",
"|",
"f",
"|",
"f",
".",
"write",
"(",
"contents",
".",
"to_conf",
")",
"end",
"end"
] | write raw contents to an asset_folder | [
"write",
"raw",
"contents",
"to",
"an",
"asset_folder"
] | d945f1cb6ac48b5689b633fcc029fd77c6a02d09 | https://github.com/robertwahler/repo_manager/blob/d945f1cb6ac48b5689b633fcc029fd77c6a02d09/lib/repo_manager/assets/asset_configuration.rb#L124-L134 | train |
SebastianSzturo/inaho | lib/inaho/entry.rb | Inaho.Entry.to_xml | def to_xml
return nil if title.nil? || body.nil?
xml = ""
xml << "<d:entry id=\"#{self.id}\" d:title=\"#{self.title}\">\n"
@index.each do |i|
xml << "\t<d:index d:value=\"#{i}\" d:title=\"#{title}\" "
xml << "d:yomi=\"#{yomi}\"" if !self.yomi.nil?
xml << "/>\n"
end
xml << "\t<div>\n"
xml << "\t\t#{@body}\n"
xml << "\t</div>\n"
xml << "</d:entry>\n"
return xml
end | ruby | def to_xml
return nil if title.nil? || body.nil?
xml = ""
xml << "<d:entry id=\"#{self.id}\" d:title=\"#{self.title}\">\n"
@index.each do |i|
xml << "\t<d:index d:value=\"#{i}\" d:title=\"#{title}\" "
xml << "d:yomi=\"#{yomi}\"" if !self.yomi.nil?
xml << "/>\n"
end
xml << "\t<div>\n"
xml << "\t\t#{@body}\n"
xml << "\t</div>\n"
xml << "</d:entry>\n"
return xml
end | [
"def",
"to_xml",
"return",
"nil",
"if",
"title",
".",
"nil?",
"||",
"body",
".",
"nil?",
"xml",
"=",
"\"\"",
"xml",
"<<",
"\"<d:entry id=\\\"#{self.id}\\\" d:title=\\\"#{self.title}\\\">\\n\"",
"@index",
".",
"each",
"do",
"|",
"i",
"|",
"xml",
"<<",
"\"\\t<d:index d:value=\\\"#{i}\\\" d:title=\\\"#{title}\\\" \"",
"xml",
"<<",
"\"d:yomi=\\\"#{yomi}\\\"\"",
"if",
"!",
"self",
".",
"yomi",
".",
"nil?",
"xml",
"<<",
"\"/>\\n\"",
"end",
"xml",
"<<",
"\"\\t<div>\\n\"",
"xml",
"<<",
"\"\\t\\t#{@body}\\n\"",
"xml",
"<<",
"\"\\t</div>\\n\"",
"xml",
"<<",
"\"</d:entry>\\n\"",
"return",
"xml",
"end"
] | Generates xml for the Entry object.
Returns String. | [
"Generates",
"xml",
"for",
"the",
"Entry",
"object",
"."
] | e3664bc59aa90197258d715a9032c18f82b84ebd | https://github.com/SebastianSzturo/inaho/blob/e3664bc59aa90197258d715a9032c18f82b84ebd/lib/inaho/entry.rb#L32-L48 | train |
hendricius/instagram_public_api | lib/instagram_public_api/client.rb | InstagramPublicApi.Client.location_media | def location_media(location_id, request_parameters: {limit: 1000}, limit: 10)
location = extract_location_media(location_id, request_parameters: request_parameters)
# check if we should get more data
paging_info = location.paging_info
# poll more data
while location.total_media_count < limit && paging_info[:has_next_page] do
request_opts = {}.merge(request_parameters)
if paging_info && paging_info[:end_cursor]
request_opts[:max_id] = paging_info[:end_cursor]
end
next_page_location = extract_location_media(location_id, request_parameters: request_opts)
location.add_media(next_page_location.media)
paging_info = next_page_location.paging_info
location
end
location
end | ruby | def location_media(location_id, request_parameters: {limit: 1000}, limit: 10)
location = extract_location_media(location_id, request_parameters: request_parameters)
# check if we should get more data
paging_info = location.paging_info
# poll more data
while location.total_media_count < limit && paging_info[:has_next_page] do
request_opts = {}.merge(request_parameters)
if paging_info && paging_info[:end_cursor]
request_opts[:max_id] = paging_info[:end_cursor]
end
next_page_location = extract_location_media(location_id, request_parameters: request_opts)
location.add_media(next_page_location.media)
paging_info = next_page_location.paging_info
location
end
location
end | [
"def",
"location_media",
"(",
"location_id",
",",
"request_parameters",
":",
"{",
"limit",
":",
"1000",
"}",
",",
"limit",
":",
"10",
")",
"location",
"=",
"extract_location_media",
"(",
"location_id",
",",
"request_parameters",
":",
"request_parameters",
")",
"paging_info",
"=",
"location",
".",
"paging_info",
"while",
"location",
".",
"total_media_count",
"<",
"limit",
"&&",
"paging_info",
"[",
":has_next_page",
"]",
"do",
"request_opts",
"=",
"{",
"}",
".",
"merge",
"(",
"request_parameters",
")",
"if",
"paging_info",
"&&",
"paging_info",
"[",
":end_cursor",
"]",
"request_opts",
"[",
":max_id",
"]",
"=",
"paging_info",
"[",
":end_cursor",
"]",
"end",
"next_page_location",
"=",
"extract_location_media",
"(",
"location_id",
",",
"request_parameters",
":",
"request_opts",
")",
"location",
".",
"add_media",
"(",
"next_page_location",
".",
"media",
")",
"paging_info",
"=",
"next_page_location",
".",
"paging_info",
"location",
"end",
"location",
"end"
] | returns a location with media attached for the given location id
limit: the amount of media that should be fetched.
request_parameters: optional parameters that will be passed to the request | [
"returns",
"a",
"location",
"with",
"media",
"attached",
"for",
"the",
"given",
"location",
"id"
] | ec7c729109135297f3e8f5dc2c8d43cc97e1d3a6 | https://github.com/hendricius/instagram_public_api/blob/ec7c729109135297f3e8f5dc2c8d43cc97e1d3a6/lib/instagram_public_api/client.rb#L15-L31 | train |
hendricius/instagram_public_api | lib/instagram_public_api/client.rb | InstagramPublicApi.Client.extract_location_media | def extract_location_media(location_id, request_parameters: {})
uri = "explore/locations/#{location_id}/"
data = request(uri: uri, parameters: request_parameters)
body = data.body[:location]
location = Entities::Location.new
attrs = %i[name lat lng id]
attrs.each do |attribute|
location.send("#{attribute}=", body[attribute])
end
media = {}
body[:media].fetch(:nodes, []).each do |medium|
media[medium[:id]] = Entities::MediumNode.new(medium)
end
location.media = media.values
location.top_posts = body[:top_posts].fetch(:nodes, []).map {|d| Entities::MediumNode.new(d)}
location.paging_info = body[:media].fetch(:page_info, {})
location
end | ruby | def extract_location_media(location_id, request_parameters: {})
uri = "explore/locations/#{location_id}/"
data = request(uri: uri, parameters: request_parameters)
body = data.body[:location]
location = Entities::Location.new
attrs = %i[name lat lng id]
attrs.each do |attribute|
location.send("#{attribute}=", body[attribute])
end
media = {}
body[:media].fetch(:nodes, []).each do |medium|
media[medium[:id]] = Entities::MediumNode.new(medium)
end
location.media = media.values
location.top_posts = body[:top_posts].fetch(:nodes, []).map {|d| Entities::MediumNode.new(d)}
location.paging_info = body[:media].fetch(:page_info, {})
location
end | [
"def",
"extract_location_media",
"(",
"location_id",
",",
"request_parameters",
":",
"{",
"}",
")",
"uri",
"=",
"\"explore/locations/#{location_id}/\"",
"data",
"=",
"request",
"(",
"uri",
":",
"uri",
",",
"parameters",
":",
"request_parameters",
")",
"body",
"=",
"data",
".",
"body",
"[",
":location",
"]",
"location",
"=",
"Entities",
"::",
"Location",
".",
"new",
"attrs",
"=",
"%i[",
"name",
"lat",
"lng",
"id",
"]",
"attrs",
".",
"each",
"do",
"|",
"attribute",
"|",
"location",
".",
"send",
"(",
"\"#{attribute}=\"",
",",
"body",
"[",
"attribute",
"]",
")",
"end",
"media",
"=",
"{",
"}",
"body",
"[",
":media",
"]",
".",
"fetch",
"(",
":nodes",
",",
"[",
"]",
")",
".",
"each",
"do",
"|",
"medium",
"|",
"media",
"[",
"medium",
"[",
":id",
"]",
"]",
"=",
"Entities",
"::",
"MediumNode",
".",
"new",
"(",
"medium",
")",
"end",
"location",
".",
"media",
"=",
"media",
".",
"values",
"location",
".",
"top_posts",
"=",
"body",
"[",
":top_posts",
"]",
".",
"fetch",
"(",
":nodes",
",",
"[",
"]",
")",
".",
"map",
"{",
"|",
"d",
"|",
"Entities",
"::",
"MediumNode",
".",
"new",
"(",
"d",
")",
"}",
"location",
".",
"paging_info",
"=",
"body",
"[",
":media",
"]",
".",
"fetch",
"(",
":page_info",
",",
"{",
"}",
")",
"location",
"end"
] | performs the actual request to the API.
returns a Location object. | [
"performs",
"the",
"actual",
"request",
"to",
"the",
"API",
"."
] | ec7c729109135297f3e8f5dc2c8d43cc97e1d3a6 | https://github.com/hendricius/instagram_public_api/blob/ec7c729109135297f3e8f5dc2c8d43cc97e1d3a6/lib/instagram_public_api/client.rb#L46-L63 | train |
hendricius/instagram_public_api | lib/instagram_public_api/client.rb | InstagramPublicApi.Client.request | def request(uri:, request_options: {}, parameters: {})
opts = {
uri: uri,
request_options: request_options,
parameters: @default_parameters.merge(parameters)
}
parse_response(http_service.perform_request(opts))
end | ruby | def request(uri:, request_options: {}, parameters: {})
opts = {
uri: uri,
request_options: request_options,
parameters: @default_parameters.merge(parameters)
}
parse_response(http_service.perform_request(opts))
end | [
"def",
"request",
"(",
"uri",
":",
",",
"request_options",
":",
"{",
"}",
",",
"parameters",
":",
"{",
"}",
")",
"opts",
"=",
"{",
"uri",
":",
"uri",
",",
"request_options",
":",
"request_options",
",",
"parameters",
":",
"@default_parameters",
".",
"merge",
"(",
"parameters",
")",
"}",
"parse_response",
"(",
"http_service",
".",
"perform_request",
"(",
"opts",
")",
")",
"end"
] | perform the actual request. receives a URI as argument. Optional parameters
and request parameter options can be passed.
returns the raw http response | [
"perform",
"the",
"actual",
"request",
".",
"receives",
"a",
"URI",
"as",
"argument",
".",
"Optional",
"parameters",
"and",
"request",
"parameter",
"options",
"can",
"be",
"passed",
"."
] | ec7c729109135297f3e8f5dc2c8d43cc97e1d3a6 | https://github.com/hendricius/instagram_public_api/blob/ec7c729109135297f3e8f5dc2c8d43cc97e1d3a6/lib/instagram_public_api/client.rb#L69-L76 | train |
hendricius/instagram_public_api | lib/instagram_public_api/client.rb | InstagramPublicApi.Client.parse_response | def parse_response(response)
OpenStruct.new(
raw_response: response,
body: JSON.parse(response.body, symbolize_names: true)
)
end | ruby | def parse_response(response)
OpenStruct.new(
raw_response: response,
body: JSON.parse(response.body, symbolize_names: true)
)
end | [
"def",
"parse_response",
"(",
"response",
")",
"OpenStruct",
".",
"new",
"(",
"raw_response",
":",
"response",
",",
"body",
":",
"JSON",
".",
"parse",
"(",
"response",
".",
"body",
",",
"symbolize_names",
":",
"true",
")",
")",
"end"
] | parses the raw response by the remote. returns an object with a raw_response
as method and the parsed body associated. | [
"parses",
"the",
"raw",
"response",
"by",
"the",
"remote",
".",
"returns",
"an",
"object",
"with",
"a",
"raw_response",
"as",
"method",
"and",
"the",
"parsed",
"body",
"associated",
"."
] | ec7c729109135297f3e8f5dc2c8d43cc97e1d3a6 | https://github.com/hendricius/instagram_public_api/blob/ec7c729109135297f3e8f5dc2c8d43cc97e1d3a6/lib/instagram_public_api/client.rb#L87-L92 | train |
mLewisLogic/saddle | lib/saddle/options.rb | Saddle.Options.default_options | def default_options
{
:host => host,
:port => port,
:path_prefix => path_prefix,
:use_ssl => use_ssl,
:request_style => request_style,
:num_retries => num_retries,
:timeout => timeout,
:extra_env => extra_env,
:http_adapter => http_adapter,
:stubs => stubs,
:return_full_response => return_full_response,
:additional_middlewares => self.additional_middlewares
}
end | ruby | def default_options
{
:host => host,
:port => port,
:path_prefix => path_prefix,
:use_ssl => use_ssl,
:request_style => request_style,
:num_retries => num_retries,
:timeout => timeout,
:extra_env => extra_env,
:http_adapter => http_adapter,
:stubs => stubs,
:return_full_response => return_full_response,
:additional_middlewares => self.additional_middlewares
}
end | [
"def",
"default_options",
"{",
":host",
"=>",
"host",
",",
":port",
"=>",
"port",
",",
":path_prefix",
"=>",
"path_prefix",
",",
":use_ssl",
"=>",
"use_ssl",
",",
":request_style",
"=>",
"request_style",
",",
":num_retries",
"=>",
"num_retries",
",",
":timeout",
"=>",
"timeout",
",",
":extra_env",
"=>",
"extra_env",
",",
":http_adapter",
"=>",
"http_adapter",
",",
":stubs",
"=>",
"stubs",
",",
":return_full_response",
"=>",
"return_full_response",
",",
":additional_middlewares",
"=>",
"self",
".",
"additional_middlewares",
"}",
"end"
] | Construct our default options, based upon the class methods | [
"Construct",
"our",
"default",
"options",
"based",
"upon",
"the",
"class",
"methods"
] | 9f470a948039dbedb75655d883e714a29b273961 | https://github.com/mLewisLogic/saddle/blob/9f470a948039dbedb75655d883e714a29b273961/lib/saddle/options.rb#L8-L23 | train |
ccocchi/heimdall | lib/heimdall_apm/probe.rb | HeimdallApm.Probe.instrument | def instrument(type, name, opts = {})
txn = ::HeimdallApm::TransactionManager.current
segment = ::HeimdallApm::Segment.new(type, name)
txn.start_segment(segment)
# TODO: maybe yield the segment here to have the block pass additional
# informations
yield
ensure
txn.stop_segment
end | ruby | def instrument(type, name, opts = {})
txn = ::HeimdallApm::TransactionManager.current
segment = ::HeimdallApm::Segment.new(type, name)
txn.start_segment(segment)
# TODO: maybe yield the segment here to have the block pass additional
# informations
yield
ensure
txn.stop_segment
end | [
"def",
"instrument",
"(",
"type",
",",
"name",
",",
"opts",
"=",
"{",
"}",
")",
"txn",
"=",
"::",
"HeimdallApm",
"::",
"TransactionManager",
".",
"current",
"segment",
"=",
"::",
"HeimdallApm",
"::",
"Segment",
".",
"new",
"(",
"type",
",",
"name",
")",
"txn",
".",
"start_segment",
"(",
"segment",
")",
"yield",
"ensure",
"txn",
".",
"stop_segment",
"end"
] | Insruments block passed to the method into the current transaction.
@param type Segment type (i.e 'ActiveRecord' or similar)
@param name Specific name for the segment | [
"Insruments",
"block",
"passed",
"to",
"the",
"method",
"into",
"the",
"current",
"transaction",
"."
] | 138e415e9a6ba9d3aceed3dd963f297464de923b | https://github.com/ccocchi/heimdall/blob/138e415e9a6ba9d3aceed3dd963f297464de923b/lib/heimdall_apm/probe.rb#L13-L23 | train |
drnic/rubigen | lib/rubigen/lookup.rb | RubiGen.Source.names | def names(filter = nil)
inject([]) do |mem, spec|
case filter
when :visible
mem << spec.name if spec.visible?
end
mem
end.sort
end | ruby | def names(filter = nil)
inject([]) do |mem, spec|
case filter
when :visible
mem << spec.name if spec.visible?
end
mem
end.sort
end | [
"def",
"names",
"(",
"filter",
"=",
"nil",
")",
"inject",
"(",
"[",
"]",
")",
"do",
"|",
"mem",
",",
"spec",
"|",
"case",
"filter",
"when",
":visible",
"mem",
"<<",
"spec",
".",
"name",
"if",
"spec",
".",
"visible?",
"end",
"mem",
"end",
".",
"sort",
"end"
] | Return a convenient sorted list of all generator names. | [
"Return",
"a",
"convenient",
"sorted",
"list",
"of",
"all",
"generator",
"names",
"."
] | 5288e0014011d6f7519c4231f65c8e5d78f48afb | https://github.com/drnic/rubigen/blob/5288e0014011d6f7519c4231f65c8e5d78f48afb/lib/rubigen/lookup.rb#L200-L208 | train |
drnic/rubigen | lib/rubigen/lookup.rb | RubiGen.PathSource.each | def each
Dir["#{path}/[a-z]*"].each do |dir|
if File.directory?(dir)
yield Spec.new(File.basename(dir), dir, label)
end
end
end | ruby | def each
Dir["#{path}/[a-z]*"].each do |dir|
if File.directory?(dir)
yield Spec.new(File.basename(dir), dir, label)
end
end
end | [
"def",
"each",
"Dir",
"[",
"\"#{path}/[a-z]*\"",
"]",
".",
"each",
"do",
"|",
"dir",
"|",
"if",
"File",
".",
"directory?",
"(",
"dir",
")",
"yield",
"Spec",
".",
"new",
"(",
"File",
".",
"basename",
"(",
"dir",
")",
",",
"dir",
",",
"label",
")",
"end",
"end",
"end"
] | Yield each eligible subdirectory. | [
"Yield",
"each",
"eligible",
"subdirectory",
"."
] | 5288e0014011d6f7519c4231f65c8e5d78f48afb | https://github.com/drnic/rubigen/blob/5288e0014011d6f7519c4231f65c8e5d78f48afb/lib/rubigen/lookup.rb#L222-L228 | train |
drnic/rubigen | lib/rubigen/lookup.rb | RubiGen.GemPathSource.each | def each
generator_full_paths.each do |generator|
yield Spec.new(File.basename(generator).sub(/_generator.rb$/, ''), File.dirname(generator), label)
end
end | ruby | def each
generator_full_paths.each do |generator|
yield Spec.new(File.basename(generator).sub(/_generator.rb$/, ''), File.dirname(generator), label)
end
end | [
"def",
"each",
"generator_full_paths",
".",
"each",
"do",
"|",
"generator",
"|",
"yield",
"Spec",
".",
"new",
"(",
"File",
".",
"basename",
"(",
"generator",
")",
".",
"sub",
"(",
"/",
"/",
",",
"''",
")",
",",
"File",
".",
"dirname",
"(",
"generator",
")",
",",
"label",
")",
"end",
"end"
] | Yield each generator within rails_generator subdirectories. | [
"Yield",
"each",
"generator",
"within",
"rails_generator",
"subdirectories",
"."
] | 5288e0014011d6f7519c4231f65c8e5d78f48afb | https://github.com/drnic/rubigen/blob/5288e0014011d6f7519c4231f65c8e5d78f48afb/lib/rubigen/lookup.rb#L271-L275 | train |
wwidea/minimalist_authentication | lib/minimalist_authentication/verifiable_token.rb | MinimalistAuthentication.VerifiableToken.secure_match? | def secure_match?(token)
ActiveSupport::SecurityUtils.secure_compare(
::Digest::SHA256.hexdigest(token),
::Digest::SHA256.hexdigest(verification_token)
)
end | ruby | def secure_match?(token)
ActiveSupport::SecurityUtils.secure_compare(
::Digest::SHA256.hexdigest(token),
::Digest::SHA256.hexdigest(verification_token)
)
end | [
"def",
"secure_match?",
"(",
"token",
")",
"ActiveSupport",
"::",
"SecurityUtils",
".",
"secure_compare",
"(",
"::",
"Digest",
"::",
"SHA256",
".",
"hexdigest",
"(",
"token",
")",
",",
"::",
"Digest",
"::",
"SHA256",
".",
"hexdigest",
"(",
"verification_token",
")",
")",
"end"
] | Compare the tokens in a time-constant manner, to mitigate timing attacks. | [
"Compare",
"the",
"tokens",
"in",
"a",
"time",
"-",
"constant",
"manner",
"to",
"mitigate",
"timing",
"attacks",
"."
] | 29372225a8ee7132bf3b989b824b36cf306cc656 | https://github.com/wwidea/minimalist_authentication/blob/29372225a8ee7132bf3b989b824b36cf306cc656/lib/minimalist_authentication/verifiable_token.rb#L44-L49 | train |
linsen/mxit-rails | lib/mxit_rails/page.rb | MxitRails.Page.render | def render *arguments
if @_mxit_emulator
output = render_to_string *arguments
output = MxitRails::Styles.add_emoticons output
super :inline => output
else
super *arguments
end
end | ruby | def render *arguments
if @_mxit_emulator
output = render_to_string *arguments
output = MxitRails::Styles.add_emoticons output
super :inline => output
else
super *arguments
end
end | [
"def",
"render",
"*",
"arguments",
"if",
"@_mxit_emulator",
"output",
"=",
"render_to_string",
"*",
"arguments",
"output",
"=",
"MxitRails",
"::",
"Styles",
".",
"add_emoticons",
"output",
"super",
":inline",
"=>",
"output",
"else",
"super",
"*",
"arguments",
"end",
"end"
] | Override render method so as to inject emoticons, etc | [
"Override",
"render",
"method",
"so",
"as",
"to",
"inject",
"emoticons",
"etc"
] | 0a076efccd5042f6b05336785818905b103796ab | https://github.com/linsen/mxit-rails/blob/0a076efccd5042f6b05336785818905b103796ab/lib/mxit_rails/page.rb#L165-L173 | train |
linsen/mxit-rails | lib/mxit_api/client.rb | MxitApi.Client.user_code_request_uri | def user_code_request_uri(redirect_uri, state, scopes)
if scopes.empty?
raise MxitApi::Exception.new("No scopes were provided.")
end
# build parameters
parameters = {
:response_type => "code",
:client_id => @client_id,
:redirect_uri => redirect_uri,
:state => state,
:scope => scopes.join(' ')
}
path = MXIT_AUTH_CODE_URI + "?#{URI.encode_www_form(parameters)}"
end | ruby | def user_code_request_uri(redirect_uri, state, scopes)
if scopes.empty?
raise MxitApi::Exception.new("No scopes were provided.")
end
# build parameters
parameters = {
:response_type => "code",
:client_id => @client_id,
:redirect_uri => redirect_uri,
:state => state,
:scope => scopes.join(' ')
}
path = MXIT_AUTH_CODE_URI + "?#{URI.encode_www_form(parameters)}"
end | [
"def",
"user_code_request_uri",
"(",
"redirect_uri",
",",
"state",
",",
"scopes",
")",
"if",
"scopes",
".",
"empty?",
"raise",
"MxitApi",
"::",
"Exception",
".",
"new",
"(",
"\"No scopes were provided.\"",
")",
"end",
"parameters",
"=",
"{",
":response_type",
"=>",
"\"code\"",
",",
":client_id",
"=>",
"@client_id",
",",
":redirect_uri",
"=>",
"redirect_uri",
",",
":state",
"=>",
"state",
",",
":scope",
"=>",
"scopes",
".",
"join",
"(",
"' '",
")",
"}",
"path",
"=",
"MXIT_AUTH_CODE_URI",
"+",
"\"?#{URI.encode_www_form(parameters)}\"",
"end"
] | The user's response to the authorisation code request will be redirected to `redirect_uri`. If
the request was successful there will be a `code` request parameter; otherwise `error`.
redirect_uri - absolute URI to which the user will be redirected after authorisation
state - passed back to `redirect_uri` as a request parameter
scopes - list of scopes to which access is required | [
"The",
"user",
"s",
"response",
"to",
"the",
"authorisation",
"code",
"request",
"will",
"be",
"redirected",
"to",
"redirect_uri",
".",
"If",
"the",
"request",
"was",
"successful",
"there",
"will",
"be",
"a",
"code",
"request",
"parameter",
";",
"otherwise",
"error",
"."
] | 0a076efccd5042f6b05336785818905b103796ab | https://github.com/linsen/mxit-rails/blob/0a076efccd5042f6b05336785818905b103796ab/lib/mxit_api/client.rb#L46-L61 | train |
cyberarm/rewrite-gameoverseer | lib/gameoverseer/messages/message_manager.rb | GameOverseer.MessageManager.message | def message(client_id, string, reliable = false, channel = ChannelManager::CHAT)
GameOverseer::ENetServer.instance.transmit(client_id, string, reliable, channel)
end | ruby | def message(client_id, string, reliable = false, channel = ChannelManager::CHAT)
GameOverseer::ENetServer.instance.transmit(client_id, string, reliable, channel)
end | [
"def",
"message",
"(",
"client_id",
",",
"string",
",",
"reliable",
"=",
"false",
",",
"channel",
"=",
"ChannelManager",
"::",
"CHAT",
")",
"GameOverseer",
"::",
"ENetServer",
".",
"instance",
".",
"transmit",
"(",
"client_id",
",",
"string",
",",
"reliable",
",",
"channel",
")",
"end"
] | Send a message to a specific client
@param client_id [Integer] ID of client
@param string [String] message to send
@param reliable [Boolean] whether or not packet delivery is reliable
@param channel [Integer] What channel to send on | [
"Send",
"a",
"message",
"to",
"a",
"specific",
"client"
] | 279ba63868ad11aa2c937fc6c2544049f05d4bca | https://github.com/cyberarm/rewrite-gameoverseer/blob/279ba63868ad11aa2c937fc6c2544049f05d4bca/lib/gameoverseer/messages/message_manager.rb#L17-L19 | train |
cyberarm/rewrite-gameoverseer | lib/gameoverseer/messages/message_manager.rb | GameOverseer.MessageManager.broadcast | def broadcast(string, reliable = false, channel = ChannelManager::CHAT)
GameOverseer::ENetServer.instance.broadcast(string, reliable, channel)
end | ruby | def broadcast(string, reliable = false, channel = ChannelManager::CHAT)
GameOverseer::ENetServer.instance.broadcast(string, reliable, channel)
end | [
"def",
"broadcast",
"(",
"string",
",",
"reliable",
"=",
"false",
",",
"channel",
"=",
"ChannelManager",
"::",
"CHAT",
")",
"GameOverseer",
"::",
"ENetServer",
".",
"instance",
".",
"broadcast",
"(",
"string",
",",
"reliable",
",",
"channel",
")",
"end"
] | Send a message to all connected clients
@param string [String] message to send
@param reliable [Boolean] whether or not packet delivery is reliable
@param channel [Integer] What channel to send on | [
"Send",
"a",
"message",
"to",
"all",
"connected",
"clients"
] | 279ba63868ad11aa2c937fc6c2544049f05d4bca | https://github.com/cyberarm/rewrite-gameoverseer/blob/279ba63868ad11aa2c937fc6c2544049f05d4bca/lib/gameoverseer/messages/message_manager.rb#L26-L28 | train |
edraut/clark-kent | app/models/clark_kent/report.rb | ClarkKent.Report.row_class | def row_class
report_columns = viable_report_columns
@row_class ||= Class.new do
report_columns.each do |report_column|
attr_accessor report_column.column_name.to_sym
end
def initialize params = {}
params.each { |key, value| send "#{key}=", value }
end
def [](key)
self.send key
end
end
end | ruby | def row_class
report_columns = viable_report_columns
@row_class ||= Class.new do
report_columns.each do |report_column|
attr_accessor report_column.column_name.to_sym
end
def initialize params = {}
params.each { |key, value| send "#{key}=", value }
end
def [](key)
self.send key
end
end
end | [
"def",
"row_class",
"report_columns",
"=",
"viable_report_columns",
"@row_class",
"||=",
"Class",
".",
"new",
"do",
"report_columns",
".",
"each",
"do",
"|",
"report_column",
"|",
"attr_accessor",
"report_column",
".",
"column_name",
".",
"to_sym",
"end",
"def",
"initialize",
"params",
"=",
"{",
"}",
"params",
".",
"each",
"{",
"|",
"key",
",",
"value",
"|",
"send",
"\"#{key}=\"",
",",
"value",
"}",
"end",
"def",
"[]",
"(",
"key",
")",
"self",
".",
"send",
"key",
"end",
"end",
"end"
] | This ephemeral class allows us to create a row object that has the same attributes as the AR response
to the query, including all the custom columns defined in the resource class report config.
currently only used for the summary row, since we can't get that in the same AR query and have to
add it to the collection after the query returns. | [
"This",
"ephemeral",
"class",
"allows",
"us",
"to",
"create",
"a",
"row",
"object",
"that",
"has",
"the",
"same",
"attributes",
"as",
"the",
"AR",
"response",
"to",
"the",
"query",
"including",
"all",
"the",
"custom",
"columns",
"defined",
"in",
"the",
"resource",
"class",
"report",
"config",
".",
"currently",
"only",
"used",
"for",
"the",
"summary",
"row",
"since",
"we",
"can",
"t",
"get",
"that",
"in",
"the",
"same",
"AR",
"query",
"and",
"have",
"to",
"add",
"it",
"to",
"the",
"collection",
"after",
"the",
"query",
"returns",
"."
] | 93d2f2dd0f7d6ee939180ba58ca4c69c3d8c1a91 | https://github.com/edraut/clark-kent/blob/93d2f2dd0f7d6ee939180ba58ca4c69c3d8c1a91/app/models/clark_kent/report.rb#L106-L121 | train |
edraut/clark-kent | app/models/clark_kent/report.rb | ClarkKent.Report.report_filter_params | def report_filter_params
Hash[*viable_report_filters.map{|filter| filter.filter_match_params}.flatten].
merge(order: self.sorter)
end | ruby | def report_filter_params
Hash[*viable_report_filters.map{|filter| filter.filter_match_params}.flatten].
merge(order: self.sorter)
end | [
"def",
"report_filter_params",
"Hash",
"[",
"*",
"viable_report_filters",
".",
"map",
"{",
"|",
"filter",
"|",
"filter",
".",
"filter_match_params",
"}",
".",
"flatten",
"]",
".",
"merge",
"(",
"order",
":",
"self",
".",
"sorter",
")",
"end"
] | These are the built-in filter params that define this report. They are merged at a later
step with the runtime params entered by the user for a specific report run.
nb. the sorter column here may be overridden by a runtime sort if requested by the user. | [
"These",
"are",
"the",
"built",
"-",
"in",
"filter",
"params",
"that",
"define",
"this",
"report",
".",
"They",
"are",
"merged",
"at",
"a",
"later",
"step",
"with",
"the",
"runtime",
"params",
"entered",
"by",
"the",
"user",
"for",
"a",
"specific",
"report",
"run",
".",
"nb",
".",
"the",
"sorter",
"column",
"here",
"may",
"be",
"overridden",
"by",
"a",
"runtime",
"sort",
"if",
"requested",
"by",
"the",
"user",
"."
] | 93d2f2dd0f7d6ee939180ba58ca4c69c3d8c1a91 | https://github.com/edraut/clark-kent/blob/93d2f2dd0f7d6ee939180ba58ca4c69c3d8c1a91/app/models/clark_kent/report.rb#L173-L176 | train |
edraut/clark-kent | app/models/clark_kent/report.rb | ClarkKent.Report.custom_filters | def custom_filters
self.resource_class.report_filter_options.select{|filter| viable_report_filters.map(&:filter_name).exclude? filter.param}
end | ruby | def custom_filters
self.resource_class.report_filter_options.select{|filter| viable_report_filters.map(&:filter_name).exclude? filter.param}
end | [
"def",
"custom_filters",
"self",
".",
"resource_class",
".",
"report_filter_options",
".",
"select",
"{",
"|",
"filter",
"|",
"viable_report_filters",
".",
"map",
"(",
"&",
":filter_name",
")",
".",
"exclude?",
"filter",
".",
"param",
"}",
"end"
] | These are the filters available at runtime, ie. not including the ones set to define this report.
If updating the report, this is the set available to add as new report definition filters. | [
"These",
"are",
"the",
"filters",
"available",
"at",
"runtime",
"ie",
".",
"not",
"including",
"the",
"ones",
"set",
"to",
"define",
"this",
"report",
".",
"If",
"updating",
"the",
"report",
"this",
"is",
"the",
"set",
"available",
"to",
"add",
"as",
"new",
"report",
"definition",
"filters",
"."
] | 93d2f2dd0f7d6ee939180ba58ca4c69c3d8c1a91 | https://github.com/edraut/clark-kent/blob/93d2f2dd0f7d6ee939180ba58ca4c69c3d8c1a91/app/models/clark_kent/report.rb#L240-L242 | train |
edraut/clark-kent | app/models/clark_kent/report.rb | ClarkKent.Report.available_columns | def available_columns
column_options.reject{|column| viable_report_columns.map(&:column_name).include? column.name.to_s}
end | ruby | def available_columns
column_options.reject{|column| viable_report_columns.map(&:column_name).include? column.name.to_s}
end | [
"def",
"available_columns",
"column_options",
".",
"reject",
"{",
"|",
"column",
"|",
"viable_report_columns",
".",
"map",
"(",
"&",
":column_name",
")",
".",
"include?",
"column",
".",
"name",
".",
"to_s",
"}",
"end"
] | This is the set of columns not chosed to use in the report. These are the ones available to add
when updating a report. | [
"This",
"is",
"the",
"set",
"of",
"columns",
"not",
"chosed",
"to",
"use",
"in",
"the",
"report",
".",
"These",
"are",
"the",
"ones",
"available",
"to",
"add",
"when",
"updating",
"a",
"report",
"."
] | 93d2f2dd0f7d6ee939180ba58ca4c69c3d8c1a91 | https://github.com/edraut/clark-kent/blob/93d2f2dd0f7d6ee939180ba58ca4c69c3d8c1a91/app/models/clark_kent/report.rb#L246-L248 | train |
jkr2255/prop_logic | lib/prop_logic/term.rb | PropLogic.Term.each_sat | def each_sat
return to_enum(:each_sat) unless block_given?
sat_loop(self) do |sat, solver|
yield sat
negated_vars = sat.terms.map do |t|
t.is_a?(NotTerm) ? t.terms[0] : ~t
end
solver << PropLogic.all_or(*negated_vars)
end
end | ruby | def each_sat
return to_enum(:each_sat) unless block_given?
sat_loop(self) do |sat, solver|
yield sat
negated_vars = sat.terms.map do |t|
t.is_a?(NotTerm) ? t.terms[0] : ~t
end
solver << PropLogic.all_or(*negated_vars)
end
end | [
"def",
"each_sat",
"return",
"to_enum",
"(",
":each_sat",
")",
"unless",
"block_given?",
"sat_loop",
"(",
"self",
")",
"do",
"|",
"sat",
",",
"solver",
"|",
"yield",
"sat",
"negated_vars",
"=",
"sat",
".",
"terms",
".",
"map",
"do",
"|",
"t",
"|",
"t",
".",
"is_a?",
"(",
"NotTerm",
")",
"?",
"t",
".",
"terms",
"[",
"0",
"]",
":",
"~",
"t",
"end",
"solver",
"<<",
"PropLogic",
".",
"all_or",
"(",
"*",
"negated_vars",
")",
"end",
"end"
] | loop with each satisfied terms.
@return [Enumerator] if block is not given.
@return [nil] if block is given. | [
"loop",
"with",
"each",
"satisfied",
"terms",
"."
] | 285654d49874195e234f575cdc54f77829a19eae | https://github.com/jkr2255/prop_logic/blob/285654d49874195e234f575cdc54f77829a19eae/lib/prop_logic/term.rb#L173-L182 | train |
suculent/apprepo | lib/apprepo/analyser.rb | AppRepo.Analyser.fetch_app_version | def fetch_app_version(options)
metadata = AppRepo::Uploader.new(options).download_manifest_only
FastlaneCore::UI.command_output('TODO: Parse version out from metadata')
puts JSON.pretty_generate(metadata) unless metadata.nil?
FastlaneCore::UI.important('TODO: parse out the bundle-version')
metadata['bundle-version']
end | ruby | def fetch_app_version(options)
metadata = AppRepo::Uploader.new(options).download_manifest_only
FastlaneCore::UI.command_output('TODO: Parse version out from metadata')
puts JSON.pretty_generate(metadata) unless metadata.nil?
FastlaneCore::UI.important('TODO: parse out the bundle-version')
metadata['bundle-version']
end | [
"def",
"fetch_app_version",
"(",
"options",
")",
"metadata",
"=",
"AppRepo",
"::",
"Uploader",
".",
"new",
"(",
"options",
")",
".",
"download_manifest_only",
"FastlaneCore",
"::",
"UI",
".",
"command_output",
"(",
"'TODO: Parse version out from metadata'",
")",
"puts",
"JSON",
".",
"pretty_generate",
"(",
"metadata",
")",
"unless",
"metadata",
".",
"nil?",
"FastlaneCore",
"::",
"UI",
".",
"important",
"(",
"'TODO: parse out the bundle-version'",
")",
"metadata",
"[",
"'bundle-version'",
"]",
"end"
] | Fetches remote app version from metadata | [
"Fetches",
"remote",
"app",
"version",
"from",
"metadata"
] | 91583c7e8eb45490c088155174f9dfc2cac7812d | https://github.com/suculent/apprepo/blob/91583c7e8eb45490c088155174f9dfc2cac7812d/lib/apprepo/analyser.rb#L18-L24 | train |
knut2/todonotes | lib/todonotes/log4r.rb | Todonotes.FixmeFormatter.format | def format(event)
#@@basicformat "%*s %s"
#~ buff = sprintf("%-*s %-5s", Log4r::MaxLevelLength, Log4r::LNAMES[event.level],
#~ event.data.is_a?(Array) ? event.data.first : event.name)
buff = "%5s" % (event.data.is_a?(Array) ? event.data.first : event.name)
#~ buff += (event.tracer.nil? ? "" : "(#{event.tracer[2]})") + ": "
buff << ": "
buff << format_object(event.data.is_a?(Array) ? event.data.last : event.data)
buff << (event.tracer.nil? ? "" : " (#{event.tracer.join('/')})")
buff << "\n"
buff
end | ruby | def format(event)
#@@basicformat "%*s %s"
#~ buff = sprintf("%-*s %-5s", Log4r::MaxLevelLength, Log4r::LNAMES[event.level],
#~ event.data.is_a?(Array) ? event.data.first : event.name)
buff = "%5s" % (event.data.is_a?(Array) ? event.data.first : event.name)
#~ buff += (event.tracer.nil? ? "" : "(#{event.tracer[2]})") + ": "
buff << ": "
buff << format_object(event.data.is_a?(Array) ? event.data.last : event.data)
buff << (event.tracer.nil? ? "" : " (#{event.tracer.join('/')})")
buff << "\n"
buff
end | [
"def",
"format",
"(",
"event",
")",
"buff",
"=",
"\"%5s\"",
"%",
"(",
"event",
".",
"data",
".",
"is_a?",
"(",
"Array",
")",
"?",
"event",
".",
"data",
".",
"first",
":",
"event",
".",
"name",
")",
"buff",
"<<",
"\": \"",
"buff",
"<<",
"format_object",
"(",
"event",
".",
"data",
".",
"is_a?",
"(",
"Array",
")",
"?",
"event",
".",
"data",
".",
"last",
":",
"event",
".",
"data",
")",
"buff",
"<<",
"(",
"event",
".",
"tracer",
".",
"nil?",
"?",
"\"\"",
":",
"\" (#{event.tracer.join('/')})\"",
")",
"buff",
"<<",
"\"\\n\"",
"buff",
"end"
] | =begin rdoc
If event is an Array, the output is adapted.
This outputter is only for internal use via Todonotes.
=end | [
"=",
"begin",
"rdoc",
"If",
"event",
"is",
"an",
"Array",
"the",
"output",
"is",
"adapted",
"."
] | 67e6e9402d2e67fb0cda320669dd33d737351fa4 | https://github.com/knut2/todonotes/blob/67e6e9402d2e67fb0cda320669dd33d737351fa4/lib/todonotes/log4r.rb#L11-L22 | train |
dennmart/wanikani-gem | lib/wanikani/client.rb | Wanikani.Client.valid_api_key? | def valid_api_key?(api_key = nil)
api_key ||= @api_key
return false if api_key.empty?
res = client.get("/api/#{@api_version}/user/#{api_key}/user-information")
return false if !res.success? || res.body.has_key?("error")
return true
end | ruby | def valid_api_key?(api_key = nil)
api_key ||= @api_key
return false if api_key.empty?
res = client.get("/api/#{@api_version}/user/#{api_key}/user-information")
return false if !res.success? || res.body.has_key?("error")
return true
end | [
"def",
"valid_api_key?",
"(",
"api_key",
"=",
"nil",
")",
"api_key",
"||=",
"@api_key",
"return",
"false",
"if",
"api_key",
".",
"empty?",
"res",
"=",
"client",
".",
"get",
"(",
"\"/api/#{@api_version}/user/#{api_key}/user-information\"",
")",
"return",
"false",
"if",
"!",
"res",
".",
"success?",
"||",
"res",
".",
"body",
".",
"has_key?",
"(",
"\"error\"",
")",
"return",
"true",
"end"
] | Initialize a client which will be used to communicate with WaniKani.
@param options [Hash] the API key (required) and API version (optional)
used to communicate with the WaniKani API.
@return [Wanikani::Client] an instance of Wanikani::Client.
Verifies if the client's API key is valid by checking WaniKani's API.
@param api_key [String] the API key to validate in WaniKani.
@return [Boolean] whether the API key is valid. | [
"Initialize",
"a",
"client",
"which",
"will",
"be",
"used",
"to",
"communicate",
"with",
"WaniKani",
"."
] | 70f9e4289f758c9663c0ee4d1172acb711487df9 | https://github.com/dennmart/wanikani-gem/blob/70f9e4289f758c9663c0ee4d1172acb711487df9/lib/wanikani/client.rb#L40-L48 | train |
dennmart/wanikani-gem | lib/wanikani/client.rb | Wanikani.Client.client | def client
Faraday.new(url: Wanikani::API_ENDPOINT) do |conn|
conn.response :json, :content_type => /\bjson$/
conn.adapter Faraday.default_adapter
end
end | ruby | def client
Faraday.new(url: Wanikani::API_ENDPOINT) do |conn|
conn.response :json, :content_type => /\bjson$/
conn.adapter Faraday.default_adapter
end
end | [
"def",
"client",
"Faraday",
".",
"new",
"(",
"url",
":",
"Wanikani",
"::",
"API_ENDPOINT",
")",
"do",
"|",
"conn",
"|",
"conn",
".",
"response",
":json",
",",
":content_type",
"=>",
"/",
"\\b",
"/",
"conn",
".",
"adapter",
"Faraday",
".",
"default_adapter",
"end",
"end"
] | Sets up the HTTP client for communicating with the WaniKani API.
@return [Faraday::Connection] the HTTP client to communicate with the
WaniKani API. | [
"Sets",
"up",
"the",
"HTTP",
"client",
"for",
"communicating",
"with",
"the",
"WaniKani",
"API",
"."
] | 70f9e4289f758c9663c0ee4d1172acb711487df9 | https://github.com/dennmart/wanikani-gem/blob/70f9e4289f758c9663c0ee4d1172acb711487df9/lib/wanikani/client.rb#L67-L72 | train |
dennmart/wanikani-gem | lib/wanikani/client.rb | Wanikani.Client.api_response | def api_response(resource, optional_arg = nil)
raise ArgumentError, "You must define a resource to query WaniKani" if resource.nil? || resource.empty?
begin
res = client.get("/api/#{@api_version}/user/#{@api_key}/#{resource}/#{optional_arg}")
if !res.success? || res.body.has_key?("error")
raise_exception(res)
else
return res.body
end
rescue => error
raise Exception, "There was an error: #{error.message}"
end
end | ruby | def api_response(resource, optional_arg = nil)
raise ArgumentError, "You must define a resource to query WaniKani" if resource.nil? || resource.empty?
begin
res = client.get("/api/#{@api_version}/user/#{@api_key}/#{resource}/#{optional_arg}")
if !res.success? || res.body.has_key?("error")
raise_exception(res)
else
return res.body
end
rescue => error
raise Exception, "There was an error: #{error.message}"
end
end | [
"def",
"api_response",
"(",
"resource",
",",
"optional_arg",
"=",
"nil",
")",
"raise",
"ArgumentError",
",",
"\"You must define a resource to query WaniKani\"",
"if",
"resource",
".",
"nil?",
"||",
"resource",
".",
"empty?",
"begin",
"res",
"=",
"client",
".",
"get",
"(",
"\"/api/#{@api_version}/user/#{@api_key}/#{resource}/#{optional_arg}\"",
")",
"if",
"!",
"res",
".",
"success?",
"||",
"res",
".",
"body",
".",
"has_key?",
"(",
"\"error\"",
")",
"raise_exception",
"(",
"res",
")",
"else",
"return",
"res",
".",
"body",
"end",
"rescue",
"=>",
"error",
"raise",
"Exception",
",",
"\"There was an error: #{error.message}\"",
"end",
"end"
] | Contacts the WaniKani API and returns the data specified.
@param resource [String] the resource to access.
@param optional_arg [String] optional arguments for the specified resource.
@return [Hash] the parsed API response. | [
"Contacts",
"the",
"WaniKani",
"API",
"and",
"returns",
"the",
"data",
"specified",
"."
] | 70f9e4289f758c9663c0ee4d1172acb711487df9 | https://github.com/dennmart/wanikani-gem/blob/70f9e4289f758c9663c0ee4d1172acb711487df9/lib/wanikani/client.rb#L79-L93 | train |
dennmart/wanikani-gem | lib/wanikani/client.rb | Wanikani.Client.raise_exception | def raise_exception(response)
raise Wanikani::InvalidKey, "The API key used for this request is invalid." and return if response.status == 401
message = if response.body.is_a?(Hash) and response.body.has_key?("error")
response.body["error"]["message"]
else
"Status code: #{response.status}"
end
raise Wanikani::Exception, "There was an error fetching the data from WaniKani (#{message})"
end | ruby | def raise_exception(response)
raise Wanikani::InvalidKey, "The API key used for this request is invalid." and return if response.status == 401
message = if response.body.is_a?(Hash) and response.body.has_key?("error")
response.body["error"]["message"]
else
"Status code: #{response.status}"
end
raise Wanikani::Exception, "There was an error fetching the data from WaniKani (#{message})"
end | [
"def",
"raise_exception",
"(",
"response",
")",
"raise",
"Wanikani",
"::",
"InvalidKey",
",",
"\"The API key used for this request is invalid.\"",
"and",
"return",
"if",
"response",
".",
"status",
"==",
"401",
"message",
"=",
"if",
"response",
".",
"body",
".",
"is_a?",
"(",
"Hash",
")",
"and",
"response",
".",
"body",
".",
"has_key?",
"(",
"\"error\"",
")",
"response",
".",
"body",
"[",
"\"error\"",
"]",
"[",
"\"message\"",
"]",
"else",
"\"Status code: #{response.status}\"",
"end",
"raise",
"Wanikani",
"::",
"Exception",
",",
"\"There was an error fetching the data from WaniKani (#{message})\"",
"end"
] | Handles exceptions according to the API response.
@param response [Hash] the parsed API response from WaniKani's API. | [
"Handles",
"exceptions",
"according",
"to",
"the",
"API",
"response",
"."
] | 70f9e4289f758c9663c0ee4d1172acb711487df9 | https://github.com/dennmart/wanikani-gem/blob/70f9e4289f758c9663c0ee4d1172acb711487df9/lib/wanikani/client.rb#L98-L107 | train |
conspire-org/lazy-json | lib/lazy-json.rb | LazyJson.Object.[] | def [](key)
if ! @fields.has_key?(key) && ! @fseq.empty?
while true
@fseq = @fseq.skip_whitespace
if @fseq.first == 125 # '}'.ord
@fseq = @fseq.skip_byte(125).skip_whitespace # '}'.ord
break
end
new_key, new_value = read_field_and_consume
@fields[new_key] = new_value
break if new_key == key
end
end
@fields[key]
end | ruby | def [](key)
if ! @fields.has_key?(key) && ! @fseq.empty?
while true
@fseq = @fseq.skip_whitespace
if @fseq.first == 125 # '}'.ord
@fseq = @fseq.skip_byte(125).skip_whitespace # '}'.ord
break
end
new_key, new_value = read_field_and_consume
@fields[new_key] = new_value
break if new_key == key
end
end
@fields[key]
end | [
"def",
"[]",
"(",
"key",
")",
"if",
"!",
"@fields",
".",
"has_key?",
"(",
"key",
")",
"&&",
"!",
"@fseq",
".",
"empty?",
"while",
"true",
"@fseq",
"=",
"@fseq",
".",
"skip_whitespace",
"if",
"@fseq",
".",
"first",
"==",
"125",
"@fseq",
"=",
"@fseq",
".",
"skip_byte",
"(",
"125",
")",
".",
"skip_whitespace",
"break",
"end",
"new_key",
",",
"new_value",
"=",
"read_field_and_consume",
"@fields",
"[",
"new_key",
"]",
"=",
"new_value",
"break",
"if",
"new_key",
"==",
"key",
"end",
"end",
"@fields",
"[",
"key",
"]",
"end"
] | Access a field, lazily parsing if not yet parsed | [
"Access",
"a",
"field",
"lazily",
"parsing",
"if",
"not",
"yet",
"parsed"
] | f655f7de0b06b9c5e61655e0f4e54f90edaf263d | https://github.com/conspire-org/lazy-json/blob/f655f7de0b06b9c5e61655e0f4e54f90edaf263d/lib/lazy-json.rb#L206-L220 | train |
conspire-org/lazy-json | lib/lazy-json.rb | LazyJson.Array.[] | def [](i)
if @elements.size <= i && ! @eseq.empty?
while true
@eseq = @eseq.skip_whitespace
if @eseq.first == 93 # ']'.ord
@eseq = @eseq.skip_byte(93).skip_whitespace # ']'.ord
break
end
new_value = read_value_and_consume
@elements << new_value
break if @elements.size > i
end
end
@elements[i]
end | ruby | def [](i)
if @elements.size <= i && ! @eseq.empty?
while true
@eseq = @eseq.skip_whitespace
if @eseq.first == 93 # ']'.ord
@eseq = @eseq.skip_byte(93).skip_whitespace # ']'.ord
break
end
new_value = read_value_and_consume
@elements << new_value
break if @elements.size > i
end
end
@elements[i]
end | [
"def",
"[]",
"(",
"i",
")",
"if",
"@elements",
".",
"size",
"<=",
"i",
"&&",
"!",
"@eseq",
".",
"empty?",
"while",
"true",
"@eseq",
"=",
"@eseq",
".",
"skip_whitespace",
"if",
"@eseq",
".",
"first",
"==",
"93",
"@eseq",
"=",
"@eseq",
".",
"skip_byte",
"(",
"93",
")",
".",
"skip_whitespace",
"break",
"end",
"new_value",
"=",
"read_value_and_consume",
"@elements",
"<<",
"new_value",
"break",
"if",
"@elements",
".",
"size",
">",
"i",
"end",
"end",
"@elements",
"[",
"i",
"]",
"end"
] | Access an element, lazily parsing if not yet parsed | [
"Access",
"an",
"element",
"lazily",
"parsing",
"if",
"not",
"yet",
"parsed"
] | f655f7de0b06b9c5e61655e0f4e54f90edaf263d | https://github.com/conspire-org/lazy-json/blob/f655f7de0b06b9c5e61655e0f4e54f90edaf263d/lib/lazy-json.rb#L248-L262 | train |
robertwahler/repo_manager | lib/repo_manager/tasks/thor_helper.rb | RepoManager.ThorHelper.configuration | def configuration(configuration_file=nil)
return @configuration if @configuration
logger.debug "getting repo_manager configuration"
app_options = {}
app_options[:config] = configuration_file || options[:config]
@configuration = ::RepoManager::Settings.new(nil, app_options)
end | ruby | def configuration(configuration_file=nil)
return @configuration if @configuration
logger.debug "getting repo_manager configuration"
app_options = {}
app_options[:config] = configuration_file || options[:config]
@configuration = ::RepoManager::Settings.new(nil, app_options)
end | [
"def",
"configuration",
"(",
"configuration_file",
"=",
"nil",
")",
"return",
"@configuration",
"if",
"@configuration",
"logger",
".",
"debug",
"\"getting repo_manager configuration\"",
"app_options",
"=",
"{",
"}",
"app_options",
"[",
":config",
"]",
"=",
"configuration_file",
"||",
"options",
"[",
":config",
"]",
"@configuration",
"=",
"::",
"RepoManager",
"::",
"Settings",
".",
"new",
"(",
"nil",
",",
"app_options",
")",
"end"
] | main repo_manager configuration setttings file | [
"main",
"repo_manager",
"configuration",
"setttings",
"file"
] | d945f1cb6ac48b5689b633fcc029fd77c6a02d09 | https://github.com/robertwahler/repo_manager/blob/d945f1cb6ac48b5689b633fcc029fd77c6a02d09/lib/repo_manager/tasks/thor_helper.rb#L11-L17 | train |
mLewisLogic/saddle | lib/saddle/endpoint.rb | Saddle.BaseEndpoint.request | def request(method, action, params={}, options={})
# Augment in interesting options
options[:call_chain] = _path_array
options[:action] = action
@requester.send(method, _path(action), params, options)
end | ruby | def request(method, action, params={}, options={})
# Augment in interesting options
options[:call_chain] = _path_array
options[:action] = action
@requester.send(method, _path(action), params, options)
end | [
"def",
"request",
"(",
"method",
",",
"action",
",",
"params",
"=",
"{",
"}",
",",
"options",
"=",
"{",
"}",
")",
"options",
"[",
":call_chain",
"]",
"=",
"_path_array",
"options",
"[",
":action",
"]",
"=",
"action",
"@requester",
".",
"send",
"(",
"method",
",",
"_path",
"(",
"action",
")",
",",
"params",
",",
"options",
")",
"end"
] | Each endpoint needs to have a requester in order to ... make ... uh ... requests.
Generic request wrapper | [
"Each",
"endpoint",
"needs",
"to",
"have",
"a",
"requester",
"in",
"order",
"to",
"...",
"make",
"...",
"uh",
"...",
"requests",
".",
"Generic",
"request",
"wrapper"
] | 9f470a948039dbedb75655d883e714a29b273961 | https://github.com/mLewisLogic/saddle/blob/9f470a948039dbedb75655d883e714a29b273961/lib/saddle/endpoint.rb#L25-L30 | train |
mLewisLogic/saddle | lib/saddle/endpoint.rb | Saddle.BaseEndpoint._build_and_attach_node | def _build_and_attach_node(endpoint_class, method_name=nil)
# Create the new endpoint
endpoint_instance = endpoint_class.new(@requester, method_name, self)
# Attach the endpoint as an instance variable and method
method_name ||= endpoint_class.name.demodulize.underscore
self.instance_variable_set("@#{method_name}", endpoint_instance)
self.define_singleton_method(method_name.to_s) { endpoint_instance }
endpoint_instance
end | ruby | def _build_and_attach_node(endpoint_class, method_name=nil)
# Create the new endpoint
endpoint_instance = endpoint_class.new(@requester, method_name, self)
# Attach the endpoint as an instance variable and method
method_name ||= endpoint_class.name.demodulize.underscore
self.instance_variable_set("@#{method_name}", endpoint_instance)
self.define_singleton_method(method_name.to_s) { endpoint_instance }
endpoint_instance
end | [
"def",
"_build_and_attach_node",
"(",
"endpoint_class",
",",
"method_name",
"=",
"nil",
")",
"endpoint_instance",
"=",
"endpoint_class",
".",
"new",
"(",
"@requester",
",",
"method_name",
",",
"self",
")",
"method_name",
"||=",
"endpoint_class",
".",
"name",
".",
"demodulize",
".",
"underscore",
"self",
".",
"instance_variable_set",
"(",
"\"@#{method_name}\"",
",",
"endpoint_instance",
")",
"self",
".",
"define_singleton_method",
"(",
"method_name",
".",
"to_s",
")",
"{",
"endpoint_instance",
"}",
"endpoint_instance",
"end"
] | Create an endpoint instance and foist it upon this node
Not private, but not part of the public interface for an endpoint | [
"Create",
"an",
"endpoint",
"instance",
"and",
"foist",
"it",
"upon",
"this",
"node",
"Not",
"private",
"but",
"not",
"part",
"of",
"the",
"public",
"interface",
"for",
"an",
"endpoint"
] | 9f470a948039dbedb75655d883e714a29b273961 | https://github.com/mLewisLogic/saddle/blob/9f470a948039dbedb75655d883e714a29b273961/lib/saddle/endpoint.rb#L62-L70 | train |
mLewisLogic/saddle | lib/saddle/endpoint.rb | Saddle.BaseEndpoint._endpoint_chain | def _endpoint_chain
chain = []
node = self
while node.is_a?(BaseEndpoint)
chain << node
node = node.parent
end
chain.reverse
end | ruby | def _endpoint_chain
chain = []
node = self
while node.is_a?(BaseEndpoint)
chain << node
node = node.parent
end
chain.reverse
end | [
"def",
"_endpoint_chain",
"chain",
"=",
"[",
"]",
"node",
"=",
"self",
"while",
"node",
".",
"is_a?",
"(",
"BaseEndpoint",
")",
"chain",
"<<",
"node",
"node",
"=",
"node",
".",
"parent",
"end",
"chain",
".",
"reverse",
"end"
] | Get the parent chain that led to this endpoint | [
"Get",
"the",
"parent",
"chain",
"that",
"led",
"to",
"this",
"endpoint"
] | 9f470a948039dbedb75655d883e714a29b273961 | https://github.com/mLewisLogic/saddle/blob/9f470a948039dbedb75655d883e714a29b273961/lib/saddle/endpoint.rb#L101-L109 | train |
hendricius/instagram_public_api | lib/instagram_public_api/http_service.rb | InstagramPublicApi.HTTPService.perform_request | def perform_request(request_options: {}, parameters: {}, uri:)
args = parameters
request_options = request_options.merge(faraday_options)
# figure out our options for this request
# set up our Faraday connection
connection = Faraday.new(faraday_options) do |faraday|
faraday.adapter Faraday.default_adapter
end
connection.get(uri, args)
end | ruby | def perform_request(request_options: {}, parameters: {}, uri:)
args = parameters
request_options = request_options.merge(faraday_options)
# figure out our options for this request
# set up our Faraday connection
connection = Faraday.new(faraday_options) do |faraday|
faraday.adapter Faraday.default_adapter
end
connection.get(uri, args)
end | [
"def",
"perform_request",
"(",
"request_options",
":",
"{",
"}",
",",
"parameters",
":",
"{",
"}",
",",
"uri",
":",
")",
"args",
"=",
"parameters",
"request_options",
"=",
"request_options",
".",
"merge",
"(",
"faraday_options",
")",
"connection",
"=",
"Faraday",
".",
"new",
"(",
"faraday_options",
")",
"do",
"|",
"faraday",
"|",
"faraday",
".",
"adapter",
"Faraday",
".",
"default_adapter",
"end",
"connection",
".",
"get",
"(",
"uri",
",",
"args",
")",
"end"
] | performs the actual http request | [
"performs",
"the",
"actual",
"http",
"request"
] | ec7c729109135297f3e8f5dc2c8d43cc97e1d3a6 | https://github.com/hendricius/instagram_public_api/blob/ec7c729109135297f3e8f5dc2c8d43cc97e1d3a6/lib/instagram_public_api/http_service.rb#L38-L47 | train |
Deradon/d3_mpq | lib/d3_mpq/analyzer.rb | D3MPQ.Analyzer.write_game_balance | def write_game_balance
write_single_file("analyze")
dir = File.join("analyze", parser_name)
dir = File.join(dir, @field.to_s) if @field
write_analyzed(dir)
end | ruby | def write_game_balance
write_single_file("analyze")
dir = File.join("analyze", parser_name)
dir = File.join(dir, @field.to_s) if @field
write_analyzed(dir)
end | [
"def",
"write_game_balance",
"write_single_file",
"(",
"\"analyze\"",
")",
"dir",
"=",
"File",
".",
"join",
"(",
"\"analyze\"",
",",
"parser_name",
")",
"dir",
"=",
"File",
".",
"join",
"(",
"dir",
",",
"@field",
".",
"to_s",
")",
"if",
"@field",
"write_analyzed",
"(",
"dir",
")",
"end"
] | Writing if GameBalance | [
"Writing",
"if",
"GameBalance"
] | 370af6dbe3c2ae5141b6d2faf1ba8fdd3ff2ca78 | https://github.com/Deradon/d3_mpq/blob/370af6dbe3c2ae5141b6d2faf1ba8fdd3ff2ca78/lib/d3_mpq/analyzer.rb#L49-L55 | train |
Deradon/d3_mpq | lib/d3_mpq/analyzer.rb | D3MPQ.Analyzer.write_analyzed | def write_analyzed(dir)
FileUtils.mkdir_p(dir)
attributes.each do |a, v|
path = File.join(dir, a.to_s)
s = "Count|Value\n" + v.map { |e| "#{e[:count]}|#{e[:value]}" }.join("\n")
File.open("#{path}.csv", 'w') { |f| f.write(s) }
end
end | ruby | def write_analyzed(dir)
FileUtils.mkdir_p(dir)
attributes.each do |a, v|
path = File.join(dir, a.to_s)
s = "Count|Value\n" + v.map { |e| "#{e[:count]}|#{e[:value]}" }.join("\n")
File.open("#{path}.csv", 'w') { |f| f.write(s) }
end
end | [
"def",
"write_analyzed",
"(",
"dir",
")",
"FileUtils",
".",
"mkdir_p",
"(",
"dir",
")",
"attributes",
".",
"each",
"do",
"|",
"a",
",",
"v",
"|",
"path",
"=",
"File",
".",
"join",
"(",
"dir",
",",
"a",
".",
"to_s",
")",
"s",
"=",
"\"Count|Value\\n\"",
"+",
"v",
".",
"map",
"{",
"|",
"e",
"|",
"\"#{e[:count]}|#{e[:value]}\"",
"}",
".",
"join",
"(",
"\"\\n\"",
")",
"File",
".",
"open",
"(",
"\"#{path}.csv\"",
",",
"'w'",
")",
"{",
"|",
"f",
"|",
"f",
".",
"write",
"(",
"s",
")",
"}",
"end",
"end"
] | Writing multiple files to given dir. | [
"Writing",
"multiple",
"files",
"to",
"given",
"dir",
"."
] | 370af6dbe3c2ae5141b6d2faf1ba8fdd3ff2ca78 | https://github.com/Deradon/d3_mpq/blob/370af6dbe3c2ae5141b6d2faf1ba8fdd3ff2ca78/lib/d3_mpq/analyzer.rb#L98-L106 | train |
Deradon/d3_mpq | lib/d3_mpq/analyzer.rb | D3MPQ.Analyzer.attributes | def attributes
return @attributes if @attributes
unsorted = Hash.new { |h,k| h[k] = Hash.new(0) }
snapshots.each do |attributes|
attributes = attributes[@field] if @field
attributes.each do |h|
h.each { |attribute, value| unsorted[attribute][value] += 1 }
end
end
@attributes = Hash.new { |h,k| h[k] = [] }
unsorted.each do |name, h|
h.each do |value, count|
@attributes[name] << { :value => value, :count => count }
end
@attributes[name].sort! { |x,y| y[:count] <=> x[:count] }
end
return @attributes
end | ruby | def attributes
return @attributes if @attributes
unsorted = Hash.new { |h,k| h[k] = Hash.new(0) }
snapshots.each do |attributes|
attributes = attributes[@field] if @field
attributes.each do |h|
h.each { |attribute, value| unsorted[attribute][value] += 1 }
end
end
@attributes = Hash.new { |h,k| h[k] = [] }
unsorted.each do |name, h|
h.each do |value, count|
@attributes[name] << { :value => value, :count => count }
end
@attributes[name].sort! { |x,y| y[:count] <=> x[:count] }
end
return @attributes
end | [
"def",
"attributes",
"return",
"@attributes",
"if",
"@attributes",
"unsorted",
"=",
"Hash",
".",
"new",
"{",
"|",
"h",
",",
"k",
"|",
"h",
"[",
"k",
"]",
"=",
"Hash",
".",
"new",
"(",
"0",
")",
"}",
"snapshots",
".",
"each",
"do",
"|",
"attributes",
"|",
"attributes",
"=",
"attributes",
"[",
"@field",
"]",
"if",
"@field",
"attributes",
".",
"each",
"do",
"|",
"h",
"|",
"h",
".",
"each",
"{",
"|",
"attribute",
",",
"value",
"|",
"unsorted",
"[",
"attribute",
"]",
"[",
"value",
"]",
"+=",
"1",
"}",
"end",
"end",
"@attributes",
"=",
"Hash",
".",
"new",
"{",
"|",
"h",
",",
"k",
"|",
"h",
"[",
"k",
"]",
"=",
"[",
"]",
"}",
"unsorted",
".",
"each",
"do",
"|",
"name",
",",
"h",
"|",
"h",
".",
"each",
"do",
"|",
"value",
",",
"count",
"|",
"@attributes",
"[",
"name",
"]",
"<<",
"{",
":value",
"=>",
"value",
",",
":count",
"=>",
"count",
"}",
"end",
"@attributes",
"[",
"name",
"]",
".",
"sort!",
"{",
"|",
"x",
",",
"y",
"|",
"y",
"[",
":count",
"]",
"<=>",
"x",
"[",
":count",
"]",
"}",
"end",
"return",
"@attributes",
"end"
] | Return analyzed attributes | [
"Return",
"analyzed",
"attributes"
] | 370af6dbe3c2ae5141b6d2faf1ba8fdd3ff2ca78 | https://github.com/Deradon/d3_mpq/blob/370af6dbe3c2ae5141b6d2faf1ba8fdd3ff2ca78/lib/d3_mpq/analyzer.rb#L109-L130 | train |
astro/remcached | lib/remcached/packet.rb | Memcached.Packet.to_s | def to_s
extras_s = extras_to_s
key_s = self[:key].to_s
value_s = self[:value].to_s
self[:extras_length] = extras_s.length
self[:key_length] = key_s.length
self[:total_body_length] = extras_s.length + key_s.length + value_s.length
header_to_s + extras_s + key_s + value_s
end | ruby | def to_s
extras_s = extras_to_s
key_s = self[:key].to_s
value_s = self[:value].to_s
self[:extras_length] = extras_s.length
self[:key_length] = key_s.length
self[:total_body_length] = extras_s.length + key_s.length + value_s.length
header_to_s + extras_s + key_s + value_s
end | [
"def",
"to_s",
"extras_s",
"=",
"extras_to_s",
"key_s",
"=",
"self",
"[",
":key",
"]",
".",
"to_s",
"value_s",
"=",
"self",
"[",
":value",
"]",
".",
"to_s",
"self",
"[",
":extras_length",
"]",
"=",
"extras_s",
".",
"length",
"self",
"[",
":key_length",
"]",
"=",
"key_s",
".",
"length",
"self",
"[",
":total_body_length",
"]",
"=",
"extras_s",
".",
"length",
"+",
"key_s",
".",
"length",
"+",
"value_s",
".",
"length",
"header_to_s",
"+",
"extras_s",
"+",
"key_s",
"+",
"value_s",
"end"
] | Serialize for wire | [
"Serialize",
"for",
"wire"
] | cd687e219c228ee718ec0e9a93e12eb01ca6a38b | https://github.com/astro/remcached/blob/cd687e219c228ee718ec0e9a93e12eb01ca6a38b/lib/remcached/packet.rb#L106-L114 | train |
mediatainment/mongoid_cart | lib/mongoid_cart/view_helpers.rb | MongoidCart.ViewHelpers.remove_from_cart_link | def remove_from_cart_link(item)
link_to(mongoid_cart.remove_item_path(item: {type: item.class.to_s, id: item._id}), {class: "btn btn-default"}) do
(tag :i, class: 'fa fa-cart-plus').concat('Remove from cart')
end
end | ruby | def remove_from_cart_link(item)
link_to(mongoid_cart.remove_item_path(item: {type: item.class.to_s, id: item._id}), {class: "btn btn-default"}) do
(tag :i, class: 'fa fa-cart-plus').concat('Remove from cart')
end
end | [
"def",
"remove_from_cart_link",
"(",
"item",
")",
"link_to",
"(",
"mongoid_cart",
".",
"remove_item_path",
"(",
"item",
":",
"{",
"type",
":",
"item",
".",
"class",
".",
"to_s",
",",
"id",
":",
"item",
".",
"_id",
"}",
")",
",",
"{",
"class",
":",
"\"btn btn-default\"",
"}",
")",
"do",
"(",
"tag",
":i",
",",
"class",
":",
"'fa fa-cart-plus'",
")",
".",
"concat",
"(",
"'Remove from cart'",
")",
"end",
"end"
] | link_to mongoid_cart.remove_item_path | [
"link_to",
"mongoid_cart",
".",
"remove_item_path"
] | 49f9d01a6b627570122d464ef134638e03535c5f | https://github.com/mediatainment/mongoid_cart/blob/49f9d01a6b627570122d464ef134638e03535c5f/lib/mongoid_cart/view_helpers.rb#L5-L9 | train |
mediatainment/mongoid_cart | lib/mongoid_cart/view_helpers.rb | MongoidCart.ViewHelpers.add_to_cart_link | def add_to_cart_link(item)
link_to(mongoid_cart.add_item_path(item: {type: item.class.to_s, id: item._id}), {class: "btn btn-default"}) do
(tag :i, class: 'fa fa-cart-plus').concat('Add to cart')
end
end | ruby | def add_to_cart_link(item)
link_to(mongoid_cart.add_item_path(item: {type: item.class.to_s, id: item._id}), {class: "btn btn-default"}) do
(tag :i, class: 'fa fa-cart-plus').concat('Add to cart')
end
end | [
"def",
"add_to_cart_link",
"(",
"item",
")",
"link_to",
"(",
"mongoid_cart",
".",
"add_item_path",
"(",
"item",
":",
"{",
"type",
":",
"item",
".",
"class",
".",
"to_s",
",",
"id",
":",
"item",
".",
"_id",
"}",
")",
",",
"{",
"class",
":",
"\"btn btn-default\"",
"}",
")",
"do",
"(",
"tag",
":i",
",",
"class",
":",
"'fa fa-cart-plus'",
")",
".",
"concat",
"(",
"'Add to cart'",
")",
"end",
"end"
] | link_to mongoid_cart.add_item_path | [
"link_to",
"mongoid_cart",
".",
"add_item_path"
] | 49f9d01a6b627570122d464ef134638e03535c5f | https://github.com/mediatainment/mongoid_cart/blob/49f9d01a6b627570122d464ef134638e03535c5f/lib/mongoid_cart/view_helpers.rb#L12-L16 | train |
astro/remcached | lib/remcached/client.rb | Memcached.Client.stats | def stats(contents={}, &callback)
send_request Request::Stats.new(contents) do |result|
callback.call result
if result[:status] == Errors::NO_ERROR && result[:key] != ''
:proceed
end
end
end | ruby | def stats(contents={}, &callback)
send_request Request::Stats.new(contents) do |result|
callback.call result
if result[:status] == Errors::NO_ERROR && result[:key] != ''
:proceed
end
end
end | [
"def",
"stats",
"(",
"contents",
"=",
"{",
"}",
",",
"&",
"callback",
")",
"send_request",
"Request",
"::",
"Stats",
".",
"new",
"(",
"contents",
")",
"do",
"|",
"result",
"|",
"callback",
".",
"call",
"result",
"if",
"result",
"[",
":status",
"]",
"==",
"Errors",
"::",
"NO_ERROR",
"&&",
"result",
"[",
":key",
"]",
"!=",
"''",
":proceed",
"end",
"end",
"end"
] | Callback will be called multiple times | [
"Callback",
"will",
"be",
"called",
"multiple",
"times"
] | cd687e219c228ee718ec0e9a93e12eb01ca6a38b | https://github.com/astro/remcached/blob/cd687e219c228ee718ec0e9a93e12eb01ca6a38b/lib/remcached/client.rb#L155-L163 | train |
jgoizueta/numerals | lib/numerals/numeral.rb | Numerals.Numeral.to_base | def to_base(other_base)
if other_base == @radix
dup
else
normalization = exact? ? :exact : :approximate
Numeral.from_quotient to_quotient, base: other_base, normalize: normalization
end
end | ruby | def to_base(other_base)
if other_base == @radix
dup
else
normalization = exact? ? :exact : :approximate
Numeral.from_quotient to_quotient, base: other_base, normalize: normalization
end
end | [
"def",
"to_base",
"(",
"other_base",
")",
"if",
"other_base",
"==",
"@radix",
"dup",
"else",
"normalization",
"=",
"exact?",
"?",
":exact",
":",
":approximate",
"Numeral",
".",
"from_quotient",
"to_quotient",
",",
"base",
":",
"other_base",
",",
"normalize",
":",
"normalization",
"end",
"end"
] | Convert a Numeral to a different base | [
"Convert",
"a",
"Numeral",
"to",
"a",
"different",
"base"
] | a195e75f689af926537f791441bf8d11590c99c0 | https://github.com/jgoizueta/numerals/blob/a195e75f689af926537f791441bf8d11590c99c0/lib/numerals/numeral.rb#L541-L548 | train |
jgoizueta/numerals | lib/numerals/numeral.rb | Numerals.Numeral.approximate! | def approximate!(number_of_digits = nil)
if number_of_digits.nil?
if exact? && !repeating?
@repeat = nil
end
else
expand! number_of_digits
@digits.truncate! number_of_digits
@repeat = nil
end
self
end | ruby | def approximate!(number_of_digits = nil)
if number_of_digits.nil?
if exact? && !repeating?
@repeat = nil
end
else
expand! number_of_digits
@digits.truncate! number_of_digits
@repeat = nil
end
self
end | [
"def",
"approximate!",
"(",
"number_of_digits",
"=",
"nil",
")",
"if",
"number_of_digits",
".",
"nil?",
"if",
"exact?",
"&&",
"!",
"repeating?",
"@repeat",
"=",
"nil",
"end",
"else",
"expand!",
"number_of_digits",
"@digits",
".",
"truncate!",
"number_of_digits",
"@repeat",
"=",
"nil",
"end",
"self",
"end"
] | Expand to the specified number of digits,
then truncate and remove repetitions.
If no number of digits is given, then it will be
converted to approximate numeral only if it is not
repeating. | [
"Expand",
"to",
"the",
"specified",
"number",
"of",
"digits",
"then",
"truncate",
"and",
"remove",
"repetitions",
".",
"If",
"no",
"number",
"of",
"digits",
"is",
"given",
"then",
"it",
"will",
"be",
"converted",
"to",
"approximate",
"numeral",
"only",
"if",
"it",
"is",
"not",
"repeating",
"."
] | a195e75f689af926537f791441bf8d11590c99c0 | https://github.com/jgoizueta/numerals/blob/a195e75f689af926537f791441bf8d11590c99c0/lib/numerals/numeral.rb#L632-L643 | train |
mova-rb/mova | lib/mova/scope.rb | Mova.Scope.flatten | def flatten(translations, current_scope = nil)
translations.each_with_object({}) do |(key, value), memo|
scope = current_scope ? join(current_scope, key) : key.to_s
if value.is_a?(Hash)
memo.merge!(flatten(value, scope))
else
memo[scope] = value
end
end
end | ruby | def flatten(translations, current_scope = nil)
translations.each_with_object({}) do |(key, value), memo|
scope = current_scope ? join(current_scope, key) : key.to_s
if value.is_a?(Hash)
memo.merge!(flatten(value, scope))
else
memo[scope] = value
end
end
end | [
"def",
"flatten",
"(",
"translations",
",",
"current_scope",
"=",
"nil",
")",
"translations",
".",
"each_with_object",
"(",
"{",
"}",
")",
"do",
"|",
"(",
"key",
",",
"value",
")",
",",
"memo",
"|",
"scope",
"=",
"current_scope",
"?",
"join",
"(",
"current_scope",
",",
"key",
")",
":",
"key",
".",
"to_s",
"if",
"value",
".",
"is_a?",
"(",
"Hash",
")",
"memo",
".",
"merge!",
"(",
"flatten",
"(",
"value",
",",
"scope",
")",
")",
"else",
"memo",
"[",
"scope",
"]",
"=",
"value",
"end",
"end",
"end"
] | Recurrently flattens hash by converting its keys to fully scoped ones.
@return [Hash{String => String}]
@param translations [Hash{String/Symbol => String/Hash}] with multiple
roots allowed
@param current_scope for internal use
@example
Scope.flatten(en: {common: {hello: "hi"}}, de: {hello: "Hallo"}) #=>
{"en.common.hello" => "hi", "de.hello" => "Hallo"} | [
"Recurrently",
"flattens",
"hash",
"by",
"converting",
"its",
"keys",
"to",
"fully",
"scoped",
"ones",
"."
] | 27f981c1f29dc20e5d11068d9342088f0e6bb318 | https://github.com/mova-rb/mova/blob/27f981c1f29dc20e5d11068d9342088f0e6bb318/lib/mova/scope.rb#L79-L88 | train |
mova-rb/mova | lib/mova/scope.rb | Mova.Scope.cross_join | def cross_join(locales, keys)
locales.flat_map do |locale|
keys.map { |key| join(locale, key) }
end
end | ruby | def cross_join(locales, keys)
locales.flat_map do |locale|
keys.map { |key| join(locale, key) }
end
end | [
"def",
"cross_join",
"(",
"locales",
",",
"keys",
")",
"locales",
".",
"flat_map",
"do",
"|",
"locale",
"|",
"keys",
".",
"map",
"{",
"|",
"key",
"|",
"join",
"(",
"locale",
",",
"key",
")",
"}",
"end",
"end"
] | Combines each locale with all keys.
@return [Array<String>]
@param locales [Array<String, Symbol>]
@param keys [Array<String, Symbol>]
@example
Scope.cross_join([:de, :en], [:hello, :hi]) #=>
["de.hello", "de.hi", "en.hello", "en.hi"] | [
"Combines",
"each",
"locale",
"with",
"all",
"keys",
"."
] | 27f981c1f29dc20e5d11068d9342088f0e6bb318 | https://github.com/mova-rb/mova/blob/27f981c1f29dc20e5d11068d9342088f0e6bb318/lib/mova/scope.rb#L99-L103 | train |
korczis/csv2psql | lib/csv2psql/analyzer/analyzer.rb | Csv2Psql.Analyzer.create_column | def create_column(data, column)
data[:columns][column] = {}
res = data[:columns][column]
analyzers.each do |analyzer|
analyzer_class = analyzer[:class]
res[analyzer[:name]] = {
class: analyzer_class.new,
results: create_results(analyzer_class)
}
end
res
end | ruby | def create_column(data, column)
data[:columns][column] = {}
res = data[:columns][column]
analyzers.each do |analyzer|
analyzer_class = analyzer[:class]
res[analyzer[:name]] = {
class: analyzer_class.new,
results: create_results(analyzer_class)
}
end
res
end | [
"def",
"create_column",
"(",
"data",
",",
"column",
")",
"data",
"[",
":columns",
"]",
"[",
"column",
"]",
"=",
"{",
"}",
"res",
"=",
"data",
"[",
":columns",
"]",
"[",
"column",
"]",
"analyzers",
".",
"each",
"do",
"|",
"analyzer",
"|",
"analyzer_class",
"=",
"analyzer",
"[",
":class",
"]",
"res",
"[",
"analyzer",
"[",
":name",
"]",
"]",
"=",
"{",
"class",
":",
"analyzer_class",
".",
"new",
",",
"results",
":",
"create_results",
"(",
"analyzer_class",
")",
"}",
"end",
"res",
"end"
] | Create column analyzers | [
"Create",
"column",
"analyzers"
] | dd1751516524b8218da229cd0587c4046e248133 | https://github.com/korczis/csv2psql/blob/dd1751516524b8218da229cd0587c4046e248133/lib/csv2psql/analyzer/analyzer.rb#L64-L77 | train |
korczis/csv2psql | lib/csv2psql/analyzer/analyzer.rb | Csv2Psql.Analyzer.update_numeric_results | def update_numeric_results(ac, ar, val)
cval = ac.convert(val)
ar[:min] = cval if ar[:min].nil? || cval < ar[:min]
ar[:max] = cval if ar[:max].nil? || cval > ar[:max]
end | ruby | def update_numeric_results(ac, ar, val)
cval = ac.convert(val)
ar[:min] = cval if ar[:min].nil? || cval < ar[:min]
ar[:max] = cval if ar[:max].nil? || cval > ar[:max]
end | [
"def",
"update_numeric_results",
"(",
"ac",
",",
"ar",
",",
"val",
")",
"cval",
"=",
"ac",
".",
"convert",
"(",
"val",
")",
"ar",
"[",
":min",
"]",
"=",
"cval",
"if",
"ar",
"[",
":min",
"]",
".",
"nil?",
"||",
"cval",
"<",
"ar",
"[",
":min",
"]",
"ar",
"[",
":max",
"]",
"=",
"cval",
"if",
"ar",
"[",
":max",
"]",
".",
"nil?",
"||",
"cval",
">",
"ar",
"[",
":max",
"]",
"end"
] | Update numeric results
@param ac analyzer class
@param ar analyzer results
@param val value to be analyzed | [
"Update",
"numeric",
"results"
] | dd1751516524b8218da229cd0587c4046e248133 | https://github.com/korczis/csv2psql/blob/dd1751516524b8218da229cd0587c4046e248133/lib/csv2psql/analyzer/analyzer.rb#L143-L147 | train |
Fingertips/peiji-san | lib/peiji_san/view_helper.rb | PeijiSan.ViewHelper.link_to_page | def link_to_page(page, paginated_set, options = {}, html_options = {})
page_parameter = peiji_san_option(:page_parameter, options)
# Sinatra/Rails differentiator
pageable_params = respond_to?(:controller) ? controller.params : self.params
url_options = (page == 1 ? pageable_params.except(page_parameter) : pageable_params.merge(page_parameter => page))
anchor = peiji_san_option(:anchor, options)
url_options[:anchor] = anchor if anchor
html_options[:class] = peiji_san_option(:current_class, options) if paginated_set.current_page?(page)
# Again a little fork here
normalized_url_options = if respond_to?(:controller) # Rails
url_for(url_options)
else # Sinatra
root_path = env['PATH_INFO'].blank? ? "/" : env["PATH_INFO"]
url_for(root_path, url_options)
end
link_to page, normalized_url_options, html_options
end | ruby | def link_to_page(page, paginated_set, options = {}, html_options = {})
page_parameter = peiji_san_option(:page_parameter, options)
# Sinatra/Rails differentiator
pageable_params = respond_to?(:controller) ? controller.params : self.params
url_options = (page == 1 ? pageable_params.except(page_parameter) : pageable_params.merge(page_parameter => page))
anchor = peiji_san_option(:anchor, options)
url_options[:anchor] = anchor if anchor
html_options[:class] = peiji_san_option(:current_class, options) if paginated_set.current_page?(page)
# Again a little fork here
normalized_url_options = if respond_to?(:controller) # Rails
url_for(url_options)
else # Sinatra
root_path = env['PATH_INFO'].blank? ? "/" : env["PATH_INFO"]
url_for(root_path, url_options)
end
link_to page, normalized_url_options, html_options
end | [
"def",
"link_to_page",
"(",
"page",
",",
"paginated_set",
",",
"options",
"=",
"{",
"}",
",",
"html_options",
"=",
"{",
"}",
")",
"page_parameter",
"=",
"peiji_san_option",
"(",
":page_parameter",
",",
"options",
")",
"pageable_params",
"=",
"respond_to?",
"(",
":controller",
")",
"?",
"controller",
".",
"params",
":",
"self",
".",
"params",
"url_options",
"=",
"(",
"page",
"==",
"1",
"?",
"pageable_params",
".",
"except",
"(",
"page_parameter",
")",
":",
"pageable_params",
".",
"merge",
"(",
"page_parameter",
"=>",
"page",
")",
")",
"anchor",
"=",
"peiji_san_option",
"(",
":anchor",
",",
"options",
")",
"url_options",
"[",
":anchor",
"]",
"=",
"anchor",
"if",
"anchor",
"html_options",
"[",
":class",
"]",
"=",
"peiji_san_option",
"(",
":current_class",
",",
"options",
")",
"if",
"paginated_set",
".",
"current_page?",
"(",
"page",
")",
"normalized_url_options",
"=",
"if",
"respond_to?",
"(",
":controller",
")",
"url_for",
"(",
"url_options",
")",
"else",
"root_path",
"=",
"env",
"[",
"'PATH_INFO'",
"]",
".",
"blank?",
"?",
"\"/\"",
":",
"env",
"[",
"\"PATH_INFO\"",
"]",
"url_for",
"(",
"root_path",
",",
"url_options",
")",
"end",
"link_to",
"page",
",",
"normalized_url_options",
",",
"html_options",
"end"
] | Creates a link using +link_to+ for a page in a pagination collection. If
the specified page is the current page then its class will be `current'.
Options:
[:page_parameter]
The name of the GET parameter used to indicate the page to display.
Defaults to <tt>:page</tt>.
[:current_class]
The CSS class name used when a page is the current page in a pagination
collection. Defaults to <tt>:current</tt>. | [
"Creates",
"a",
"link",
"using",
"+",
"link_to",
"+",
"for",
"a",
"page",
"in",
"a",
"pagination",
"collection",
".",
"If",
"the",
"specified",
"page",
"is",
"the",
"current",
"page",
"then",
"its",
"class",
"will",
"be",
"current",
"."
] | 6bd1bc7c152961dcde376a8bcb2ca393b5b45829 | https://github.com/Fingertips/peiji-san/blob/6bd1bc7c152961dcde376a8bcb2ca393b5b45829/lib/peiji_san/view_helper.rb#L48-L68 | train |
Fingertips/peiji-san | lib/peiji_san/view_helper.rb | PeijiSan.ViewHelper.pages_to_link_to | def pages_to_link_to(paginated_set, options = {})
current, last = paginated_set.current_page, paginated_set.page_count
max = peiji_san_option(:max_visible, options)
separator = peiji_san_option(:separator, options)
if last <= max
(1..last).to_a
elsif current <= ((max / 2) + 1)
(1..(max - 2)).to_a + [separator, last]
elsif current >= (last - (max / 2))
[1, separator, *((last - (max - 3))..last)]
else
offset = (max - 4) / 2
[1, separator] + ((current - offset)..(current + offset)).to_a + [separator, last]
end
end | ruby | def pages_to_link_to(paginated_set, options = {})
current, last = paginated_set.current_page, paginated_set.page_count
max = peiji_san_option(:max_visible, options)
separator = peiji_san_option(:separator, options)
if last <= max
(1..last).to_a
elsif current <= ((max / 2) + 1)
(1..(max - 2)).to_a + [separator, last]
elsif current >= (last - (max / 2))
[1, separator, *((last - (max - 3))..last)]
else
offset = (max - 4) / 2
[1, separator] + ((current - offset)..(current + offset)).to_a + [separator, last]
end
end | [
"def",
"pages_to_link_to",
"(",
"paginated_set",
",",
"options",
"=",
"{",
"}",
")",
"current",
",",
"last",
"=",
"paginated_set",
".",
"current_page",
",",
"paginated_set",
".",
"page_count",
"max",
"=",
"peiji_san_option",
"(",
":max_visible",
",",
"options",
")",
"separator",
"=",
"peiji_san_option",
"(",
":separator",
",",
"options",
")",
"if",
"last",
"<=",
"max",
"(",
"1",
"..",
"last",
")",
".",
"to_a",
"elsif",
"current",
"<=",
"(",
"(",
"max",
"/",
"2",
")",
"+",
"1",
")",
"(",
"1",
"..",
"(",
"max",
"-",
"2",
")",
")",
".",
"to_a",
"+",
"[",
"separator",
",",
"last",
"]",
"elsif",
"current",
">=",
"(",
"last",
"-",
"(",
"max",
"/",
"2",
")",
")",
"[",
"1",
",",
"separator",
",",
"*",
"(",
"(",
"last",
"-",
"(",
"max",
"-",
"3",
")",
")",
"..",
"last",
")",
"]",
"else",
"offset",
"=",
"(",
"max",
"-",
"4",
")",
"/",
"2",
"[",
"1",
",",
"separator",
"]",
"+",
"(",
"(",
"current",
"-",
"offset",
")",
"..",
"(",
"current",
"+",
"offset",
")",
")",
".",
"to_a",
"+",
"[",
"separator",
",",
"last",
"]",
"end",
"end"
] | Returns an array of pages to link to. This array includes the separator, so
make sure to keep this in mind when iterating over the array and creating
links.
For consistency’s sake, it is adviced to use an odd number for
<tt>:max_visible</tt>.
Options:
[:max_visible]
The maximum amount of elements in the array, this includes the
separator(s). Defaults to 11.
[:separator]
The separator string used to indicate a range between the first or last
page and the ones surrounding the current page.
collection = Model.all.page(40)
collection.page_count # => 80
pages_to_link_to(collection) # => [1, '…', 37, 38, 39, 40, 41, 42, 43, '…', 80] | [
"Returns",
"an",
"array",
"of",
"pages",
"to",
"link",
"to",
".",
"This",
"array",
"includes",
"the",
"separator",
"so",
"make",
"sure",
"to",
"keep",
"this",
"in",
"mind",
"when",
"iterating",
"over",
"the",
"array",
"and",
"creating",
"links",
"."
] | 6bd1bc7c152961dcde376a8bcb2ca393b5b45829 | https://github.com/Fingertips/peiji-san/blob/6bd1bc7c152961dcde376a8bcb2ca393b5b45829/lib/peiji_san/view_helper.rb#L106-L121 | train |
gevans/expedition | lib/expedition/client.rb | Expedition.Client.devices | def devices
send(:devdetails) do |body|
body[:devdetails].collect { |attrs|
attrs.delete(:devdetails)
attrs[:variant] = attrs.delete(:name).downcase
attrs
}
end
end | ruby | def devices
send(:devdetails) do |body|
body[:devdetails].collect { |attrs|
attrs.delete(:devdetails)
attrs[:variant] = attrs.delete(:name).downcase
attrs
}
end
end | [
"def",
"devices",
"send",
"(",
":devdetails",
")",
"do",
"|",
"body",
"|",
"body",
"[",
":devdetails",
"]",
".",
"collect",
"{",
"|",
"attrs",
"|",
"attrs",
".",
"delete",
"(",
":devdetails",
")",
"attrs",
"[",
":variant",
"]",
"=",
"attrs",
".",
"delete",
"(",
":name",
")",
".",
"downcase",
"attrs",
"}",
"end",
"end"
] | Initializes a new `Client` for executing commands.
@param [String] host
The host to connect to.
@param [Integer] port
The port to connect to.
Sends the `devdetails` command, returning an array of devices found in the
service's response.
@return [Response]
An array of devices. | [
"Initializes",
"a",
"new",
"Client",
"for",
"executing",
"commands",
"."
] | a9ce897900002469ed57617d065a2bbdefd5ced5 | https://github.com/gevans/expedition/blob/a9ce897900002469ed57617d065a2bbdefd5ced5/lib/expedition/client.rb#L38-L46 | train |
gevans/expedition | lib/expedition/client.rb | Expedition.Client.send | def send(command, *parameters, &block)
socket = TCPSocket.open(host, port)
socket.puts command_json(command, *parameters)
parse(socket.gets, &block)
ensure
socket.close if socket.respond_to?(:close)
end | ruby | def send(command, *parameters, &block)
socket = TCPSocket.open(host, port)
socket.puts command_json(command, *parameters)
parse(socket.gets, &block)
ensure
socket.close if socket.respond_to?(:close)
end | [
"def",
"send",
"(",
"command",
",",
"*",
"parameters",
",",
"&",
"block",
")",
"socket",
"=",
"TCPSocket",
".",
"open",
"(",
"host",
",",
"port",
")",
"socket",
".",
"puts",
"command_json",
"(",
"command",
",",
"*",
"parameters",
")",
"parse",
"(",
"socket",
".",
"gets",
",",
"&",
"block",
")",
"ensure",
"socket",
".",
"close",
"if",
"socket",
".",
"respond_to?",
"(",
":close",
")",
"end"
] | Sends the supplied `command` with optionally supplied `parameters` to the
service and returns the result, if any.
**Note:** Since `Object#send` is overridden, use `Object#__send__` to call
an actual method.
@param [Symbol, String] command
The command to send to the service.
@param [Array] parameters
Optional parameters to send to the service.
@return [Response]
The service's response. | [
"Sends",
"the",
"supplied",
"command",
"with",
"optionally",
"supplied",
"parameters",
"to",
"the",
"service",
"and",
"returns",
"the",
"result",
"if",
"any",
"."
] | a9ce897900002469ed57617d065a2bbdefd5ced5 | https://github.com/gevans/expedition/blob/a9ce897900002469ed57617d065a2bbdefd5ced5/lib/expedition/client.rb#L87-L94 | train |
tatemae/muck-engine | lib/muck-engine/flash_errors.rb | MuckEngine.FlashErrors.output_errors | def output_errors(title, options = {}, fields = nil, flash_only = false)
fields = [fields] unless fields.is_a?(Array)
flash_html = render(:partial => 'shared/flash_messages')
flash.clear
css_class = "class=\"#{options[:class] || 'error'}\"" unless options[:class].nil?
field_errors = render(:partial => 'shared/field_error', :collection => fields)
if flash_only || (!flash_html.empty? && field_errors.empty?)
# Only flash. Don't render errors for any fields
render(:partial => 'shared/flash_error_box', :locals => {:flash_html => flash_html, :css_class => css_class})
elsif !field_errors.empty?
# Field errors and/or flash
render(:partial => 'shared/error_box', :locals => {:title => title,
:flash_html => flash_html,
:field_errors => field_errors,
:css_class => css_class,
:extra_html => options[:extra_html]})
else
#nothing
''
end
end | ruby | def output_errors(title, options = {}, fields = nil, flash_only = false)
fields = [fields] unless fields.is_a?(Array)
flash_html = render(:partial => 'shared/flash_messages')
flash.clear
css_class = "class=\"#{options[:class] || 'error'}\"" unless options[:class].nil?
field_errors = render(:partial => 'shared/field_error', :collection => fields)
if flash_only || (!flash_html.empty? && field_errors.empty?)
# Only flash. Don't render errors for any fields
render(:partial => 'shared/flash_error_box', :locals => {:flash_html => flash_html, :css_class => css_class})
elsif !field_errors.empty?
# Field errors and/or flash
render(:partial => 'shared/error_box', :locals => {:title => title,
:flash_html => flash_html,
:field_errors => field_errors,
:css_class => css_class,
:extra_html => options[:extra_html]})
else
#nothing
''
end
end | [
"def",
"output_errors",
"(",
"title",
",",
"options",
"=",
"{",
"}",
",",
"fields",
"=",
"nil",
",",
"flash_only",
"=",
"false",
")",
"fields",
"=",
"[",
"fields",
"]",
"unless",
"fields",
".",
"is_a?",
"(",
"Array",
")",
"flash_html",
"=",
"render",
"(",
":partial",
"=>",
"'shared/flash_messages'",
")",
"flash",
".",
"clear",
"css_class",
"=",
"\"class=\\\"#{options[:class] || 'error'}\\\"\"",
"unless",
"options",
"[",
":class",
"]",
".",
"nil?",
"field_errors",
"=",
"render",
"(",
":partial",
"=>",
"'shared/field_error'",
",",
":collection",
"=>",
"fields",
")",
"if",
"flash_only",
"||",
"(",
"!",
"flash_html",
".",
"empty?",
"&&",
"field_errors",
".",
"empty?",
")",
"render",
"(",
":partial",
"=>",
"'shared/flash_error_box'",
",",
":locals",
"=>",
"{",
":flash_html",
"=>",
"flash_html",
",",
":css_class",
"=>",
"css_class",
"}",
")",
"elsif",
"!",
"field_errors",
".",
"empty?",
"render",
"(",
":partial",
"=>",
"'shared/error_box'",
",",
":locals",
"=>",
"{",
":title",
"=>",
"title",
",",
":flash_html",
"=>",
"flash_html",
",",
":field_errors",
"=>",
"field_errors",
",",
":css_class",
"=>",
"css_class",
",",
":extra_html",
"=>",
"options",
"[",
":extra_html",
"]",
"}",
")",
"else",
"''",
"end",
"end"
] | Output flash and object errors | [
"Output",
"flash",
"and",
"object",
"errors"
] | 41fc072dce3a365b3ce4a73d4f60a4ff24026d51 | https://github.com/tatemae/muck-engine/blob/41fc072dce3a365b3ce4a73d4f60a4ff24026d51/lib/muck-engine/flash_errors.rb#L10-L31 | train |
tatemae/muck-engine | lib/muck-engine/flash_errors.rb | MuckEngine.FlashErrors.output_admin_messages | def output_admin_messages(fields = nil, title = '', options = { :class => 'notify-box' }, flash_only = false)
output_errors_ajax('admin-messages', title, options, fields, flash_only)
end | ruby | def output_admin_messages(fields = nil, title = '', options = { :class => 'notify-box' }, flash_only = false)
output_errors_ajax('admin-messages', title, options, fields, flash_only)
end | [
"def",
"output_admin_messages",
"(",
"fields",
"=",
"nil",
",",
"title",
"=",
"''",
",",
"options",
"=",
"{",
":class",
"=>",
"'notify-box'",
"}",
",",
"flash_only",
"=",
"false",
")",
"output_errors_ajax",
"(",
"'admin-messages'",
",",
"title",
",",
"options",
",",
"fields",
",",
"flash_only",
")",
"end"
] | Output a page update that will display messages in the flash | [
"Output",
"a",
"page",
"update",
"that",
"will",
"display",
"messages",
"in",
"the",
"flash"
] | 41fc072dce3a365b3ce4a73d4f60a4ff24026d51 | https://github.com/tatemae/muck-engine/blob/41fc072dce3a365b3ce4a73d4f60a4ff24026d51/lib/muck-engine/flash_errors.rb#L42-L44 | train |
renz45/table_me | lib/table_me/table_pagination.rb | TableMe.TablePagination.pagination_number_list | def pagination_number_list
(0...page_button_count).to_a.map do |n|
link_number = n + page_number_offset
number_span(link_number)
end.join(' ')
end | ruby | def pagination_number_list
(0...page_button_count).to_a.map do |n|
link_number = n + page_number_offset
number_span(link_number)
end.join(' ')
end | [
"def",
"pagination_number_list",
"(",
"0",
"...",
"page_button_count",
")",
".",
"to_a",
".",
"map",
"do",
"|",
"n",
"|",
"link_number",
"=",
"n",
"+",
"page_number_offset",
"number_span",
"(",
"link_number",
")",
"end",
".",
"join",
"(",
"' '",
")",
"end"
] | List of number links for the number range between next and previous | [
"List",
"of",
"number",
"links",
"for",
"the",
"number",
"range",
"between",
"next",
"and",
"previous"
] | a04bd7c26497828b2f8f0178631253b6749025cf | https://github.com/renz45/table_me/blob/a04bd7c26497828b2f8f0178631253b6749025cf/lib/table_me/table_pagination.rb#L56-L61 | train |
riddopic/garcun | lib/garcon/task/copy_on_write_observer_set.rb | Garcon.CopyOnWriteObserverSet.add_observer | def add_observer(observer=nil, func=:update, &block)
if observer.nil? && block.nil?
raise ArgumentError, 'should pass observer as a first argument or block'
elsif observer && block
raise ArgumentError.new('cannot provide both an observer and a block')
end
if block
observer = block
func = :call
end
begin
@mutex.lock
new_observers = @observers.dup
new_observers[observer] = func
@observers = new_observers
observer
ensure
@mutex.unlock
end
end | ruby | def add_observer(observer=nil, func=:update, &block)
if observer.nil? && block.nil?
raise ArgumentError, 'should pass observer as a first argument or block'
elsif observer && block
raise ArgumentError.new('cannot provide both an observer and a block')
end
if block
observer = block
func = :call
end
begin
@mutex.lock
new_observers = @observers.dup
new_observers[observer] = func
@observers = new_observers
observer
ensure
@mutex.unlock
end
end | [
"def",
"add_observer",
"(",
"observer",
"=",
"nil",
",",
"func",
"=",
":update",
",",
"&",
"block",
")",
"if",
"observer",
".",
"nil?",
"&&",
"block",
".",
"nil?",
"raise",
"ArgumentError",
",",
"'should pass observer as a first argument or block'",
"elsif",
"observer",
"&&",
"block",
"raise",
"ArgumentError",
".",
"new",
"(",
"'cannot provide both an observer and a block'",
")",
"end",
"if",
"block",
"observer",
"=",
"block",
"func",
"=",
":call",
"end",
"begin",
"@mutex",
".",
"lock",
"new_observers",
"=",
"@observers",
".",
"dup",
"new_observers",
"[",
"observer",
"]",
"=",
"func",
"@observers",
"=",
"new_observers",
"observer",
"ensure",
"@mutex",
".",
"unlock",
"end",
"end"
] | Adds an observer to this set. If a block is passed, the observer will be
created by this method and no other params should be passed
@param [Object] observer
the observer to add
@param [Symbol] func
the function to call on the observer during notification. The default
is :update.
@return [Object]
the added observer | [
"Adds",
"an",
"observer",
"to",
"this",
"set",
".",
"If",
"a",
"block",
"is",
"passed",
"the",
"observer",
"will",
"be",
"created",
"by",
"this",
"method",
"and",
"no",
"other",
"params",
"should",
"be",
"passed"
] | c2409bd8cf9c14b967a719810dab5269d69b42de | https://github.com/riddopic/garcun/blob/c2409bd8cf9c14b967a719810dab5269d69b42de/lib/garcon/task/copy_on_write_observer_set.rb#L45-L66 | train |
rolandasb/gogcom | lib/gogcom/news.rb | Gogcom.News.parse | def parse(data)
rss = SimpleRSS.parse data
news = Array.new
rss.items.each do |item|
news_item = NewsItem.new(item.title, item.link, item.description.force_encoding("UTF-8"), item.pubDate)
news.push news_item
end
unless @limit.nil?
news.take(@limit)
else
news
end
end | ruby | def parse(data)
rss = SimpleRSS.parse data
news = Array.new
rss.items.each do |item|
news_item = NewsItem.new(item.title, item.link, item.description.force_encoding("UTF-8"), item.pubDate)
news.push news_item
end
unless @limit.nil?
news.take(@limit)
else
news
end
end | [
"def",
"parse",
"(",
"data",
")",
"rss",
"=",
"SimpleRSS",
".",
"parse",
"data",
"news",
"=",
"Array",
".",
"new",
"rss",
".",
"items",
".",
"each",
"do",
"|",
"item",
"|",
"news_item",
"=",
"NewsItem",
".",
"new",
"(",
"item",
".",
"title",
",",
"item",
".",
"link",
",",
"item",
".",
"description",
".",
"force_encoding",
"(",
"\"UTF-8\"",
")",
",",
"item",
".",
"pubDate",
")",
"news",
".",
"push",
"news_item",
"end",
"unless",
"@limit",
".",
"nil?",
"news",
".",
"take",
"(",
"@limit",
")",
"else",
"news",
"end",
"end"
] | Parses raw data and returns news items
@return [Array] | [
"Parses",
"raw",
"data",
"and",
"returns",
"news",
"items"
] | 015de453bb214c9ccb51665ecadce1367e6d987d | https://github.com/rolandasb/gogcom/blob/015de453bb214c9ccb51665ecadce1367e6d987d/lib/gogcom/news.rb#L27-L42 | train |
kevgo/mortadella | lib/mortadella/horizontal.rb | Mortadella.Horizontal.columns_indeces_to_drop | def columns_indeces_to_drop columns
result = []
headers = @table[0]
headers.each_with_index do |header, i|
result << i unless columns.include? header
end
result
end | ruby | def columns_indeces_to_drop columns
result = []
headers = @table[0]
headers.each_with_index do |header, i|
result << i unless columns.include? header
end
result
end | [
"def",
"columns_indeces_to_drop",
"columns",
"result",
"=",
"[",
"]",
"headers",
"=",
"@table",
"[",
"0",
"]",
"headers",
".",
"each_with_index",
"do",
"|",
"header",
",",
"i",
"|",
"result",
"<<",
"i",
"unless",
"columns",
".",
"include?",
"header",
"end",
"result",
"end"
] | Returns the column indeces to drop to make this table have the given columns | [
"Returns",
"the",
"column",
"indeces",
"to",
"drop",
"to",
"make",
"this",
"table",
"have",
"the",
"given",
"columns"
] | 723d06f7a74fb581bf2679505d9cb06e7b128c88 | https://github.com/kevgo/mortadella/blob/723d06f7a74fb581bf2679505d9cb06e7b128c88/lib/mortadella/horizontal.rb#L56-L63 | train |
kevgo/mortadella | lib/mortadella/horizontal.rb | Mortadella.Horizontal.dry_up | def dry_up row
return row unless @previous_row
row.clone.tap do |result|
row.length.times do |i|
if can_dry?(@headers[i]) && row[i] == @previous_row[i]
result[i] = ''
else
break
end
end
end
end | ruby | def dry_up row
return row unless @previous_row
row.clone.tap do |result|
row.length.times do |i|
if can_dry?(@headers[i]) && row[i] == @previous_row[i]
result[i] = ''
else
break
end
end
end
end | [
"def",
"dry_up",
"row",
"return",
"row",
"unless",
"@previous_row",
"row",
".",
"clone",
".",
"tap",
"do",
"|",
"result",
"|",
"row",
".",
"length",
".",
"times",
"do",
"|",
"i",
"|",
"if",
"can_dry?",
"(",
"@headers",
"[",
"i",
"]",
")",
"&&",
"row",
"[",
"i",
"]",
"==",
"@previous_row",
"[",
"i",
"]",
"result",
"[",
"i",
"]",
"=",
"''",
"else",
"break",
"end",
"end",
"end",
"end"
] | Returns a dried up version of the given row
based on the row that came before in the table
In a dried up row, any values that match the previous row are removed,
stopping on the first difference | [
"Returns",
"a",
"dried",
"up",
"version",
"of",
"the",
"given",
"row",
"based",
"on",
"the",
"row",
"that",
"came",
"before",
"in",
"the",
"table"
] | 723d06f7a74fb581bf2679505d9cb06e7b128c88 | https://github.com/kevgo/mortadella/blob/723d06f7a74fb581bf2679505d9cb06e7b128c88/lib/mortadella/horizontal.rb#L71-L82 | train |
coralnexus/nucleon | lib/core/config.rb | Nucleon.Config.fetch | def fetch(data, keys, default = nil, format = false)
if keys.is_a?(String) || keys.is_a?(Symbol)
keys = [ keys ]
end
keys = keys.flatten.compact
key = keys.shift
if data.has_key?(key)
value = data[key]
if keys.empty?
return filter(value, format)
else
return fetch(data[key], keys, default, format) if data[key].is_a?(Hash)
end
end
return filter(default, format)
end | ruby | def fetch(data, keys, default = nil, format = false)
if keys.is_a?(String) || keys.is_a?(Symbol)
keys = [ keys ]
end
keys = keys.flatten.compact
key = keys.shift
if data.has_key?(key)
value = data[key]
if keys.empty?
return filter(value, format)
else
return fetch(data[key], keys, default, format) if data[key].is_a?(Hash)
end
end
return filter(default, format)
end | [
"def",
"fetch",
"(",
"data",
",",
"keys",
",",
"default",
"=",
"nil",
",",
"format",
"=",
"false",
")",
"if",
"keys",
".",
"is_a?",
"(",
"String",
")",
"||",
"keys",
".",
"is_a?",
"(",
"Symbol",
")",
"keys",
"=",
"[",
"keys",
"]",
"end",
"keys",
"=",
"keys",
".",
"flatten",
".",
"compact",
"key",
"=",
"keys",
".",
"shift",
"if",
"data",
".",
"has_key?",
"(",
"key",
")",
"value",
"=",
"data",
"[",
"key",
"]",
"if",
"keys",
".",
"empty?",
"return",
"filter",
"(",
"value",
",",
"format",
")",
"else",
"return",
"fetch",
"(",
"data",
"[",
"key",
"]",
",",
"keys",
",",
"default",
",",
"format",
")",
"if",
"data",
"[",
"key",
"]",
".",
"is_a?",
"(",
"Hash",
")",
"end",
"end",
"return",
"filter",
"(",
"default",
",",
"format",
")",
"end"
] | Recursively fetch value for key path in the configuration object.
This method serves as a base accessor to the properties that are defined in
the central property collection. It is used and built upon by other
accessors defined in the class.
Hash data is assumed to already be symbolized.
* *Parameters*
- [Hash] *data* Configuration property data
- [Array<String, Symbol>, String, Symbol] *keys* Key path to fetch
- [ANY] *default* Default value is no value is found for key path
- [false, Symbol, String] *format* Format to filter final returned value or false for none
* *Returns*
- [ANY] Filtered value for key path from configuration object
* *Errors*
See:
- #filter
- Nucleon::Util::Data::filter | [
"Recursively",
"fetch",
"value",
"for",
"key",
"path",
"in",
"the",
"configuration",
"object",
"."
] | 3a3c489251139c184e0884feaa55269cf64cad44 | https://github.com/coralnexus/nucleon/blob/3a3c489251139c184e0884feaa55269cf64cad44/lib/core/config.rb#L336-L354 | train |
coralnexus/nucleon | lib/core/config.rb | Nucleon.Config.modify | def modify(data, keys, value = nil, delete_nil = false, &block) # :yields: key, value, existing
if keys.is_a?(String) || keys.is_a?(Symbol)
keys = [ keys ]
end
keys = keys.flatten.compact
key = keys.shift
has_key = data.has_key?(key)
existing = {
:key => key,
:value => ( has_key ? data[key] : nil )
}
if keys.empty?
if value.nil? && delete_nil
data.delete(key) if has_key
else
value = symbol_map(value) if value.is_a?(Hash)
data[key] = block ? block.call(key, value, existing[:value]) : value
end
else
data[key] = {} unless has_key
if data[key].is_a?(Hash)
existing = modify(data[key], keys, value, delete_nil, &block)
else
existing[:value] = nil
end
end
return existing
end | ruby | def modify(data, keys, value = nil, delete_nil = false, &block) # :yields: key, value, existing
if keys.is_a?(String) || keys.is_a?(Symbol)
keys = [ keys ]
end
keys = keys.flatten.compact
key = keys.shift
has_key = data.has_key?(key)
existing = {
:key => key,
:value => ( has_key ? data[key] : nil )
}
if keys.empty?
if value.nil? && delete_nil
data.delete(key) if has_key
else
value = symbol_map(value) if value.is_a?(Hash)
data[key] = block ? block.call(key, value, existing[:value]) : value
end
else
data[key] = {} unless has_key
if data[key].is_a?(Hash)
existing = modify(data[key], keys, value, delete_nil, &block)
else
existing[:value] = nil
end
end
return existing
end | [
"def",
"modify",
"(",
"data",
",",
"keys",
",",
"value",
"=",
"nil",
",",
"delete_nil",
"=",
"false",
",",
"&",
"block",
")",
"if",
"keys",
".",
"is_a?",
"(",
"String",
")",
"||",
"keys",
".",
"is_a?",
"(",
"Symbol",
")",
"keys",
"=",
"[",
"keys",
"]",
"end",
"keys",
"=",
"keys",
".",
"flatten",
".",
"compact",
"key",
"=",
"keys",
".",
"shift",
"has_key",
"=",
"data",
".",
"has_key?",
"(",
"key",
")",
"existing",
"=",
"{",
":key",
"=>",
"key",
",",
":value",
"=>",
"(",
"has_key",
"?",
"data",
"[",
"key",
"]",
":",
"nil",
")",
"}",
"if",
"keys",
".",
"empty?",
"if",
"value",
".",
"nil?",
"&&",
"delete_nil",
"data",
".",
"delete",
"(",
"key",
")",
"if",
"has_key",
"else",
"value",
"=",
"symbol_map",
"(",
"value",
")",
"if",
"value",
".",
"is_a?",
"(",
"Hash",
")",
"data",
"[",
"key",
"]",
"=",
"block",
"?",
"block",
".",
"call",
"(",
"key",
",",
"value",
",",
"existing",
"[",
":value",
"]",
")",
":",
"value",
"end",
"else",
"data",
"[",
"key",
"]",
"=",
"{",
"}",
"unless",
"has_key",
"if",
"data",
"[",
"key",
"]",
".",
"is_a?",
"(",
"Hash",
")",
"existing",
"=",
"modify",
"(",
"data",
"[",
"key",
"]",
",",
"keys",
",",
"value",
",",
"delete_nil",
",",
"&",
"block",
")",
"else",
"existing",
"[",
":value",
"]",
"=",
"nil",
"end",
"end",
"return",
"existing",
"end"
] | Modify value for key path in the configuration object.
This method serves as a base modifier to the properties that are defined in
the central property collection. It is used and built upon by other
modifiers defined in the class.
Hash data is assumed to already be symbolized.
* *Parameters*
- [Hash] *data* Configuration property data
- [Array<String, Symbol>, String, Symbol] *keys* Key path to modify
- [ANY] *value* Value to set for key path
- [Boolean] *delete_nil* Delete nil value (serves as an internal way to delete properties)
* *Returns*
- [ANY] Existing value for key path from configuration object (before update)
* *Errors*
* *Yields*
- [Symbol] *key* Configuration key to modify
- [ANY] *value* New value of configuration key
- [ANY] *existing* Existing value being replaced for the configuration key
See:
- #symbol_map
- Nucleon::Util::Data::symbol_map | [
"Modify",
"value",
"for",
"key",
"path",
"in",
"the",
"configuration",
"object",
"."
] | 3a3c489251139c184e0884feaa55269cf64cad44 | https://github.com/coralnexus/nucleon/blob/3a3c489251139c184e0884feaa55269cf64cad44/lib/core/config.rb#L385-L416 | train |
coralnexus/nucleon | lib/core/config.rb | Nucleon.Config.get | def get(keys, default = nil, format = false)
return fetch(@properties, symbol_array(array(keys).flatten), default, format)
end | ruby | def get(keys, default = nil, format = false)
return fetch(@properties, symbol_array(array(keys).flatten), default, format)
end | [
"def",
"get",
"(",
"keys",
",",
"default",
"=",
"nil",
",",
"format",
"=",
"false",
")",
"return",
"fetch",
"(",
"@properties",
",",
"symbol_array",
"(",
"array",
"(",
"keys",
")",
".",
"flatten",
")",
",",
"default",
",",
"format",
")",
"end"
] | Fetch value for key path in the configuration object.
* *Parameters*
- [Array<String, Symbol>, String, Symbol] *keys* Key path to fetch
- [ANY] *default* Default value is no value is found for key path
- [false, Symbol, String] *format* Format to filter final returned value or false for none
* *Returns*
- [ANY] Filtered value for key path from configuration object
* *Errors*
See:
- #fetch
See also:
- #array | [
"Fetch",
"value",
"for",
"key",
"path",
"in",
"the",
"configuration",
"object",
"."
] | 3a3c489251139c184e0884feaa55269cf64cad44 | https://github.com/coralnexus/nucleon/blob/3a3c489251139c184e0884feaa55269cf64cad44/lib/core/config.rb#L437-L439 | train |
coralnexus/nucleon | lib/core/config.rb | Nucleon.Config.set | def set(keys, value, delete_nil = false, &code) # :yields: key, value, existing
modify(@properties, symbol_array(array(keys).flatten), value, delete_nil, &code)
return self
end | ruby | def set(keys, value, delete_nil = false, &code) # :yields: key, value, existing
modify(@properties, symbol_array(array(keys).flatten), value, delete_nil, &code)
return self
end | [
"def",
"set",
"(",
"keys",
",",
"value",
",",
"delete_nil",
"=",
"false",
",",
"&",
"code",
")",
"modify",
"(",
"@properties",
",",
"symbol_array",
"(",
"array",
"(",
"keys",
")",
".",
"flatten",
")",
",",
"value",
",",
"delete_nil",
",",
"&",
"code",
")",
"return",
"self",
"end"
] | Set value for key path in the configuration object.
* *Parameters*
- [Array<String, Symbol>, String, Symbol] *keys* Key path to modify
- [ANY] *value* Value to set for key path
- [Boolean] *delete_nil* Delete nil value (serves as an internal way to delete properties)
* *Returns*
- [Nucleon::Config] Returns reference to self for compound operations
* *Errors*
* *Yields*
- [Symbol] *key* Configuration key to modify
- [ANY] *value* New value of configuration key
- [ANY] *existing* Existing value being replaced for the configuration key
See:
- #modify
See also:
- #array | [
"Set",
"value",
"for",
"key",
"path",
"in",
"the",
"configuration",
"object",
"."
] | 3a3c489251139c184e0884feaa55269cf64cad44 | https://github.com/coralnexus/nucleon/blob/3a3c489251139c184e0884feaa55269cf64cad44/lib/core/config.rb#L550-L553 | train |
coralnexus/nucleon | lib/core/config.rb | Nucleon.Config.append | def append(keys, value)
modify(@properties, symbol_array(array(keys).flatten), value, false) do |key, processed_value, existing|
if existing.is_a?(Array)
[ existing, processed_value ].flatten
else
[ processed_value ]
end
end
return self
end | ruby | def append(keys, value)
modify(@properties, symbol_array(array(keys).flatten), value, false) do |key, processed_value, existing|
if existing.is_a?(Array)
[ existing, processed_value ].flatten
else
[ processed_value ]
end
end
return self
end | [
"def",
"append",
"(",
"keys",
",",
"value",
")",
"modify",
"(",
"@properties",
",",
"symbol_array",
"(",
"array",
"(",
"keys",
")",
".",
"flatten",
")",
",",
"value",
",",
"false",
")",
"do",
"|",
"key",
",",
"processed_value",
",",
"existing",
"|",
"if",
"existing",
".",
"is_a?",
"(",
"Array",
")",
"[",
"existing",
",",
"processed_value",
"]",
".",
"flatten",
"else",
"[",
"processed_value",
"]",
"end",
"end",
"return",
"self",
"end"
] | Append a value for an array key path in the configuration object.
* *Parameters*
- [Array<String, Symbol>, String, Symbol] *keys* Key path to modify
- [ANY] *value* Value to set for key path
* *Returns*
- [Nucleon::Config] Returns reference to self for compound operations
* *Errors*
See:
- #modify
See also:
- #array | [
"Append",
"a",
"value",
"for",
"an",
"array",
"key",
"path",
"in",
"the",
"configuration",
"object",
"."
] | 3a3c489251139c184e0884feaa55269cf64cad44 | https://github.com/coralnexus/nucleon/blob/3a3c489251139c184e0884feaa55269cf64cad44/lib/core/config.rb#L572-L581 | train |
coralnexus/nucleon | lib/core/config.rb | Nucleon.Config.prepend | def prepend(keys, value, reverse = false)
modify(@properties, symbol_array(array(keys).flatten), value, false) do |key, processed_value, existing|
processed_value = processed_value.reverse if reverse && processed_value.is_a?(Array)
if existing.is_a?(Array)
[ processed_value, existing ].flatten
else
[ processed_value ]
end
end
return self
end | ruby | def prepend(keys, value, reverse = false)
modify(@properties, symbol_array(array(keys).flatten), value, false) do |key, processed_value, existing|
processed_value = processed_value.reverse if reverse && processed_value.is_a?(Array)
if existing.is_a?(Array)
[ processed_value, existing ].flatten
else
[ processed_value ]
end
end
return self
end | [
"def",
"prepend",
"(",
"keys",
",",
"value",
",",
"reverse",
"=",
"false",
")",
"modify",
"(",
"@properties",
",",
"symbol_array",
"(",
"array",
"(",
"keys",
")",
".",
"flatten",
")",
",",
"value",
",",
"false",
")",
"do",
"|",
"key",
",",
"processed_value",
",",
"existing",
"|",
"processed_value",
"=",
"processed_value",
".",
"reverse",
"if",
"reverse",
"&&",
"processed_value",
".",
"is_a?",
"(",
"Array",
")",
"if",
"existing",
".",
"is_a?",
"(",
"Array",
")",
"[",
"processed_value",
",",
"existing",
"]",
".",
"flatten",
"else",
"[",
"processed_value",
"]",
"end",
"end",
"return",
"self",
"end"
] | Prepend a value to an array key path in the configuration object.
* *Parameters*
- [Array<String, Symbol>, String, Symbol] *keys* Key path to modify
- [ANY] *value* Value to set for key path
- [Boolean] *reverse* Whether or not to reverse any input value arrays given before prepending
* *Returns*
- [Nucleon::Config] Returns reference to self for compound operations
* *Errors*
See:
- #modify
See also:
- #array | [
"Prepend",
"a",
"value",
"to",
"an",
"array",
"key",
"path",
"in",
"the",
"configuration",
"object",
"."
] | 3a3c489251139c184e0884feaa55269cf64cad44 | https://github.com/coralnexus/nucleon/blob/3a3c489251139c184e0884feaa55269cf64cad44/lib/core/config.rb#L601-L612 | train |
coralnexus/nucleon | lib/core/config.rb | Nucleon.Config.delete | def delete(keys, default = nil)
existing = modify(@properties, symbol_array(array(keys).flatten), nil, true)
return existing[:value] unless existing[:value].nil?
return default
end | ruby | def delete(keys, default = nil)
existing = modify(@properties, symbol_array(array(keys).flatten), nil, true)
return existing[:value] unless existing[:value].nil?
return default
end | [
"def",
"delete",
"(",
"keys",
",",
"default",
"=",
"nil",
")",
"existing",
"=",
"modify",
"(",
"@properties",
",",
"symbol_array",
"(",
"array",
"(",
"keys",
")",
".",
"flatten",
")",
",",
"nil",
",",
"true",
")",
"return",
"existing",
"[",
":value",
"]",
"unless",
"existing",
"[",
":value",
"]",
".",
"nil?",
"return",
"default",
"end"
] | Delete key path from the configuration object.
* *Parameters*
- [Array<String, Symbol>, String, Symbol] *keys* Key path to remove
- [ANY] *default* Default value to return if no existing value found
* *Returns*
- [ANY] Returns default or last value removed from configuration object
* *Errors*
See:
- #modify
See also:
- #array | [
"Delete",
"key",
"path",
"from",
"the",
"configuration",
"object",
"."
] | 3a3c489251139c184e0884feaa55269cf64cad44 | https://github.com/coralnexus/nucleon/blob/3a3c489251139c184e0884feaa55269cf64cad44/lib/core/config.rb#L652-L656 | train |
coralnexus/nucleon | lib/core/config.rb | Nucleon.Config.defaults | def defaults(defaults, options = {})
config = Config.new(options).set(:import_type, :default)
return import_base(defaults, config)
end | ruby | def defaults(defaults, options = {})
config = Config.new(options).set(:import_type, :default)
return import_base(defaults, config)
end | [
"def",
"defaults",
"(",
"defaults",
",",
"options",
"=",
"{",
"}",
")",
"config",
"=",
"Config",
".",
"new",
"(",
"options",
")",
".",
"set",
"(",
":import_type",
",",
":default",
")",
"return",
"import_base",
"(",
"defaults",
",",
"config",
")",
"end"
] | Set default property values in the configuration object if they don't exist.
If defaults are given as a string or symbol and the configuration object
has a lookup method implemented (corl gem) then the defaults will be
dynamically looked up and set.
* *Parameters*
- [String, Symbol, Array, Hash] *defaults* Data to set as defaults
- [Hash] *options* Import options
* *Returns*
- [Nucleon::Config] Returns reference to self for compound operations
* *Errors*
See:
- #import_base
See also:
- ::new
- #set | [
"Set",
"default",
"property",
"values",
"in",
"the",
"configuration",
"object",
"if",
"they",
"don",
"t",
"exist",
"."
] | 3a3c489251139c184e0884feaa55269cf64cad44 | https://github.com/coralnexus/nucleon/blob/3a3c489251139c184e0884feaa55269cf64cad44/lib/core/config.rb#L780-L783 | train |
coralnexus/nucleon | lib/core/config.rb | Nucleon.Config.symbol_array | def symbol_array(array)
result = []
array.each do |item|
result << item.to_sym unless item.nil?
end
result
end | ruby | def symbol_array(array)
result = []
array.each do |item|
result << item.to_sym unless item.nil?
end
result
end | [
"def",
"symbol_array",
"(",
"array",
")",
"result",
"=",
"[",
"]",
"array",
".",
"each",
"do",
"|",
"item",
"|",
"result",
"<<",
"item",
".",
"to_sym",
"unless",
"item",
".",
"nil?",
"end",
"result",
"end"
] | Return a symbolized array
* *Parameters*
- [Array<String, Symbol>] *array* Array of strings or symbols
* *Returns*
- [Array<Symbol>] Returns array of symbols
* *Errors* | [
"Return",
"a",
"symbolized",
"array"
] | 3a3c489251139c184e0884feaa55269cf64cad44 | https://github.com/coralnexus/nucleon/blob/3a3c489251139c184e0884feaa55269cf64cad44/lib/core/config.rb#L835-L841 | train |
OutlawAndy/stripe_local | lib/stripe_local/instance_delegation.rb | StripeLocal.InstanceDelegation.signup | def signup params
plan = params.delete( :plan )
lines = params.delete( :lines ) || []
_customer_ = Stripe::Customer.create( params )
lines.each do |(amount,desc)|
_customer_.add_invoice_item({currency: 'usd', amount: amount, description: desc})
end
_customer_.update_subscription({ plan: plan })
StripeLocal::Customer.create _customer_.to_hash.reverse_merge({model_id: self.id})
end | ruby | def signup params
plan = params.delete( :plan )
lines = params.delete( :lines ) || []
_customer_ = Stripe::Customer.create( params )
lines.each do |(amount,desc)|
_customer_.add_invoice_item({currency: 'usd', amount: amount, description: desc})
end
_customer_.update_subscription({ plan: plan })
StripeLocal::Customer.create _customer_.to_hash.reverse_merge({model_id: self.id})
end | [
"def",
"signup",
"params",
"plan",
"=",
"params",
".",
"delete",
"(",
":plan",
")",
"lines",
"=",
"params",
".",
"delete",
"(",
":lines",
")",
"||",
"[",
"]",
"_customer_",
"=",
"Stripe",
"::",
"Customer",
".",
"create",
"(",
"params",
")",
"lines",
".",
"each",
"do",
"|",
"(",
"amount",
",",
"desc",
")",
"|",
"_customer_",
".",
"add_invoice_item",
"(",
"{",
"currency",
":",
"'usd'",
",",
"amount",
":",
"amount",
",",
"description",
":",
"desc",
"}",
")",
"end",
"_customer_",
".",
"update_subscription",
"(",
"{",
"plan",
":",
"plan",
"}",
")",
"StripeLocal",
"::",
"Customer",
".",
"create",
"_customer_",
".",
"to_hash",
".",
"reverse_merge",
"(",
"{",
"model_id",
":",
"self",
".",
"id",
"}",
")",
"end"
] | ==this is the primary interface for subscribing.
params::
* +card+ (required) -> the token returned by stripe.js
* +plan+ (required) -> the id of the plan being subscribed to
* +email+ (optional) -> the client's email address
* +description+ (optional) -> a description to attach to the stripe object for future reference
* +coupon+ (optional) -> the id of a coupon if the subscription should be discounted
* +lines+ (optional) -> an array of (amount,description) tuples
example::
:card => "tok_abc123",
:plan => "MySaaS",
:email => subscriber.email,
:description => "a one year subscription to our flagship service at $99.00 per month"
:lines => [
[ 20000, "a one time setup fee of $200.00 for new members" ]
] | [
"==",
"this",
"is",
"the",
"primary",
"interface",
"for",
"subscribing",
"."
] | 78b685d1b35a848e02d19e4c57015f2a02fdc882 | https://github.com/OutlawAndy/stripe_local/blob/78b685d1b35a848e02d19e4c57015f2a02fdc882/lib/stripe_local/instance_delegation.rb#L20-L32 | train |
barkerest/barkest_core | lib/barkest_core/extensions/axlsx_extenstions.rb | Axlsx.Package.simple | def simple(name = nil)
workbook.add_worksheet(name: name || 'Sheet 1') do |sheet|
yield sheet, workbook.predefined_styles if block_given?
sheet.add_row
end
end | ruby | def simple(name = nil)
workbook.add_worksheet(name: name || 'Sheet 1') do |sheet|
yield sheet, workbook.predefined_styles if block_given?
sheet.add_row
end
end | [
"def",
"simple",
"(",
"name",
"=",
"nil",
")",
"workbook",
".",
"add_worksheet",
"(",
"name",
":",
"name",
"||",
"'Sheet 1'",
")",
"do",
"|",
"sheet",
"|",
"yield",
"sheet",
",",
"workbook",
".",
"predefined_styles",
"if",
"block_given?",
"sheet",
".",
"add_row",
"end",
"end"
] | Creates a simple workbook with one sheet.
Predefines multiple styles that can be used to format cells.
The +sheet+ and +styles+ are yielded to the provided block.
See Axlsx::Workbook#predefined_styles for a list of predefined styles. | [
"Creates",
"a",
"simple",
"workbook",
"with",
"one",
"sheet",
"."
] | 3eeb025ec870888cacbc9bae252a39ebf9295f61 | https://github.com/barkerest/barkest_core/blob/3eeb025ec870888cacbc9bae252a39ebf9295f61/lib/barkest_core/extensions/axlsx_extenstions.rb#L19-L24 | train |
barkerest/barkest_core | lib/barkest_core/extensions/axlsx_extenstions.rb | Axlsx.Workbook.predefined_styles | def predefined_styles
@predefined_styles ||=
begin
tmp = {}
styles do |s|
tmp = {
bold: s.add_style(b: true, alignment: { vertical: :top }),
date: s.add_style(format_code: 'mm/dd/yyyy', alignment: { vertical: :top }),
float: s.add_style(format_code: '#,##0.00', alignment: { vertical: :top }),
integer: s.add_style(format_code: '#,##0', alignment: { vertical: :top }),
percent: s.add_style(num_fmt: 9, alignment: { vertical: :top }),
currency: s.add_style(num_fmt: 7, alignment: { vertical: :top }),
text: s.add_style(format_code: '@', alignment: { vertical: :top }),
wrapped: s.add_style(alignment: { wrap_text: true, vertical: :top }),
normal: s.add_style(alignment: { vertical: :top })
}
end
tmp
end
end | ruby | def predefined_styles
@predefined_styles ||=
begin
tmp = {}
styles do |s|
tmp = {
bold: s.add_style(b: true, alignment: { vertical: :top }),
date: s.add_style(format_code: 'mm/dd/yyyy', alignment: { vertical: :top }),
float: s.add_style(format_code: '#,##0.00', alignment: { vertical: :top }),
integer: s.add_style(format_code: '#,##0', alignment: { vertical: :top }),
percent: s.add_style(num_fmt: 9, alignment: { vertical: :top }),
currency: s.add_style(num_fmt: 7, alignment: { vertical: :top }),
text: s.add_style(format_code: '@', alignment: { vertical: :top }),
wrapped: s.add_style(alignment: { wrap_text: true, vertical: :top }),
normal: s.add_style(alignment: { vertical: :top })
}
end
tmp
end
end | [
"def",
"predefined_styles",
"@predefined_styles",
"||=",
"begin",
"tmp",
"=",
"{",
"}",
"styles",
"do",
"|",
"s",
"|",
"tmp",
"=",
"{",
"bold",
":",
"s",
".",
"add_style",
"(",
"b",
":",
"true",
",",
"alignment",
":",
"{",
"vertical",
":",
":top",
"}",
")",
",",
"date",
":",
"s",
".",
"add_style",
"(",
"format_code",
":",
"'mm/dd/yyyy'",
",",
"alignment",
":",
"{",
"vertical",
":",
":top",
"}",
")",
",",
"float",
":",
"s",
".",
"add_style",
"(",
"format_code",
":",
"'#,##0.00'",
",",
"alignment",
":",
"{",
"vertical",
":",
":top",
"}",
")",
",",
"integer",
":",
"s",
".",
"add_style",
"(",
"format_code",
":",
"'#,##0'",
",",
"alignment",
":",
"{",
"vertical",
":",
":top",
"}",
")",
",",
"percent",
":",
"s",
".",
"add_style",
"(",
"num_fmt",
":",
"9",
",",
"alignment",
":",
"{",
"vertical",
":",
":top",
"}",
")",
",",
"currency",
":",
"s",
".",
"add_style",
"(",
"num_fmt",
":",
"7",
",",
"alignment",
":",
"{",
"vertical",
":",
":top",
"}",
")",
",",
"text",
":",
"s",
".",
"add_style",
"(",
"format_code",
":",
"'@'",
",",
"alignment",
":",
"{",
"vertical",
":",
":top",
"}",
")",
",",
"wrapped",
":",
"s",
".",
"add_style",
"(",
"alignment",
":",
"{",
"wrap_text",
":",
"true",
",",
"vertical",
":",
":top",
"}",
")",
",",
"normal",
":",
"s",
".",
"add_style",
"(",
"alignment",
":",
"{",
"vertical",
":",
":top",
"}",
")",
"}",
"end",
"tmp",
"end",
"end"
] | Gets the predefined style list.
The +predefined_styles+ hash contains :bold, :date, :float, :integer, :percent, :currency, :text, :wrapped, and :normal
styles for you to use. | [
"Gets",
"the",
"predefined",
"style",
"list",
"."
] | 3eeb025ec870888cacbc9bae252a39ebf9295f61 | https://github.com/barkerest/barkest_core/blob/3eeb025ec870888cacbc9bae252a39ebf9295f61/lib/barkest_core/extensions/axlsx_extenstions.rb#L50-L69 | train |
barkerest/barkest_core | lib/barkest_core/extensions/axlsx_extenstions.rb | Axlsx.Worksheet.add_combined_row | def add_combined_row(row_data, keys = [ :value, :style, :type ])
val_index = keys.index(:value) || keys.index('value')
style_index = keys.index(:style) || keys.index('style')
type_index = keys.index(:type) || keys.index('type')
raise ArgumentError.new('Missing :value key') unless val_index
values = row_data.map{|v| v.is_a?(Array) ? v[val_index] : v }
styles = style_index ? row_data.map{ |v| v.is_a?(Array) ? v[style_index] : nil } : []
types = type_index ? row_data.map{ |v| v.is_a?(Array) ? v[type_index] : nil } : []
# allows specifying the style as just a symbol.
styles.each_with_index do |style,index|
if style.is_a?(String) || style.is_a?(Symbol)
styles[index] = workbook.predefined_styles[style.to_sym]
end
end
add_row values, style: styles, types: types
end | ruby | def add_combined_row(row_data, keys = [ :value, :style, :type ])
val_index = keys.index(:value) || keys.index('value')
style_index = keys.index(:style) || keys.index('style')
type_index = keys.index(:type) || keys.index('type')
raise ArgumentError.new('Missing :value key') unless val_index
values = row_data.map{|v| v.is_a?(Array) ? v[val_index] : v }
styles = style_index ? row_data.map{ |v| v.is_a?(Array) ? v[style_index] : nil } : []
types = type_index ? row_data.map{ |v| v.is_a?(Array) ? v[type_index] : nil } : []
# allows specifying the style as just a symbol.
styles.each_with_index do |style,index|
if style.is_a?(String) || style.is_a?(Symbol)
styles[index] = workbook.predefined_styles[style.to_sym]
end
end
add_row values, style: styles, types: types
end | [
"def",
"add_combined_row",
"(",
"row_data",
",",
"keys",
"=",
"[",
":value",
",",
":style",
",",
":type",
"]",
")",
"val_index",
"=",
"keys",
".",
"index",
"(",
":value",
")",
"||",
"keys",
".",
"index",
"(",
"'value'",
")",
"style_index",
"=",
"keys",
".",
"index",
"(",
":style",
")",
"||",
"keys",
".",
"index",
"(",
"'style'",
")",
"type_index",
"=",
"keys",
".",
"index",
"(",
":type",
")",
"||",
"keys",
".",
"index",
"(",
"'type'",
")",
"raise",
"ArgumentError",
".",
"new",
"(",
"'Missing :value key'",
")",
"unless",
"val_index",
"values",
"=",
"row_data",
".",
"map",
"{",
"|",
"v",
"|",
"v",
".",
"is_a?",
"(",
"Array",
")",
"?",
"v",
"[",
"val_index",
"]",
":",
"v",
"}",
"styles",
"=",
"style_index",
"?",
"row_data",
".",
"map",
"{",
"|",
"v",
"|",
"v",
".",
"is_a?",
"(",
"Array",
")",
"?",
"v",
"[",
"style_index",
"]",
":",
"nil",
"}",
":",
"[",
"]",
"types",
"=",
"type_index",
"?",
"row_data",
".",
"map",
"{",
"|",
"v",
"|",
"v",
".",
"is_a?",
"(",
"Array",
")",
"?",
"v",
"[",
"type_index",
"]",
":",
"nil",
"}",
":",
"[",
"]",
"styles",
".",
"each_with_index",
"do",
"|",
"style",
",",
"index",
"|",
"if",
"style",
".",
"is_a?",
"(",
"String",
")",
"||",
"style",
".",
"is_a?",
"(",
"Symbol",
")",
"styles",
"[",
"index",
"]",
"=",
"workbook",
".",
"predefined_styles",
"[",
"style",
".",
"to_sym",
"]",
"end",
"end",
"add_row",
"values",
",",
"style",
":",
"styles",
",",
"types",
":",
"types",
"end"
] | Adds a row to the worksheet with combined data.
Currently we support specifying the +values+, +styles+, and +types+ using this method.
The +row_data+ value should be an array of arrays.
Each subarray represents a value in the row with up to three values specifying the +value+, +style+, and +type+.
Value is the only item required.
[['Value 1', :bold, :string], ['Value 2'], ['Value 3', nil, :string]]
In fact, if a subarray is replaced by a value, it is treated the same as an array only containing that value.
[['Value 1', :bold, :string], 'Value 2', ['Value 3', nil, :string]]
The +keys+ parameter defines the location of the data elements within the sub arrays.
The default would be [ :value, :style, :type ]. If your array happens to have additional data or data arranged
in a different format, you can set this to anything you like to get the method to process your data
appropriately.
keys = [ :ignored, :value, :ignored, :ignored, :style, :ignored, :type ]
Styles can be specified as a symbol to use the predefined styles, or as a style object you created. | [
"Adds",
"a",
"row",
"to",
"the",
"worksheet",
"with",
"combined",
"data",
"."
] | 3eeb025ec870888cacbc9bae252a39ebf9295f61 | https://github.com/barkerest/barkest_core/blob/3eeb025ec870888cacbc9bae252a39ebf9295f61/lib/barkest_core/extensions/axlsx_extenstions.rb#L135-L153 | train |
jinx/migrate | spec/csv/join/join_helper.rb | Jinx.JoinHelper.join | def join(source, target, *fields, &block)
FileUtils.rm_rf OUTPUT
sf = File.expand_path("#{source}.csv", File.dirname(__FILE__))
tf = File.expand_path("#{target}.csv", File.dirname(__FILE__))
Jinx::CsvIO.join(sf, :to => tf, :for => fields, :as => OUTPUT, &block)
if File.exists?(OUTPUT) then
File.readlines(OUTPUT).map do |line|
line.chomp.split(',').map { |s| s unless s.blank? }
end
else
Array::EMPTY_ARRAY
end
end | ruby | def join(source, target, *fields, &block)
FileUtils.rm_rf OUTPUT
sf = File.expand_path("#{source}.csv", File.dirname(__FILE__))
tf = File.expand_path("#{target}.csv", File.dirname(__FILE__))
Jinx::CsvIO.join(sf, :to => tf, :for => fields, :as => OUTPUT, &block)
if File.exists?(OUTPUT) then
File.readlines(OUTPUT).map do |line|
line.chomp.split(',').map { |s| s unless s.blank? }
end
else
Array::EMPTY_ARRAY
end
end | [
"def",
"join",
"(",
"source",
",",
"target",
",",
"*",
"fields",
",",
"&",
"block",
")",
"FileUtils",
".",
"rm_rf",
"OUTPUT",
"sf",
"=",
"File",
".",
"expand_path",
"(",
"\"#{source}.csv\"",
",",
"File",
".",
"dirname",
"(",
"__FILE__",
")",
")",
"tf",
"=",
"File",
".",
"expand_path",
"(",
"\"#{target}.csv\"",
",",
"File",
".",
"dirname",
"(",
"__FILE__",
")",
")",
"Jinx",
"::",
"CsvIO",
".",
"join",
"(",
"sf",
",",
":to",
"=>",
"tf",
",",
":for",
"=>",
"fields",
",",
":as",
"=>",
"OUTPUT",
",",
"&",
"block",
")",
"if",
"File",
".",
"exists?",
"(",
"OUTPUT",
")",
"then",
"File",
".",
"readlines",
"(",
"OUTPUT",
")",
".",
"map",
"do",
"|",
"line",
"|",
"line",
".",
"chomp",
".",
"split",
"(",
"','",
")",
".",
"map",
"{",
"|",
"s",
"|",
"s",
"unless",
"s",
".",
"blank?",
"}",
"end",
"else",
"Array",
"::",
"EMPTY_ARRAY",
"end",
"end"
] | Joins the given source fixture to the target fixture on the specified fields.
@param [Symbol] source the source file fixture in the join spec directory
@param [Symbol] target the target file fixture in the join spec directory
@param [<String>] fields the source fields (default is all source fields)
@return [<<String>>] the output records | [
"Joins",
"the",
"given",
"source",
"fixture",
"to",
"the",
"target",
"fixture",
"on",
"the",
"specified",
"fields",
"."
] | 309957a470d72da3bd074f8173dbbe2f12449883 | https://github.com/jinx/migrate/blob/309957a470d72da3bd074f8173dbbe2f12449883/spec/csv/join/join_helper.rb#L21-L33 | train |
tatemae/muck-engine | lib/muck-engine/form_builder.rb | MuckEngine.FormBuilder.state_select | def state_select(method, options = {}, html_options = {}, additional_state = nil)
country_id_field_name = options.delete(:country_id) || 'country_id'
country_id = get_instance_object_value(country_id_field_name)
@states = country_id.nil? ? [] : (additional_state ? [additional_state] : []) + State.find(:all, :conditions => ["country_id = ?", country_id], :order => "name asc")
self.menu_select(method, I18n.t('muck.engine.choose_state'), @states, options.merge(:prompt => I18n.t('muck.engine.select_state_prompt'), :wrapper_id => 'states-container'), html_options.merge(:id => 'states'))
end | ruby | def state_select(method, options = {}, html_options = {}, additional_state = nil)
country_id_field_name = options.delete(:country_id) || 'country_id'
country_id = get_instance_object_value(country_id_field_name)
@states = country_id.nil? ? [] : (additional_state ? [additional_state] : []) + State.find(:all, :conditions => ["country_id = ?", country_id], :order => "name asc")
self.menu_select(method, I18n.t('muck.engine.choose_state'), @states, options.merge(:prompt => I18n.t('muck.engine.select_state_prompt'), :wrapper_id => 'states-container'), html_options.merge(:id => 'states'))
end | [
"def",
"state_select",
"(",
"method",
",",
"options",
"=",
"{",
"}",
",",
"html_options",
"=",
"{",
"}",
",",
"additional_state",
"=",
"nil",
")",
"country_id_field_name",
"=",
"options",
".",
"delete",
"(",
":country_id",
")",
"||",
"'country_id'",
"country_id",
"=",
"get_instance_object_value",
"(",
"country_id_field_name",
")",
"@states",
"=",
"country_id",
".",
"nil?",
"?",
"[",
"]",
":",
"(",
"additional_state",
"?",
"[",
"additional_state",
"]",
":",
"[",
"]",
")",
"+",
"State",
".",
"find",
"(",
":all",
",",
":conditions",
"=>",
"[",
"\"country_id = ?\"",
",",
"country_id",
"]",
",",
":order",
"=>",
"\"name asc\"",
")",
"self",
".",
"menu_select",
"(",
"method",
",",
"I18n",
".",
"t",
"(",
"'muck.engine.choose_state'",
")",
",",
"@states",
",",
"options",
".",
"merge",
"(",
":prompt",
"=>",
"I18n",
".",
"t",
"(",
"'muck.engine.select_state_prompt'",
")",
",",
":wrapper_id",
"=>",
"'states-container'",
")",
",",
"html_options",
".",
"merge",
"(",
":id",
"=>",
"'states'",
")",
")",
"end"
] | creates a select control with states. Default id is 'states'. If 'retain' is passed for the class value the value of this
control will be written into a cookie with the key 'states'. | [
"creates",
"a",
"select",
"control",
"with",
"states",
".",
"Default",
"id",
"is",
"states",
".",
"If",
"retain",
"is",
"passed",
"for",
"the",
"class",
"value",
"the",
"value",
"of",
"this",
"control",
"will",
"be",
"written",
"into",
"a",
"cookie",
"with",
"the",
"key",
"states",
"."
] | 41fc072dce3a365b3ce4a73d4f60a4ff24026d51 | https://github.com/tatemae/muck-engine/blob/41fc072dce3a365b3ce4a73d4f60a4ff24026d51/lib/muck-engine/form_builder.rb#L149-L154 | train |
tatemae/muck-engine | lib/muck-engine/form_builder.rb | MuckEngine.FormBuilder.country_select | def country_select(method, options = {}, html_options = {}, additional_country = nil)
@countries ||= (additional_country ? [additional_country] : []) + Country.find(:all, :order => 'sort, name asc')
self.menu_select(method, I18n.t('muck.engine.choose_country'), @countries, options.merge(:prompt => I18n.t('muck.engine.select_country_prompt'), :wrapper_id => 'countries-container'), html_options.merge(:id => 'countries'))
end | ruby | def country_select(method, options = {}, html_options = {}, additional_country = nil)
@countries ||= (additional_country ? [additional_country] : []) + Country.find(:all, :order => 'sort, name asc')
self.menu_select(method, I18n.t('muck.engine.choose_country'), @countries, options.merge(:prompt => I18n.t('muck.engine.select_country_prompt'), :wrapper_id => 'countries-container'), html_options.merge(:id => 'countries'))
end | [
"def",
"country_select",
"(",
"method",
",",
"options",
"=",
"{",
"}",
",",
"html_options",
"=",
"{",
"}",
",",
"additional_country",
"=",
"nil",
")",
"@countries",
"||=",
"(",
"additional_country",
"?",
"[",
"additional_country",
"]",
":",
"[",
"]",
")",
"+",
"Country",
".",
"find",
"(",
":all",
",",
":order",
"=>",
"'sort, name asc'",
")",
"self",
".",
"menu_select",
"(",
"method",
",",
"I18n",
".",
"t",
"(",
"'muck.engine.choose_country'",
")",
",",
"@countries",
",",
"options",
".",
"merge",
"(",
":prompt",
"=>",
"I18n",
".",
"t",
"(",
"'muck.engine.select_country_prompt'",
")",
",",
":wrapper_id",
"=>",
"'countries-container'",
")",
",",
"html_options",
".",
"merge",
"(",
":id",
"=>",
"'countries'",
")",
")",
"end"
] | creates a select control with countries. Default id is 'countries'. If 'retain' is passed for the class value the value of this
control will be written into a cookie with the key 'countries'. | [
"creates",
"a",
"select",
"control",
"with",
"countries",
".",
"Default",
"id",
"is",
"countries",
".",
"If",
"retain",
"is",
"passed",
"for",
"the",
"class",
"value",
"the",
"value",
"of",
"this",
"control",
"will",
"be",
"written",
"into",
"a",
"cookie",
"with",
"the",
"key",
"countries",
"."
] | 41fc072dce3a365b3ce4a73d4f60a4ff24026d51 | https://github.com/tatemae/muck-engine/blob/41fc072dce3a365b3ce4a73d4f60a4ff24026d51/lib/muck-engine/form_builder.rb#L158-L161 | train |
tatemae/muck-engine | lib/muck-engine/form_builder.rb | MuckEngine.FormBuilder.language_select | def language_select(method, options = {}, html_options = {}, additional_language = nil)
@languages ||= (additional_language ? [additional_language] : []) + Language.find(:all, :order => 'name asc')
self.menu_select(method, I18n.t('muck.engine.choose_language'), @languages, options.merge(:prompt => I18n.t('muck.engine.select_language_prompt'), :wrapper_id => 'languages-container'), html_options.merge(:id => 'languages'))
end | ruby | def language_select(method, options = {}, html_options = {}, additional_language = nil)
@languages ||= (additional_language ? [additional_language] : []) + Language.find(:all, :order => 'name asc')
self.menu_select(method, I18n.t('muck.engine.choose_language'), @languages, options.merge(:prompt => I18n.t('muck.engine.select_language_prompt'), :wrapper_id => 'languages-container'), html_options.merge(:id => 'languages'))
end | [
"def",
"language_select",
"(",
"method",
",",
"options",
"=",
"{",
"}",
",",
"html_options",
"=",
"{",
"}",
",",
"additional_language",
"=",
"nil",
")",
"@languages",
"||=",
"(",
"additional_language",
"?",
"[",
"additional_language",
"]",
":",
"[",
"]",
")",
"+",
"Language",
".",
"find",
"(",
":all",
",",
":order",
"=>",
"'name asc'",
")",
"self",
".",
"menu_select",
"(",
"method",
",",
"I18n",
".",
"t",
"(",
"'muck.engine.choose_language'",
")",
",",
"@languages",
",",
"options",
".",
"merge",
"(",
":prompt",
"=>",
"I18n",
".",
"t",
"(",
"'muck.engine.select_language_prompt'",
")",
",",
":wrapper_id",
"=>",
"'languages-container'",
")",
",",
"html_options",
".",
"merge",
"(",
":id",
"=>",
"'languages'",
")",
")",
"end"
] | creates a select control with languages. Default id is 'languages'. If 'retain' is passed for the class value the value of this
control will be written into a cookie with the key 'languages'. | [
"creates",
"a",
"select",
"control",
"with",
"languages",
".",
"Default",
"id",
"is",
"languages",
".",
"If",
"retain",
"is",
"passed",
"for",
"the",
"class",
"value",
"the",
"value",
"of",
"this",
"control",
"will",
"be",
"written",
"into",
"a",
"cookie",
"with",
"the",
"key",
"languages",
"."
] | 41fc072dce3a365b3ce4a73d4f60a4ff24026d51 | https://github.com/tatemae/muck-engine/blob/41fc072dce3a365b3ce4a73d4f60a4ff24026d51/lib/muck-engine/form_builder.rb#L165-L168 | train |
barkerest/incline | lib/incline/auth_engine_base.rb | Incline.AuthEngineBase.add_success_to | def add_success_to(user, message, client_ip) # :doc:
Incline::Log::info "LOGIN(#{user}) SUCCESS FROM #{client_ip}: #{message}"
purge_old_history_for user
user.login_histories.create(ip_address: client_ip, successful: true, message: message)
end | ruby | def add_success_to(user, message, client_ip) # :doc:
Incline::Log::info "LOGIN(#{user}) SUCCESS FROM #{client_ip}: #{message}"
purge_old_history_for user
user.login_histories.create(ip_address: client_ip, successful: true, message: message)
end | [
"def",
"add_success_to",
"(",
"user",
",",
"message",
",",
"client_ip",
")",
"Incline",
"::",
"Log",
"::",
"info",
"\"LOGIN(#{user}) SUCCESS FROM #{client_ip}: #{message}\"",
"purge_old_history_for",
"user",
"user",
".",
"login_histories",
".",
"create",
"(",
"ip_address",
":",
"client_ip",
",",
"successful",
":",
"true",
",",
"message",
":",
"message",
")",
"end"
] | Logs a success message for a user. | [
"Logs",
"a",
"success",
"message",
"for",
"a",
"user",
"."
] | 1ff08db7aa8ab7f86b223268b700bc67d15bb8aa | https://github.com/barkerest/incline/blob/1ff08db7aa8ab7f86b223268b700bc67d15bb8aa/lib/incline/auth_engine_base.rb#L53-L57 | train |
khiemns54/sp2db | lib/sp2db/config.rb | Sp2db.Config.credential= | def credential=cr
if File.exist?(cr) && File.file?(cr)
cr = File.read cr
end
@credential = case cr
when Hash, ActiveSupport::HashWithIndifferentAccess
cr
when String
JSON.parse cr
else
raise "Invalid data type"
end
end | ruby | def credential=cr
if File.exist?(cr) && File.file?(cr)
cr = File.read cr
end
@credential = case cr
when Hash, ActiveSupport::HashWithIndifferentAccess
cr
when String
JSON.parse cr
else
raise "Invalid data type"
end
end | [
"def",
"credential",
"=",
"cr",
"if",
"File",
".",
"exist?",
"(",
"cr",
")",
"&&",
"File",
".",
"file?",
"(",
"cr",
")",
"cr",
"=",
"File",
".",
"read",
"cr",
"end",
"@credential",
"=",
"case",
"cr",
"when",
"Hash",
",",
"ActiveSupport",
"::",
"HashWithIndifferentAccess",
"cr",
"when",
"String",
"JSON",
".",
"parse",
"cr",
"else",
"raise",
"\"Invalid data type\"",
"end",
"end"
] | File name or json string or hash | [
"File",
"name",
"or",
"json",
"string",
"or",
"hash"
] | 76c78df07ea19d6f1b5ff2e883ae206a0e94de27 | https://github.com/khiemns54/sp2db/blob/76c78df07ea19d6f1b5ff2e883ae206a0e94de27/lib/sp2db/config.rb#L53-L66 | train |
PragTob/wingtips | lib/wingtips/slide.rb | Wingtips.Slide.method_missing | def method_missing(method, *args, &blk)
if app_should_handle_method? method
app.send(method, *args, &blk)
else
super
end
end | ruby | def method_missing(method, *args, &blk)
if app_should_handle_method? method
app.send(method, *args, &blk)
else
super
end
end | [
"def",
"method_missing",
"(",
"method",
",",
"*",
"args",
",",
"&",
"blk",
")",
"if",
"app_should_handle_method?",
"method",
"app",
".",
"send",
"(",
"method",
",",
"*",
"args",
",",
"&",
"blk",
")",
"else",
"super",
"end",
"end"
] | copied from the URL implementation... weird but I want to have
classes not methods for this | [
"copied",
"from",
"the",
"URL",
"implementation",
"...",
"weird",
"but",
"I",
"want",
"to",
"have",
"classes",
"not",
"methods",
"for",
"this"
] | df47ecdf19fdd9e7091e96232a24c2d7fb43a3ab | https://github.com/PragTob/wingtips/blob/df47ecdf19fdd9e7091e96232a24c2d7fb43a3ab/lib/wingtips/slide.rb#L43-L49 | train |
right-solutions/usman | app/helpers/usman/authentication_helper.rb | Usman.AuthenticationHelper.require_super_admin | def require_super_admin
unless @current_user.super_admin?
text = "#{I18n.t("authentication.permission_denied.heading")}: #{I18n.t("authentication.permission_denied.message")}"
set_flash_message(text, :error, false) if defined?(flash) && flash
redirect_or_popup_to_default_sign_in_page(false)
end
end | ruby | def require_super_admin
unless @current_user.super_admin?
text = "#{I18n.t("authentication.permission_denied.heading")}: #{I18n.t("authentication.permission_denied.message")}"
set_flash_message(text, :error, false) if defined?(flash) && flash
redirect_or_popup_to_default_sign_in_page(false)
end
end | [
"def",
"require_super_admin",
"unless",
"@current_user",
".",
"super_admin?",
"text",
"=",
"\"#{I18n.t(\"authentication.permission_denied.heading\")}: #{I18n.t(\"authentication.permission_denied.message\")}\"",
"set_flash_message",
"(",
"text",
",",
":error",
",",
"false",
")",
"if",
"defined?",
"(",
"flash",
")",
"&&",
"flash",
"redirect_or_popup_to_default_sign_in_page",
"(",
"false",
")",
"end",
"end"
] | This method is usually used as a before filter from admin controllers to ensure that the logged in user is a super admin | [
"This",
"method",
"is",
"usually",
"used",
"as",
"a",
"before",
"filter",
"from",
"admin",
"controllers",
"to",
"ensure",
"that",
"the",
"logged",
"in",
"user",
"is",
"a",
"super",
"admin"
] | 66bc427a03d0ed96ab7239c0b3969d566251a7f7 | https://github.com/right-solutions/usman/blob/66bc427a03d0ed96ab7239c0b3969d566251a7f7/app/helpers/usman/authentication_helper.rb#L111-L117 | train |
pjb3/curtain | lib/curtain/rendering.rb | Curtain.Rendering.render | def render(*args)
name = get_template_name(*args)
locals = args.last.is_a?(Hash) ? args.last : {}
# TODO: Cache Template objects
template_file = self.class.find_template(name)
ext = template_file.split('.').last
orig_buffer = @output_buffer
@output_buffer = Curtain::OutputBuffer.new
case ext
when 'slim'
template = ::Slim::Template.new(template_file, :buffer => '@output_buffer', :use_html_safe => true, :disable_capture => true, :generator => Temple::Generators::RailsOutputBuffer )
when 'erb'
template = ::Curtain::ErubisTemplate.new(template_file, :buffer => '@output_buffer', :use_html_safe => true, :disable_capture => true, :generator => Temple::Generators::RailsOutputBuffer )
else
raise "Curtain cannot process .#{ext} templates"
end
template.render(self, variables.merge(locals))
@output_buffer
ensure
@output_buffer = orig_buffer
end | ruby | def render(*args)
name = get_template_name(*args)
locals = args.last.is_a?(Hash) ? args.last : {}
# TODO: Cache Template objects
template_file = self.class.find_template(name)
ext = template_file.split('.').last
orig_buffer = @output_buffer
@output_buffer = Curtain::OutputBuffer.new
case ext
when 'slim'
template = ::Slim::Template.new(template_file, :buffer => '@output_buffer', :use_html_safe => true, :disable_capture => true, :generator => Temple::Generators::RailsOutputBuffer )
when 'erb'
template = ::Curtain::ErubisTemplate.new(template_file, :buffer => '@output_buffer', :use_html_safe => true, :disable_capture => true, :generator => Temple::Generators::RailsOutputBuffer )
else
raise "Curtain cannot process .#{ext} templates"
end
template.render(self, variables.merge(locals))
@output_buffer
ensure
@output_buffer = orig_buffer
end | [
"def",
"render",
"(",
"*",
"args",
")",
"name",
"=",
"get_template_name",
"(",
"*",
"args",
")",
"locals",
"=",
"args",
".",
"last",
".",
"is_a?",
"(",
"Hash",
")",
"?",
"args",
".",
"last",
":",
"{",
"}",
"template_file",
"=",
"self",
".",
"class",
".",
"find_template",
"(",
"name",
")",
"ext",
"=",
"template_file",
".",
"split",
"(",
"'.'",
")",
".",
"last",
"orig_buffer",
"=",
"@output_buffer",
"@output_buffer",
"=",
"Curtain",
"::",
"OutputBuffer",
".",
"new",
"case",
"ext",
"when",
"'slim'",
"template",
"=",
"::",
"Slim",
"::",
"Template",
".",
"new",
"(",
"template_file",
",",
":buffer",
"=>",
"'@output_buffer'",
",",
":use_html_safe",
"=>",
"true",
",",
":disable_capture",
"=>",
"true",
",",
":generator",
"=>",
"Temple",
"::",
"Generators",
"::",
"RailsOutputBuffer",
")",
"when",
"'erb'",
"template",
"=",
"::",
"Curtain",
"::",
"ErubisTemplate",
".",
"new",
"(",
"template_file",
",",
":buffer",
"=>",
"'@output_buffer'",
",",
":use_html_safe",
"=>",
"true",
",",
":disable_capture",
"=>",
"true",
",",
":generator",
"=>",
"Temple",
"::",
"Generators",
"::",
"RailsOutputBuffer",
")",
"else",
"raise",
"\"Curtain cannot process .#{ext} templates\"",
"end",
"template",
".",
"render",
"(",
"self",
",",
"variables",
".",
"merge",
"(",
"locals",
")",
")",
"@output_buffer",
"ensure",
"@output_buffer",
"=",
"orig_buffer",
"end"
] | Renders the template
@example Render the default template
view.render
@example Render the foo template
view.render "foo.slim"
@example You can use symbols and omit the extension
view.render :foo
@example You can specify what the local variables for the template should be
view.render :foo, :bar => "baz"
@example You can use the default template an specify locals
view.render :bar => "baz"
@param [String, Symbol] name The name of the template.
The extension can be omitted.
This parameter can be omiitted and the default template will be used.
@param [Hash] locals
@return [String] The result of rendering the template
@see #default_template_name | [
"Renders",
"the",
"template"
] | ab4f3dccea9b887148689084137f1375278f2dcf | https://github.com/pjb3/curtain/blob/ab4f3dccea9b887148689084137f1375278f2dcf/lib/curtain/rendering.rb#L30-L53 | train |
Bastes/CellularMap | lib/cellular_map/map.rb | CellularMap.Map.[] | def [](x, y)
if x.respond_to?(:to_i) && y.respond_to?(:to_i)
Cell.new(x, y, self)
else
Zone.new(x, y, self)
end
end | ruby | def [](x, y)
if x.respond_to?(:to_i) && y.respond_to?(:to_i)
Cell.new(x, y, self)
else
Zone.new(x, y, self)
end
end | [
"def",
"[]",
"(",
"x",
",",
"y",
")",
"if",
"x",
".",
"respond_to?",
"(",
":to_i",
")",
"&&",
"y",
".",
"respond_to?",
"(",
":to_i",
")",
"Cell",
".",
"new",
"(",
"x",
",",
"y",
",",
"self",
")",
"else",
"Zone",
".",
"new",
"(",
"x",
",",
"y",
",",
"self",
")",
"end",
"end"
] | Accessing a cell or a zone. | [
"Accessing",
"a",
"cell",
"or",
"a",
"zone",
"."
] | e9cfa44ce820b16cdc5ca5b59291e80e53363d1f | https://github.com/Bastes/CellularMap/blob/e9cfa44ce820b16cdc5ca5b59291e80e53363d1f/lib/cellular_map/map.rb#L21-L27 | train |
Bastes/CellularMap | lib/cellular_map/map.rb | CellularMap.Map.[]= | def []=(x, y, content)
if content.nil?
@store.delete([x, y]) && nil
else
@store[[x, y]] = content
end
end | ruby | def []=(x, y, content)
if content.nil?
@store.delete([x, y]) && nil
else
@store[[x, y]] = content
end
end | [
"def",
"[]=",
"(",
"x",
",",
"y",
",",
"content",
")",
"if",
"content",
".",
"nil?",
"@store",
".",
"delete",
"(",
"[",
"x",
",",
"y",
"]",
")",
"&&",
"nil",
"else",
"@store",
"[",
"[",
"x",
",",
"y",
"]",
"]",
"=",
"content",
"end",
"end"
] | Putting new content in a cell. | [
"Putting",
"new",
"content",
"in",
"a",
"cell",
"."
] | e9cfa44ce820b16cdc5ca5b59291e80e53363d1f | https://github.com/Bastes/CellularMap/blob/e9cfa44ce820b16cdc5ca5b59291e80e53363d1f/lib/cellular_map/map.rb#L30-L36 | train |
codescrum/bebox | lib/bebox/wizards/node_wizard.rb | Bebox.NodeWizard.create_new_node | def create_new_node(project_root, environment)
# Ask the hostname for node
hostname = ask_not_existing_hostname(project_root, environment)
# Ask IP for node
ip = ask_ip(environment)
# Node creation
node = Bebox::Node.new(environment, project_root, hostname, ip)
output = node.create
ok _('wizard.node.creation_success')
return output
end | ruby | def create_new_node(project_root, environment)
# Ask the hostname for node
hostname = ask_not_existing_hostname(project_root, environment)
# Ask IP for node
ip = ask_ip(environment)
# Node creation
node = Bebox::Node.new(environment, project_root, hostname, ip)
output = node.create
ok _('wizard.node.creation_success')
return output
end | [
"def",
"create_new_node",
"(",
"project_root",
",",
"environment",
")",
"hostname",
"=",
"ask_not_existing_hostname",
"(",
"project_root",
",",
"environment",
")",
"ip",
"=",
"ask_ip",
"(",
"environment",
")",
"node",
"=",
"Bebox",
"::",
"Node",
".",
"new",
"(",
"environment",
",",
"project_root",
",",
"hostname",
",",
"ip",
")",
"output",
"=",
"node",
".",
"create",
"ok",
"_",
"(",
"'wizard.node.creation_success'",
")",
"return",
"output",
"end"
] | Create a new node | [
"Create",
"a",
"new",
"node"
] | 0d19315847103341e599d32837ab0bd75524e5be | https://github.com/codescrum/bebox/blob/0d19315847103341e599d32837ab0bd75524e5be/lib/bebox/wizards/node_wizard.rb#L9-L19 | train |
codescrum/bebox | lib/bebox/wizards/node_wizard.rb | Bebox.NodeWizard.remove_node | def remove_node(project_root, environment, hostname)
# Ask for a node to remove
nodes = Bebox::Node.list(project_root, environment, 'nodes')
if nodes.count > 0
hostname = choose_option(nodes, _('wizard.node.choose_node'))
else
error _('wizard.node.no_nodes')%{environment: environment}
return true
end
# Ask for deletion confirmation
return warn(_('wizard.no_changes')) unless confirm_action?(_('wizard.node.confirm_deletion'))
# Node deletion
node = Bebox::Node.new(environment, project_root, hostname, nil)
output = node.remove
ok _('wizard.node.deletion_success')
return output
end | ruby | def remove_node(project_root, environment, hostname)
# Ask for a node to remove
nodes = Bebox::Node.list(project_root, environment, 'nodes')
if nodes.count > 0
hostname = choose_option(nodes, _('wizard.node.choose_node'))
else
error _('wizard.node.no_nodes')%{environment: environment}
return true
end
# Ask for deletion confirmation
return warn(_('wizard.no_changes')) unless confirm_action?(_('wizard.node.confirm_deletion'))
# Node deletion
node = Bebox::Node.new(environment, project_root, hostname, nil)
output = node.remove
ok _('wizard.node.deletion_success')
return output
end | [
"def",
"remove_node",
"(",
"project_root",
",",
"environment",
",",
"hostname",
")",
"nodes",
"=",
"Bebox",
"::",
"Node",
".",
"list",
"(",
"project_root",
",",
"environment",
",",
"'nodes'",
")",
"if",
"nodes",
".",
"count",
">",
"0",
"hostname",
"=",
"choose_option",
"(",
"nodes",
",",
"_",
"(",
"'wizard.node.choose_node'",
")",
")",
"else",
"error",
"_",
"(",
"'wizard.node.no_nodes'",
")",
"%",
"{",
"environment",
":",
"environment",
"}",
"return",
"true",
"end",
"return",
"warn",
"(",
"_",
"(",
"'wizard.no_changes'",
")",
")",
"unless",
"confirm_action?",
"(",
"_",
"(",
"'wizard.node.confirm_deletion'",
")",
")",
"node",
"=",
"Bebox",
"::",
"Node",
".",
"new",
"(",
"environment",
",",
"project_root",
",",
"hostname",
",",
"nil",
")",
"output",
"=",
"node",
".",
"remove",
"ok",
"_",
"(",
"'wizard.node.deletion_success'",
")",
"return",
"output",
"end"
] | Removes an existing node | [
"Removes",
"an",
"existing",
"node"
] | 0d19315847103341e599d32837ab0bd75524e5be | https://github.com/codescrum/bebox/blob/0d19315847103341e599d32837ab0bd75524e5be/lib/bebox/wizards/node_wizard.rb#L22-L38 | train |
codescrum/bebox | lib/bebox/wizards/node_wizard.rb | Bebox.NodeWizard.set_role | def set_role(project_root, environment)
roles = Bebox::Role.list(project_root)
nodes = Bebox::Node.list(project_root, environment, 'nodes')
node = choose_option(nodes, _('wizard.choose_node'))
role = choose_option(roles, _('wizard.choose_role'))
output = Bebox::Provision.associate_node_role(project_root, environment, node, role)
ok _('wizard.node.role_set_success')
return output
end | ruby | def set_role(project_root, environment)
roles = Bebox::Role.list(project_root)
nodes = Bebox::Node.list(project_root, environment, 'nodes')
node = choose_option(nodes, _('wizard.choose_node'))
role = choose_option(roles, _('wizard.choose_role'))
output = Bebox::Provision.associate_node_role(project_root, environment, node, role)
ok _('wizard.node.role_set_success')
return output
end | [
"def",
"set_role",
"(",
"project_root",
",",
"environment",
")",
"roles",
"=",
"Bebox",
"::",
"Role",
".",
"list",
"(",
"project_root",
")",
"nodes",
"=",
"Bebox",
"::",
"Node",
".",
"list",
"(",
"project_root",
",",
"environment",
",",
"'nodes'",
")",
"node",
"=",
"choose_option",
"(",
"nodes",
",",
"_",
"(",
"'wizard.choose_node'",
")",
")",
"role",
"=",
"choose_option",
"(",
"roles",
",",
"_",
"(",
"'wizard.choose_role'",
")",
")",
"output",
"=",
"Bebox",
"::",
"Provision",
".",
"associate_node_role",
"(",
"project_root",
",",
"environment",
",",
"node",
",",
"role",
")",
"ok",
"_",
"(",
"'wizard.node.role_set_success'",
")",
"return",
"output",
"end"
] | Associate a role with a node in a environment | [
"Associate",
"a",
"role",
"with",
"a",
"node",
"in",
"a",
"environment"
] | 0d19315847103341e599d32837ab0bd75524e5be | https://github.com/codescrum/bebox/blob/0d19315847103341e599d32837ab0bd75524e5be/lib/bebox/wizards/node_wizard.rb#L41-L49 | train |
codescrum/bebox | lib/bebox/wizards/node_wizard.rb | Bebox.NodeWizard.prepare | def prepare(project_root, environment)
# Check already prepared nodes
nodes_to_prepare = check_nodes_to_prepare(project_root, environment)
# Output the nodes to be prepared
if nodes_to_prepare.count > 0
title _('wizard.node.prepare_title')
nodes_to_prepare.each{|node| msg(node.hostname)}
linebreak
# For all environments regenerate the deploy file
Bebox::Node.regenerate_deploy_file(project_root, environment, nodes_to_prepare)
# If environment is 'vagrant' Prepare and Up the machines
up_vagrant_machines(project_root, nodes_to_prepare) if environment == 'vagrant'
# For all the environments do the preparation
nodes_to_prepare.each do |node|
node.prepare
ok _('wizard.node.preparation_success')
end
else
warn _('wizard.node.no_prepare_nodes')
end
return true
end | ruby | def prepare(project_root, environment)
# Check already prepared nodes
nodes_to_prepare = check_nodes_to_prepare(project_root, environment)
# Output the nodes to be prepared
if nodes_to_prepare.count > 0
title _('wizard.node.prepare_title')
nodes_to_prepare.each{|node| msg(node.hostname)}
linebreak
# For all environments regenerate the deploy file
Bebox::Node.regenerate_deploy_file(project_root, environment, nodes_to_prepare)
# If environment is 'vagrant' Prepare and Up the machines
up_vagrant_machines(project_root, nodes_to_prepare) if environment == 'vagrant'
# For all the environments do the preparation
nodes_to_prepare.each do |node|
node.prepare
ok _('wizard.node.preparation_success')
end
else
warn _('wizard.node.no_prepare_nodes')
end
return true
end | [
"def",
"prepare",
"(",
"project_root",
",",
"environment",
")",
"nodes_to_prepare",
"=",
"check_nodes_to_prepare",
"(",
"project_root",
",",
"environment",
")",
"if",
"nodes_to_prepare",
".",
"count",
">",
"0",
"title",
"_",
"(",
"'wizard.node.prepare_title'",
")",
"nodes_to_prepare",
".",
"each",
"{",
"|",
"node",
"|",
"msg",
"(",
"node",
".",
"hostname",
")",
"}",
"linebreak",
"Bebox",
"::",
"Node",
".",
"regenerate_deploy_file",
"(",
"project_root",
",",
"environment",
",",
"nodes_to_prepare",
")",
"up_vagrant_machines",
"(",
"project_root",
",",
"nodes_to_prepare",
")",
"if",
"environment",
"==",
"'vagrant'",
"nodes_to_prepare",
".",
"each",
"do",
"|",
"node",
"|",
"node",
".",
"prepare",
"ok",
"_",
"(",
"'wizard.node.preparation_success'",
")",
"end",
"else",
"warn",
"_",
"(",
"'wizard.node.no_prepare_nodes'",
")",
"end",
"return",
"true",
"end"
] | Prepare the nodes in a environment | [
"Prepare",
"the",
"nodes",
"in",
"a",
"environment"
] | 0d19315847103341e599d32837ab0bd75524e5be | https://github.com/codescrum/bebox/blob/0d19315847103341e599d32837ab0bd75524e5be/lib/bebox/wizards/node_wizard.rb#L52-L73 | train |
codescrum/bebox | lib/bebox/wizards/node_wizard.rb | Bebox.NodeWizard.check_nodes_to_prepare | def check_nodes_to_prepare(project_root, environment)
nodes_to_prepare = []
nodes = Bebox::Node.nodes_in_environment(project_root, environment, 'nodes')
prepared_nodes = Bebox::Node.list(project_root, environment, 'prepared_nodes')
nodes.each do |node|
if prepared_nodes.include?(node.hostname)
message = _('wizard.node.confirm_preparation')%{hostname: node.hostname, start: node.checkpoint_parameter_from_file('prepared_nodes', 'started_at'), end: node.checkpoint_parameter_from_file('prepared_nodes', 'finished_at')}
nodes_to_prepare << node if confirm_action?(message)
else
nodes_to_prepare << node
end
end
nodes_to_prepare
end | ruby | def check_nodes_to_prepare(project_root, environment)
nodes_to_prepare = []
nodes = Bebox::Node.nodes_in_environment(project_root, environment, 'nodes')
prepared_nodes = Bebox::Node.list(project_root, environment, 'prepared_nodes')
nodes.each do |node|
if prepared_nodes.include?(node.hostname)
message = _('wizard.node.confirm_preparation')%{hostname: node.hostname, start: node.checkpoint_parameter_from_file('prepared_nodes', 'started_at'), end: node.checkpoint_parameter_from_file('prepared_nodes', 'finished_at')}
nodes_to_prepare << node if confirm_action?(message)
else
nodes_to_prepare << node
end
end
nodes_to_prepare
end | [
"def",
"check_nodes_to_prepare",
"(",
"project_root",
",",
"environment",
")",
"nodes_to_prepare",
"=",
"[",
"]",
"nodes",
"=",
"Bebox",
"::",
"Node",
".",
"nodes_in_environment",
"(",
"project_root",
",",
"environment",
",",
"'nodes'",
")",
"prepared_nodes",
"=",
"Bebox",
"::",
"Node",
".",
"list",
"(",
"project_root",
",",
"environment",
",",
"'prepared_nodes'",
")",
"nodes",
".",
"each",
"do",
"|",
"node",
"|",
"if",
"prepared_nodes",
".",
"include?",
"(",
"node",
".",
"hostname",
")",
"message",
"=",
"_",
"(",
"'wizard.node.confirm_preparation'",
")",
"%",
"{",
"hostname",
":",
"node",
".",
"hostname",
",",
"start",
":",
"node",
".",
"checkpoint_parameter_from_file",
"(",
"'prepared_nodes'",
",",
"'started_at'",
")",
",",
"end",
":",
"node",
".",
"checkpoint_parameter_from_file",
"(",
"'prepared_nodes'",
",",
"'finished_at'",
")",
"}",
"nodes_to_prepare",
"<<",
"node",
"if",
"confirm_action?",
"(",
"message",
")",
"else",
"nodes_to_prepare",
"<<",
"node",
"end",
"end",
"nodes_to_prepare",
"end"
] | Check the nodes already prepared and ask confirmation to re-do-it | [
"Check",
"the",
"nodes",
"already",
"prepared",
"and",
"ask",
"confirmation",
"to",
"re",
"-",
"do",
"-",
"it"
] | 0d19315847103341e599d32837ab0bd75524e5be | https://github.com/codescrum/bebox/blob/0d19315847103341e599d32837ab0bd75524e5be/lib/bebox/wizards/node_wizard.rb#L82-L95 | train |
codescrum/bebox | lib/bebox/wizards/node_wizard.rb | Bebox.NodeWizard.ask_not_existing_hostname | def ask_not_existing_hostname(project_root, environment)
hostname = ask_hostname(project_root, environment)
# Check if the node not exist
if node_exists?(project_root, environment, hostname)
error _('wizard.node.hostname_exist')
ask_hostname(project_root, environment)
else
return hostname
end
end | ruby | def ask_not_existing_hostname(project_root, environment)
hostname = ask_hostname(project_root, environment)
# Check if the node not exist
if node_exists?(project_root, environment, hostname)
error _('wizard.node.hostname_exist')
ask_hostname(project_root, environment)
else
return hostname
end
end | [
"def",
"ask_not_existing_hostname",
"(",
"project_root",
",",
"environment",
")",
"hostname",
"=",
"ask_hostname",
"(",
"project_root",
",",
"environment",
")",
"if",
"node_exists?",
"(",
"project_root",
",",
"environment",
",",
"hostname",
")",
"error",
"_",
"(",
"'wizard.node.hostname_exist'",
")",
"ask_hostname",
"(",
"project_root",
",",
"environment",
")",
"else",
"return",
"hostname",
"end",
"end"
] | Keep asking for a hostname that not exist | [
"Keep",
"asking",
"for",
"a",
"hostname",
"that",
"not",
"exist"
] | 0d19315847103341e599d32837ab0bd75524e5be | https://github.com/codescrum/bebox/blob/0d19315847103341e599d32837ab0bd75524e5be/lib/bebox/wizards/node_wizard.rb#L103-L112 | train |
codescrum/bebox | lib/bebox/wizards/node_wizard.rb | Bebox.NodeWizard.ask_ip | def ask_ip(environment)
ip = write_input(_('wizard.node.ask_ip'), nil, /\.(.*)/, _('wizard.node.valid_ip'))
# If the environment is not vagrant don't check ip free
return ip if environment != 'vagrant'
# Check if the ip address is free
if free_ip?(ip)
return ip
else
error _('wizard.node.non_free_ip')
ask_ip(environment)
end
end | ruby | def ask_ip(environment)
ip = write_input(_('wizard.node.ask_ip'), nil, /\.(.*)/, _('wizard.node.valid_ip'))
# If the environment is not vagrant don't check ip free
return ip if environment != 'vagrant'
# Check if the ip address is free
if free_ip?(ip)
return ip
else
error _('wizard.node.non_free_ip')
ask_ip(environment)
end
end | [
"def",
"ask_ip",
"(",
"environment",
")",
"ip",
"=",
"write_input",
"(",
"_",
"(",
"'wizard.node.ask_ip'",
")",
",",
"nil",
",",
"/",
"\\.",
"/",
",",
"_",
"(",
"'wizard.node.valid_ip'",
")",
")",
"return",
"ip",
"if",
"environment",
"!=",
"'vagrant'",
"if",
"free_ip?",
"(",
"ip",
")",
"return",
"ip",
"else",
"error",
"_",
"(",
"'wizard.node.non_free_ip'",
")",
"ask_ip",
"(",
"environment",
")",
"end",
"end"
] | Ask for the ip until is valid | [
"Ask",
"for",
"the",
"ip",
"until",
"is",
"valid"
] | 0d19315847103341e599d32837ab0bd75524e5be | https://github.com/codescrum/bebox/blob/0d19315847103341e599d32837ab0bd75524e5be/lib/bebox/wizards/node_wizard.rb#L120-L131 | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.