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 |
---|---|---|---|---|---|---|---|---|---|---|---|
jimjh/genie-parser | lib/spirit/logger.rb | Spirit.Logger.max_action_length | def max_action_length
@max_action_length ||= actions.reduce(0) { |m, a| [m, a.to_s.length].max }
end | ruby | def max_action_length
@max_action_length ||= actions.reduce(0) { |m, a| [m, a.to_s.length].max }
end | [
"def",
"max_action_length",
"@max_action_length",
"||=",
"actions",
".",
"reduce",
"(",
"0",
")",
"{",
"|",
"m",
",",
"a",
"|",
"[",
"m",
",",
"a",
".",
"to_s",
".",
"length",
"]",
".",
"max",
"}",
"end"
] | the maximum length of all the actions known to the logger. | [
"the",
"maximum",
"length",
"of",
"all",
"the",
"actions",
"known",
"to",
"the",
"logger",
"."
] | d627c1c1cc07c0ea082a2599ee45cd7e7ba9c932 | https://github.com/jimjh/genie-parser/blob/d627c1c1cc07c0ea082a2599ee45cd7e7ba9c932/lib/spirit/logger.rb#L38-L40 | train |
jacquescrocker/viewfu | lib/view_fu/browser_detect.rb | ViewFu.BrowserDetect.browser_name | def browser_name
@browser_name ||= begin
ua = request.user_agent.to_s.downcase
if ua.index('msie') && !ua.index('opera') && !ua.index('webtv')
'ie'+ua[ua.index('msie')+5].chr
elsif ua.index('gecko/')
'gecko'
elsif ua.index('opera')
'opera'
elsif ua.index('konqueror')
'konqueror'
elsif ua.index('iphone')
'iphone'
elsif ua.index('applewebkit/')
'safari'
elsif ua.index('mozilla/')
'gecko'
else
""
end
end
end | ruby | def browser_name
@browser_name ||= begin
ua = request.user_agent.to_s.downcase
if ua.index('msie') && !ua.index('opera') && !ua.index('webtv')
'ie'+ua[ua.index('msie')+5].chr
elsif ua.index('gecko/')
'gecko'
elsif ua.index('opera')
'opera'
elsif ua.index('konqueror')
'konqueror'
elsif ua.index('iphone')
'iphone'
elsif ua.index('applewebkit/')
'safari'
elsif ua.index('mozilla/')
'gecko'
else
""
end
end
end | [
"def",
"browser_name",
"@browser_name",
"||=",
"begin",
"ua",
"=",
"request",
".",
"user_agent",
".",
"to_s",
".",
"downcase",
"if",
"ua",
".",
"index",
"(",
"'msie'",
")",
"&&",
"!",
"ua",
".",
"index",
"(",
"'opera'",
")",
"&&",
"!",
"ua",
".",
"index",
"(",
"'webtv'",
")",
"'ie'",
"+",
"ua",
"[",
"ua",
".",
"index",
"(",
"'msie'",
")",
"+",
"5",
"]",
".",
"chr",
"elsif",
"ua",
".",
"index",
"(",
"'gecko/'",
")",
"'gecko'",
"elsif",
"ua",
".",
"index",
"(",
"'opera'",
")",
"'opera'",
"elsif",
"ua",
".",
"index",
"(",
"'konqueror'",
")",
"'konqueror'",
"elsif",
"ua",
".",
"index",
"(",
"'iphone'",
")",
"'iphone'",
"elsif",
"ua",
".",
"index",
"(",
"'applewebkit/'",
")",
"'safari'",
"elsif",
"ua",
".",
"index",
"(",
"'mozilla/'",
")",
"'gecko'",
"else",
"\"\"",
"end",
"end",
"end"
] | find the current browser name | [
"find",
"the",
"current",
"browser",
"name"
] | a21946e74553a1e83790ba7ea2a2ef4daa729458 | https://github.com/jacquescrocker/viewfu/blob/a21946e74553a1e83790ba7ea2a2ef4daa729458/lib/view_fu/browser_detect.rb#L23-L44 | train |
nilsding/Empyrean | lib/empyrean/configloader.rb | Empyrean.ConfigLoader.load | def load(file)
if File.exist? file
symbolize_keys(YAML.load_file(File.expand_path('.', file)))
else
{}
end
end | ruby | def load(file)
if File.exist? file
symbolize_keys(YAML.load_file(File.expand_path('.', file)))
else
{}
end
end | [
"def",
"load",
"(",
"file",
")",
"if",
"File",
".",
"exist?",
"file",
"symbolize_keys",
"(",
"YAML",
".",
"load_file",
"(",
"File",
".",
"expand_path",
"(",
"'.'",
",",
"file",
")",
")",
")",
"else",
"{",
"}",
"end",
"end"
] | Loads a YAML file, parses it and returns a hash with symbolized keys. | [
"Loads",
"a",
"YAML",
"file",
"parses",
"it",
"and",
"returns",
"a",
"hash",
"with",
"symbolized",
"keys",
"."
] | e652fb8966dfcd32968789af75e8d5a4f63134ec | https://github.com/nilsding/Empyrean/blob/e652fb8966dfcd32968789af75e8d5a4f63134ec/lib/empyrean/configloader.rb#L30-L36 | train |
nilsding/Empyrean | lib/empyrean/configloader.rb | Empyrean.ConfigLoader.load_config | def load_config(file = @options.config)
config = load(file)
config[:timezone_difference] = 0 if config[:timezone_difference].nil?
config[:mentions] = {} if config[:mentions].nil?
config[:mentions][:enabled] = true if config[:mentions][:enabled].nil?
config[:mentions][:top] = 10 if config[:mentions][:top].nil?
config[:mentions][:notop] = 20 if config[:mentions][:notop].nil?
config[:clients] = {} if config[:clients].nil?
config[:clients][:enabled] = true if config[:clients][:enabled].nil?
config[:clients][:top] = 10 if config[:clients][:top].nil?
config[:clients][:notop] = 20 if config[:clients][:notop].nil?
config[:hashtags] = {} if config[:hashtags].nil?
config[:hashtags][:enabled] = true if config[:hashtags][:enabled].nil?
config[:hashtags][:top] = 10 if config[:hashtags][:top].nil?
config[:hashtags][:notop] = 20 if config[:hashtags][:notop].nil?
config[:smileys] = {} if config[:smileys].nil?
config[:smileys][:enabled] = true if config[:smileys][:enabled].nil?
config[:smileys][:top] = 10 if config[:smileys][:top].nil?
config[:smileys][:notop] = 0 if config[:smileys][:notop].nil?
config[:ignored_users] = [] if config[:ignored_users].nil?
config[:renamed_users] = [] if config[:renamed_users].nil?
args_override config
end | ruby | def load_config(file = @options.config)
config = load(file)
config[:timezone_difference] = 0 if config[:timezone_difference].nil?
config[:mentions] = {} if config[:mentions].nil?
config[:mentions][:enabled] = true if config[:mentions][:enabled].nil?
config[:mentions][:top] = 10 if config[:mentions][:top].nil?
config[:mentions][:notop] = 20 if config[:mentions][:notop].nil?
config[:clients] = {} if config[:clients].nil?
config[:clients][:enabled] = true if config[:clients][:enabled].nil?
config[:clients][:top] = 10 if config[:clients][:top].nil?
config[:clients][:notop] = 20 if config[:clients][:notop].nil?
config[:hashtags] = {} if config[:hashtags].nil?
config[:hashtags][:enabled] = true if config[:hashtags][:enabled].nil?
config[:hashtags][:top] = 10 if config[:hashtags][:top].nil?
config[:hashtags][:notop] = 20 if config[:hashtags][:notop].nil?
config[:smileys] = {} if config[:smileys].nil?
config[:smileys][:enabled] = true if config[:smileys][:enabled].nil?
config[:smileys][:top] = 10 if config[:smileys][:top].nil?
config[:smileys][:notop] = 0 if config[:smileys][:notop].nil?
config[:ignored_users] = [] if config[:ignored_users].nil?
config[:renamed_users] = [] if config[:renamed_users].nil?
args_override config
end | [
"def",
"load_config",
"(",
"file",
"=",
"@options",
".",
"config",
")",
"config",
"=",
"load",
"(",
"file",
")",
"config",
"[",
":timezone_difference",
"]",
"=",
"0",
"if",
"config",
"[",
":timezone_difference",
"]",
".",
"nil?",
"config",
"[",
":mentions",
"]",
"=",
"{",
"}",
"if",
"config",
"[",
":mentions",
"]",
".",
"nil?",
"config",
"[",
":mentions",
"]",
"[",
":enabled",
"]",
"=",
"true",
"if",
"config",
"[",
":mentions",
"]",
"[",
":enabled",
"]",
".",
"nil?",
"config",
"[",
":mentions",
"]",
"[",
":top",
"]",
"=",
"10",
"if",
"config",
"[",
":mentions",
"]",
"[",
":top",
"]",
".",
"nil?",
"config",
"[",
":mentions",
"]",
"[",
":notop",
"]",
"=",
"20",
"if",
"config",
"[",
":mentions",
"]",
"[",
":notop",
"]",
".",
"nil?",
"config",
"[",
":clients",
"]",
"=",
"{",
"}",
"if",
"config",
"[",
":clients",
"]",
".",
"nil?",
"config",
"[",
":clients",
"]",
"[",
":enabled",
"]",
"=",
"true",
"if",
"config",
"[",
":clients",
"]",
"[",
":enabled",
"]",
".",
"nil?",
"config",
"[",
":clients",
"]",
"[",
":top",
"]",
"=",
"10",
"if",
"config",
"[",
":clients",
"]",
"[",
":top",
"]",
".",
"nil?",
"config",
"[",
":clients",
"]",
"[",
":notop",
"]",
"=",
"20",
"if",
"config",
"[",
":clients",
"]",
"[",
":notop",
"]",
".",
"nil?",
"config",
"[",
":hashtags",
"]",
"=",
"{",
"}",
"if",
"config",
"[",
":hashtags",
"]",
".",
"nil?",
"config",
"[",
":hashtags",
"]",
"[",
":enabled",
"]",
"=",
"true",
"if",
"config",
"[",
":hashtags",
"]",
"[",
":enabled",
"]",
".",
"nil?",
"config",
"[",
":hashtags",
"]",
"[",
":top",
"]",
"=",
"10",
"if",
"config",
"[",
":hashtags",
"]",
"[",
":top",
"]",
".",
"nil?",
"config",
"[",
":hashtags",
"]",
"[",
":notop",
"]",
"=",
"20",
"if",
"config",
"[",
":hashtags",
"]",
"[",
":notop",
"]",
".",
"nil?",
"config",
"[",
":smileys",
"]",
"=",
"{",
"}",
"if",
"config",
"[",
":smileys",
"]",
".",
"nil?",
"config",
"[",
":smileys",
"]",
"[",
":enabled",
"]",
"=",
"true",
"if",
"config",
"[",
":smileys",
"]",
"[",
":enabled",
"]",
".",
"nil?",
"config",
"[",
":smileys",
"]",
"[",
":top",
"]",
"=",
"10",
"if",
"config",
"[",
":smileys",
"]",
"[",
":top",
"]",
".",
"nil?",
"config",
"[",
":smileys",
"]",
"[",
":notop",
"]",
"=",
"0",
"if",
"config",
"[",
":smileys",
"]",
"[",
":notop",
"]",
".",
"nil?",
"config",
"[",
":ignored_users",
"]",
"=",
"[",
"]",
"if",
"config",
"[",
":ignored_users",
"]",
".",
"nil?",
"config",
"[",
":renamed_users",
"]",
"=",
"[",
"]",
"if",
"config",
"[",
":renamed_users",
"]",
".",
"nil?",
"args_override",
"config",
"end"
] | Loads a YAML file, parses it and checks if all values are given. If a
value is missing, it will be set with the default value. | [
"Loads",
"a",
"YAML",
"file",
"parses",
"it",
"and",
"checks",
"if",
"all",
"values",
"are",
"given",
".",
"If",
"a",
"value",
"is",
"missing",
"it",
"will",
"be",
"set",
"with",
"the",
"default",
"value",
"."
] | e652fb8966dfcd32968789af75e8d5a4f63134ec | https://github.com/nilsding/Empyrean/blob/e652fb8966dfcd32968789af75e8d5a4f63134ec/lib/empyrean/configloader.rb#L40-L62 | train |
ecssiah/project-euler-cli | lib/project_euler_cli/archive_viewer.rb | ProjectEulerCli.ArchiveViewer.display_recent | def display_recent
load_recent
puts
(Problem.total).downto(Problem.total - 9) do |i|
puts "#{i} - #{Problem[i].title}"
end
end | ruby | def display_recent
load_recent
puts
(Problem.total).downto(Problem.total - 9) do |i|
puts "#{i} - #{Problem[i].title}"
end
end | [
"def",
"display_recent",
"load_recent",
"puts",
"(",
"Problem",
".",
"total",
")",
".",
"downto",
"(",
"Problem",
".",
"total",
"-",
"9",
")",
"do",
"|",
"i",
"|",
"puts",
"\"#{i} - #{Problem[i].title}\"",
"end",
"end"
] | Displays the 10 most recently added problems. | [
"Displays",
"the",
"10",
"most",
"recently",
"added",
"problems",
"."
] | ae6fb1fb516bd9bcf193e3e1f1c82894198fe997 | https://github.com/ecssiah/project-euler-cli/blob/ae6fb1fb516bd9bcf193e3e1f1c82894198fe997/lib/project_euler_cli/archive_viewer.rb#L12-L20 | train |
ecssiah/project-euler-cli | lib/project_euler_cli/archive_viewer.rb | ProjectEulerCli.ArchiveViewer.display_page | def display_page(page)
load_page(page)
puts
start = (page - 1) * Page::LENGTH + 1
start.upto(start + Page::LENGTH - 1) do |i|
puts "#{i} - #{Problem[i].title}" unless i >= Problem.total - 9
end
end | ruby | def display_page(page)
load_page(page)
puts
start = (page - 1) * Page::LENGTH + 1
start.upto(start + Page::LENGTH - 1) do |i|
puts "#{i} - #{Problem[i].title}" unless i >= Problem.total - 9
end
end | [
"def",
"display_page",
"(",
"page",
")",
"load_page",
"(",
"page",
")",
"puts",
"start",
"=",
"(",
"page",
"-",
"1",
")",
"*",
"Page",
"::",
"LENGTH",
"+",
"1",
"start",
".",
"upto",
"(",
"start",
"+",
"Page",
"::",
"LENGTH",
"-",
"1",
")",
"do",
"|",
"i",
"|",
"puts",
"\"#{i} - #{Problem[i].title}\"",
"unless",
"i",
">=",
"Problem",
".",
"total",
"-",
"9",
"end",
"end"
] | Displays the problem numbers and titles for an individual page of the
archive. | [
"Displays",
"the",
"problem",
"numbers",
"and",
"titles",
"for",
"an",
"individual",
"page",
"of",
"the",
"archive",
"."
] | ae6fb1fb516bd9bcf193e3e1f1c82894198fe997 | https://github.com/ecssiah/project-euler-cli/blob/ae6fb1fb516bd9bcf193e3e1f1c82894198fe997/lib/project_euler_cli/archive_viewer.rb#L24-L33 | train |
ecssiah/project-euler-cli | lib/project_euler_cli/archive_viewer.rb | ProjectEulerCli.ArchiveViewer.display_problem | def display_problem(id)
load_problem_details(id)
puts
puts "=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-="
puts
puts Problem[id].title.upcase
puts "Problem #{id}"
puts
puts Problem[id].published
puts Problem[id].solved_by
puts Problem[id].difficulty if id < Problem.total - 9
puts
puts "https://projecteuler.net/problem=#{id}"
puts
puts "=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-="
end | ruby | def display_problem(id)
load_problem_details(id)
puts
puts "=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-="
puts
puts Problem[id].title.upcase
puts "Problem #{id}"
puts
puts Problem[id].published
puts Problem[id].solved_by
puts Problem[id].difficulty if id < Problem.total - 9
puts
puts "https://projecteuler.net/problem=#{id}"
puts
puts "=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-="
end | [
"def",
"display_problem",
"(",
"id",
")",
"load_problem_details",
"(",
"id",
")",
"puts",
"puts",
"\"=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=\"",
"puts",
"puts",
"Problem",
"[",
"id",
"]",
".",
"title",
".",
"upcase",
"puts",
"\"Problem #{id}\"",
"puts",
"puts",
"Problem",
"[",
"id",
"]",
".",
"published",
"puts",
"Problem",
"[",
"id",
"]",
".",
"solved_by",
"puts",
"Problem",
"[",
"id",
"]",
".",
"difficulty",
"if",
"id",
"<",
"Problem",
".",
"total",
"-",
"9",
"puts",
"puts",
"\"https://projecteuler.net/problem=#{id}\"",
"puts",
"puts",
"\"=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=\"",
"end"
] | Displays the details of an individual problem.
* +id+ - ID of the problem to be displayed | [
"Displays",
"the",
"details",
"of",
"an",
"individual",
"problem",
"."
] | ae6fb1fb516bd9bcf193e3e1f1c82894198fe997 | https://github.com/ecssiah/project-euler-cli/blob/ae6fb1fb516bd9bcf193e3e1f1c82894198fe997/lib/project_euler_cli/archive_viewer.rb#L38-L54 | train |
conorh/rfgraph | lib/rfgraph/auth.rb | RFGraph.Auth.authorize | def authorize(callback_url, code)
data = open("#{BASE_URL}/oauth/access_token?client_id=#{app_id}&redirect_uri=#{CGI.escape callback_url}&client_secret=#{app_secret}&code=#{CGI.escape code}").read
# The expiration date is not necessarily set, as the app might have
# requested offline_access to the data
match_data = data.match(/expires=([^&]+)/)
@expires = match_data && match_data[1] || nil
# Extract the access token
@access_token = data.match(/access_token=([^&]+)/)[1]
end | ruby | def authorize(callback_url, code)
data = open("#{BASE_URL}/oauth/access_token?client_id=#{app_id}&redirect_uri=#{CGI.escape callback_url}&client_secret=#{app_secret}&code=#{CGI.escape code}").read
# The expiration date is not necessarily set, as the app might have
# requested offline_access to the data
match_data = data.match(/expires=([^&]+)/)
@expires = match_data && match_data[1] || nil
# Extract the access token
@access_token = data.match(/access_token=([^&]+)/)[1]
end | [
"def",
"authorize",
"(",
"callback_url",
",",
"code",
")",
"data",
"=",
"open",
"(",
"\"#{BASE_URL}/oauth/access_token?client_id=#{app_id}&redirect_uri=#{CGI.escape callback_url}&client_secret=#{app_secret}&code=#{CGI.escape code}\"",
")",
".",
"read",
"# The expiration date is not necessarily set, as the app might have",
"# requested offline_access to the data",
"match_data",
"=",
"data",
".",
"match",
"(",
"/",
"/",
")",
"@expires",
"=",
"match_data",
"&&",
"match_data",
"[",
"1",
"]",
"||",
"nil",
"# Extract the access token",
"@access_token",
"=",
"data",
".",
"match",
"(",
"/",
"/",
")",
"[",
"1",
"]",
"end"
] | Take the oauth2 request token and turn it into an access token
which can be used to access private data | [
"Take",
"the",
"oauth2",
"request",
"token",
"and",
"turn",
"it",
"into",
"an",
"access",
"token",
"which",
"can",
"be",
"used",
"to",
"access",
"private",
"data"
] | 455fff563f0cb0f9e33714d8ce952fd8ec88ac7e | https://github.com/conorh/rfgraph/blob/455fff563f0cb0f9e33714d8ce952fd8ec88ac7e/lib/rfgraph/auth.rb#L33-L43 | train |
xiuxian123/loyals | projects/loyal_devise/lib/devise/rails/routes.rb | ActionDispatch::Routing.Mapper.devise_for | def devise_for(*resources)
@devise_finalized = false
options = resources.extract_options!
options[:as] ||= @scope[:as] if @scope[:as].present?
options[:module] ||= @scope[:module] if @scope[:module].present?
options[:path_prefix] ||= @scope[:path] if @scope[:path].present?
options[:path_names] = (@scope[:path_names] || {}).merge(options[:path_names] || {})
options[:constraints] = (@scope[:constraints] || {}).merge(options[:constraints] || {})
options[:defaults] = (@scope[:defaults] || {}).merge(options[:defaults] || {})
options[:options] = @scope[:options] || {}
options[:options][:format] = false if options[:format] == false
resources.map!(&:to_sym)
resources.each do |resource|
mapping = Devise.add_mapping(resource, options)
begin
raise_no_devise_method_error!(mapping.class_name) unless mapping.to.respond_to?(:devise)
rescue NameError => e
raise unless mapping.class_name == resource.to_s.classify
warn "[WARNING] You provided devise_for #{resource.inspect} but there is " <<
"no model #{mapping.class_name} defined in your application"
next
rescue NoMethodError => e
raise unless e.message.include?("undefined method `devise'")
raise_no_devise_method_error!(mapping.class_name)
end
routes = mapping.used_routes
devise_scope mapping.name do
if block_given?
ActiveSupport::Deprecation.warn "Passing a block to devise_for is deprecated. " \
"Please remove the block from devise_for (only the block, the call to " \
"devise_for must still exist) and call devise_scope :#{mapping.name} do ... end " \
"with the block instead", caller
yield
end
with_devise_exclusive_scope mapping.fullpath, mapping.name, options do
routes.each { |mod| send("devise_#{mod}", mapping, mapping.controllers) }
end
end
end
end | ruby | def devise_for(*resources)
@devise_finalized = false
options = resources.extract_options!
options[:as] ||= @scope[:as] if @scope[:as].present?
options[:module] ||= @scope[:module] if @scope[:module].present?
options[:path_prefix] ||= @scope[:path] if @scope[:path].present?
options[:path_names] = (@scope[:path_names] || {}).merge(options[:path_names] || {})
options[:constraints] = (@scope[:constraints] || {}).merge(options[:constraints] || {})
options[:defaults] = (@scope[:defaults] || {}).merge(options[:defaults] || {})
options[:options] = @scope[:options] || {}
options[:options][:format] = false if options[:format] == false
resources.map!(&:to_sym)
resources.each do |resource|
mapping = Devise.add_mapping(resource, options)
begin
raise_no_devise_method_error!(mapping.class_name) unless mapping.to.respond_to?(:devise)
rescue NameError => e
raise unless mapping.class_name == resource.to_s.classify
warn "[WARNING] You provided devise_for #{resource.inspect} but there is " <<
"no model #{mapping.class_name} defined in your application"
next
rescue NoMethodError => e
raise unless e.message.include?("undefined method `devise'")
raise_no_devise_method_error!(mapping.class_name)
end
routes = mapping.used_routes
devise_scope mapping.name do
if block_given?
ActiveSupport::Deprecation.warn "Passing a block to devise_for is deprecated. " \
"Please remove the block from devise_for (only the block, the call to " \
"devise_for must still exist) and call devise_scope :#{mapping.name} do ... end " \
"with the block instead", caller
yield
end
with_devise_exclusive_scope mapping.fullpath, mapping.name, options do
routes.each { |mod| send("devise_#{mod}", mapping, mapping.controllers) }
end
end
end
end | [
"def",
"devise_for",
"(",
"*",
"resources",
")",
"@devise_finalized",
"=",
"false",
"options",
"=",
"resources",
".",
"extract_options!",
"options",
"[",
":as",
"]",
"||=",
"@scope",
"[",
":as",
"]",
"if",
"@scope",
"[",
":as",
"]",
".",
"present?",
"options",
"[",
":module",
"]",
"||=",
"@scope",
"[",
":module",
"]",
"if",
"@scope",
"[",
":module",
"]",
".",
"present?",
"options",
"[",
":path_prefix",
"]",
"||=",
"@scope",
"[",
":path",
"]",
"if",
"@scope",
"[",
":path",
"]",
".",
"present?",
"options",
"[",
":path_names",
"]",
"=",
"(",
"@scope",
"[",
":path_names",
"]",
"||",
"{",
"}",
")",
".",
"merge",
"(",
"options",
"[",
":path_names",
"]",
"||",
"{",
"}",
")",
"options",
"[",
":constraints",
"]",
"=",
"(",
"@scope",
"[",
":constraints",
"]",
"||",
"{",
"}",
")",
".",
"merge",
"(",
"options",
"[",
":constraints",
"]",
"||",
"{",
"}",
")",
"options",
"[",
":defaults",
"]",
"=",
"(",
"@scope",
"[",
":defaults",
"]",
"||",
"{",
"}",
")",
".",
"merge",
"(",
"options",
"[",
":defaults",
"]",
"||",
"{",
"}",
")",
"options",
"[",
":options",
"]",
"=",
"@scope",
"[",
":options",
"]",
"||",
"{",
"}",
"options",
"[",
":options",
"]",
"[",
":format",
"]",
"=",
"false",
"if",
"options",
"[",
":format",
"]",
"==",
"false",
"resources",
".",
"map!",
"(",
":to_sym",
")",
"resources",
".",
"each",
"do",
"|",
"resource",
"|",
"mapping",
"=",
"Devise",
".",
"add_mapping",
"(",
"resource",
",",
"options",
")",
"begin",
"raise_no_devise_method_error!",
"(",
"mapping",
".",
"class_name",
")",
"unless",
"mapping",
".",
"to",
".",
"respond_to?",
"(",
":devise",
")",
"rescue",
"NameError",
"=>",
"e",
"raise",
"unless",
"mapping",
".",
"class_name",
"==",
"resource",
".",
"to_s",
".",
"classify",
"warn",
"\"[WARNING] You provided devise_for #{resource.inspect} but there is \"",
"<<",
"\"no model #{mapping.class_name} defined in your application\"",
"next",
"rescue",
"NoMethodError",
"=>",
"e",
"raise",
"unless",
"e",
".",
"message",
".",
"include?",
"(",
"\"undefined method `devise'\"",
")",
"raise_no_devise_method_error!",
"(",
"mapping",
".",
"class_name",
")",
"end",
"routes",
"=",
"mapping",
".",
"used_routes",
"devise_scope",
"mapping",
".",
"name",
"do",
"if",
"block_given?",
"ActiveSupport",
"::",
"Deprecation",
".",
"warn",
"\"Passing a block to devise_for is deprecated. \"",
"\"Please remove the block from devise_for (only the block, the call to \"",
"\"devise_for must still exist) and call devise_scope :#{mapping.name} do ... end \"",
"\"with the block instead\"",
",",
"caller",
"yield",
"end",
"with_devise_exclusive_scope",
"mapping",
".",
"fullpath",
",",
"mapping",
".",
"name",
",",
"options",
"do",
"routes",
".",
"each",
"{",
"|",
"mod",
"|",
"send",
"(",
"\"devise_#{mod}\"",
",",
"mapping",
",",
"mapping",
".",
"controllers",
")",
"}",
"end",
"end",
"end",
"end"
] | Includes devise_for method for routes. This method is responsible to
generate all needed routes for devise, based on what modules you have
defined in your model.
==== Examples
Let's say you have an User model configured to use authenticatable,
confirmable and recoverable modules. After creating this inside your routes:
devise_for :users
This method is going to look inside your User model and create the
needed routes:
# Session routes for Authenticatable (default)
new_user_session GET /users/sign_in {:controller=>"devise/sessions", :action=>"new"}
user_session POST /users/sign_in {:controller=>"devise/sessions", :action=>"create"}
destroy_user_session DELETE /users/sign_out {:controller=>"devise/sessions", :action=>"destroy"}
# Password routes for Recoverable, if User model has :recoverable configured
new_user_password GET /users/password/new(.:format) {:controller=>"devise/passwords", :action=>"new"}
edit_user_password GET /users/password/edit(.:format) {:controller=>"devise/passwords", :action=>"edit"}
user_password PUT /users/password(.:format) {:controller=>"devise/passwords", :action=>"update"}
POST /users/password(.:format) {:controller=>"devise/passwords", :action=>"create"}
# Confirmation routes for Confirmable, if User model has :confirmable configured
new_user_confirmation GET /users/confirmation/new(.:format) {:controller=>"devise/confirmations", :action=>"new"}
user_confirmation GET /users/confirmation(.:format) {:controller=>"devise/confirmations", :action=>"show"}
POST /users/confirmation(.:format) {:controller=>"devise/confirmations", :action=>"create"}
==== Options
You can configure your routes with some options:
* :class_name => setup a different class to be looked up by devise, if it cannot be
properly found by the route name.
devise_for :users, :class_name => 'Account'
* :path => allows you to setup path name that will be used, as rails routes does.
The following route configuration would setup your route as /accounts instead of /users:
devise_for :users, :path => 'accounts'
* :singular => setup the singular name for the given resource. This is used as the instance variable
name in controller, as the name in routes and the scope given to warden.
devise_for :users, :singular => :user
* :path_names => configure different path names to overwrite defaults :sign_in, :sign_out, :sign_up,
:password, :confirmation, :unlock.
devise_for :users, :path_names => { :sign_in => 'login', :sign_out => 'logout', :password => 'secret', :confirmation => 'verification' }
* :controllers => the controller which should be used. All routes by default points to Devise controllers.
However, if you want them to point to custom controller, you should do:
devise_for :users, :controllers => { :sessions => "users/sessions" }
* :failure_app => a rack app which is invoked whenever there is a failure. Strings representing a given
are also allowed as parameter.
* :sign_out_via => the HTTP method(s) accepted for the :sign_out action (default: :get),
if you wish to restrict this to accept only :post or :delete requests you should do:
devise_for :users, :sign_out_via => [ :post, :delete ]
You need to make sure that your sign_out controls trigger a request with a matching HTTP method.
* :module => the namespace to find controllers (default: "devise", thus
accessing devise/sessions, devise/registrations, and so on). If you want
to namespace all at once, use module:
devise_for :users, :module => "users"
Notice that whenever you use namespace in the router DSL, it automatically sets the module.
So the following setup:
namespace :publisher do
devise_for :account
end
Will use publisher/sessions controller instead of devise/sessions controller. You can revert
this by providing the :module option to devise_for.
Also pay attention that when you use a namespace it will affect all the helpers and methods for controllers
and views. For example, using the above setup you'll end with following methods:
current_publisher_account, authenticate_publisher_account!, publisher_account_signed_in, etc.
* :skip => tell which controller you want to skip routes from being created:
devise_for :users, :skip => :sessions
* :only => the opposite of :skip, tell which controllers only to generate routes to:
devise_for :users, :only => :sessions
* :skip_helpers => skip generating Devise url helpers like new_session_path(@user).
This is useful to avoid conflicts with previous routes and is false by default.
It accepts true as option, meaning it will skip all the helpers for the controllers
given in :skip but it also accepts specific helpers to be skipped:
devise_for :users, :skip => [:registrations, :confirmations], :skip_helpers => true
devise_for :users, :skip_helpers => [:registrations, :confirmations]
* :format => include "(.:format)" in the generated routes? true by default, set to false to disable:
devise_for :users, :format => false
* :constraints => works the same as Rails' constraints
* :defaults => works the same as Rails' defaults
==== Scoping
Following Rails 3 routes DSL, you can nest devise_for calls inside a scope:
scope "/my" do
devise_for :users
end
However, since Devise uses the request path to retrieve the current user,
this has one caveat: If you are using a dynamic segment, like so ...
scope ":locale" do
devise_for :users
end
you are required to configure default_url_options in your
ApplicationController class, so Devise can pick it:
class ApplicationController < ActionController::Base
def self.default_url_options
{ :locale => I18n.locale }
end
end
==== Adding custom actions to override controllers
You can pass a block to devise_for that will add any routes defined in the block to Devise's
list of known actions. This is important if you add a custom action to a controller that
overrides an out of the box Devise controller.
For example:
class RegistrationsController < Devise::RegistrationsController
def update
# do something different here
end
def deactivate
# not a standard action
# deactivate code here
end
end
In order to get Devise to recognize the deactivate action, your devise_scope entry should look like this:
devise_scope :owner do
post "deactivate", :to => "registrations#deactivate", :as => "deactivate_registration"
end | [
"Includes",
"devise_for",
"method",
"for",
"routes",
".",
"This",
"method",
"is",
"responsible",
"to",
"generate",
"all",
"needed",
"routes",
"for",
"devise",
"based",
"on",
"what",
"modules",
"you",
"have",
"defined",
"in",
"your",
"model",
"."
] | 41f586ca1551f64e5375ad32a406d5fca0afae43 | https://github.com/xiuxian123/loyals/blob/41f586ca1551f64e5375ad32a406d5fca0afae43/projects/loyal_devise/lib/devise/rails/routes.rb#L192-L238 | train |
tbuehlmann/ponder | lib/ponder/channel_list.rb | Ponder.ChannelList.remove | def remove(channel_or_channel_name)
@mutex.synchronize do
if channel_or_channel_name.is_a?(String)
channel_or_channel_name = find(channel_or_channel_name)
end
@channels.delete(channel_or_channel_name)
end
end | ruby | def remove(channel_or_channel_name)
@mutex.synchronize do
if channel_or_channel_name.is_a?(String)
channel_or_channel_name = find(channel_or_channel_name)
end
@channels.delete(channel_or_channel_name)
end
end | [
"def",
"remove",
"(",
"channel_or_channel_name",
")",
"@mutex",
".",
"synchronize",
"do",
"if",
"channel_or_channel_name",
".",
"is_a?",
"(",
"String",
")",
"channel_or_channel_name",
"=",
"find",
"(",
"channel_or_channel_name",
")",
"end",
"@channels",
".",
"delete",
"(",
"channel_or_channel_name",
")",
"end",
"end"
] | Removes a Channel from the ChannelList. | [
"Removes",
"a",
"Channel",
"from",
"the",
"ChannelList",
"."
] | 930912e1b78b41afa1359121aca46197e9edff9c | https://github.com/tbuehlmann/ponder/blob/930912e1b78b41afa1359121aca46197e9edff9c/lib/ponder/channel_list.rb#L18-L26 | train |
tbuehlmann/ponder | lib/ponder/channel_list.rb | Ponder.ChannelList.remove_user | def remove_user(nick)
@mutex.synchronize do
channels = Set.new
@channels.each do |channel|
if channel.remove_user(nick)
channels << channel
end
end
channels
end
end | ruby | def remove_user(nick)
@mutex.synchronize do
channels = Set.new
@channels.each do |channel|
if channel.remove_user(nick)
channels << channel
end
end
channels
end
end | [
"def",
"remove_user",
"(",
"nick",
")",
"@mutex",
".",
"synchronize",
"do",
"channels",
"=",
"Set",
".",
"new",
"@channels",
".",
"each",
"do",
"|",
"channel",
"|",
"if",
"channel",
".",
"remove_user",
"(",
"nick",
")",
"channels",
"<<",
"channel",
"end",
"end",
"channels",
"end",
"end"
] | Removes a User from all Channels from the ChannelList.
Returning a Set of Channels in which the User was. | [
"Removes",
"a",
"User",
"from",
"all",
"Channels",
"from",
"the",
"ChannelList",
".",
"Returning",
"a",
"Set",
"of",
"Channels",
"in",
"which",
"the",
"User",
"was",
"."
] | 930912e1b78b41afa1359121aca46197e9edff9c | https://github.com/tbuehlmann/ponder/blob/930912e1b78b41afa1359121aca46197e9edff9c/lib/ponder/channel_list.rb#L30-L42 | train |
tbuehlmann/ponder | lib/ponder/channel_list.rb | Ponder.ChannelList.users | def users
users = Set.new
@channels.each do |channel|
users.merge channel.users
end
users
end | ruby | def users
users = Set.new
@channels.each do |channel|
users.merge channel.users
end
users
end | [
"def",
"users",
"users",
"=",
"Set",
".",
"new",
"@channels",
".",
"each",
"do",
"|",
"channel",
"|",
"users",
".",
"merge",
"channel",
".",
"users",
"end",
"users",
"end"
] | Returns a Set of all Users that are in one of the Channels from the
ChannelList. | [
"Returns",
"a",
"Set",
"of",
"all",
"Users",
"that",
"are",
"in",
"one",
"of",
"the",
"Channels",
"from",
"the",
"ChannelList",
"."
] | 930912e1b78b41afa1359121aca46197e9edff9c | https://github.com/tbuehlmann/ponder/blob/930912e1b78b41afa1359121aca46197e9edff9c/lib/ponder/channel_list.rb#L60-L68 | train |
AndreasWurm/pingback | lib/pingback/client.rb | Pingback.Client.ping | def ping(source_uri, target_uri)
header = request_header target_uri
pingback_server = header['X-Pingback']
unless pingback_server
doc = Nokogiri::HTML(request_all(target_uri).body)
link = doc.xpath('//link[@rel="pingback"]/attribute::href').first
pingback_server = URI.escape(link.content) if link
end
raise InvalidTargetException unless pingback_server
send_pingback pingback_server, source_uri, target_uri
end | ruby | def ping(source_uri, target_uri)
header = request_header target_uri
pingback_server = header['X-Pingback']
unless pingback_server
doc = Nokogiri::HTML(request_all(target_uri).body)
link = doc.xpath('//link[@rel="pingback"]/attribute::href').first
pingback_server = URI.escape(link.content) if link
end
raise InvalidTargetException unless pingback_server
send_pingback pingback_server, source_uri, target_uri
end | [
"def",
"ping",
"(",
"source_uri",
",",
"target_uri",
")",
"header",
"=",
"request_header",
"target_uri",
"pingback_server",
"=",
"header",
"[",
"'X-Pingback'",
"]",
"unless",
"pingback_server",
"doc",
"=",
"Nokogiri",
"::",
"HTML",
"(",
"request_all",
"(",
"target_uri",
")",
".",
"body",
")",
"link",
"=",
"doc",
".",
"xpath",
"(",
"'//link[@rel=\"pingback\"]/attribute::href'",
")",
".",
"first",
"pingback_server",
"=",
"URI",
".",
"escape",
"(",
"link",
".",
"content",
")",
"if",
"link",
"end",
"raise",
"InvalidTargetException",
"unless",
"pingback_server",
"send_pingback",
"pingback_server",
",",
"source_uri",
",",
"target_uri",
"end"
] | send an pingback request to the targets associated pingback server.
@param [String] source_uri the address of the site containing the link.
@param [String] target_uri the target of the link on the source site.
@raise [Pingback::InvalidTargetException] raised if the target is not a pingback-enabled resource
@raise [XMLRPC::FaultException] raised if the server responds with a faultcode
@return [String] message indicating that the request was successful | [
"send",
"an",
"pingback",
"request",
"to",
"the",
"targets",
"associated",
"pingback",
"server",
"."
] | 44028aa94420b5cb5454ee56d459f0e4ff31194f | https://github.com/AndreasWurm/pingback/blob/44028aa94420b5cb5454ee56d459f0e4ff31194f/lib/pingback/client.rb#L16-L29 | train |
akwiatkowski/simple_metar_parser | lib/simple_metar_parser/metar/wind.rb | SimpleMetarParser.Wind.decode_wind | def decode_wind(s)
if s =~ /(\d{3})(\d{2})G?(\d{2})?(KT|MPS|KMH)/
# different units
wind = case $4
when "KT" then
$2.to_f * KNOTS_TO_METERS_PER_SECOND
when "MPS" then
$2.to_f
when "KMH" then
$2.to_f * KILOMETERS_PER_HOUR_TO_METERS_PER_SECOND
else
nil
end
wind_max = case $4
when "KT" then
$3.to_f * KNOTS_TO_METERS_PER_SECOND
when "MPS" then
$3.to_f
when "KMH" then
$3.to_f * KILOMETERS_PER_HOUR_TO_METERS_PER_SECOND
else
nil
end
# wind_max is not less than normal wind
if wind_max < wind or wind_max.nil?
wind_max = wind
end
@winds << {
:wind => wind,
:wind_max => wind_max,
:wind_direction => $1.to_i
}
end
# variable/unknown direction
if s =~ /VRB(\d{2})(KT|MPS|KMH)/
wind = case $2
when "KT" then
$1.to_f * KNOTS_TO_METERS_PER_SECOND
when "MPS" then
$1.to_f
when "KMH" then
$1.to_f * KILOMETERS_PER_HOUR_TO_METERS_PER_SECOND
else
nil
end
@winds << {
:wind => wind
}
end
end | ruby | def decode_wind(s)
if s =~ /(\d{3})(\d{2})G?(\d{2})?(KT|MPS|KMH)/
# different units
wind = case $4
when "KT" then
$2.to_f * KNOTS_TO_METERS_PER_SECOND
when "MPS" then
$2.to_f
when "KMH" then
$2.to_f * KILOMETERS_PER_HOUR_TO_METERS_PER_SECOND
else
nil
end
wind_max = case $4
when "KT" then
$3.to_f * KNOTS_TO_METERS_PER_SECOND
when "MPS" then
$3.to_f
when "KMH" then
$3.to_f * KILOMETERS_PER_HOUR_TO_METERS_PER_SECOND
else
nil
end
# wind_max is not less than normal wind
if wind_max < wind or wind_max.nil?
wind_max = wind
end
@winds << {
:wind => wind,
:wind_max => wind_max,
:wind_direction => $1.to_i
}
end
# variable/unknown direction
if s =~ /VRB(\d{2})(KT|MPS|KMH)/
wind = case $2
when "KT" then
$1.to_f * KNOTS_TO_METERS_PER_SECOND
when "MPS" then
$1.to_f
when "KMH" then
$1.to_f * KILOMETERS_PER_HOUR_TO_METERS_PER_SECOND
else
nil
end
@winds << {
:wind => wind
}
end
end | [
"def",
"decode_wind",
"(",
"s",
")",
"if",
"s",
"=~",
"/",
"\\d",
"\\d",
"\\d",
"/",
"# different units",
"wind",
"=",
"case",
"$4",
"when",
"\"KT\"",
"then",
"$2",
".",
"to_f",
"*",
"KNOTS_TO_METERS_PER_SECOND",
"when",
"\"MPS\"",
"then",
"$2",
".",
"to_f",
"when",
"\"KMH\"",
"then",
"$2",
".",
"to_f",
"*",
"KILOMETERS_PER_HOUR_TO_METERS_PER_SECOND",
"else",
"nil",
"end",
"wind_max",
"=",
"case",
"$4",
"when",
"\"KT\"",
"then",
"$3",
".",
"to_f",
"*",
"KNOTS_TO_METERS_PER_SECOND",
"when",
"\"MPS\"",
"then",
"$3",
".",
"to_f",
"when",
"\"KMH\"",
"then",
"$3",
".",
"to_f",
"*",
"KILOMETERS_PER_HOUR_TO_METERS_PER_SECOND",
"else",
"nil",
"end",
"# wind_max is not less than normal wind",
"if",
"wind_max",
"<",
"wind",
"or",
"wind_max",
".",
"nil?",
"wind_max",
"=",
"wind",
"end",
"@winds",
"<<",
"{",
":wind",
"=>",
"wind",
",",
":wind_max",
"=>",
"wind_max",
",",
":wind_direction",
"=>",
"$1",
".",
"to_i",
"}",
"end",
"# variable/unknown direction",
"if",
"s",
"=~",
"/",
"\\d",
"/",
"wind",
"=",
"case",
"$2",
"when",
"\"KT\"",
"then",
"$1",
".",
"to_f",
"*",
"KNOTS_TO_METERS_PER_SECOND",
"when",
"\"MPS\"",
"then",
"$1",
".",
"to_f",
"when",
"\"KMH\"",
"then",
"$1",
".",
"to_f",
"*",
"KILOMETERS_PER_HOUR_TO_METERS_PER_SECOND",
"else",
"nil",
"end",
"@winds",
"<<",
"{",
":wind",
"=>",
"wind",
"}",
"end",
"end"
] | Wind parameters in meters per second | [
"Wind",
"parameters",
"in",
"meters",
"per",
"second"
] | ff8ea6162c7be6137c8e56b768784e58d7c8ad01 | https://github.com/akwiatkowski/simple_metar_parser/blob/ff8ea6162c7be6137c8e56b768784e58d7c8ad01/lib/simple_metar_parser/metar/wind.rb#L24-L80 | train |
akwiatkowski/simple_metar_parser | lib/simple_metar_parser/metar/wind.rb | SimpleMetarParser.Wind.recalculate_winds | def recalculate_winds
wind_sum = @winds.collect { |w| w[:wind] }.inject(0) { |b, i| b + i }
@wind = wind_sum.to_f / @winds.size
if @winds.size == 1
@wind_direction = @winds.first[:wind_direction]
else
@wind_direction = nil
end
end | ruby | def recalculate_winds
wind_sum = @winds.collect { |w| w[:wind] }.inject(0) { |b, i| b + i }
@wind = wind_sum.to_f / @winds.size
if @winds.size == 1
@wind_direction = @winds.first[:wind_direction]
else
@wind_direction = nil
end
end | [
"def",
"recalculate_winds",
"wind_sum",
"=",
"@winds",
".",
"collect",
"{",
"|",
"w",
"|",
"w",
"[",
":wind",
"]",
"}",
".",
"inject",
"(",
"0",
")",
"{",
"|",
"b",
",",
"i",
"|",
"b",
"+",
"i",
"}",
"@wind",
"=",
"wind_sum",
".",
"to_f",
"/",
"@winds",
".",
"size",
"if",
"@winds",
".",
"size",
"==",
"1",
"@wind_direction",
"=",
"@winds",
".",
"first",
"[",
":wind_direction",
"]",
"else",
"@wind_direction",
"=",
"nil",
"end",
"end"
] | Calculate wind parameters, some metar string has multiple winds recorded | [
"Calculate",
"wind",
"parameters",
"some",
"metar",
"string",
"has",
"multiple",
"winds",
"recorded"
] | ff8ea6162c7be6137c8e56b768784e58d7c8ad01 | https://github.com/akwiatkowski/simple_metar_parser/blob/ff8ea6162c7be6137c8e56b768784e58d7c8ad01/lib/simple_metar_parser/metar/wind.rb#L95-L103 | train |
fotonauts/fwissr | lib/fwissr/registry.rb | Fwissr.Registry.add_source | def add_source(source)
@semaphore.synchronize do
@sources << source
end
if @registry.frozen?
# already frozen, must reload everything
self.reload!
else
@semaphore.synchronize do
Fwissr.merge_conf!(@registry, source.get_conf)
end
end
self.ensure_refresh_thread
end | ruby | def add_source(source)
@semaphore.synchronize do
@sources << source
end
if @registry.frozen?
# already frozen, must reload everything
self.reload!
else
@semaphore.synchronize do
Fwissr.merge_conf!(@registry, source.get_conf)
end
end
self.ensure_refresh_thread
end | [
"def",
"add_source",
"(",
"source",
")",
"@semaphore",
".",
"synchronize",
"do",
"@sources",
"<<",
"source",
"end",
"if",
"@registry",
".",
"frozen?",
"# already frozen, must reload everything",
"self",
".",
"reload!",
"else",
"@semaphore",
".",
"synchronize",
"do",
"Fwissr",
".",
"merge_conf!",
"(",
"@registry",
",",
"source",
".",
"get_conf",
")",
"end",
"end",
"self",
".",
"ensure_refresh_thread",
"end"
] | Init
Add a source to registry
@param source [Fwissr::Source] Concrete source instance | [
"Init",
"Add",
"a",
"source",
"to",
"registry"
] | 10da86492f104e98c11fbcd44e4b3cb1f5ac268f | https://github.com/fotonauts/fwissr/blob/10da86492f104e98c11fbcd44e4b3cb1f5ac268f/lib/fwissr/registry.rb#L33-L48 | train |
fotonauts/fwissr | lib/fwissr/registry.rb | Fwissr.Registry.get | def get(key)
# split key
key_ary = key.split('/')
# remove first empty part
key_ary.shift if (key_ary.first == '')
cur_hash = self.registry
key_ary.each do |key_part|
cur_hash = cur_hash[key_part]
return nil if cur_hash.nil?
end
cur_hash
end | ruby | def get(key)
# split key
key_ary = key.split('/')
# remove first empty part
key_ary.shift if (key_ary.first == '')
cur_hash = self.registry
key_ary.each do |key_part|
cur_hash = cur_hash[key_part]
return nil if cur_hash.nil?
end
cur_hash
end | [
"def",
"get",
"(",
"key",
")",
"# split key",
"key_ary",
"=",
"key",
".",
"split",
"(",
"'/'",
")",
"# remove first empty part",
"key_ary",
".",
"shift",
"if",
"(",
"key_ary",
".",
"first",
"==",
"''",
")",
"cur_hash",
"=",
"self",
".",
"registry",
"key_ary",
".",
"each",
"do",
"|",
"key_part",
"|",
"cur_hash",
"=",
"cur_hash",
"[",
"key_part",
"]",
"return",
"nil",
"if",
"cur_hash",
".",
"nil?",
"end",
"cur_hash",
"end"
] | Get a registry key value
@param key [String] Key
@return [Object] Value | [
"Get",
"a",
"registry",
"key",
"value"
] | 10da86492f104e98c11fbcd44e4b3cb1f5ac268f | https://github.com/fotonauts/fwissr/blob/10da86492f104e98c11fbcd44e4b3cb1f5ac268f/lib/fwissr/registry.rb#L60-L74 | train |
acesuares/validation_hints | lib/active_model/hints.rb | ActiveModel.Hints.hints_for | def hints_for(attribute)
result = Array.new
@base.class.validators_on(attribute).map do |v|
validator = v.class.to_s.split('::').last.underscore.gsub('_validator','')
if v.options[:message].is_a?(Symbol)
message_key = [validator, v.options[:message]].join('.') # if a message was supplied as a symbol, we use it instead
result << generate_message(attribute, message_key, v.options)
else
message_key = validator
message_key = [validator, ".must_be_a_number"].join('.') if validator == 'numericality' # create an option for numericality; the way YAML works a key (numericality) with subkeys (greater_than, etc etc) can not have a string itself. So we create a subkey for numericality
result << generate_message(attribute, message_key, v.options) unless VALIDATORS_WITHOUT_MAIN_KEYS.include?(validator)
v.options.each do |o|
if MESSAGES_FOR_OPTIONS.include?(o.first.to_s)
count = o.last
count = (o.last.to_sentence if %w(inclusion exclusion).include?(validator)) rescue o.last
result << generate_message(attribute, [ validator, o.first.to_s ].join('.'), { :count => count } )
end
end
end
end
result
end | ruby | def hints_for(attribute)
result = Array.new
@base.class.validators_on(attribute).map do |v|
validator = v.class.to_s.split('::').last.underscore.gsub('_validator','')
if v.options[:message].is_a?(Symbol)
message_key = [validator, v.options[:message]].join('.') # if a message was supplied as a symbol, we use it instead
result << generate_message(attribute, message_key, v.options)
else
message_key = validator
message_key = [validator, ".must_be_a_number"].join('.') if validator == 'numericality' # create an option for numericality; the way YAML works a key (numericality) with subkeys (greater_than, etc etc) can not have a string itself. So we create a subkey for numericality
result << generate_message(attribute, message_key, v.options) unless VALIDATORS_WITHOUT_MAIN_KEYS.include?(validator)
v.options.each do |o|
if MESSAGES_FOR_OPTIONS.include?(o.first.to_s)
count = o.last
count = (o.last.to_sentence if %w(inclusion exclusion).include?(validator)) rescue o.last
result << generate_message(attribute, [ validator, o.first.to_s ].join('.'), { :count => count } )
end
end
end
end
result
end | [
"def",
"hints_for",
"(",
"attribute",
")",
"result",
"=",
"Array",
".",
"new",
"@base",
".",
"class",
".",
"validators_on",
"(",
"attribute",
")",
".",
"map",
"do",
"|",
"v",
"|",
"validator",
"=",
"v",
".",
"class",
".",
"to_s",
".",
"split",
"(",
"'::'",
")",
".",
"last",
".",
"underscore",
".",
"gsub",
"(",
"'_validator'",
",",
"''",
")",
"if",
"v",
".",
"options",
"[",
":message",
"]",
".",
"is_a?",
"(",
"Symbol",
")",
"message_key",
"=",
"[",
"validator",
",",
"v",
".",
"options",
"[",
":message",
"]",
"]",
".",
"join",
"(",
"'.'",
")",
"# if a message was supplied as a symbol, we use it instead",
"result",
"<<",
"generate_message",
"(",
"attribute",
",",
"message_key",
",",
"v",
".",
"options",
")",
"else",
"message_key",
"=",
"validator",
"message_key",
"=",
"[",
"validator",
",",
"\".must_be_a_number\"",
"]",
".",
"join",
"(",
"'.'",
")",
"if",
"validator",
"==",
"'numericality'",
"# create an option for numericality; the way YAML works a key (numericality) with subkeys (greater_than, etc etc) can not have a string itself. So we create a subkey for numericality",
"result",
"<<",
"generate_message",
"(",
"attribute",
",",
"message_key",
",",
"v",
".",
"options",
")",
"unless",
"VALIDATORS_WITHOUT_MAIN_KEYS",
".",
"include?",
"(",
"validator",
")",
"v",
".",
"options",
".",
"each",
"do",
"|",
"o",
"|",
"if",
"MESSAGES_FOR_OPTIONS",
".",
"include?",
"(",
"o",
".",
"first",
".",
"to_s",
")",
"count",
"=",
"o",
".",
"last",
"count",
"=",
"(",
"o",
".",
"last",
".",
"to_sentence",
"if",
"%w(",
"inclusion",
"exclusion",
")",
".",
"include?",
"(",
"validator",
")",
")",
"rescue",
"o",
".",
"last",
"result",
"<<",
"generate_message",
"(",
"attribute",
",",
"[",
"validator",
",",
"o",
".",
"first",
".",
"to_s",
"]",
".",
"join",
"(",
"'.'",
")",
",",
"{",
":count",
"=>",
"count",
"}",
")",
"end",
"end",
"end",
"end",
"result",
"end"
] | Pass in the instance of the object that is using the errors object.
class Person
def initialize
@errors = ActiveModel::Errors.new(self)
end
end | [
"Pass",
"in",
"the",
"instance",
"of",
"the",
"object",
"that",
"is",
"using",
"the",
"errors",
"object",
"."
] | d6fde8190b06eb266d78019f48ce1e3fa1a99bfe | https://github.com/acesuares/validation_hints/blob/d6fde8190b06eb266d78019f48ce1e3fa1a99bfe/lib/active_model/hints.rb#L46-L67 | train |
atpsoft/dohmysql | lib/dohmysql/handle.rb | DohDb.Handle.select | def select(statement, build_arg = nil)
result_set = generic_query(statement)
DohDb.logger.call('result', "selected #{result_set.size} rows")
rows = get_row_builder(build_arg).build_rows(result_set)
rows
end | ruby | def select(statement, build_arg = nil)
result_set = generic_query(statement)
DohDb.logger.call('result', "selected #{result_set.size} rows")
rows = get_row_builder(build_arg).build_rows(result_set)
rows
end | [
"def",
"select",
"(",
"statement",
",",
"build_arg",
"=",
"nil",
")",
"result_set",
"=",
"generic_query",
"(",
"statement",
")",
"DohDb",
".",
"logger",
".",
"call",
"(",
"'result'",
",",
"\"selected #{result_set.size} rows\"",
")",
"rows",
"=",
"get_row_builder",
"(",
"build_arg",
")",
".",
"build_rows",
"(",
"result_set",
")",
"rows",
"end"
] | The most generic form of select.
It calls to_s on the statement object to facilitate the use of sql builder objects. | [
"The",
"most",
"generic",
"form",
"of",
"select",
".",
"It",
"calls",
"to_s",
"on",
"the",
"statement",
"object",
"to",
"facilitate",
"the",
"use",
"of",
"sql",
"builder",
"objects",
"."
] | 39ba8e4efdc9e7522d531a4498fa9f977901ddaf | https://github.com/atpsoft/dohmysql/blob/39ba8e4efdc9e7522d531a4498fa9f977901ddaf/lib/dohmysql/handle.rb#L100-L105 | train |
atpsoft/dohmysql | lib/dohmysql/handle.rb | DohDb.Handle.select_row | def select_row(statement, build_arg = nil)
rows = select(statement, build_arg)
raise UnexpectedQueryResult, "selected #{rows.size} rows; expected 1" unless rows.size == 1
rows[0]
end | ruby | def select_row(statement, build_arg = nil)
rows = select(statement, build_arg)
raise UnexpectedQueryResult, "selected #{rows.size} rows; expected 1" unless rows.size == 1
rows[0]
end | [
"def",
"select_row",
"(",
"statement",
",",
"build_arg",
"=",
"nil",
")",
"rows",
"=",
"select",
"(",
"statement",
",",
"build_arg",
")",
"raise",
"UnexpectedQueryResult",
",",
"\"selected #{rows.size} rows; expected 1\"",
"unless",
"rows",
".",
"size",
"==",
"1",
"rows",
"[",
"0",
"]",
"end"
] | Simple convenience wrapper around the generic select call.
Throws an exception unless the result set is a single row.
Returns the row selected. | [
"Simple",
"convenience",
"wrapper",
"around",
"the",
"generic",
"select",
"call",
".",
"Throws",
"an",
"exception",
"unless",
"the",
"result",
"set",
"is",
"a",
"single",
"row",
".",
"Returns",
"the",
"row",
"selected",
"."
] | 39ba8e4efdc9e7522d531a4498fa9f977901ddaf | https://github.com/atpsoft/dohmysql/blob/39ba8e4efdc9e7522d531a4498fa9f977901ddaf/lib/dohmysql/handle.rb#L110-L114 | train |
atpsoft/dohmysql | lib/dohmysql/handle.rb | DohDb.Handle.select_optional_row | def select_optional_row(statement, build_arg = nil)
rows = select(statement, build_arg)
raise UnexpectedQueryResult, "selected #{rows.size} rows; expected 0 or 1" if rows.size > 1
if rows.empty? then nil else rows[0] end
end | ruby | def select_optional_row(statement, build_arg = nil)
rows = select(statement, build_arg)
raise UnexpectedQueryResult, "selected #{rows.size} rows; expected 0 or 1" if rows.size > 1
if rows.empty? then nil else rows[0] end
end | [
"def",
"select_optional_row",
"(",
"statement",
",",
"build_arg",
"=",
"nil",
")",
"rows",
"=",
"select",
"(",
"statement",
",",
"build_arg",
")",
"raise",
"UnexpectedQueryResult",
",",
"\"selected #{rows.size} rows; expected 0 or 1\"",
"if",
"rows",
".",
"size",
">",
"1",
"if",
"rows",
".",
"empty?",
"then",
"nil",
"else",
"rows",
"[",
"0",
"]",
"end",
"end"
] | Simple convenience wrapper around the generic select call.
Throws an exception unless the result set is empty or a single row.
Returns nil if the result set is empty, or the row selected. | [
"Simple",
"convenience",
"wrapper",
"around",
"the",
"generic",
"select",
"call",
".",
"Throws",
"an",
"exception",
"unless",
"the",
"result",
"set",
"is",
"empty",
"or",
"a",
"single",
"row",
".",
"Returns",
"nil",
"if",
"the",
"result",
"set",
"is",
"empty",
"or",
"the",
"row",
"selected",
"."
] | 39ba8e4efdc9e7522d531a4498fa9f977901ddaf | https://github.com/atpsoft/dohmysql/blob/39ba8e4efdc9e7522d531a4498fa9f977901ddaf/lib/dohmysql/handle.rb#L119-L123 | train |
atpsoft/dohmysql | lib/dohmysql/handle.rb | DohDb.Handle.select_transpose | def select_transpose(statement, build_arg = nil)
rows = select(statement, build_arg)
return {} if rows.empty?
field_count = rows.first.size
if field_count < 2
raise UnexpectedQueryResult, "must select at least 2 fields in order to transpose"
elsif field_count == 2
Doh.array_to_hash(rows) { |row| [row.at(0), row.at(1)] }
else
key_field = rows.first.keys.first
Doh.array_to_hash(rows) do |row|
value = row.to_h
value.delete(key_field)
[row.at(0), value]
end
end
end | ruby | def select_transpose(statement, build_arg = nil)
rows = select(statement, build_arg)
return {} if rows.empty?
field_count = rows.first.size
if field_count < 2
raise UnexpectedQueryResult, "must select at least 2 fields in order to transpose"
elsif field_count == 2
Doh.array_to_hash(rows) { |row| [row.at(0), row.at(1)] }
else
key_field = rows.first.keys.first
Doh.array_to_hash(rows) do |row|
value = row.to_h
value.delete(key_field)
[row.at(0), value]
end
end
end | [
"def",
"select_transpose",
"(",
"statement",
",",
"build_arg",
"=",
"nil",
")",
"rows",
"=",
"select",
"(",
"statement",
",",
"build_arg",
")",
"return",
"{",
"}",
"if",
"rows",
".",
"empty?",
"field_count",
"=",
"rows",
".",
"first",
".",
"size",
"if",
"field_count",
"<",
"2",
"raise",
"UnexpectedQueryResult",
",",
"\"must select at least 2 fields in order to transpose\"",
"elsif",
"field_count",
"==",
"2",
"Doh",
".",
"array_to_hash",
"(",
"rows",
")",
"{",
"|",
"row",
"|",
"[",
"row",
".",
"at",
"(",
"0",
")",
",",
"row",
".",
"at",
"(",
"1",
")",
"]",
"}",
"else",
"key_field",
"=",
"rows",
".",
"first",
".",
"keys",
".",
"first",
"Doh",
".",
"array_to_hash",
"(",
"rows",
")",
"do",
"|",
"row",
"|",
"value",
"=",
"row",
".",
"to_h",
"value",
".",
"delete",
"(",
"key_field",
")",
"[",
"row",
".",
"at",
"(",
"0",
")",
",",
"value",
"]",
"end",
"end",
"end"
] | Rows in the result set must have 2 or more fields.
If there are 2 fields, returns a hash where each key is the first field in the result set, and the value is the second field.
If there are more than 2 fields, returns a hash where each key is the first field in the result set,
and the value is the row itself, as a Hash, and without the field used as a key. | [
"Rows",
"in",
"the",
"result",
"set",
"must",
"have",
"2",
"or",
"more",
"fields",
".",
"If",
"there",
"are",
"2",
"fields",
"returns",
"a",
"hash",
"where",
"each",
"key",
"is",
"the",
"first",
"field",
"in",
"the",
"result",
"set",
"and",
"the",
"value",
"is",
"the",
"second",
"field",
".",
"If",
"there",
"are",
"more",
"than",
"2",
"fields",
"returns",
"a",
"hash",
"where",
"each",
"key",
"is",
"the",
"first",
"field",
"in",
"the",
"result",
"set",
"and",
"the",
"value",
"is",
"the",
"row",
"itself",
"as",
"a",
"Hash",
"and",
"without",
"the",
"field",
"used",
"as",
"a",
"key",
"."
] | 39ba8e4efdc9e7522d531a4498fa9f977901ddaf | https://github.com/atpsoft/dohmysql/blob/39ba8e4efdc9e7522d531a4498fa9f977901ddaf/lib/dohmysql/handle.rb#L142-L158 | train |
npepinpe/redstruct | lib/redstruct/hash.rb | Redstruct.Hash.get | def get(*keys)
return self.connection.hget(@key, keys.first) if keys.size == 1
return self.connection.mapped_hmget(@key, *keys).reject { |_, v| v.nil? }
end | ruby | def get(*keys)
return self.connection.hget(@key, keys.first) if keys.size == 1
return self.connection.mapped_hmget(@key, *keys).reject { |_, v| v.nil? }
end | [
"def",
"get",
"(",
"*",
"keys",
")",
"return",
"self",
".",
"connection",
".",
"hget",
"(",
"@key",
",",
"keys",
".",
"first",
")",
"if",
"keys",
".",
"size",
"==",
"1",
"return",
"self",
".",
"connection",
".",
"mapped_hmget",
"(",
"@key",
",",
"keys",
")",
".",
"reject",
"{",
"|",
"_",
",",
"v",
"|",
"v",
".",
"nil?",
"}",
"end"
] | Returns the value at key
@param [Array<#to_s>] keys a list of keys to fetch; can be only one
@return [Hash<String, String>] if only one key was passed, then return the value for it; otherwise returns a Ruby hash
where each key in the `keys` is mapped to the value returned by redis | [
"Returns",
"the",
"value",
"at",
"key"
] | c97b45e7227f8ed9029f0effff352fc4d82dc3cb | https://github.com/npepinpe/redstruct/blob/c97b45e7227f8ed9029f0effff352fc4d82dc3cb/lib/redstruct/hash.rb#L22-L25 | train |
npepinpe/redstruct | lib/redstruct/hash.rb | Redstruct.Hash.set | def set(key, value, overwrite: true)
result = if overwrite
self.connection.hset(@key, key, value)
else
self.connection.hsetnx(@key, key, value)
end
return coerce_bool(result)
end | ruby | def set(key, value, overwrite: true)
result = if overwrite
self.connection.hset(@key, key, value)
else
self.connection.hsetnx(@key, key, value)
end
return coerce_bool(result)
end | [
"def",
"set",
"(",
"key",
",",
"value",
",",
"overwrite",
":",
"true",
")",
"result",
"=",
"if",
"overwrite",
"self",
".",
"connection",
".",
"hset",
"(",
"@key",
",",
"key",
",",
"value",
")",
"else",
"self",
".",
"connection",
".",
"hsetnx",
"(",
"@key",
",",
"key",
",",
"value",
")",
"end",
"return",
"coerce_bool",
"(",
"result",
")",
"end"
] | Sets or updates the value at key
@param [#to_s] key the hash key
@param [#to_s] value the new value to set
@return [Boolean] true if the field was set (not updated!), false otherwise | [
"Sets",
"or",
"updates",
"the",
"value",
"at",
"key"
] | c97b45e7227f8ed9029f0effff352fc4d82dc3cb | https://github.com/npepinpe/redstruct/blob/c97b45e7227f8ed9029f0effff352fc4d82dc3cb/lib/redstruct/hash.rb#L39-L47 | train |
npepinpe/redstruct | lib/redstruct/hash.rb | Redstruct.Hash.increment | def increment(key, by: 1)
if by.is_a?(Float)
self.connection.hincrbyfloat(@key, key, by.to_f).to_f
else
self.connection.hincrby(@key, key, by.to_i).to_i
end
end | ruby | def increment(key, by: 1)
if by.is_a?(Float)
self.connection.hincrbyfloat(@key, key, by.to_f).to_f
else
self.connection.hincrby(@key, key, by.to_i).to_i
end
end | [
"def",
"increment",
"(",
"key",
",",
"by",
":",
"1",
")",
"if",
"by",
".",
"is_a?",
"(",
"Float",
")",
"self",
".",
"connection",
".",
"hincrbyfloat",
"(",
"@key",
",",
"key",
",",
"by",
".",
"to_f",
")",
".",
"to_f",
"else",
"self",
".",
"connection",
".",
"hincrby",
"(",
"@key",
",",
"key",
",",
"by",
".",
"to_i",
")",
".",
"to_i",
"end",
"end"
] | Increments the value at the given key
@param [#to_s] key the hash key
@param [Integer, Float] by defaults to 1
@return [Integer, Float] returns the incremented value | [
"Increments",
"the",
"value",
"at",
"the",
"given",
"key"
] | c97b45e7227f8ed9029f0effff352fc4d82dc3cb | https://github.com/npepinpe/redstruct/blob/c97b45e7227f8ed9029f0effff352fc4d82dc3cb/lib/redstruct/hash.rb#L74-L80 | train |
ZhKostev/zh_kostev_ext | lib/controller_extensions/url_ext.rb | ControllerExtensions.UrlExt.url_for | def url_for(options = {})
options = case options
when String
uri = Addressable::URI.new
uri.query_values = @hash_of_additional_params
options + (options.index('?').nil? ? '?' : '&') + "#{uri.query}"
when Hash
options.reverse_merge(@hash_of_additional_params || {})
else
options
end
super
end | ruby | def url_for(options = {})
options = case options
when String
uri = Addressable::URI.new
uri.query_values = @hash_of_additional_params
options + (options.index('?').nil? ? '?' : '&') + "#{uri.query}"
when Hash
options.reverse_merge(@hash_of_additional_params || {})
else
options
end
super
end | [
"def",
"url_for",
"(",
"options",
"=",
"{",
"}",
")",
"options",
"=",
"case",
"options",
"when",
"String",
"uri",
"=",
"Addressable",
"::",
"URI",
".",
"new",
"uri",
".",
"query_values",
"=",
"@hash_of_additional_params",
"options",
"+",
"(",
"options",
".",
"index",
"(",
"'?'",
")",
".",
"nil?",
"?",
"'?'",
":",
"'&'",
")",
"+",
"\"#{uri.query}\"",
"when",
"Hash",
"options",
".",
"reverse_merge",
"(",
"@hash_of_additional_params",
"||",
"{",
"}",
")",
"else",
"options",
"end",
"super",
"end"
] | override default url_for method. Add ability to set default params.
Example:
'auctions_path' return '/auctions' by default
if you set @hash_of_additional_params = {:test => 1, my_param => 2} 'auctions_path' will return '/auctions?test=1&my_param=2'
You can use before_filer to do this stuff automatically.
Example:
in HomeController:
before_filter { @hash_of_additional_params = {:test => '1'} } #this will add test param to all urls in home views | [
"override",
"default",
"url_for",
"method",
".",
"Add",
"ability",
"to",
"set",
"default",
"params",
"."
] | 5233a0896e9a2ffd7414ff09f5e4549099ace2fa | https://github.com/ZhKostev/zh_kostev_ext/blob/5233a0896e9a2ffd7414ff09f5e4549099ace2fa/lib/controller_extensions/url_ext.rb#L15-L28 | train |
NUBIC/aker | lib/aker/group.rb | Aker.Group.include? | def include?(other)
other_name =
case other
when Group; other.name;
else other.to_s;
end
self.find { |g| g.name.downcase == other_name.downcase }
end | ruby | def include?(other)
other_name =
case other
when Group; other.name;
else other.to_s;
end
self.find { |g| g.name.downcase == other_name.downcase }
end | [
"def",
"include?",
"(",
"other",
")",
"other_name",
"=",
"case",
"other",
"when",
"Group",
";",
"other",
".",
"name",
";",
"else",
"other",
".",
"to_s",
";",
"end",
"self",
".",
"find",
"{",
"|",
"g",
"|",
"g",
".",
"name",
".",
"downcase",
"==",
"other_name",
".",
"downcase",
"}",
"end"
] | Creates a new group with the given name. You can add children
using `<<`.
@param [#to_s] name the desired name
@param [Array,nil] args additional arguments. Included for
marshalling compatibility with the base class.
Determines whether this group or any of its children matches the
given parameter for authorization purposes.
@param [#to_s,Group] other the thing to compare this
group to
@return [Boolean] true if the name of this group or any of its
children is a case-insensitive match for the other. | [
"Creates",
"a",
"new",
"group",
"with",
"the",
"given",
"name",
".",
"You",
"can",
"add",
"children",
"using",
"<<",
"."
] | ff43606a8812e38f96bbe71b46e7f631cbeacf1c | https://github.com/NUBIC/aker/blob/ff43606a8812e38f96bbe71b46e7f631cbeacf1c/lib/aker/group.rb#L33-L40 | train |
NUBIC/aker | lib/aker/group.rb | Aker.Group.marshal_load | def marshal_load(dumped_tree_array)
nodes = { }
for node_hash in dumped_tree_array do
name = node_hash[:name]
parent_name = node_hash[:parent]
content = Marshal.load(node_hash[:content])
if parent_name then
nodes[name] = current_node = self.class.new(name, content)
nodes[parent_name].add current_node
else
# This is the root node, hence initialize self.
initialize(name, content)
nodes[name] = self # Add self to the list of nodes
end
end
end | ruby | def marshal_load(dumped_tree_array)
nodes = { }
for node_hash in dumped_tree_array do
name = node_hash[:name]
parent_name = node_hash[:parent]
content = Marshal.load(node_hash[:content])
if parent_name then
nodes[name] = current_node = self.class.new(name, content)
nodes[parent_name].add current_node
else
# This is the root node, hence initialize self.
initialize(name, content)
nodes[name] = self # Add self to the list of nodes
end
end
end | [
"def",
"marshal_load",
"(",
"dumped_tree_array",
")",
"nodes",
"=",
"{",
"}",
"for",
"node_hash",
"in",
"dumped_tree_array",
"do",
"name",
"=",
"node_hash",
"[",
":name",
"]",
"parent_name",
"=",
"node_hash",
"[",
":parent",
"]",
"content",
"=",
"Marshal",
".",
"load",
"(",
"node_hash",
"[",
":content",
"]",
")",
"if",
"parent_name",
"then",
"nodes",
"[",
"name",
"]",
"=",
"current_node",
"=",
"self",
".",
"class",
".",
"new",
"(",
"name",
",",
"content",
")",
"nodes",
"[",
"parent_name",
"]",
".",
"add",
"current_node",
"else",
"# This is the root node, hence initialize self.",
"initialize",
"(",
"name",
",",
"content",
")",
"nodes",
"[",
"name",
"]",
"=",
"self",
"# Add self to the list of nodes",
"end",
"end",
"end"
] | Copy-pasted from parent in order to use appropriate class when
deserializing children.
@private | [
"Copy",
"-",
"pasted",
"from",
"parent",
"in",
"order",
"to",
"use",
"appropriate",
"class",
"when",
"deserializing",
"children",
"."
] | ff43606a8812e38f96bbe71b46e7f631cbeacf1c | https://github.com/NUBIC/aker/blob/ff43606a8812e38f96bbe71b46e7f631cbeacf1c/lib/aker/group.rb#L47-L65 | train |
sugaryourcoffee/syclink | lib/syclink/chrome.rb | SycLink.Chrome.read | def read
serialized = File.read(path)
extract_links(JSON.parse(serialized)).flatten.each_slice(4).to_a
end | ruby | def read
serialized = File.read(path)
extract_links(JSON.parse(serialized)).flatten.each_slice(4).to_a
end | [
"def",
"read",
"serialized",
"=",
"File",
".",
"read",
"(",
"path",
")",
"extract_links",
"(",
"JSON",
".",
"parse",
"(",
"serialized",
")",
")",
".",
"flatten",
".",
"each_slice",
"(",
"4",
")",
".",
"to_a",
"end"
] | Reads the content of the Google Chrome bookmarks file | [
"Reads",
"the",
"content",
"of",
"the",
"Google",
"Chrome",
"bookmarks",
"file"
] | 941ee2045c946daa1e0db394eb643aa82c1254cc | https://github.com/sugaryourcoffee/syclink/blob/941ee2045c946daa1e0db394eb643aa82c1254cc/lib/syclink/chrome.rb#L10-L13 | train |
sugaryourcoffee/syclink | lib/syclink/chrome.rb | SycLink.Chrome.extract_children | def extract_children(tag, children)
children.map do |child|
if child["children"]
extract_children("#{tag},#{child['name']}", child["children"])
else
[child["url"], child["name"], "", tag]
end
end
end | ruby | def extract_children(tag, children)
children.map do |child|
if child["children"]
extract_children("#{tag},#{child['name']}", child["children"])
else
[child["url"], child["name"], "", tag]
end
end
end | [
"def",
"extract_children",
"(",
"tag",
",",
"children",
")",
"children",
".",
"map",
"do",
"|",
"child",
"|",
"if",
"child",
"[",
"\"children\"",
"]",
"extract_children",
"(",
"\"#{tag},#{child['name']}\"",
",",
"child",
"[",
"\"children\"",
"]",
")",
"else",
"[",
"child",
"[",
"\"url\"",
"]",
",",
"child",
"[",
"\"name\"",
"]",
",",
"\"\"",
",",
"tag",
"]",
"end",
"end",
"end"
] | Extracts the children from the JSON file | [
"Extracts",
"the",
"children",
"from",
"the",
"JSON",
"file"
] | 941ee2045c946daa1e0db394eb643aa82c1254cc | https://github.com/sugaryourcoffee/syclink/blob/941ee2045c946daa1e0db394eb643aa82c1254cc/lib/syclink/chrome.rb#L25-L33 | train |
zohararad/handlebarer | lib/handlebarer/template.rb | Handlebarer.Template.evaluate | def evaluate(scope, locals, &block)
c = Handlebarer::Compiler.new
c.compile(data)
end | ruby | def evaluate(scope, locals, &block)
c = Handlebarer::Compiler.new
c.compile(data)
end | [
"def",
"evaluate",
"(",
"scope",
",",
"locals",
",",
"&",
"block",
")",
"c",
"=",
"Handlebarer",
"::",
"Compiler",
".",
"new",
"c",
".",
"compile",
"(",
"data",
")",
"end"
] | Evaluate the template. Compiles the template for JST
@return [String] JST-compliant compiled version of the Handlebars template being rendered | [
"Evaluate",
"the",
"template",
".",
"Compiles",
"the",
"template",
"for",
"JST"
] | f5b2db17cb72fd2874ebe8268cf6f2ae17e74002 | https://github.com/zohararad/handlebarer/blob/f5b2db17cb72fd2874ebe8268cf6f2ae17e74002/lib/handlebarer/template.rb#L24-L27 | train |
mntnorv/puttext | lib/puttext/cmdline.rb | PutText.Cmdline.run | def run(args)
options = parse_args(args)
po_file = Extractor.new.extract(options[:path])
if options[:output_file]
with_output_file(options[:output_file]) { |f| po_file.write_to(f) }
else
po_file.write_to(STDOUT)
end
rescue => e
error(e)
end | ruby | def run(args)
options = parse_args(args)
po_file = Extractor.new.extract(options[:path])
if options[:output_file]
with_output_file(options[:output_file]) { |f| po_file.write_to(f) }
else
po_file.write_to(STDOUT)
end
rescue => e
error(e)
end | [
"def",
"run",
"(",
"args",
")",
"options",
"=",
"parse_args",
"(",
"args",
")",
"po_file",
"=",
"Extractor",
".",
"new",
".",
"extract",
"(",
"options",
"[",
":path",
"]",
")",
"if",
"options",
"[",
":output_file",
"]",
"with_output_file",
"(",
"options",
"[",
":output_file",
"]",
")",
"{",
"|",
"f",
"|",
"po_file",
".",
"write_to",
"(",
"f",
")",
"}",
"else",
"po_file",
".",
"write_to",
"(",
"STDOUT",
")",
"end",
"rescue",
"=>",
"e",
"error",
"(",
"e",
")",
"end"
] | Run the commmand line tool puttext.
@param [Array<String>] args the command line arguments. | [
"Run",
"the",
"commmand",
"line",
"tool",
"puttext",
"."
] | c5c210dff4e11f714418b6b426dc9e2739fe9876 | https://github.com/mntnorv/puttext/blob/c5c210dff4e11f714418b6b426dc9e2739fe9876/lib/puttext/cmdline.rb#L18-L29 | train |
groupdocs-comparison-cloud/groupdocs-comparison-cloud-ruby | lib/groupdocs_comparison_cloud/api/changes_api.rb | GroupDocsComparisonCloud.ChangesApi.put_changes_document_stream_with_http_info | def put_changes_document_stream_with_http_info(request)
raise ArgumentError, 'Incorrect request type' unless request.is_a? PutChangesDocumentStreamRequest
@api_client.config.logger.debug 'Calling API: ChangesApi.put_changes_document_stream ...' if @api_client.config.debugging
# resource path
local_var_path = '/comparison/compareDocuments/changes/stream'
# query parameters
query_params = {}
# header parameters
header_params = {}
# HTTP header 'Accept' (if needed)
header_params['Accept'] = @api_client.select_header_accept(['application/json', 'application/xml'])
# HTTP header 'Content-Type'
header_params['Content-Type'] = @api_client.select_header_content_type(['application/json', 'application/xml'])
# form parameters
form_params = {}
# http body (model)
post_body = @api_client.object_to_http_body(request.request)
data, status_code, headers = @api_client.call_api(:PUT, local_var_path,
header_params: header_params,
query_params: query_params,
form_params: form_params,
body: post_body,
access_token: get_access_token,
return_type: 'File')
if @api_client.config.debugging
@api_client.config.logger.debug "API called:
ChangesApi#put_changes_document_stream\nData: #{data.inspect}\nStatus code: #{status_code}\nHeaders: #{headers}"
end
[data, status_code, headers]
end | ruby | def put_changes_document_stream_with_http_info(request)
raise ArgumentError, 'Incorrect request type' unless request.is_a? PutChangesDocumentStreamRequest
@api_client.config.logger.debug 'Calling API: ChangesApi.put_changes_document_stream ...' if @api_client.config.debugging
# resource path
local_var_path = '/comparison/compareDocuments/changes/stream'
# query parameters
query_params = {}
# header parameters
header_params = {}
# HTTP header 'Accept' (if needed)
header_params['Accept'] = @api_client.select_header_accept(['application/json', 'application/xml'])
# HTTP header 'Content-Type'
header_params['Content-Type'] = @api_client.select_header_content_type(['application/json', 'application/xml'])
# form parameters
form_params = {}
# http body (model)
post_body = @api_client.object_to_http_body(request.request)
data, status_code, headers = @api_client.call_api(:PUT, local_var_path,
header_params: header_params,
query_params: query_params,
form_params: form_params,
body: post_body,
access_token: get_access_token,
return_type: 'File')
if @api_client.config.debugging
@api_client.config.logger.debug "API called:
ChangesApi#put_changes_document_stream\nData: #{data.inspect}\nStatus code: #{status_code}\nHeaders: #{headers}"
end
[data, status_code, headers]
end | [
"def",
"put_changes_document_stream_with_http_info",
"(",
"request",
")",
"raise",
"ArgumentError",
",",
"'Incorrect request type'",
"unless",
"request",
".",
"is_a?",
"PutChangesDocumentStreamRequest",
"@api_client",
".",
"config",
".",
"logger",
".",
"debug",
"'Calling API: ChangesApi.put_changes_document_stream ...'",
"if",
"@api_client",
".",
"config",
".",
"debugging",
"# resource path",
"local_var_path",
"=",
"'/comparison/compareDocuments/changes/stream'",
"# query parameters",
"query_params",
"=",
"{",
"}",
"# header parameters",
"header_params",
"=",
"{",
"}",
"# HTTP header 'Accept' (if needed)",
"header_params",
"[",
"'Accept'",
"]",
"=",
"@api_client",
".",
"select_header_accept",
"(",
"[",
"'application/json'",
",",
"'application/xml'",
"]",
")",
"# HTTP header 'Content-Type'",
"header_params",
"[",
"'Content-Type'",
"]",
"=",
"@api_client",
".",
"select_header_content_type",
"(",
"[",
"'application/json'",
",",
"'application/xml'",
"]",
")",
"# form parameters",
"form_params",
"=",
"{",
"}",
"# http body (model)",
"post_body",
"=",
"@api_client",
".",
"object_to_http_body",
"(",
"request",
".",
"request",
")",
"data",
",",
"status_code",
",",
"headers",
"=",
"@api_client",
".",
"call_api",
"(",
":PUT",
",",
"local_var_path",
",",
"header_params",
":",
"header_params",
",",
"query_params",
":",
"query_params",
",",
"form_params",
":",
"form_params",
",",
"body",
":",
"post_body",
",",
"access_token",
":",
"get_access_token",
",",
"return_type",
":",
"'File'",
")",
"if",
"@api_client",
".",
"config",
".",
"debugging",
"@api_client",
".",
"config",
".",
"logger",
".",
"debug",
"\"API called:\n ChangesApi#put_changes_document_stream\\nData: #{data.inspect}\\nStatus code: #{status_code}\\nHeaders: #{headers}\"",
"end",
"[",
"data",
",",
"status_code",
",",
"headers",
"]",
"end"
] | Applies changes to the document and returns stream of document with the result of comparison
@param request put_changes_document_stream_request
@return [Array<(File, Fixnum, Hash)>]
File data, response status code and response headers | [
"Applies",
"changes",
"to",
"the",
"document",
"and",
"returns",
"stream",
"of",
"document",
"with",
"the",
"result",
"of",
"comparison"
] | c39ed1a23dd7808f98e4a4029031c8d6014f9287 | https://github.com/groupdocs-comparison-cloud/groupdocs-comparison-cloud-ruby/blob/c39ed1a23dd7808f98e4a4029031c8d6014f9287/lib/groupdocs_comparison_cloud/api/changes_api.rb#L243-L277 | train |
groupdocs-comparison-cloud/groupdocs-comparison-cloud-ruby | lib/groupdocs_comparison_cloud/api/changes_api.rb | GroupDocsComparisonCloud.ChangesApi.put_changes_images_with_http_info | def put_changes_images_with_http_info(request)
raise ArgumentError, 'Incorrect request type' unless request.is_a? PutChangesImagesRequest
@api_client.config.logger.debug 'Calling API: ChangesApi.put_changes_images ...' if @api_client.config.debugging
# resource path
local_var_path = '/comparison/compareDocuments/changes/images'
# query parameters
query_params = {}
if local_var_path.include? ('{' + downcase_first_letter('OutFolder') + '}')
local_var_path = local_var_path.sub('{' + downcase_first_letter('OutFolder') + '}', request.out_folder.to_s)
else
query_params[downcase_first_letter('OutFolder')] = request.out_folder unless request.out_folder.nil?
end
# header parameters
header_params = {}
# HTTP header 'Accept' (if needed)
header_params['Accept'] = @api_client.select_header_accept(['application/json', 'application/xml'])
# HTTP header 'Content-Type'
header_params['Content-Type'] = @api_client.select_header_content_type(['application/json', 'application/xml'])
# form parameters
form_params = {}
# http body (model)
post_body = @api_client.object_to_http_body(request.request)
data, status_code, headers = @api_client.call_api(:PUT, local_var_path,
header_params: header_params,
query_params: query_params,
form_params: form_params,
body: post_body,
access_token: get_access_token,
return_type: 'Array<Link>')
if @api_client.config.debugging
@api_client.config.logger.debug "API called:
ChangesApi#put_changes_images\nData: #{data.inspect}\nStatus code: #{status_code}\nHeaders: #{headers}"
end
[data, status_code, headers]
end | ruby | def put_changes_images_with_http_info(request)
raise ArgumentError, 'Incorrect request type' unless request.is_a? PutChangesImagesRequest
@api_client.config.logger.debug 'Calling API: ChangesApi.put_changes_images ...' if @api_client.config.debugging
# resource path
local_var_path = '/comparison/compareDocuments/changes/images'
# query parameters
query_params = {}
if local_var_path.include? ('{' + downcase_first_letter('OutFolder') + '}')
local_var_path = local_var_path.sub('{' + downcase_first_letter('OutFolder') + '}', request.out_folder.to_s)
else
query_params[downcase_first_letter('OutFolder')] = request.out_folder unless request.out_folder.nil?
end
# header parameters
header_params = {}
# HTTP header 'Accept' (if needed)
header_params['Accept'] = @api_client.select_header_accept(['application/json', 'application/xml'])
# HTTP header 'Content-Type'
header_params['Content-Type'] = @api_client.select_header_content_type(['application/json', 'application/xml'])
# form parameters
form_params = {}
# http body (model)
post_body = @api_client.object_to_http_body(request.request)
data, status_code, headers = @api_client.call_api(:PUT, local_var_path,
header_params: header_params,
query_params: query_params,
form_params: form_params,
body: post_body,
access_token: get_access_token,
return_type: 'Array<Link>')
if @api_client.config.debugging
@api_client.config.logger.debug "API called:
ChangesApi#put_changes_images\nData: #{data.inspect}\nStatus code: #{status_code}\nHeaders: #{headers}"
end
[data, status_code, headers]
end | [
"def",
"put_changes_images_with_http_info",
"(",
"request",
")",
"raise",
"ArgumentError",
",",
"'Incorrect request type'",
"unless",
"request",
".",
"is_a?",
"PutChangesImagesRequest",
"@api_client",
".",
"config",
".",
"logger",
".",
"debug",
"'Calling API: ChangesApi.put_changes_images ...'",
"if",
"@api_client",
".",
"config",
".",
"debugging",
"# resource path",
"local_var_path",
"=",
"'/comparison/compareDocuments/changes/images'",
"# query parameters",
"query_params",
"=",
"{",
"}",
"if",
"local_var_path",
".",
"include?",
"(",
"'{'",
"+",
"downcase_first_letter",
"(",
"'OutFolder'",
")",
"+",
"'}'",
")",
"local_var_path",
"=",
"local_var_path",
".",
"sub",
"(",
"'{'",
"+",
"downcase_first_letter",
"(",
"'OutFolder'",
")",
"+",
"'}'",
",",
"request",
".",
"out_folder",
".",
"to_s",
")",
"else",
"query_params",
"[",
"downcase_first_letter",
"(",
"'OutFolder'",
")",
"]",
"=",
"request",
".",
"out_folder",
"unless",
"request",
".",
"out_folder",
".",
"nil?",
"end",
"# header parameters",
"header_params",
"=",
"{",
"}",
"# HTTP header 'Accept' (if needed)",
"header_params",
"[",
"'Accept'",
"]",
"=",
"@api_client",
".",
"select_header_accept",
"(",
"[",
"'application/json'",
",",
"'application/xml'",
"]",
")",
"# HTTP header 'Content-Type'",
"header_params",
"[",
"'Content-Type'",
"]",
"=",
"@api_client",
".",
"select_header_content_type",
"(",
"[",
"'application/json'",
",",
"'application/xml'",
"]",
")",
"# form parameters",
"form_params",
"=",
"{",
"}",
"# http body (model)",
"post_body",
"=",
"@api_client",
".",
"object_to_http_body",
"(",
"request",
".",
"request",
")",
"data",
",",
"status_code",
",",
"headers",
"=",
"@api_client",
".",
"call_api",
"(",
":PUT",
",",
"local_var_path",
",",
"header_params",
":",
"header_params",
",",
"query_params",
":",
"query_params",
",",
"form_params",
":",
"form_params",
",",
"body",
":",
"post_body",
",",
"access_token",
":",
"get_access_token",
",",
"return_type",
":",
"'Array<Link>'",
")",
"if",
"@api_client",
".",
"config",
".",
"debugging",
"@api_client",
".",
"config",
".",
"logger",
".",
"debug",
"\"API called:\n ChangesApi#put_changes_images\\nData: #{data.inspect}\\nStatus code: #{status_code}\\nHeaders: #{headers}\"",
"end",
"[",
"data",
",",
"status_code",
",",
"headers",
"]",
"end"
] | Applies changes to the document and returns images of document with the result of comparison
@param request put_changes_images_request
@return [Array<(Array<Link>, Fixnum, Hash)>]
Array<Link> data, response status code and response headers | [
"Applies",
"changes",
"to",
"the",
"document",
"and",
"returns",
"images",
"of",
"document",
"with",
"the",
"result",
"of",
"comparison"
] | c39ed1a23dd7808f98e4a4029031c8d6014f9287 | https://github.com/groupdocs-comparison-cloud/groupdocs-comparison-cloud-ruby/blob/c39ed1a23dd7808f98e4a4029031c8d6014f9287/lib/groupdocs_comparison_cloud/api/changes_api.rb#L293-L332 | train |
boxgrinder/boxgrinder-core | lib/boxgrinder-core/helpers/appliance-definition-helper.rb | BoxGrinder.ApplianceDefinitionHelper.read_definitions | def read_definitions(definition, content_type = nil)
@appliance_parser.load_schemas
if File.exists?(definition)
definition_file_extension = File.extname(definition)
appliance_config =
case definition_file_extension
when '.appl', '.yml', '.yaml'
@appliance_parser.parse_definition(definition)
else
unless content_type.nil?
case content_type
when 'application/x-yaml', 'text/yaml'
@appliance_parser.parse_definition(definition)
end
end
end
return if appliance_config.nil?
@appliance_configs << appliance_config
appliances = []
@appliance_configs.each { |config| appliances << config.name }
appliance_config.appliances.reverse.each do |appliance_name|
read_definitions("#{File.dirname(definition)}/#{appliance_name}#{definition_file_extension}") unless appliances.include?(appliance_name)
end unless appliance_config.appliances.nil? or !appliance_config.appliances.is_a?(Array)
else
# Assuming that the definition is provided as string
@appliance_configs << @appliance_parser.parse_definition(definition, false)
end
end | ruby | def read_definitions(definition, content_type = nil)
@appliance_parser.load_schemas
if File.exists?(definition)
definition_file_extension = File.extname(definition)
appliance_config =
case definition_file_extension
when '.appl', '.yml', '.yaml'
@appliance_parser.parse_definition(definition)
else
unless content_type.nil?
case content_type
when 'application/x-yaml', 'text/yaml'
@appliance_parser.parse_definition(definition)
end
end
end
return if appliance_config.nil?
@appliance_configs << appliance_config
appliances = []
@appliance_configs.each { |config| appliances << config.name }
appliance_config.appliances.reverse.each do |appliance_name|
read_definitions("#{File.dirname(definition)}/#{appliance_name}#{definition_file_extension}") unless appliances.include?(appliance_name)
end unless appliance_config.appliances.nil? or !appliance_config.appliances.is_a?(Array)
else
# Assuming that the definition is provided as string
@appliance_configs << @appliance_parser.parse_definition(definition, false)
end
end | [
"def",
"read_definitions",
"(",
"definition",
",",
"content_type",
"=",
"nil",
")",
"@appliance_parser",
".",
"load_schemas",
"if",
"File",
".",
"exists?",
"(",
"definition",
")",
"definition_file_extension",
"=",
"File",
".",
"extname",
"(",
"definition",
")",
"appliance_config",
"=",
"case",
"definition_file_extension",
"when",
"'.appl'",
",",
"'.yml'",
",",
"'.yaml'",
"@appliance_parser",
".",
"parse_definition",
"(",
"definition",
")",
"else",
"unless",
"content_type",
".",
"nil?",
"case",
"content_type",
"when",
"'application/x-yaml'",
",",
"'text/yaml'",
"@appliance_parser",
".",
"parse_definition",
"(",
"definition",
")",
"end",
"end",
"end",
"return",
"if",
"appliance_config",
".",
"nil?",
"@appliance_configs",
"<<",
"appliance_config",
"appliances",
"=",
"[",
"]",
"@appliance_configs",
".",
"each",
"{",
"|",
"config",
"|",
"appliances",
"<<",
"config",
".",
"name",
"}",
"appliance_config",
".",
"appliances",
".",
"reverse",
".",
"each",
"do",
"|",
"appliance_name",
"|",
"read_definitions",
"(",
"\"#{File.dirname(definition)}/#{appliance_name}#{definition_file_extension}\"",
")",
"unless",
"appliances",
".",
"include?",
"(",
"appliance_name",
")",
"end",
"unless",
"appliance_config",
".",
"appliances",
".",
"nil?",
"or",
"!",
"appliance_config",
".",
"appliances",
".",
"is_a?",
"(",
"Array",
")",
"else",
"# Assuming that the definition is provided as string",
"@appliance_configs",
"<<",
"@appliance_parser",
".",
"parse_definition",
"(",
"definition",
",",
"false",
")",
"end",
"end"
] | Reads definition provided as string. This string can be a YAML document. In this case
definition is parsed and an ApplianceConfig object is returned. In other cases it tries to search
for a file with provided name. | [
"Reads",
"definition",
"provided",
"as",
"string",
".",
"This",
"string",
"can",
"be",
"a",
"YAML",
"document",
".",
"In",
"this",
"case",
"definition",
"is",
"parsed",
"and",
"an",
"ApplianceConfig",
"object",
"is",
"returned",
".",
"In",
"other",
"cases",
"it",
"tries",
"to",
"search",
"for",
"a",
"file",
"with",
"provided",
"name",
"."
] | 7d54ad1ddf040078b6bab0a4dc94392b2492bde5 | https://github.com/boxgrinder/boxgrinder-core/blob/7d54ad1ddf040078b6bab0a4dc94392b2492bde5/lib/boxgrinder-core/helpers/appliance-definition-helper.rb#L37-L69 | train |
NUBIC/aker | lib/aker/rack/authenticate.rb | Aker::Rack.Authenticate.call | def call(env)
configuration = configuration(env)
warden = env['warden']
if interactive?(env)
warden.authenticate(configuration.ui_mode)
else
warden.authenticate(*configuration.api_modes)
end
env['aker.check'] = Facade.new(configuration, warden.user)
@app.call(env)
end | ruby | def call(env)
configuration = configuration(env)
warden = env['warden']
if interactive?(env)
warden.authenticate(configuration.ui_mode)
else
warden.authenticate(*configuration.api_modes)
end
env['aker.check'] = Facade.new(configuration, warden.user)
@app.call(env)
end | [
"def",
"call",
"(",
"env",
")",
"configuration",
"=",
"configuration",
"(",
"env",
")",
"warden",
"=",
"env",
"[",
"'warden'",
"]",
"if",
"interactive?",
"(",
"env",
")",
"warden",
".",
"authenticate",
"(",
"configuration",
".",
"ui_mode",
")",
"else",
"warden",
".",
"authenticate",
"(",
"configuration",
".",
"api_modes",
")",
"end",
"env",
"[",
"'aker.check'",
"]",
"=",
"Facade",
".",
"new",
"(",
"configuration",
",",
"warden",
".",
"user",
")",
"@app",
".",
"call",
"(",
"env",
")",
"end"
] | Authenticates incoming requests using Warden.
Additionally, this class exposes the `aker.check` environment
variable to downstream middleware and the app. It is an
instance of {Aker::Rack::Facade} permitting authentication and
authorization queries about the current user (if any). | [
"Authenticates",
"incoming",
"requests",
"using",
"Warden",
"."
] | ff43606a8812e38f96bbe71b46e7f631cbeacf1c | https://github.com/NUBIC/aker/blob/ff43606a8812e38f96bbe71b46e7f631cbeacf1c/lib/aker/rack/authenticate.rb#L22-L35 | train |
kot-begemot/localization-middleware | lib/localization-middleware.rb | Localization.Middleware.locale_from_url | def locale_from_url path_info = nil
@locale_set ||= begin
@locale ||= (match = (path_info || @env['PATH_INFO']).match(locale_pattern)) ? match[1] : nil
@env['PATH_INFO'] = match[2] if match && @env.try(:fetch, 'PATH_INFO')
true
end
@locale
end | ruby | def locale_from_url path_info = nil
@locale_set ||= begin
@locale ||= (match = (path_info || @env['PATH_INFO']).match(locale_pattern)) ? match[1] : nil
@env['PATH_INFO'] = match[2] if match && @env.try(:fetch, 'PATH_INFO')
true
end
@locale
end | [
"def",
"locale_from_url",
"path_info",
"=",
"nil",
"@locale_set",
"||=",
"begin",
"@locale",
"||=",
"(",
"match",
"=",
"(",
"path_info",
"||",
"@env",
"[",
"'PATH_INFO'",
"]",
")",
".",
"match",
"(",
"locale_pattern",
")",
")",
"?",
"match",
"[",
"1",
"]",
":",
"nil",
"@env",
"[",
"'PATH_INFO'",
"]",
"=",
"match",
"[",
"2",
"]",
"if",
"match",
"&&",
"@env",
".",
"try",
"(",
":fetch",
",",
"'PATH_INFO'",
")",
"true",
"end",
"@locale",
"end"
] | Determine locale from the request URL and return it as a string, it it
is matching any of provided locales
If locale matching failed an empty String will be returned.
Examples:
#http://www.example.com/se
locale_from_url # => 'se'
#http://www.example.com/de/posts
locale_from_url # => 'se'
#http://www.example.com/ursers
locale_from_url # => '' | [
"Determine",
"locale",
"from",
"the",
"request",
"URL",
"and",
"return",
"it",
"as",
"a",
"string",
"it",
"it",
"is",
"matching",
"any",
"of",
"provided",
"locales",
"If",
"locale",
"matching",
"failed",
"an",
"empty",
"String",
"will",
"be",
"returned",
"."
] | 90df50b28f2b15bfda7d18faf9220d37814da86f | https://github.com/kot-begemot/localization-middleware/blob/90df50b28f2b15bfda7d18faf9220d37814da86f/lib/localization-middleware.rb#L66-L73 | train |
maxim/has_price | lib/has_price/price.rb | HasPrice.Price.method_missing | def method_missing(meth, *args, &blk)
value = select{|k,v| k.underscore == meth.to_s}.first
if !value
super
elsif value.last.is_a?(Hash)
self.class[value.last]
else
value.last
end
end | ruby | def method_missing(meth, *args, &blk)
value = select{|k,v| k.underscore == meth.to_s}.first
if !value
super
elsif value.last.is_a?(Hash)
self.class[value.last]
else
value.last
end
end | [
"def",
"method_missing",
"(",
"meth",
",",
"*",
"args",
",",
"&",
"blk",
")",
"value",
"=",
"select",
"{",
"|",
"k",
",",
"v",
"|",
"k",
".",
"underscore",
"==",
"meth",
".",
"to_s",
"}",
".",
"first",
"if",
"!",
"value",
"super",
"elsif",
"value",
".",
"last",
".",
"is_a?",
"(",
"Hash",
")",
"self",
".",
"class",
"[",
"value",
".",
"last",
"]",
"else",
"value",
".",
"last",
"end",
"end"
] | Provides access to price items and groups using magic methods and chaining.
@example
class Product
has_price do
item 400, "base"
group "tax" do
item 100, "federal"
item 50, "state"
end
end
end
product = Product.new
product.price # => Full Price object
product.price.base # => 400
product.price.tax # => Price object on group tax
product.price.tax.federal # => 100
product.price.tax.total # => 150
@return [Price, Fixnum] Price object if method matches a group, Fixnum if method matches an item. | [
"Provides",
"access",
"to",
"price",
"items",
"and",
"groups",
"using",
"magic",
"methods",
"and",
"chaining",
"."
] | 671c5c7463b0e6540cbb8ac3114da08b99c697bd | https://github.com/maxim/has_price/blob/671c5c7463b0e6540cbb8ac3114da08b99c697bd/lib/has_price/price.rb#L32-L42 | train |
qtcloudservices/qtc-sdk-ruby | lib/qtc/client.rb | Qtc.Client.get | def get(path, params = nil, headers = {})
response = http_client.get(request_uri(path), params, request_headers(headers))
if response.status == 200
parse_response(response)
else
handle_error_response(response)
end
end | ruby | def get(path, params = nil, headers = {})
response = http_client.get(request_uri(path), params, request_headers(headers))
if response.status == 200
parse_response(response)
else
handle_error_response(response)
end
end | [
"def",
"get",
"(",
"path",
",",
"params",
"=",
"nil",
",",
"headers",
"=",
"{",
"}",
")",
"response",
"=",
"http_client",
".",
"get",
"(",
"request_uri",
"(",
"path",
")",
",",
"params",
",",
"request_headers",
"(",
"headers",
")",
")",
"if",
"response",
".",
"status",
"==",
"200",
"parse_response",
"(",
"response",
")",
"else",
"handle_error_response",
"(",
"response",
")",
"end",
"end"
] | Initialize api client
@param [String] api_url
@param [Hash] default_headers
Get request
@param [String] path
@param [Hash,NilClass] params
@return [Hash] | [
"Initialize",
"api",
"client"
] | 42c4f7e2188b63be7e67eca281dd1978809c3886 | https://github.com/qtcloudservices/qtc-sdk-ruby/blob/42c4f7e2188b63be7e67eca281dd1978809c3886/lib/qtc/client.rb#L26-L33 | train |
mixflame/Hokkaido | chronic/lib/chronic/handler.rb | Chronic.Handler.match | def match(tokens, definitions)
token_index = 0
@pattern.each do |element|
name = element.to_s
optional = name[-1, 1] == '?'
name = name.chop if optional
case element
when Symbol
if tags_match?(name, tokens, token_index)
token_index += 1
next
else
if optional
next
else
return false
end
end
when String
return true if optional && token_index == tokens.size
if definitions.key?(name.to_sym)
sub_handlers = definitions[name.to_sym]
else
raise ChronicPain, "Invalid subset #{name} specified"
end
sub_handlers.each do |sub_handler|
return true if sub_handler.match(tokens[token_index..tokens.size], definitions)
end
else
raise ChronicPain, "Invalid match type: #{element.class}"
end
end
return false if token_index != tokens.size
return true
end | ruby | def match(tokens, definitions)
token_index = 0
@pattern.each do |element|
name = element.to_s
optional = name[-1, 1] == '?'
name = name.chop if optional
case element
when Symbol
if tags_match?(name, tokens, token_index)
token_index += 1
next
else
if optional
next
else
return false
end
end
when String
return true if optional && token_index == tokens.size
if definitions.key?(name.to_sym)
sub_handlers = definitions[name.to_sym]
else
raise ChronicPain, "Invalid subset #{name} specified"
end
sub_handlers.each do |sub_handler|
return true if sub_handler.match(tokens[token_index..tokens.size], definitions)
end
else
raise ChronicPain, "Invalid match type: #{element.class}"
end
end
return false if token_index != tokens.size
return true
end | [
"def",
"match",
"(",
"tokens",
",",
"definitions",
")",
"token_index",
"=",
"0",
"@pattern",
".",
"each",
"do",
"|",
"element",
"|",
"name",
"=",
"element",
".",
"to_s",
"optional",
"=",
"name",
"[",
"-",
"1",
",",
"1",
"]",
"==",
"'?'",
"name",
"=",
"name",
".",
"chop",
"if",
"optional",
"case",
"element",
"when",
"Symbol",
"if",
"tags_match?",
"(",
"name",
",",
"tokens",
",",
"token_index",
")",
"token_index",
"+=",
"1",
"next",
"else",
"if",
"optional",
"next",
"else",
"return",
"false",
"end",
"end",
"when",
"String",
"return",
"true",
"if",
"optional",
"&&",
"token_index",
"==",
"tokens",
".",
"size",
"if",
"definitions",
".",
"key?",
"(",
"name",
".",
"to_sym",
")",
"sub_handlers",
"=",
"definitions",
"[",
"name",
".",
"to_sym",
"]",
"else",
"raise",
"ChronicPain",
",",
"\"Invalid subset #{name} specified\"",
"end",
"sub_handlers",
".",
"each",
"do",
"|",
"sub_handler",
"|",
"return",
"true",
"if",
"sub_handler",
".",
"match",
"(",
"tokens",
"[",
"token_index",
"..",
"tokens",
".",
"size",
"]",
",",
"definitions",
")",
"end",
"else",
"raise",
"ChronicPain",
",",
"\"Invalid match type: #{element.class}\"",
"end",
"end",
"return",
"false",
"if",
"token_index",
"!=",
"tokens",
".",
"size",
"return",
"true",
"end"
] | pattern - An Array of patterns to match tokens against.
handler_method - A Symbole representing the method to be invoked
when patterns are matched.
tokens - An Array of tokens to process.
definitions - A Hash of definitions to check against.
Returns true if a match is found. | [
"pattern",
"-",
"An",
"Array",
"of",
"patterns",
"to",
"match",
"tokens",
"against",
".",
"handler_method",
"-",
"A",
"Symbole",
"representing",
"the",
"method",
"to",
"be",
"invoked",
"when",
"patterns",
"are",
"matched",
".",
"tokens",
"-",
"An",
"Array",
"of",
"tokens",
"to",
"process",
".",
"definitions",
"-",
"A",
"Hash",
"of",
"definitions",
"to",
"check",
"against",
"."
] | bf21e7915044576ef74495ccd70d7ff5ee1bcd4b | https://github.com/mixflame/Hokkaido/blob/bf21e7915044576ef74495ccd70d7ff5ee1bcd4b/chronic/lib/chronic/handler.rb#L20-L59 | train |
cdarne/triton | lib/triton/messenger.rb | Triton.Messenger.add_listener | def add_listener(type, once=false, &callback)
listener = Listener.new(type, callback, once)
listeners[type] ||= []
listeners[type] << listener
emit(:new_listener, self, type, once, callback)
listener
end | ruby | def add_listener(type, once=false, &callback)
listener = Listener.new(type, callback, once)
listeners[type] ||= []
listeners[type] << listener
emit(:new_listener, self, type, once, callback)
listener
end | [
"def",
"add_listener",
"(",
"type",
",",
"once",
"=",
"false",
",",
"&",
"callback",
")",
"listener",
"=",
"Listener",
".",
"new",
"(",
"type",
",",
"callback",
",",
"once",
")",
"listeners",
"[",
"type",
"]",
"||=",
"[",
"]",
"listeners",
"[",
"type",
"]",
"<<",
"listener",
"emit",
"(",
":new_listener",
",",
"self",
",",
"type",
",",
"once",
",",
"callback",
")",
"listener",
"end"
] | Register the given block to be called when the events of type +type+ will be emitted.
if +once+, the block will be called once | [
"Register",
"the",
"given",
"block",
"to",
"be",
"called",
"when",
"the",
"events",
"of",
"type",
"+",
"type",
"+",
"will",
"be",
"emitted",
".",
"if",
"+",
"once",
"+",
"the",
"block",
"will",
"be",
"called",
"once"
] | 196ce7784fc414d9751a3492427b506054203185 | https://github.com/cdarne/triton/blob/196ce7784fc414d9751a3492427b506054203185/lib/triton/messenger.rb#L20-L26 | train |
cdarne/triton | lib/triton/messenger.rb | Triton.Messenger.remove_listener | def remove_listener(listener)
type = listener.type
if listeners.has_key? type
listeners[type].delete(listener)
listeners.delete(type) if listeners[type].empty?
end
end | ruby | def remove_listener(listener)
type = listener.type
if listeners.has_key? type
listeners[type].delete(listener)
listeners.delete(type) if listeners[type].empty?
end
end | [
"def",
"remove_listener",
"(",
"listener",
")",
"type",
"=",
"listener",
".",
"type",
"if",
"listeners",
".",
"has_key?",
"type",
"listeners",
"[",
"type",
"]",
".",
"delete",
"(",
"listener",
")",
"listeners",
".",
"delete",
"(",
"type",
")",
"if",
"listeners",
"[",
"type",
"]",
".",
"empty?",
"end",
"end"
] | Unregister the given block. It won't be call then went an event is emitted. | [
"Unregister",
"the",
"given",
"block",
".",
"It",
"won",
"t",
"be",
"call",
"then",
"went",
"an",
"event",
"is",
"emitted",
"."
] | 196ce7784fc414d9751a3492427b506054203185 | https://github.com/cdarne/triton/blob/196ce7784fc414d9751a3492427b506054203185/lib/triton/messenger.rb#L36-L42 | train |
cdarne/triton | lib/triton/messenger.rb | Triton.Messenger.emit | def emit(type, sender=nil, *args)
listeners[type].each { |l| l.fire(sender, *args) } if listeners.has_key? type
end | ruby | def emit(type, sender=nil, *args)
listeners[type].each { |l| l.fire(sender, *args) } if listeners.has_key? type
end | [
"def",
"emit",
"(",
"type",
",",
"sender",
"=",
"nil",
",",
"*",
"args",
")",
"listeners",
"[",
"type",
"]",
".",
"each",
"{",
"|",
"l",
"|",
"l",
".",
"fire",
"(",
"sender",
",",
"args",
")",
"}",
"if",
"listeners",
".",
"has_key?",
"type",
"end"
] | Emit an event of type +type+ and call all the registered listeners to this event.
The +sender+ param will help the listener to identify who is emitting the event.
You can pass then every additional arguments you'll need | [
"Emit",
"an",
"event",
"of",
"type",
"+",
"type",
"+",
"and",
"call",
"all",
"the",
"registered",
"listeners",
"to",
"this",
"event",
".",
"The",
"+",
"sender",
"+",
"param",
"will",
"help",
"the",
"listener",
"to",
"identify",
"who",
"is",
"emitting",
"the",
"event",
".",
"You",
"can",
"pass",
"then",
"every",
"additional",
"arguments",
"you",
"ll",
"need"
] | 196ce7784fc414d9751a3492427b506054203185 | https://github.com/cdarne/triton/blob/196ce7784fc414d9751a3492427b506054203185/lib/triton/messenger.rb#L57-L59 | train |
yipdw/analysand | lib/analysand/change_watcher.rb | Analysand.ChangeWatcher.changes_feed_uri | def changes_feed_uri
query = {
'feed' => 'continuous',
'heartbeat' => '10000'
}
customize_query(query)
uri = (@db.respond_to?(:uri) ? @db.uri : URI(@db)).dup
uri.path += '/_changes'
uri.query = build_query(query)
uri
end | ruby | def changes_feed_uri
query = {
'feed' => 'continuous',
'heartbeat' => '10000'
}
customize_query(query)
uri = (@db.respond_to?(:uri) ? @db.uri : URI(@db)).dup
uri.path += '/_changes'
uri.query = build_query(query)
uri
end | [
"def",
"changes_feed_uri",
"query",
"=",
"{",
"'feed'",
"=>",
"'continuous'",
",",
"'heartbeat'",
"=>",
"'10000'",
"}",
"customize_query",
"(",
"query",
")",
"uri",
"=",
"(",
"@db",
".",
"respond_to?",
"(",
":uri",
")",
"?",
"@db",
".",
"uri",
":",
"URI",
"(",
"@db",
")",
")",
".",
"dup",
"uri",
".",
"path",
"+=",
"'/_changes'",
"uri",
".",
"query",
"=",
"build_query",
"(",
"query",
")",
"uri",
"end"
] | Checks services. If all services pass muster, enters a read loop.
The database parameter may be either a URL-as-string or a
Analysand::Database.
If overriding the initializer, you MUST call super.
The URI of the changes feed. This URI incorporates any changes
made by customize_query. | [
"Checks",
"services",
".",
"If",
"all",
"services",
"pass",
"muster",
"enters",
"a",
"read",
"loop",
"."
] | bc62e67031bf7e813e49538669f7434f2efd9ee9 | https://github.com/yipdw/analysand/blob/bc62e67031bf7e813e49538669f7434f2efd9ee9/lib/analysand/change_watcher.rb#L93-L105 | train |
yipdw/analysand | lib/analysand/change_watcher.rb | Analysand.ChangeWatcher.waiter_for | def waiter_for(id)
@waiting[id] = true
Waiter.new do
loop do
break true if !@waiting[id]
sleep 0.1
end
end
end | ruby | def waiter_for(id)
@waiting[id] = true
Waiter.new do
loop do
break true if !@waiting[id]
sleep 0.1
end
end
end | [
"def",
"waiter_for",
"(",
"id",
")",
"@waiting",
"[",
"id",
"]",
"=",
"true",
"Waiter",
".",
"new",
"do",
"loop",
"do",
"break",
"true",
"if",
"!",
"@waiting",
"[",
"id",
"]",
"sleep",
"0.1",
"end",
"end",
"end"
] | Returns an object that can be used to block a thread until a document
with the given ID has been processed.
Intended for testing. | [
"Returns",
"an",
"object",
"that",
"can",
"be",
"used",
"to",
"block",
"a",
"thread",
"until",
"a",
"document",
"with",
"the",
"given",
"ID",
"has",
"been",
"processed",
"."
] | bc62e67031bf7e813e49538669f7434f2efd9ee9 | https://github.com/yipdw/analysand/blob/bc62e67031bf7e813e49538669f7434f2efd9ee9/lib/analysand/change_watcher.rb#L208-L217 | train |
netzpirat/guard-rspectacle | lib/guard/rspectacle.rb | Guard.RSpectacle.reload | def reload
Dir.glob('**/*.rb').each { |file| Reloader.reload_file(file) }
self.last_run_passed = true
self.rerun_specs = []
end | ruby | def reload
Dir.glob('**/*.rb').each { |file| Reloader.reload_file(file) }
self.last_run_passed = true
self.rerun_specs = []
end | [
"def",
"reload",
"Dir",
".",
"glob",
"(",
"'**/*.rb'",
")",
".",
"each",
"{",
"|",
"file",
"|",
"Reloader",
".",
"reload_file",
"(",
"file",
")",
"}",
"self",
".",
"last_run_passed",
"=",
"true",
"self",
".",
"rerun_specs",
"=",
"[",
"]",
"end"
] | Gets called when the Guard should reload itself.
@raise [:task_has_failed] when run_on_change has failed | [
"Gets",
"called",
"when",
"the",
"Guard",
"should",
"reload",
"itself",
"."
] | e71dacfa8ab0a2d7f3ec8c0933190268ed17344a | https://github.com/netzpirat/guard-rspectacle/blob/e71dacfa8ab0a2d7f3ec8c0933190268ed17344a/lib/guard/rspectacle.rb#L66-L71 | train |
ktonon/code_node | spec/fixtures/activerecord/src/active_record/counter_cache.rb | ActiveRecord.CounterCache.reset_counters | def reset_counters(id, *counters)
object = find(id)
counters.each do |association|
has_many_association = reflect_on_association(association.to_sym)
if has_many_association.options[:as]
has_many_association.options[:as].to_s.classify
else
self.name
end
if has_many_association.is_a? ActiveRecord::Reflection::ThroughReflection
has_many_association = has_many_association.through_reflection
end
foreign_key = has_many_association.foreign_key.to_s
child_class = has_many_association.klass
belongs_to = child_class.reflect_on_all_associations(:belongs_to)
reflection = belongs_to.find { |e| e.foreign_key.to_s == foreign_key && e.options[:counter_cache].present? }
counter_name = reflection.counter_cache_column
stmt = unscoped.where(arel_table[primary_key].eq(object.id)).arel.compile_update({
arel_table[counter_name] => object.send(association).count
})
connection.update stmt
end
return true
end | ruby | def reset_counters(id, *counters)
object = find(id)
counters.each do |association|
has_many_association = reflect_on_association(association.to_sym)
if has_many_association.options[:as]
has_many_association.options[:as].to_s.classify
else
self.name
end
if has_many_association.is_a? ActiveRecord::Reflection::ThroughReflection
has_many_association = has_many_association.through_reflection
end
foreign_key = has_many_association.foreign_key.to_s
child_class = has_many_association.klass
belongs_to = child_class.reflect_on_all_associations(:belongs_to)
reflection = belongs_to.find { |e| e.foreign_key.to_s == foreign_key && e.options[:counter_cache].present? }
counter_name = reflection.counter_cache_column
stmt = unscoped.where(arel_table[primary_key].eq(object.id)).arel.compile_update({
arel_table[counter_name] => object.send(association).count
})
connection.update stmt
end
return true
end | [
"def",
"reset_counters",
"(",
"id",
",",
"*",
"counters",
")",
"object",
"=",
"find",
"(",
"id",
")",
"counters",
".",
"each",
"do",
"|",
"association",
"|",
"has_many_association",
"=",
"reflect_on_association",
"(",
"association",
".",
"to_sym",
")",
"if",
"has_many_association",
".",
"options",
"[",
":as",
"]",
"has_many_association",
".",
"options",
"[",
":as",
"]",
".",
"to_s",
".",
"classify",
"else",
"self",
".",
"name",
"end",
"if",
"has_many_association",
".",
"is_a?",
"ActiveRecord",
"::",
"Reflection",
"::",
"ThroughReflection",
"has_many_association",
"=",
"has_many_association",
".",
"through_reflection",
"end",
"foreign_key",
"=",
"has_many_association",
".",
"foreign_key",
".",
"to_s",
"child_class",
"=",
"has_many_association",
".",
"klass",
"belongs_to",
"=",
"child_class",
".",
"reflect_on_all_associations",
"(",
":belongs_to",
")",
"reflection",
"=",
"belongs_to",
".",
"find",
"{",
"|",
"e",
"|",
"e",
".",
"foreign_key",
".",
"to_s",
"==",
"foreign_key",
"&&",
"e",
".",
"options",
"[",
":counter_cache",
"]",
".",
"present?",
"}",
"counter_name",
"=",
"reflection",
".",
"counter_cache_column",
"stmt",
"=",
"unscoped",
".",
"where",
"(",
"arel_table",
"[",
"primary_key",
"]",
".",
"eq",
"(",
"object",
".",
"id",
")",
")",
".",
"arel",
".",
"compile_update",
"(",
"{",
"arel_table",
"[",
"counter_name",
"]",
"=>",
"object",
".",
"send",
"(",
"association",
")",
".",
"count",
"}",
")",
"connection",
".",
"update",
"stmt",
"end",
"return",
"true",
"end"
] | Resets one or more counter caches to their correct value using an SQL
count query. This is useful when adding new counter caches, or if the
counter has been corrupted or modified directly by SQL.
==== Parameters
* +id+ - The id of the object you wish to reset a counter on.
* +counters+ - One or more counter names to reset
==== Examples
# For Post with id #1 records reset the comments_count
Post.reset_counters(1, :comments) | [
"Resets",
"one",
"or",
"more",
"counter",
"caches",
"to",
"their",
"correct",
"value",
"using",
"an",
"SQL",
"count",
"query",
".",
"This",
"is",
"useful",
"when",
"adding",
"new",
"counter",
"caches",
"or",
"if",
"the",
"counter",
"has",
"been",
"corrupted",
"or",
"modified",
"directly",
"by",
"SQL",
"."
] | 48d5d1a7442d9cade602be4fb782a1b56c7677f5 | https://github.com/ktonon/code_node/blob/48d5d1a7442d9cade602be4fb782a1b56c7677f5/spec/fixtures/activerecord/src/active_record/counter_cache.rb#L17-L44 | train |
iamcutler/deal-redemptions | app/controllers/deal_redemptions/admin/redeem_codes_controller.rb | DealRedemptions.Admin::RedeemCodesController.build_search_query | def build_search_query
string = params[:search].split ' '
redeem_codes = DealRedemptions::RedeemCode.arel_table
companies = DealRedemptions::Company.arel_table
query = redeem_codes.project(
redeem_codes[:id],
redeem_codes[:company_id],
redeem_codes[:code],
redeem_codes[:status],
redeem_codes[:created_at]
)
.join(companies)
.on(redeem_codes[:company_id]
.eq(companies[:id]))
string.each do |s|
query.where(redeem_codes[:code].matches("%#{s}%"))
end
query.to_sql
end | ruby | def build_search_query
string = params[:search].split ' '
redeem_codes = DealRedemptions::RedeemCode.arel_table
companies = DealRedemptions::Company.arel_table
query = redeem_codes.project(
redeem_codes[:id],
redeem_codes[:company_id],
redeem_codes[:code],
redeem_codes[:status],
redeem_codes[:created_at]
)
.join(companies)
.on(redeem_codes[:company_id]
.eq(companies[:id]))
string.each do |s|
query.where(redeem_codes[:code].matches("%#{s}%"))
end
query.to_sql
end | [
"def",
"build_search_query",
"string",
"=",
"params",
"[",
":search",
"]",
".",
"split",
"' '",
"redeem_codes",
"=",
"DealRedemptions",
"::",
"RedeemCode",
".",
"arel_table",
"companies",
"=",
"DealRedemptions",
"::",
"Company",
".",
"arel_table",
"query",
"=",
"redeem_codes",
".",
"project",
"(",
"redeem_codes",
"[",
":id",
"]",
",",
"redeem_codes",
"[",
":company_id",
"]",
",",
"redeem_codes",
"[",
":code",
"]",
",",
"redeem_codes",
"[",
":status",
"]",
",",
"redeem_codes",
"[",
":created_at",
"]",
")",
".",
"join",
"(",
"companies",
")",
".",
"on",
"(",
"redeem_codes",
"[",
":company_id",
"]",
".",
"eq",
"(",
"companies",
"[",
":id",
"]",
")",
")",
"string",
".",
"each",
"do",
"|",
"s",
"|",
"query",
".",
"where",
"(",
"redeem_codes",
"[",
":code",
"]",
".",
"matches",
"(",
"\"%#{s}%\"",
")",
")",
"end",
"query",
".",
"to_sql",
"end"
] | Search redemption codes | [
"Search",
"redemption",
"codes"
] | b9b06df288c84a5bb0c0588ad0beca80b14edd31 | https://github.com/iamcutler/deal-redemptions/blob/b9b06df288c84a5bb0c0588ad0beca80b14edd31/app/controllers/deal_redemptions/admin/redeem_codes_controller.rb#L80-L100 | train |
ryansobol/mango | lib/mango/runner.rb | Mango.Runner.create | def create(path)
self.destination_root = path
copy_file(".gitignore")
copy_file("config.ru")
copy_file("Gemfile")
copy_file("Procfile")
copy_file("README.md")
copy_content
copy_themes
end | ruby | def create(path)
self.destination_root = path
copy_file(".gitignore")
copy_file("config.ru")
copy_file("Gemfile")
copy_file("Procfile")
copy_file("README.md")
copy_content
copy_themes
end | [
"def",
"create",
"(",
"path",
")",
"self",
".",
"destination_root",
"=",
"path",
"copy_file",
"(",
"\".gitignore\"",
")",
"copy_file",
"(",
"\"config.ru\"",
")",
"copy_file",
"(",
"\"Gemfile\"",
")",
"copy_file",
"(",
"\"Procfile\"",
")",
"copy_file",
"(",
"\"README.md\"",
")",
"copy_content",
"copy_themes",
"end"
] | Creates a new Mango application at the specified path
@param [String] path | [
"Creates",
"a",
"new",
"Mango",
"application",
"at",
"the",
"specified",
"path"
] | f28f1fb9ff2820f11e6b9f96cdd92576774da12f | https://github.com/ryansobol/mango/blob/f28f1fb9ff2820f11e6b9f96cdd92576774da12f/lib/mango/runner.rb#L18-L29 | train |
conversation/raca | lib/raca/server.rb | Raca.Server.details | def details
data = servers_client.get(server_path, json_headers).body
JSON.parse(data)['server']
end | ruby | def details
data = servers_client.get(server_path, json_headers).body
JSON.parse(data)['server']
end | [
"def",
"details",
"data",
"=",
"servers_client",
".",
"get",
"(",
"server_path",
",",
"json_headers",
")",
".",
"body",
"JSON",
".",
"parse",
"(",
"data",
")",
"[",
"'server'",
"]",
"end"
] | A Hash of various matadata about the server | [
"A",
"Hash",
"of",
"various",
"matadata",
"about",
"the",
"server"
] | fa69dfde22359cc0e06f655055be4eadcc7019c0 | https://github.com/conversation/raca/blob/fa69dfde22359cc0e06f655055be4eadcc7019c0/lib/raca/server.rb#L51-L54 | train |
brianmichel/Crate-API | lib/crate_api/crates.rb | CrateAPI.Crates.add | def add(name)
response = JSON.parse(CrateAPI::Base.call("#{CrateAPI::Base::CRATES_URL}/#{CRATE_ACTIONS[:add]}", :post, {:body => {:name => name}}))
raise CrateLimitReachedError, response["message"] unless response["status"] != "failure"
end | ruby | def add(name)
response = JSON.parse(CrateAPI::Base.call("#{CrateAPI::Base::CRATES_URL}/#{CRATE_ACTIONS[:add]}", :post, {:body => {:name => name}}))
raise CrateLimitReachedError, response["message"] unless response["status"] != "failure"
end | [
"def",
"add",
"(",
"name",
")",
"response",
"=",
"JSON",
".",
"parse",
"(",
"CrateAPI",
"::",
"Base",
".",
"call",
"(",
"\"#{CrateAPI::Base::CRATES_URL}/#{CRATE_ACTIONS[:add]}\"",
",",
":post",
",",
"{",
":body",
"=>",
"{",
":name",
"=>",
"name",
"}",
"}",
")",
")",
"raise",
"CrateLimitReachedError",
",",
"response",
"[",
"\"message\"",
"]",
"unless",
"response",
"[",
"\"status\"",
"]",
"!=",
"\"failure\"",
"end"
] | Add a new crate.
@param [String] name of the crate to add.
@return [nil] no output from this method is expected if everything goes right. | [
"Add",
"a",
"new",
"crate",
"."
] | 722fcbd08a40c5e0a622a2bdaa3687a753cc7970 | https://github.com/brianmichel/Crate-API/blob/722fcbd08a40c5e0a622a2bdaa3687a753cc7970/lib/crate_api/crates.rb#L20-L23 | train |
OSHPark/ruby-api-client | lib/oshpark/client.rb | Oshpark.Client.authenticate | def authenticate email, credentials={}
if password = credentials[:with_password]
refresh_token email: email, password: password
elsif secret = credentials[:with_api_secret]
api_key = OpenSSL::Digest::SHA256.new("#{email}:#{secret}:#{token.token}").to_s
refresh_token email: email, api_key: api_key
else
raise ArgumentError, "Must provide either `with_password` or `with_api_secret` arguments."
end
end | ruby | def authenticate email, credentials={}
if password = credentials[:with_password]
refresh_token email: email, password: password
elsif secret = credentials[:with_api_secret]
api_key = OpenSSL::Digest::SHA256.new("#{email}:#{secret}:#{token.token}").to_s
refresh_token email: email, api_key: api_key
else
raise ArgumentError, "Must provide either `with_password` or `with_api_secret` arguments."
end
end | [
"def",
"authenticate",
"email",
",",
"credentials",
"=",
"{",
"}",
"if",
"password",
"=",
"credentials",
"[",
":with_password",
"]",
"refresh_token",
"email",
":",
"email",
",",
"password",
":",
"password",
"elsif",
"secret",
"=",
"credentials",
"[",
":with_api_secret",
"]",
"api_key",
"=",
"OpenSSL",
"::",
"Digest",
"::",
"SHA256",
".",
"new",
"(",
"\"#{email}:#{secret}:#{token.token}\"",
")",
".",
"to_s",
"refresh_token",
"email",
":",
"email",
",",
"api_key",
":",
"api_key",
"else",
"raise",
"ArgumentError",
",",
"\"Must provide either `with_password` or `with_api_secret` arguments.\"",
"end",
"end"
] | Create an new Client object.
@param connection:
pass in a subclass of connection which implements the `request` method
with whichever HTTP client library you prefer. Default is Net::HTTP.
Authenticate to the API using a email and password.
@param email
@param credentials
A hash with either the `with_password` or `with_api_secret` key. | [
"Create",
"an",
"new",
"Client",
"object",
"."
] | 629c633c6c2189e2634b4b8721e6f0711209703b | https://github.com/OSHPark/ruby-api-client/blob/629c633c6c2189e2634b4b8721e6f0711209703b/lib/oshpark/client.rb#L30-L39 | train |
OSHPark/ruby-api-client | lib/oshpark/client.rb | Oshpark.Client.pricing | def pricing width, height, pcb_layers, quantity = nil
post_request "pricing", {width_in_mils: width, height_in_mils: height, pcb_layers: pcb_layers, quantity: quantity}
end | ruby | def pricing width, height, pcb_layers, quantity = nil
post_request "pricing", {width_in_mils: width, height_in_mils: height, pcb_layers: pcb_layers, quantity: quantity}
end | [
"def",
"pricing",
"width",
",",
"height",
",",
"pcb_layers",
",",
"quantity",
"=",
"nil",
"post_request",
"\"pricing\"",
",",
"{",
"width_in_mils",
":",
"width",
",",
"height_in_mils",
":",
"height",
",",
"pcb_layers",
":",
"pcb_layers",
",",
"quantity",
":",
"quantity",
"}",
"end"
] | Request a price estimate
@param width In thousands of an Inch
@param height In thousands of an Inch
@param layers
@param quantity Optional Defaults to the minimum quantity | [
"Request",
"a",
"price",
"estimate"
] | 629c633c6c2189e2634b4b8721e6f0711209703b | https://github.com/OSHPark/ruby-api-client/blob/629c633c6c2189e2634b4b8721e6f0711209703b/lib/oshpark/client.rb#L91-L93 | train |
OSHPark/ruby-api-client | lib/oshpark/client.rb | Oshpark.Client.add_order_item | def add_order_item id, project_id, quantity
post_request "orders/#{id}/add_item", {order: {project_id: project_id, quantity: quantity}}
end | ruby | def add_order_item id, project_id, quantity
post_request "orders/#{id}/add_item", {order: {project_id: project_id, quantity: quantity}}
end | [
"def",
"add_order_item",
"id",
",",
"project_id",
",",
"quantity",
"post_request",
"\"orders/#{id}/add_item\"",
",",
"{",
"order",
":",
"{",
"project_id",
":",
"project_id",
",",
"quantity",
":",
"quantity",
"}",
"}",
"end"
] | Add a Project to an Order
@param id
@param project_id
@param quantity | [
"Add",
"a",
"Project",
"to",
"an",
"Order"
] | 629c633c6c2189e2634b4b8721e6f0711209703b | https://github.com/OSHPark/ruby-api-client/blob/629c633c6c2189e2634b4b8721e6f0711209703b/lib/oshpark/client.rb#L117-L119 | train |
butchmarshall/ruby-jive-signed_request | lib/jive/signed_request.rb | Jive.SignedRequest.sign | def sign(string, secret, algorithm = nil)
plain = ::Base64.decode64(secret.gsub(/\.s$/,''))
# if no override algorithm passed try and extract from string
if algorithm.nil?
paramMap = ::CGI.parse string
if !paramMap.has_key?("algorithm")
raise ArgumentError, "missing algorithm"
end
algorithm = paramMap["algorithm"].first.gsub(/^hmac/i,'')
end
hmac = ::OpenSSL::HMAC.digest(algorithm, plain, string)
Base64::encode64(hmac).gsub(/\n$/,'')
end | ruby | def sign(string, secret, algorithm = nil)
plain = ::Base64.decode64(secret.gsub(/\.s$/,''))
# if no override algorithm passed try and extract from string
if algorithm.nil?
paramMap = ::CGI.parse string
if !paramMap.has_key?("algorithm")
raise ArgumentError, "missing algorithm"
end
algorithm = paramMap["algorithm"].first.gsub(/^hmac/i,'')
end
hmac = ::OpenSSL::HMAC.digest(algorithm, plain, string)
Base64::encode64(hmac).gsub(/\n$/,'')
end | [
"def",
"sign",
"(",
"string",
",",
"secret",
",",
"algorithm",
"=",
"nil",
")",
"plain",
"=",
"::",
"Base64",
".",
"decode64",
"(",
"secret",
".",
"gsub",
"(",
"/",
"\\.",
"/",
",",
"''",
")",
")",
"# if no override algorithm passed try and extract from string",
"if",
"algorithm",
".",
"nil?",
"paramMap",
"=",
"::",
"CGI",
".",
"parse",
"string",
"if",
"!",
"paramMap",
".",
"has_key?",
"(",
"\"algorithm\"",
")",
"raise",
"ArgumentError",
",",
"\"missing algorithm\"",
"end",
"algorithm",
"=",
"paramMap",
"[",
"\"algorithm\"",
"]",
".",
"first",
".",
"gsub",
"(",
"/",
"/i",
",",
"''",
")",
"end",
"hmac",
"=",
"::",
"OpenSSL",
"::",
"HMAC",
".",
"digest",
"(",
"algorithm",
",",
"plain",
",",
"string",
")",
"Base64",
"::",
"encode64",
"(",
"hmac",
")",
".",
"gsub",
"(",
"/",
"\\n",
"/",
",",
"''",
")",
"end"
] | Sign a string with a secret
Sign a string with a secret and get the signature
* *Args* :
- +string+ -> the string to sign
- +secret+ -> the secret to use
* *Returns* :
- the signature
* *Raises* :
- +ArgumentError+ -> if no algorithm passed and algorithm could not be derived from the string | [
"Sign",
"a",
"string",
"with",
"a",
"secret"
] | 98dbbcdfbba7a212cfad6dbeeca620f6a634a3a9 | https://github.com/butchmarshall/ruby-jive-signed_request/blob/98dbbcdfbba7a212cfad6dbeeca620f6a634a3a9/lib/jive/signed_request.rb#L23-L39 | train |
butchmarshall/ruby-jive-signed_request | lib/jive/signed_request.rb | Jive.SignedRequest.authenticate | def authenticate(authorization_header, client_secret)
# Validate JiveEXTN part of header
if !authorization_header.match(/^JiveEXTN/)
raise ArgumentError, "Jive authorization header is not properly formatted, must start with JiveEXTN"
end
paramMap = ::CGI.parse authorization_header.gsub(/^JiveEXTN\s/,'')
# Validate all parameters are passed from header
if !paramMap.has_key?("algorithm") ||
!paramMap.has_key?("client_id") ||
!paramMap.has_key?("jive_url") ||
!paramMap.has_key?("tenant_id") ||
!paramMap.has_key?("timestamp") ||
!paramMap.has_key?("signature")
raise ArgumentError, "Jive authorization header is partial"
end
# Validate timestamp is still valid
timestamp = Time.at(paramMap["timestamp"].first.to_i/1000)
secondsPassed = Time.now - timestamp
if secondsPassed < 0 || secondsPassed > (5*60)
raise ArgumentError, "Jive authorization is rejected since it's #{ secondsPassed } seconds old (max. allowed is 5 minutes)"
end
self.sign(authorization_header.gsub(/^JiveEXTN\s/,'').gsub(/\&signature[^$]+/,''), client_secret) === paramMap["signature"].first
end | ruby | def authenticate(authorization_header, client_secret)
# Validate JiveEXTN part of header
if !authorization_header.match(/^JiveEXTN/)
raise ArgumentError, "Jive authorization header is not properly formatted, must start with JiveEXTN"
end
paramMap = ::CGI.parse authorization_header.gsub(/^JiveEXTN\s/,'')
# Validate all parameters are passed from header
if !paramMap.has_key?("algorithm") ||
!paramMap.has_key?("client_id") ||
!paramMap.has_key?("jive_url") ||
!paramMap.has_key?("tenant_id") ||
!paramMap.has_key?("timestamp") ||
!paramMap.has_key?("signature")
raise ArgumentError, "Jive authorization header is partial"
end
# Validate timestamp is still valid
timestamp = Time.at(paramMap["timestamp"].first.to_i/1000)
secondsPassed = Time.now - timestamp
if secondsPassed < 0 || secondsPassed > (5*60)
raise ArgumentError, "Jive authorization is rejected since it's #{ secondsPassed } seconds old (max. allowed is 5 minutes)"
end
self.sign(authorization_header.gsub(/^JiveEXTN\s/,'').gsub(/\&signature[^$]+/,''), client_secret) === paramMap["signature"].first
end | [
"def",
"authenticate",
"(",
"authorization_header",
",",
"client_secret",
")",
"# Validate JiveEXTN part of header",
"if",
"!",
"authorization_header",
".",
"match",
"(",
"/",
"/",
")",
"raise",
"ArgumentError",
",",
"\"Jive authorization header is not properly formatted, must start with JiveEXTN\"",
"end",
"paramMap",
"=",
"::",
"CGI",
".",
"parse",
"authorization_header",
".",
"gsub",
"(",
"/",
"\\s",
"/",
",",
"''",
")",
"# Validate all parameters are passed from header",
"if",
"!",
"paramMap",
".",
"has_key?",
"(",
"\"algorithm\"",
")",
"||",
"!",
"paramMap",
".",
"has_key?",
"(",
"\"client_id\"",
")",
"||",
"!",
"paramMap",
".",
"has_key?",
"(",
"\"jive_url\"",
")",
"||",
"!",
"paramMap",
".",
"has_key?",
"(",
"\"tenant_id\"",
")",
"||",
"!",
"paramMap",
".",
"has_key?",
"(",
"\"timestamp\"",
")",
"||",
"!",
"paramMap",
".",
"has_key?",
"(",
"\"signature\"",
")",
"raise",
"ArgumentError",
",",
"\"Jive authorization header is partial\"",
"end",
"# Validate timestamp is still valid",
"timestamp",
"=",
"Time",
".",
"at",
"(",
"paramMap",
"[",
"\"timestamp\"",
"]",
".",
"first",
".",
"to_i",
"/",
"1000",
")",
"secondsPassed",
"=",
"Time",
".",
"now",
"-",
"timestamp",
"if",
"secondsPassed",
"<",
"0",
"||",
"secondsPassed",
">",
"(",
"5",
"*",
"60",
")",
"raise",
"ArgumentError",
",",
"\"Jive authorization is rejected since it's #{ secondsPassed } seconds old (max. allowed is 5 minutes)\"",
"end",
"self",
".",
"sign",
"(",
"authorization_header",
".",
"gsub",
"(",
"/",
"\\s",
"/",
",",
"''",
")",
".",
"gsub",
"(",
"/",
"\\&",
"/",
",",
"''",
")",
",",
"client_secret",
")",
"===",
"paramMap",
"[",
"\"signature\"",
"]",
".",
"first",
"end"
] | Authenticate an authorization header
Authenticates that an authorization header sent by Jive is valid given an apps secret
* *Args* :
- +authorization_header+ -> the entire Authorization header sent by Jive
- +client_secret+ -> the client secret to authenticate the header with
* *Returns* :
- the signature
* *Raises* :
- +ArgumentError+ -> if the authorization_header does not contain JiveEXTN
- +ArgumentError+ -> if the heauthorization_header does not contain all the required parameters
- +ArgumentError+ -> if the heauthorization_header has expired (more than 5 minutes old) | [
"Authenticate",
"an",
"authorization",
"header"
] | 98dbbcdfbba7a212cfad6dbeeca620f6a634a3a9 | https://github.com/butchmarshall/ruby-jive-signed_request/blob/98dbbcdfbba7a212cfad6dbeeca620f6a634a3a9/lib/jive/signed_request.rb#L55-L82 | train |
butchmarshall/ruby-jive-signed_request | lib/jive/signed_request.rb | Jive.SignedRequest.validate_registration | def validate_registration(validationBlock, *args)
options = ((args.last.is_a?(Hash)) ? args.pop : {})
require "open-uri"
require "net/http"
require "openssl"
jive_signature_url = validationBlock[:jiveSignatureURL]
jive_signature = validationBlock[:jiveSignature]
validationBlock.delete(:jiveSignature)
if !validationBlock[:clientSecret].nil?
validationBlock[:clientSecret] = Digest::SHA256.hexdigest(validationBlock[:clientSecret])
end
uri = URI.parse(jive_signature_url)
http = Net::HTTP.new(uri.host, uri.port)
http.use_ssl = true
http.verify_mode = OpenSSL::SSL::VERIFY_NONE if http.use_ssl? && !options[:verify_ssl]
buffer = ''
validationBlock = validationBlock.sort
(validationBlock.respond_to?(:to_h) ? validationBlock.to_h : Hash[validationBlock] ).each_pair { |k,v|
buffer = "#{buffer}#{k}:#{v}\n"
}
request = Net::HTTP::Post.new(uri.request_uri)
request.body = buffer
request["X-Jive-MAC"] = jive_signature
request["Content-Type"] = "application/json"
response = http.request(request)
(response.code.to_i === 204)
end | ruby | def validate_registration(validationBlock, *args)
options = ((args.last.is_a?(Hash)) ? args.pop : {})
require "open-uri"
require "net/http"
require "openssl"
jive_signature_url = validationBlock[:jiveSignatureURL]
jive_signature = validationBlock[:jiveSignature]
validationBlock.delete(:jiveSignature)
if !validationBlock[:clientSecret].nil?
validationBlock[:clientSecret] = Digest::SHA256.hexdigest(validationBlock[:clientSecret])
end
uri = URI.parse(jive_signature_url)
http = Net::HTTP.new(uri.host, uri.port)
http.use_ssl = true
http.verify_mode = OpenSSL::SSL::VERIFY_NONE if http.use_ssl? && !options[:verify_ssl]
buffer = ''
validationBlock = validationBlock.sort
(validationBlock.respond_to?(:to_h) ? validationBlock.to_h : Hash[validationBlock] ).each_pair { |k,v|
buffer = "#{buffer}#{k}:#{v}\n"
}
request = Net::HTTP::Post.new(uri.request_uri)
request.body = buffer
request["X-Jive-MAC"] = jive_signature
request["Content-Type"] = "application/json"
response = http.request(request)
(response.code.to_i === 204)
end | [
"def",
"validate_registration",
"(",
"validationBlock",
",",
"*",
"args",
")",
"options",
"=",
"(",
"(",
"args",
".",
"last",
".",
"is_a?",
"(",
"Hash",
")",
")",
"?",
"args",
".",
"pop",
":",
"{",
"}",
")",
"require",
"\"open-uri\"",
"require",
"\"net/http\"",
"require",
"\"openssl\"",
"jive_signature_url",
"=",
"validationBlock",
"[",
":jiveSignatureURL",
"]",
"jive_signature",
"=",
"validationBlock",
"[",
":jiveSignature",
"]",
"validationBlock",
".",
"delete",
"(",
":jiveSignature",
")",
"if",
"!",
"validationBlock",
"[",
":clientSecret",
"]",
".",
"nil?",
"validationBlock",
"[",
":clientSecret",
"]",
"=",
"Digest",
"::",
"SHA256",
".",
"hexdigest",
"(",
"validationBlock",
"[",
":clientSecret",
"]",
")",
"end",
"uri",
"=",
"URI",
".",
"parse",
"(",
"jive_signature_url",
")",
"http",
"=",
"Net",
"::",
"HTTP",
".",
"new",
"(",
"uri",
".",
"host",
",",
"uri",
".",
"port",
")",
"http",
".",
"use_ssl",
"=",
"true",
"http",
".",
"verify_mode",
"=",
"OpenSSL",
"::",
"SSL",
"::",
"VERIFY_NONE",
"if",
"http",
".",
"use_ssl?",
"&&",
"!",
"options",
"[",
":verify_ssl",
"]",
"buffer",
"=",
"''",
"validationBlock",
"=",
"validationBlock",
".",
"sort",
"(",
"validationBlock",
".",
"respond_to?",
"(",
":to_h",
")",
"?",
"validationBlock",
".",
"to_h",
":",
"Hash",
"[",
"validationBlock",
"]",
")",
".",
"each_pair",
"{",
"|",
"k",
",",
"v",
"|",
"buffer",
"=",
"\"#{buffer}#{k}:#{v}\\n\"",
"}",
"request",
"=",
"Net",
"::",
"HTTP",
"::",
"Post",
".",
"new",
"(",
"uri",
".",
"request_uri",
")",
"request",
".",
"body",
"=",
"buffer",
"request",
"[",
"\"X-Jive-MAC\"",
"]",
"=",
"jive_signature",
"request",
"[",
"\"Content-Type\"",
"]",
"=",
"\"application/json\"",
"response",
"=",
"http",
".",
"request",
"(",
"request",
")",
"(",
"response",
".",
"code",
".",
"to_i",
"===",
"204",
")",
"end"
] | Validates an app registration
Validates an app registration came from where it claims via jiveSignatureURL
* *Args* :
- +validationBlock+ -> the request body of the registration
- +args+ -> additional arguments
* *Returns* :
- boolean | [
"Validates",
"an",
"app",
"registration"
] | 98dbbcdfbba7a212cfad6dbeeca620f6a634a3a9 | https://github.com/butchmarshall/ruby-jive-signed_request/blob/98dbbcdfbba7a212cfad6dbeeca620f6a634a3a9/lib/jive/signed_request.rb#L94-L131 | train |
sj26/rubygems-keychain | lib/rubygems/keychain.rb | Gem::Keychain.ConfigFileExtensions.load_api_keys | def load_api_keys
fallback = load_file(credentials_path) if File.exists?(credentials_path)
@api_keys = Gem::Keychain::ApiKeys.new(fallback: fallback)
end | ruby | def load_api_keys
fallback = load_file(credentials_path) if File.exists?(credentials_path)
@api_keys = Gem::Keychain::ApiKeys.new(fallback: fallback)
end | [
"def",
"load_api_keys",
"fallback",
"=",
"load_file",
"(",
"credentials_path",
")",
"if",
"File",
".",
"exists?",
"(",
"credentials_path",
")",
"@api_keys",
"=",
"Gem",
"::",
"Keychain",
"::",
"ApiKeys",
".",
"new",
"(",
"fallback",
":",
"fallback",
")",
"end"
] | Override api key methods with proxy object | [
"Override",
"api",
"key",
"methods",
"with",
"proxy",
"object"
] | 9599383c207ef53972b8193e8d9908f3211cc3b6 | https://github.com/sj26/rubygems-keychain/blob/9599383c207ef53972b8193e8d9908f3211cc3b6/lib/rubygems/keychain.rb#L110-L114 | train |
cbrumelle/blueprintr | lib/blueprint-css/lib/blueprint/custom_layout.rb | Blueprint.CustomLayout.generate_grid_css | def generate_grid_css
# loads up erb template to evaluate custom widths
css = ERB::new(File.path_to_string(CustomLayout::CSS_ERB_FILE))
# bind it to this instance
css.result(binding)
end | ruby | def generate_grid_css
# loads up erb template to evaluate custom widths
css = ERB::new(File.path_to_string(CustomLayout::CSS_ERB_FILE))
# bind it to this instance
css.result(binding)
end | [
"def",
"generate_grid_css",
"# loads up erb template to evaluate custom widths",
"css",
"=",
"ERB",
"::",
"new",
"(",
"File",
".",
"path_to_string",
"(",
"CustomLayout",
"::",
"CSS_ERB_FILE",
")",
")",
"# bind it to this instance",
"css",
".",
"result",
"(",
"binding",
")",
"end"
] | Loads grid.css.erb file, binds it to current instance, and returns output | [
"Loads",
"grid",
".",
"css",
".",
"erb",
"file",
"binds",
"it",
"to",
"current",
"instance",
"and",
"returns",
"output"
] | b414436f614a8d97d77b47b588ddcf3f5e61b6bd | https://github.com/cbrumelle/blueprintr/blob/b414436f614a8d97d77b47b588ddcf3f5e61b6bd/lib/blueprint-css/lib/blueprint/custom_layout.rb#L63-L69 | train |
geminisbs/common_view_helpers | lib/common_view_helpers/common_view_helpers.rb | CommonViewHelpers.ViewHelpers.info_pair | def info_pair(label, value)
value = content_tag(:span, "None", :class => "blank") if value.blank?
label = content_tag(:span, "#{label}:", :class => "label")
content_tag(:span, [label, value].join(" "), :class => "info_pair")
end | ruby | def info_pair(label, value)
value = content_tag(:span, "None", :class => "blank") if value.blank?
label = content_tag(:span, "#{label}:", :class => "label")
content_tag(:span, [label, value].join(" "), :class => "info_pair")
end | [
"def",
"info_pair",
"(",
"label",
",",
"value",
")",
"value",
"=",
"content_tag",
"(",
":span",
",",
"\"None\"",
",",
":class",
"=>",
"\"blank\"",
")",
"if",
"value",
".",
"blank?",
"label",
"=",
"content_tag",
"(",
":span",
",",
"\"#{label}:\"",
",",
":class",
"=>",
"\"label\"",
")",
"content_tag",
"(",
":span",
",",
"[",
"label",
",",
"value",
"]",
".",
"join",
"(",
"\" \"",
")",
",",
":class",
"=>",
"\"info_pair\"",
")",
"end"
] | Output an easily styleable key-value pair | [
"Output",
"an",
"easily",
"styleable",
"key",
"-",
"value",
"pair"
] | a5b16957f61f201a27bda632db553991c7d42af4 | https://github.com/geminisbs/common_view_helpers/blob/a5b16957f61f201a27bda632db553991c7d42af4/lib/common_view_helpers/common_view_helpers.rb#L17-L21 | train |
geminisbs/common_view_helpers | lib/common_view_helpers/common_view_helpers.rb | CommonViewHelpers.ViewHelpers.generate_table | def generate_table(collection, headers=nil, options={})
return if collection.blank?
thead = content_tag(:thead) do
content_tag(:tr) do
headers.map {|header| content_tag(:th, header)}
end
end unless headers.nil?
tbody = content_tag(:tbody) do
collection.map do |values|
content_tag(:tr) do
values.map {|value| content_tag(:td, value)}
end
end
end
content_tag(:table, [thead, tbody].compact.join("\n"), options)
end | ruby | def generate_table(collection, headers=nil, options={})
return if collection.blank?
thead = content_tag(:thead) do
content_tag(:tr) do
headers.map {|header| content_tag(:th, header)}
end
end unless headers.nil?
tbody = content_tag(:tbody) do
collection.map do |values|
content_tag(:tr) do
values.map {|value| content_tag(:td, value)}
end
end
end
content_tag(:table, [thead, tbody].compact.join("\n"), options)
end | [
"def",
"generate_table",
"(",
"collection",
",",
"headers",
"=",
"nil",
",",
"options",
"=",
"{",
"}",
")",
"return",
"if",
"collection",
".",
"blank?",
"thead",
"=",
"content_tag",
"(",
":thead",
")",
"do",
"content_tag",
"(",
":tr",
")",
"do",
"headers",
".",
"map",
"{",
"|",
"header",
"|",
"content_tag",
"(",
":th",
",",
"header",
")",
"}",
"end",
"end",
"unless",
"headers",
".",
"nil?",
"tbody",
"=",
"content_tag",
"(",
":tbody",
")",
"do",
"collection",
".",
"map",
"do",
"|",
"values",
"|",
"content_tag",
"(",
":tr",
")",
"do",
"values",
".",
"map",
"{",
"|",
"value",
"|",
"content_tag",
"(",
":td",
",",
"value",
")",
"}",
"end",
"end",
"end",
"content_tag",
"(",
":table",
",",
"[",
"thead",
",",
"tbody",
"]",
".",
"compact",
".",
"join",
"(",
"\"\\n\"",
")",
",",
"options",
")",
"end"
] | Build an HTML table
For collection, pass an array of arrays
For headers, pass an array of label strings for the top of the table
All other options will be passed along to the table content_tag | [
"Build",
"an",
"HTML",
"table",
"For",
"collection",
"pass",
"an",
"array",
"of",
"arrays",
"For",
"headers",
"pass",
"an",
"array",
"of",
"label",
"strings",
"for",
"the",
"top",
"of",
"the",
"table",
"All",
"other",
"options",
"will",
"be",
"passed",
"along",
"to",
"the",
"table",
"content_tag"
] | a5b16957f61f201a27bda632db553991c7d42af4 | https://github.com/geminisbs/common_view_helpers/blob/a5b16957f61f201a27bda632db553991c7d42af4/lib/common_view_helpers/common_view_helpers.rb#L46-L61 | train |
geminisbs/common_view_helpers | lib/common_view_helpers/common_view_helpers.rb | CommonViewHelpers.ViewHelpers.options_td | def options_td(record_or_name_or_array, hide_destroy = false)
items = []
items << link_to('Edit', edit_polymorphic_path(record_or_name_or_array))
items << link_to('Delete', polymorphic_path(record_or_name_or_array), :confirm => 'Are you sure?', :method => :delete, :class => "destructive") unless hide_destroy
list = content_tag(:ul, convert_to_list_items(items))
content_tag(:td, list, :class => "options")
end | ruby | def options_td(record_or_name_or_array, hide_destroy = false)
items = []
items << link_to('Edit', edit_polymorphic_path(record_or_name_or_array))
items << link_to('Delete', polymorphic_path(record_or_name_or_array), :confirm => 'Are you sure?', :method => :delete, :class => "destructive") unless hide_destroy
list = content_tag(:ul, convert_to_list_items(items))
content_tag(:td, list, :class => "options")
end | [
"def",
"options_td",
"(",
"record_or_name_or_array",
",",
"hide_destroy",
"=",
"false",
")",
"items",
"=",
"[",
"]",
"items",
"<<",
"link_to",
"(",
"'Edit'",
",",
"edit_polymorphic_path",
"(",
"record_or_name_or_array",
")",
")",
"items",
"<<",
"link_to",
"(",
"'Delete'",
",",
"polymorphic_path",
"(",
"record_or_name_or_array",
")",
",",
":confirm",
"=>",
"'Are you sure?'",
",",
":method",
"=>",
":delete",
",",
":class",
"=>",
"\"destructive\"",
")",
"unless",
"hide_destroy",
"list",
"=",
"content_tag",
"(",
":ul",
",",
"convert_to_list_items",
"(",
"items",
")",
")",
"content_tag",
"(",
":td",
",",
"list",
",",
":class",
"=>",
"\"options\"",
")",
"end"
] | Pass in an ActiveRecord object, get back edit and delete links inside a TD tag | [
"Pass",
"in",
"an",
"ActiveRecord",
"object",
"get",
"back",
"edit",
"and",
"delete",
"links",
"inside",
"a",
"TD",
"tag"
] | a5b16957f61f201a27bda632db553991c7d42af4 | https://github.com/geminisbs/common_view_helpers/blob/a5b16957f61f201a27bda632db553991c7d42af4/lib/common_view_helpers/common_view_helpers.rb#L64-L70 | train |
geminisbs/common_view_helpers | lib/common_view_helpers/common_view_helpers.rb | CommonViewHelpers.ViewHelpers.link | def link(name, options={}, html_options={})
link_to_unless_current(name, options, html_options) do
html_options[:class] = (html_options[:class] || "").split(" ").push("active").join(" ")
link_to(name, options, html_options)
end
end | ruby | def link(name, options={}, html_options={})
link_to_unless_current(name, options, html_options) do
html_options[:class] = (html_options[:class] || "").split(" ").push("active").join(" ")
link_to(name, options, html_options)
end
end | [
"def",
"link",
"(",
"name",
",",
"options",
"=",
"{",
"}",
",",
"html_options",
"=",
"{",
"}",
")",
"link_to_unless_current",
"(",
"name",
",",
"options",
",",
"html_options",
")",
"do",
"html_options",
"[",
":class",
"]",
"=",
"(",
"html_options",
"[",
":class",
"]",
"||",
"\"\"",
")",
".",
"split",
"(",
"\" \"",
")",
".",
"push",
"(",
"\"active\"",
")",
".",
"join",
"(",
"\" \"",
")",
"link_to",
"(",
"name",
",",
"options",
",",
"html_options",
")",
"end",
"end"
] | This works just like link_to, but with one difference..
If the link is to the current page, a class of 'active' is added | [
"This",
"works",
"just",
"like",
"link_to",
"but",
"with",
"one",
"difference",
"..",
"If",
"the",
"link",
"is",
"to",
"the",
"current",
"page",
"a",
"class",
"of",
"active",
"is",
"added"
] | a5b16957f61f201a27bda632db553991c7d42af4 | https://github.com/geminisbs/common_view_helpers/blob/a5b16957f61f201a27bda632db553991c7d42af4/lib/common_view_helpers/common_view_helpers.rb#L74-L79 | train |
geminisbs/common_view_helpers | lib/common_view_helpers/common_view_helpers.rb | CommonViewHelpers.ViewHelpers.list_model_columns | def list_model_columns(obj)
items = obj.class.columns.map{ |col| info_pair(col.name, obj[col.name]) }
content_tag(:ul, convert_to_list_items(items), :class => "model_columns")
end | ruby | def list_model_columns(obj)
items = obj.class.columns.map{ |col| info_pair(col.name, obj[col.name]) }
content_tag(:ul, convert_to_list_items(items), :class => "model_columns")
end | [
"def",
"list_model_columns",
"(",
"obj",
")",
"items",
"=",
"obj",
".",
"class",
".",
"columns",
".",
"map",
"{",
"|",
"col",
"|",
"info_pair",
"(",
"col",
".",
"name",
",",
"obj",
"[",
"col",
".",
"name",
"]",
")",
"}",
"content_tag",
"(",
":ul",
",",
"convert_to_list_items",
"(",
"items",
")",
",",
":class",
"=>",
"\"model_columns\"",
")",
"end"
] | Generate a list of column name-value pairs for an AR object | [
"Generate",
"a",
"list",
"of",
"column",
"name",
"-",
"value",
"pairs",
"for",
"an",
"AR",
"object"
] | a5b16957f61f201a27bda632db553991c7d42af4 | https://github.com/geminisbs/common_view_helpers/blob/a5b16957f61f201a27bda632db553991c7d42af4/lib/common_view_helpers/common_view_helpers.rb#L92-L95 | train |
ktonon/code_node | spec/fixtures/activerecord/src/active_record/migration.rb | ActiveRecord.Migrator.ddl_transaction | def ddl_transaction(&block)
if Base.connection.supports_ddl_transactions?
Base.transaction { block.call }
else
block.call
end
end | ruby | def ddl_transaction(&block)
if Base.connection.supports_ddl_transactions?
Base.transaction { block.call }
else
block.call
end
end | [
"def",
"ddl_transaction",
"(",
"&",
"block",
")",
"if",
"Base",
".",
"connection",
".",
"supports_ddl_transactions?",
"Base",
".",
"transaction",
"{",
"block",
".",
"call",
"}",
"else",
"block",
".",
"call",
"end",
"end"
] | Wrap the migration in a transaction only if supported by the adapter. | [
"Wrap",
"the",
"migration",
"in",
"a",
"transaction",
"only",
"if",
"supported",
"by",
"the",
"adapter",
"."
] | 48d5d1a7442d9cade602be4fb782a1b56c7677f5 | https://github.com/ktonon/code_node/blob/48d5d1a7442d9cade602be4fb782a1b56c7677f5/spec/fixtures/activerecord/src/active_record/migration.rb#L773-L779 | train |
tomdionysus/stringtree-ruby | lib/stringtree/node.rb | StringTree.Node.add_vertical | def add_vertical(str, value)
node = nil
str.each_char { |c|
if (node == nil)
node = self.add_horizontal_char(c)
elsif (node.down != nil)
node = node.down.add_horizontal_char(c)
else
node.down = Node.new(c, node)
node = node.down
end
}
node.value = value
end | ruby | def add_vertical(str, value)
node = nil
str.each_char { |c|
if (node == nil)
node = self.add_horizontal_char(c)
elsif (node.down != nil)
node = node.down.add_horizontal_char(c)
else
node.down = Node.new(c, node)
node = node.down
end
}
node.value = value
end | [
"def",
"add_vertical",
"(",
"str",
",",
"value",
")",
"node",
"=",
"nil",
"str",
".",
"each_char",
"{",
"|",
"c",
"|",
"if",
"(",
"node",
"==",
"nil",
")",
"node",
"=",
"self",
".",
"add_horizontal_char",
"(",
"c",
")",
"elsif",
"(",
"node",
".",
"down",
"!=",
"nil",
")",
"node",
"=",
"node",
".",
"down",
".",
"add_horizontal_char",
"(",
"c",
")",
"else",
"node",
".",
"down",
"=",
"Node",
".",
"new",
"(",
"c",
",",
"node",
")",
"node",
"=",
"node",
".",
"down",
"end",
"}",
"node",
".",
"value",
"=",
"value",
"end"
] | Add the given String str and value vertically to this node, by adding or finding each character
horizontally, then stepping down and repeating with the next character and so on, writing the
value to the last node. | [
"Add",
"the",
"given",
"String",
"str",
"and",
"value",
"vertically",
"to",
"this",
"node",
"by",
"adding",
"or",
"finding",
"each",
"character",
"horizontally",
"then",
"stepping",
"down",
"and",
"repeating",
"with",
"the",
"next",
"character",
"and",
"so",
"on",
"writing",
"the",
"value",
"to",
"the",
"last",
"node",
"."
] | b5cf8a327e80855bf4b2bd6fe71950e0cbdff215 | https://github.com/tomdionysus/stringtree-ruby/blob/b5cf8a327e80855bf4b2bd6fe71950e0cbdff215/lib/stringtree/node.rb#L78-L91 | train |
tomdionysus/stringtree-ruby | lib/stringtree/node.rb | StringTree.Node.find_vertical | def find_vertical(str, offset = 0, length = str.length-offset)
node = nil
i = offset
while (i<offset+length)
c = str[i]
if (node == nil)
node = self.find_horizontal(c)
elsif (node.down != nil)
node = node.down.find_horizontal(c)
else
return nil
end
return nil if (node == nil)
i += 1
end
node
end | ruby | def find_vertical(str, offset = 0, length = str.length-offset)
node = nil
i = offset
while (i<offset+length)
c = str[i]
if (node == nil)
node = self.find_horizontal(c)
elsif (node.down != nil)
node = node.down.find_horizontal(c)
else
return nil
end
return nil if (node == nil)
i += 1
end
node
end | [
"def",
"find_vertical",
"(",
"str",
",",
"offset",
"=",
"0",
",",
"length",
"=",
"str",
".",
"length",
"-",
"offset",
")",
"node",
"=",
"nil",
"i",
"=",
"offset",
"while",
"(",
"i",
"<",
"offset",
"+",
"length",
")",
"c",
"=",
"str",
"[",
"i",
"]",
"if",
"(",
"node",
"==",
"nil",
")",
"node",
"=",
"self",
".",
"find_horizontal",
"(",
"c",
")",
"elsif",
"(",
"node",
".",
"down",
"!=",
"nil",
")",
"node",
"=",
"node",
".",
"down",
".",
"find_horizontal",
"(",
"c",
")",
"else",
"return",
"nil",
"end",
"return",
"nil",
"if",
"(",
"node",
"==",
"nil",
")",
"i",
"+=",
"1",
"end",
"node",
"end"
] | Find the given String str vertically by finding each character horizontally, then stepping down
and repeating with the next character and so on. Return the last node if found, or nil if any
horizontal search fails.
Optionally, set the offset into the string and its length | [
"Find",
"the",
"given",
"String",
"str",
"vertically",
"by",
"finding",
"each",
"character",
"horizontally",
"then",
"stepping",
"down",
"and",
"repeating",
"with",
"the",
"next",
"character",
"and",
"so",
"on",
".",
"Return",
"the",
"last",
"node",
"if",
"found",
"or",
"nil",
"if",
"any",
"horizontal",
"search",
"fails",
".",
"Optionally",
"set",
"the",
"offset",
"into",
"the",
"string",
"and",
"its",
"length"
] | b5cf8a327e80855bf4b2bd6fe71950e0cbdff215 | https://github.com/tomdionysus/stringtree-ruby/blob/b5cf8a327e80855bf4b2bd6fe71950e0cbdff215/lib/stringtree/node.rb#L97-L114 | train |
tomdionysus/stringtree-ruby | lib/stringtree/node.rb | StringTree.Node.balance | def balance
node = self
i = (node.count(:right) - node.count(:left))/2
while (i!=0)
if (i>0)
mvnode = node.right
node.right = nil
mvnode.add_horizontal node
i -= 1
else
mvnode = node.left
node.left = nil
mvnode.add_horizontal node
i += 1
end
node = mvnode
end
if (node.left != nil)
node.left = node.left.balance
end
if (node.right != nil)
node.right = node.right.balance
end
if (node.down != nil)
node.down = node.down.balance
end
node
end | ruby | def balance
node = self
i = (node.count(:right) - node.count(:left))/2
while (i!=0)
if (i>0)
mvnode = node.right
node.right = nil
mvnode.add_horizontal node
i -= 1
else
mvnode = node.left
node.left = nil
mvnode.add_horizontal node
i += 1
end
node = mvnode
end
if (node.left != nil)
node.left = node.left.balance
end
if (node.right != nil)
node.right = node.right.balance
end
if (node.down != nil)
node.down = node.down.balance
end
node
end | [
"def",
"balance",
"node",
"=",
"self",
"i",
"=",
"(",
"node",
".",
"count",
"(",
":right",
")",
"-",
"node",
".",
"count",
"(",
":left",
")",
")",
"/",
"2",
"while",
"(",
"i!",
"=",
"0",
")",
"if",
"(",
"i",
">",
"0",
")",
"mvnode",
"=",
"node",
".",
"right",
"node",
".",
"right",
"=",
"nil",
"mvnode",
".",
"add_horizontal",
"node",
"i",
"-=",
"1",
"else",
"mvnode",
"=",
"node",
".",
"left",
"node",
".",
"left",
"=",
"nil",
"mvnode",
".",
"add_horizontal",
"node",
"i",
"+=",
"1",
"end",
"node",
"=",
"mvnode",
"end",
"if",
"(",
"node",
".",
"left",
"!=",
"nil",
")",
"node",
".",
"left",
"=",
"node",
".",
"left",
".",
"balance",
"end",
"if",
"(",
"node",
".",
"right",
"!=",
"nil",
")",
"node",
".",
"right",
"=",
"node",
".",
"right",
".",
"balance",
"end",
"if",
"(",
"node",
".",
"down",
"!=",
"nil",
")",
"node",
".",
"down",
"=",
"node",
".",
"down",
".",
"balance",
"end",
"node",
"end"
] | Recursively balance this node in its own tree, and every node in all four directions,
and return the new root node. | [
"Recursively",
"balance",
"this",
"node",
"in",
"its",
"own",
"tree",
"and",
"every",
"node",
"in",
"all",
"four",
"directions",
"and",
"return",
"the",
"new",
"root",
"node",
"."
] | b5cf8a327e80855bf4b2bd6fe71950e0cbdff215 | https://github.com/tomdionysus/stringtree-ruby/blob/b5cf8a327e80855bf4b2bd6fe71950e0cbdff215/lib/stringtree/node.rb#L152-L179 | train |
tomdionysus/stringtree-ruby | lib/stringtree/node.rb | StringTree.Node.walk | def walk(str="", &block)
@down.walk(str+char, &block) if @down != nil
@left.walk(str, &block) if @left != nil
yield str+@char, @value if @value != nil
@right.walk(str, &block) if @right != nil
end | ruby | def walk(str="", &block)
@down.walk(str+char, &block) if @down != nil
@left.walk(str, &block) if @left != nil
yield str+@char, @value if @value != nil
@right.walk(str, &block) if @right != nil
end | [
"def",
"walk",
"(",
"str",
"=",
"\"\"",
",",
"&",
"block",
")",
"@down",
".",
"walk",
"(",
"str",
"+",
"char",
",",
"block",
")",
"if",
"@down",
"!=",
"nil",
"@left",
".",
"walk",
"(",
"str",
",",
"block",
")",
"if",
"@left",
"!=",
"nil",
"yield",
"str",
"+",
"@char",
",",
"@value",
"if",
"@value",
"!=",
"nil",
"@right",
".",
"walk",
"(",
"str",
",",
"block",
")",
"if",
"@right",
"!=",
"nil",
"end"
] | Walk the tree from this node, yielding all strings and values where the
value is not nil. Optionally, use the given prefix String str. | [
"Walk",
"the",
"tree",
"from",
"this",
"node",
"yielding",
"all",
"strings",
"and",
"values",
"where",
"the",
"value",
"is",
"not",
"nil",
".",
"Optionally",
"use",
"the",
"given",
"prefix",
"String",
"str",
"."
] | b5cf8a327e80855bf4b2bd6fe71950e0cbdff215 | https://github.com/tomdionysus/stringtree-ruby/blob/b5cf8a327e80855bf4b2bd6fe71950e0cbdff215/lib/stringtree/node.rb#L183-L188 | train |
tomdionysus/stringtree-ruby | lib/stringtree/node.rb | StringTree.Node.to_s | def to_s
st = @char
node = self
while node != nil
node = node.up
break if node==nil
st = node.char+st
end
st
end | ruby | def to_s
st = @char
node = self
while node != nil
node = node.up
break if node==nil
st = node.char+st
end
st
end | [
"def",
"to_s",
"st",
"=",
"@char",
"node",
"=",
"self",
"while",
"node",
"!=",
"nil",
"node",
"=",
"node",
".",
"up",
"break",
"if",
"node",
"==",
"nil",
"st",
"=",
"node",
".",
"char",
"+",
"st",
"end",
"st",
"end"
] | Return the complete string from the tree root up to and including this node
i.e. The total string key for this node from root. | [
"Return",
"the",
"complete",
"string",
"from",
"the",
"tree",
"root",
"up",
"to",
"and",
"including",
"this",
"node",
"i",
".",
"e",
".",
"The",
"total",
"string",
"key",
"for",
"this",
"node",
"from",
"root",
"."
] | b5cf8a327e80855bf4b2bd6fe71950e0cbdff215 | https://github.com/tomdionysus/stringtree-ruby/blob/b5cf8a327e80855bf4b2bd6fe71950e0cbdff215/lib/stringtree/node.rb#L192-L201 | train |
tomdionysus/stringtree-ruby | lib/stringtree/node.rb | StringTree.Node.all_partials | def all_partials(str = "")
list = []
@down.walk(str) { |str| list << str } unless @down.nil?
list
end | ruby | def all_partials(str = "")
list = []
@down.walk(str) { |str| list << str } unless @down.nil?
list
end | [
"def",
"all_partials",
"(",
"str",
"=",
"\"\"",
")",
"list",
"=",
"[",
"]",
"@down",
".",
"walk",
"(",
"str",
")",
"{",
"|",
"str",
"|",
"list",
"<<",
"str",
"}",
"unless",
"@down",
".",
"nil?",
"list",
"end"
] | Return an Array of Strings of all possible partial string from this node.
Optionally, use the given prefix String str. | [
"Return",
"an",
"Array",
"of",
"Strings",
"of",
"all",
"possible",
"partial",
"string",
"from",
"this",
"node",
".",
"Optionally",
"use",
"the",
"given",
"prefix",
"String",
"str",
"."
] | b5cf8a327e80855bf4b2bd6fe71950e0cbdff215 | https://github.com/tomdionysus/stringtree-ruby/blob/b5cf8a327e80855bf4b2bd6fe71950e0cbdff215/lib/stringtree/node.rb#L210-L214 | train |
tomdionysus/stringtree-ruby | lib/stringtree/node.rb | StringTree.Node.prune | def prune
return true if [email protected]? && down.prune
return true if [email protected]? && left.prune
return true if [email protected]? && right.prune
return true unless @value.nil?
up.down = nil if !up.nil? && left.nil? && right.nil?
false
end | ruby | def prune
return true if [email protected]? && down.prune
return true if [email protected]? && left.prune
return true if [email protected]? && right.prune
return true unless @value.nil?
up.down = nil if !up.nil? && left.nil? && right.nil?
false
end | [
"def",
"prune",
"return",
"true",
"if",
"!",
"@down",
".",
"nil?",
"&&",
"down",
".",
"prune",
"return",
"true",
"if",
"!",
"@left",
".",
"nil?",
"&&",
"left",
".",
"prune",
"return",
"true",
"if",
"!",
"@right",
".",
"nil?",
"&&",
"right",
".",
"prune",
"return",
"true",
"unless",
"@value",
".",
"nil?",
"up",
".",
"down",
"=",
"nil",
"if",
"!",
"up",
".",
"nil?",
"&&",
"left",
".",
"nil?",
"&&",
"right",
".",
"nil?",
"false",
"end"
] | Prune the tree back from this node onward so that all leaves have values. | [
"Prune",
"the",
"tree",
"back",
"from",
"this",
"node",
"onward",
"so",
"that",
"all",
"leaves",
"have",
"values",
"."
] | b5cf8a327e80855bf4b2bd6fe71950e0cbdff215 | https://github.com/tomdionysus/stringtree-ruby/blob/b5cf8a327e80855bf4b2bd6fe71950e0cbdff215/lib/stringtree/node.rb#L217-L224 | train |
humpyard/humpyard | app/controllers/humpyard/pages_controller.rb | Humpyard.PagesController.index | def index
authorize! :manage, Humpyard::Page
@root_page = Humpyard::Page.root
@page = Humpyard::Page.find_by_id(params[:actual_page_id])
unless @page.nil?
@page = @page.content_data
end
render :partial => 'index'
end | ruby | def index
authorize! :manage, Humpyard::Page
@root_page = Humpyard::Page.root
@page = Humpyard::Page.find_by_id(params[:actual_page_id])
unless @page.nil?
@page = @page.content_data
end
render :partial => 'index'
end | [
"def",
"index",
"authorize!",
":manage",
",",
"Humpyard",
"::",
"Page",
"@root_page",
"=",
"Humpyard",
"::",
"Page",
".",
"root",
"@page",
"=",
"Humpyard",
"::",
"Page",
".",
"find_by_id",
"(",
"params",
"[",
":actual_page_id",
"]",
")",
"unless",
"@page",
".",
"nil?",
"@page",
"=",
"@page",
".",
"content_data",
"end",
"render",
":partial",
"=>",
"'index'",
"end"
] | Probably unneccassary - may be removed later | [
"Probably",
"unneccassary",
"-",
"may",
"be",
"removed",
"later"
] | f344ab851f1dfd824c1e4cb4b92f7c62ac0acefd | https://github.com/humpyard/humpyard/blob/f344ab851f1dfd824c1e4cb4b92f7c62ac0acefd/app/controllers/humpyard/pages_controller.rb#L8-L18 | train |
humpyard/humpyard | app/controllers/humpyard/pages_controller.rb | Humpyard.PagesController.new | def new
@page = Humpyard::config.page_types[params[:type]].new
unless can? :create, @page.page
render :json => {
:status => :failed
}, :status => 403
return
end
@page_type = params[:type]
@prev = Humpyard::Page.find_by_id(params[:prev_id])
@next = Humpyard::Page.find_by_id(params[:next_id])
render :partial => 'edit'
end | ruby | def new
@page = Humpyard::config.page_types[params[:type]].new
unless can? :create, @page.page
render :json => {
:status => :failed
}, :status => 403
return
end
@page_type = params[:type]
@prev = Humpyard::Page.find_by_id(params[:prev_id])
@next = Humpyard::Page.find_by_id(params[:next_id])
render :partial => 'edit'
end | [
"def",
"new",
"@page",
"=",
"Humpyard",
"::",
"config",
".",
"page_types",
"[",
"params",
"[",
":type",
"]",
"]",
".",
"new",
"unless",
"can?",
":create",
",",
"@page",
".",
"page",
"render",
":json",
"=>",
"{",
":status",
"=>",
":failed",
"}",
",",
":status",
"=>",
"403",
"return",
"end",
"@page_type",
"=",
"params",
"[",
":type",
"]",
"@prev",
"=",
"Humpyard",
"::",
"Page",
".",
"find_by_id",
"(",
"params",
"[",
":prev_id",
"]",
")",
"@next",
"=",
"Humpyard",
"::",
"Page",
".",
"find_by_id",
"(",
"params",
"[",
":next_id",
"]",
")",
"render",
":partial",
"=>",
"'edit'",
"end"
] | Dialog content for a new page | [
"Dialog",
"content",
"for",
"a",
"new",
"page"
] | f344ab851f1dfd824c1e4cb4b92f7c62ac0acefd | https://github.com/humpyard/humpyard/blob/f344ab851f1dfd824c1e4cb4b92f7c62ac0acefd/app/controllers/humpyard/pages_controller.rb#L21-L36 | train |
humpyard/humpyard | app/controllers/humpyard/pages_controller.rb | Humpyard.PagesController.update | def update
@page = Humpyard::Page.find(params[:id]).content_data
if @page
unless can? :update, @page.page
render :json => {
:status => :failed
}, :status => 403
return
end
if @page.update_attributes params[:page]
@page.title_for_url = @page.page.suggested_title_for_url
@page.save
render :json => {
:status => :ok,
# :dialog => :close,
:replace => [
{
:element => "hy-page-treeview-text-#{@page.id}",
:content => @page.title
}
],
:flash => {
:level => 'info',
:content => I18n.t('humpyard_form.flashes.update_success', :model => Humpyard::Page.model_name.human)
}
}
else
render :json => {
:status => :failed,
:errors => @page.errors,
:flash => {
:level => 'error',
:content => I18n.t('humpyard_form.flashes.update_fail', :model => Humpyard::Page.model_name.human)
}
}
end
else
render :json => {
:status => :failed
}, :status => 404
end
end | ruby | def update
@page = Humpyard::Page.find(params[:id]).content_data
if @page
unless can? :update, @page.page
render :json => {
:status => :failed
}, :status => 403
return
end
if @page.update_attributes params[:page]
@page.title_for_url = @page.page.suggested_title_for_url
@page.save
render :json => {
:status => :ok,
# :dialog => :close,
:replace => [
{
:element => "hy-page-treeview-text-#{@page.id}",
:content => @page.title
}
],
:flash => {
:level => 'info',
:content => I18n.t('humpyard_form.flashes.update_success', :model => Humpyard::Page.model_name.human)
}
}
else
render :json => {
:status => :failed,
:errors => @page.errors,
:flash => {
:level => 'error',
:content => I18n.t('humpyard_form.flashes.update_fail', :model => Humpyard::Page.model_name.human)
}
}
end
else
render :json => {
:status => :failed
}, :status => 404
end
end | [
"def",
"update",
"@page",
"=",
"Humpyard",
"::",
"Page",
".",
"find",
"(",
"params",
"[",
":id",
"]",
")",
".",
"content_data",
"if",
"@page",
"unless",
"can?",
":update",
",",
"@page",
".",
"page",
"render",
":json",
"=>",
"{",
":status",
"=>",
":failed",
"}",
",",
":status",
"=>",
"403",
"return",
"end",
"if",
"@page",
".",
"update_attributes",
"params",
"[",
":page",
"]",
"@page",
".",
"title_for_url",
"=",
"@page",
".",
"page",
".",
"suggested_title_for_url",
"@page",
".",
"save",
"render",
":json",
"=>",
"{",
":status",
"=>",
":ok",
",",
"# :dialog => :close,",
":replace",
"=>",
"[",
"{",
":element",
"=>",
"\"hy-page-treeview-text-#{@page.id}\"",
",",
":content",
"=>",
"@page",
".",
"title",
"}",
"]",
",",
":flash",
"=>",
"{",
":level",
"=>",
"'info'",
",",
":content",
"=>",
"I18n",
".",
"t",
"(",
"'humpyard_form.flashes.update_success'",
",",
":model",
"=>",
"Humpyard",
"::",
"Page",
".",
"model_name",
".",
"human",
")",
"}",
"}",
"else",
"render",
":json",
"=>",
"{",
":status",
"=>",
":failed",
",",
":errors",
"=>",
"@page",
".",
"errors",
",",
":flash",
"=>",
"{",
":level",
"=>",
"'error'",
",",
":content",
"=>",
"I18n",
".",
"t",
"(",
"'humpyard_form.flashes.update_fail'",
",",
":model",
"=>",
"Humpyard",
"::",
"Page",
".",
"model_name",
".",
"human",
")",
"}",
"}",
"end",
"else",
"render",
":json",
"=>",
"{",
":status",
"=>",
":failed",
"}",
",",
":status",
"=>",
"404",
"end",
"end"
] | Update an existing page | [
"Update",
"an",
"existing",
"page"
] | f344ab851f1dfd824c1e4cb4b92f7c62ac0acefd | https://github.com/humpyard/humpyard/blob/f344ab851f1dfd824c1e4cb4b92f7c62ac0acefd/app/controllers/humpyard/pages_controller.rb#L99-L143 | train |
humpyard/humpyard | app/controllers/humpyard/pages_controller.rb | Humpyard.PagesController.move | def move
@page = Humpyard::Page.find(params[:id])
if @page
unless can? :update, @page
render :json => {
:status => :failed
}, :status => 403
return
end
parent = Humpyard::Page.find_by_id(params[:parent_id])
# by default, make it possible to move page to root, uncomment to do otherwise:
#unless parent
# parent = Humpyard::Page.root_page
#end
@page.update_attribute :parent, parent
@prev = Humpyard::Page.find_by_id(params[:prev_id])
@next = Humpyard::Page.find_by_id(params[:next_id])
do_move(@page, @prev, @next)
replace_options = {
:element => "hy-page-treeview",
:content => render_to_string(:partial => "tree.html", :locals => {:page => @page})
}
render :json => {
:status => :ok,
:replace => [replace_options]
}
else
render :json => {
:status => :failed
}, :status => 404
end
end | ruby | def move
@page = Humpyard::Page.find(params[:id])
if @page
unless can? :update, @page
render :json => {
:status => :failed
}, :status => 403
return
end
parent = Humpyard::Page.find_by_id(params[:parent_id])
# by default, make it possible to move page to root, uncomment to do otherwise:
#unless parent
# parent = Humpyard::Page.root_page
#end
@page.update_attribute :parent, parent
@prev = Humpyard::Page.find_by_id(params[:prev_id])
@next = Humpyard::Page.find_by_id(params[:next_id])
do_move(@page, @prev, @next)
replace_options = {
:element => "hy-page-treeview",
:content => render_to_string(:partial => "tree.html", :locals => {:page => @page})
}
render :json => {
:status => :ok,
:replace => [replace_options]
}
else
render :json => {
:status => :failed
}, :status => 404
end
end | [
"def",
"move",
"@page",
"=",
"Humpyard",
"::",
"Page",
".",
"find",
"(",
"params",
"[",
":id",
"]",
")",
"if",
"@page",
"unless",
"can?",
":update",
",",
"@page",
"render",
":json",
"=>",
"{",
":status",
"=>",
":failed",
"}",
",",
":status",
"=>",
"403",
"return",
"end",
"parent",
"=",
"Humpyard",
"::",
"Page",
".",
"find_by_id",
"(",
"params",
"[",
":parent_id",
"]",
")",
"# by default, make it possible to move page to root, uncomment to do otherwise:",
"#unless parent",
"# parent = Humpyard::Page.root_page",
"#end",
"@page",
".",
"update_attribute",
":parent",
",",
"parent",
"@prev",
"=",
"Humpyard",
"::",
"Page",
".",
"find_by_id",
"(",
"params",
"[",
":prev_id",
"]",
")",
"@next",
"=",
"Humpyard",
"::",
"Page",
".",
"find_by_id",
"(",
"params",
"[",
":next_id",
"]",
")",
"do_move",
"(",
"@page",
",",
"@prev",
",",
"@next",
")",
"replace_options",
"=",
"{",
":element",
"=>",
"\"hy-page-treeview\"",
",",
":content",
"=>",
"render_to_string",
"(",
":partial",
"=>",
"\"tree.html\"",
",",
":locals",
"=>",
"{",
":page",
"=>",
"@page",
"}",
")",
"}",
"render",
":json",
"=>",
"{",
":status",
"=>",
":ok",
",",
":replace",
"=>",
"[",
"replace_options",
"]",
"}",
"else",
"render",
":json",
"=>",
"{",
":status",
"=>",
":failed",
"}",
",",
":status",
"=>",
"404",
"end",
"end"
] | Move a page | [
"Move",
"a",
"page"
] | f344ab851f1dfd824c1e4cb4b92f7c62ac0acefd | https://github.com/humpyard/humpyard/blob/f344ab851f1dfd824c1e4cb4b92f7c62ac0acefd/app/controllers/humpyard/pages_controller.rb#L146-L182 | train |
humpyard/humpyard | app/controllers/humpyard/pages_controller.rb | Humpyard.PagesController.show | def show
# No page found at the beginning
@page = nil
if params[:locale] and Humpyard.config.locales.include? params[:locale].to_sym
I18n.locale = params[:locale]
elsif session[:humpyard_locale]
I18n.locale = session[:humpyard_locale]
else
I18n.locale = Humpyard.config.locales.first
end
# Find page by name
if not params[:webpath].blank?
dyn_page_path = false
parent_page = nil
params[:webpath].split('/').each do |path_part|
# Ignore multiple slashes in URLs
unless(path_part.blank?)
if(dyn_page_path)
dyn_page_path << path_part
else
# Find page by name and parent; parent=nil means page on root level
@page = Page.with_translated_attribute(:title_for_url, CGI::escape(path_part), I18n.locale).first
# Raise 404 if no page was found for the URL or subpart
raise ::ActionController::RoutingError, "No route matches \"#{request.path}\" (X4201) [#{path_part}]" if @page.nil?
raise ::ActionController::RoutingError, "No route matches \"#{request.path}\" (X4202)" if not (@page.parent == parent_page or @page.parent == Humpyard::Page.root_page)
parent_page = @page unless @page.is_root_page?
dyn_page_path = [] if @page.content_data.is_humpyard_dynamic_page?
end
end
end
if @page.content_data.is_humpyard_dynamic_page? and dyn_page_path.size > 0
@sub_page = @page.parse_path(dyn_page_path)
# Raise 404 if no page was found for the sub_page part
raise ::ActionController::RoutingError, "No route matches \"#{request.path}\" (D4201)" if @sub_page.blank?
@page_partial = "/humpyard/pages/#{@page.content_data_type.split('::').last.underscore.pluralize}/#{@sub_page[:partial]}" if @sub_page[:partial]
@local_vars = {:page => @page}.merge(@sub_page[:locals]) if @sub_page[:locals] and @sub_page[:locals].class == Hash
# render partial only if request was an AJAX-call
if request.xhr?
respond_to do |format|
format.html {
render :partial => @page_partial, :locals => @local_vars
}
end
return
end
end
# Find page by id
elsif not params[:id].blank?
# Render page by id if not webpath was given but an id
@page = Page.find(params[:id])
# Find root page
else
# Render index page if neither id or webpath was given
@page = Page.root_page :force_reload => true
unless @page
@page = Page.new
render '/humpyard/pages/welcome'
return false
end
end
# Raise 404 if no page was found
raise ::ActionController::RoutingError, "No route matches \"#{request.path}\"" if @page.nil? or @page.content_data.is_humpyard_virtual_page?
response.headers['X-Humpyard-Page'] = "#{@page.id}"
response.headers['X-Humpyard-Modified'] = "#{@page.last_modified}"
response.headers['X-Humpyard-ServerTime'] = "#{Time.now.utc}"
@page_partial ||= "/humpyard/pages/#{@page.content_data_type.split('::').last.underscore.pluralize}/show"
@local_vars ||= {:page => @page}
self.class.layout(@page.template_name)
if Rails.application.config.action_controller.perform_caching and not @page.always_refresh
fresh_when :etag => "#{humpyard_user.nil? ? '' : humpyard_user}p#{@page.id}m#{@page.last_modified}", :last_modified => @page.last_modified(:include_pages => true), :public => @humpyard_user.nil?
end
end | ruby | def show
# No page found at the beginning
@page = nil
if params[:locale] and Humpyard.config.locales.include? params[:locale].to_sym
I18n.locale = params[:locale]
elsif session[:humpyard_locale]
I18n.locale = session[:humpyard_locale]
else
I18n.locale = Humpyard.config.locales.first
end
# Find page by name
if not params[:webpath].blank?
dyn_page_path = false
parent_page = nil
params[:webpath].split('/').each do |path_part|
# Ignore multiple slashes in URLs
unless(path_part.blank?)
if(dyn_page_path)
dyn_page_path << path_part
else
# Find page by name and parent; parent=nil means page on root level
@page = Page.with_translated_attribute(:title_for_url, CGI::escape(path_part), I18n.locale).first
# Raise 404 if no page was found for the URL or subpart
raise ::ActionController::RoutingError, "No route matches \"#{request.path}\" (X4201) [#{path_part}]" if @page.nil?
raise ::ActionController::RoutingError, "No route matches \"#{request.path}\" (X4202)" if not (@page.parent == parent_page or @page.parent == Humpyard::Page.root_page)
parent_page = @page unless @page.is_root_page?
dyn_page_path = [] if @page.content_data.is_humpyard_dynamic_page?
end
end
end
if @page.content_data.is_humpyard_dynamic_page? and dyn_page_path.size > 0
@sub_page = @page.parse_path(dyn_page_path)
# Raise 404 if no page was found for the sub_page part
raise ::ActionController::RoutingError, "No route matches \"#{request.path}\" (D4201)" if @sub_page.blank?
@page_partial = "/humpyard/pages/#{@page.content_data_type.split('::').last.underscore.pluralize}/#{@sub_page[:partial]}" if @sub_page[:partial]
@local_vars = {:page => @page}.merge(@sub_page[:locals]) if @sub_page[:locals] and @sub_page[:locals].class == Hash
# render partial only if request was an AJAX-call
if request.xhr?
respond_to do |format|
format.html {
render :partial => @page_partial, :locals => @local_vars
}
end
return
end
end
# Find page by id
elsif not params[:id].blank?
# Render page by id if not webpath was given but an id
@page = Page.find(params[:id])
# Find root page
else
# Render index page if neither id or webpath was given
@page = Page.root_page :force_reload => true
unless @page
@page = Page.new
render '/humpyard/pages/welcome'
return false
end
end
# Raise 404 if no page was found
raise ::ActionController::RoutingError, "No route matches \"#{request.path}\"" if @page.nil? or @page.content_data.is_humpyard_virtual_page?
response.headers['X-Humpyard-Page'] = "#{@page.id}"
response.headers['X-Humpyard-Modified'] = "#{@page.last_modified}"
response.headers['X-Humpyard-ServerTime'] = "#{Time.now.utc}"
@page_partial ||= "/humpyard/pages/#{@page.content_data_type.split('::').last.underscore.pluralize}/show"
@local_vars ||= {:page => @page}
self.class.layout(@page.template_name)
if Rails.application.config.action_controller.perform_caching and not @page.always_refresh
fresh_when :etag => "#{humpyard_user.nil? ? '' : humpyard_user}p#{@page.id}m#{@page.last_modified}", :last_modified => @page.last_modified(:include_pages => true), :public => @humpyard_user.nil?
end
end | [
"def",
"show",
"# No page found at the beginning",
"@page",
"=",
"nil",
"if",
"params",
"[",
":locale",
"]",
"and",
"Humpyard",
".",
"config",
".",
"locales",
".",
"include?",
"params",
"[",
":locale",
"]",
".",
"to_sym",
"I18n",
".",
"locale",
"=",
"params",
"[",
":locale",
"]",
"elsif",
"session",
"[",
":humpyard_locale",
"]",
"I18n",
".",
"locale",
"=",
"session",
"[",
":humpyard_locale",
"]",
"else",
"I18n",
".",
"locale",
"=",
"Humpyard",
".",
"config",
".",
"locales",
".",
"first",
"end",
"# Find page by name",
"if",
"not",
"params",
"[",
":webpath",
"]",
".",
"blank?",
"dyn_page_path",
"=",
"false",
"parent_page",
"=",
"nil",
"params",
"[",
":webpath",
"]",
".",
"split",
"(",
"'/'",
")",
".",
"each",
"do",
"|",
"path_part",
"|",
"# Ignore multiple slashes in URLs",
"unless",
"(",
"path_part",
".",
"blank?",
")",
"if",
"(",
"dyn_page_path",
")",
"dyn_page_path",
"<<",
"path_part",
"else",
"# Find page by name and parent; parent=nil means page on root level",
"@page",
"=",
"Page",
".",
"with_translated_attribute",
"(",
":title_for_url",
",",
"CGI",
"::",
"escape",
"(",
"path_part",
")",
",",
"I18n",
".",
"locale",
")",
".",
"first",
"# Raise 404 if no page was found for the URL or subpart",
"raise",
"::",
"ActionController",
"::",
"RoutingError",
",",
"\"No route matches \\\"#{request.path}\\\" (X4201) [#{path_part}]\"",
"if",
"@page",
".",
"nil?",
"raise",
"::",
"ActionController",
"::",
"RoutingError",
",",
"\"No route matches \\\"#{request.path}\\\" (X4202)\"",
"if",
"not",
"(",
"@page",
".",
"parent",
"==",
"parent_page",
"or",
"@page",
".",
"parent",
"==",
"Humpyard",
"::",
"Page",
".",
"root_page",
")",
"parent_page",
"=",
"@page",
"unless",
"@page",
".",
"is_root_page?",
"dyn_page_path",
"=",
"[",
"]",
"if",
"@page",
".",
"content_data",
".",
"is_humpyard_dynamic_page?",
"end",
"end",
"end",
"if",
"@page",
".",
"content_data",
".",
"is_humpyard_dynamic_page?",
"and",
"dyn_page_path",
".",
"size",
">",
"0",
"@sub_page",
"=",
"@page",
".",
"parse_path",
"(",
"dyn_page_path",
")",
"# Raise 404 if no page was found for the sub_page part",
"raise",
"::",
"ActionController",
"::",
"RoutingError",
",",
"\"No route matches \\\"#{request.path}\\\" (D4201)\"",
"if",
"@sub_page",
".",
"blank?",
"@page_partial",
"=",
"\"/humpyard/pages/#{@page.content_data_type.split('::').last.underscore.pluralize}/#{@sub_page[:partial]}\"",
"if",
"@sub_page",
"[",
":partial",
"]",
"@local_vars",
"=",
"{",
":page",
"=>",
"@page",
"}",
".",
"merge",
"(",
"@sub_page",
"[",
":locals",
"]",
")",
"if",
"@sub_page",
"[",
":locals",
"]",
"and",
"@sub_page",
"[",
":locals",
"]",
".",
"class",
"==",
"Hash",
"# render partial only if request was an AJAX-call",
"if",
"request",
".",
"xhr?",
"respond_to",
"do",
"|",
"format",
"|",
"format",
".",
"html",
"{",
"render",
":partial",
"=>",
"@page_partial",
",",
":locals",
"=>",
"@local_vars",
"}",
"end",
"return",
"end",
"end",
"# Find page by id",
"elsif",
"not",
"params",
"[",
":id",
"]",
".",
"blank?",
"# Render page by id if not webpath was given but an id",
"@page",
"=",
"Page",
".",
"find",
"(",
"params",
"[",
":id",
"]",
")",
"# Find root page",
"else",
"# Render index page if neither id or webpath was given",
"@page",
"=",
"Page",
".",
"root_page",
":force_reload",
"=>",
"true",
"unless",
"@page",
"@page",
"=",
"Page",
".",
"new",
"render",
"'/humpyard/pages/welcome'",
"return",
"false",
"end",
"end",
"# Raise 404 if no page was found",
"raise",
"::",
"ActionController",
"::",
"RoutingError",
",",
"\"No route matches \\\"#{request.path}\\\"\"",
"if",
"@page",
".",
"nil?",
"or",
"@page",
".",
"content_data",
".",
"is_humpyard_virtual_page?",
"response",
".",
"headers",
"[",
"'X-Humpyard-Page'",
"]",
"=",
"\"#{@page.id}\"",
"response",
".",
"headers",
"[",
"'X-Humpyard-Modified'",
"]",
"=",
"\"#{@page.last_modified}\"",
"response",
".",
"headers",
"[",
"'X-Humpyard-ServerTime'",
"]",
"=",
"\"#{Time.now.utc}\"",
"@page_partial",
"||=",
"\"/humpyard/pages/#{@page.content_data_type.split('::').last.underscore.pluralize}/show\"",
"@local_vars",
"||=",
"{",
":page",
"=>",
"@page",
"}",
"self",
".",
"class",
".",
"layout",
"(",
"@page",
".",
"template_name",
")",
"if",
"Rails",
".",
"application",
".",
"config",
".",
"action_controller",
".",
"perform_caching",
"and",
"not",
"@page",
".",
"always_refresh",
"fresh_when",
":etag",
"=>",
"\"#{humpyard_user.nil? ? '' : humpyard_user}p#{@page.id}m#{@page.last_modified}\"",
",",
":last_modified",
"=>",
"@page",
".",
"last_modified",
"(",
":include_pages",
"=>",
"true",
")",
",",
":public",
"=>",
"@humpyard_user",
".",
"nil?",
"end",
"end"
] | Render a given page
When a "webpath" parameter is given it will render the page with that name.
This is what happens when you call a page with it's pretty URL.
When no "name" is given and an "id" parameter is given it will render the
page with the given id.
When no "name" nor "id" parameter is given it will render the root page. | [
"Render",
"a",
"given",
"page"
] | f344ab851f1dfd824c1e4cb4b92f7c62ac0acefd | https://github.com/humpyard/humpyard/blob/f344ab851f1dfd824c1e4cb4b92f7c62ac0acefd/app/controllers/humpyard/pages_controller.rb#L203-L287 | train |
humpyard/humpyard | app/controllers/humpyard/pages_controller.rb | Humpyard.PagesController.sitemap | def sitemap
require 'builder'
xml = ::Builder::XmlMarkup.new :indent => 2
xml.instruct!
xml.tag! :urlset, {
'xmlns'=>"http://www.sitemaps.org/schemas/sitemap/0.9",
'xmlns:xsi'=>"http://www.w3.org/2001/XMLSchema-instance",
'xsi:schemaLocation'=>"http://www.sitemaps.org/schemas/sitemap/0.9\nhttp://www.sitemaps.org/schemas/sitemap/0.9/sitemap.xsd"
} do
base_url = "#{request.protocol}#{request.host}#{request.port==80 ? '' : ":#{request.port}"}"
if root_page = Page.root_page
Humpyard.config.locales.each do |locale|
add_to_sitemap xml, base_url, locale, [{
:index => true,
:url => root_page.human_url(:locale => locale),
:lastmod => root_page.last_modified,
:children => []
}] + root_page.child_pages(:single_root => true).map{|p| p.content_data.site_map(locale)}
end
end
end
render :xml => xml.target!
end | ruby | def sitemap
require 'builder'
xml = ::Builder::XmlMarkup.new :indent => 2
xml.instruct!
xml.tag! :urlset, {
'xmlns'=>"http://www.sitemaps.org/schemas/sitemap/0.9",
'xmlns:xsi'=>"http://www.w3.org/2001/XMLSchema-instance",
'xsi:schemaLocation'=>"http://www.sitemaps.org/schemas/sitemap/0.9\nhttp://www.sitemaps.org/schemas/sitemap/0.9/sitemap.xsd"
} do
base_url = "#{request.protocol}#{request.host}#{request.port==80 ? '' : ":#{request.port}"}"
if root_page = Page.root_page
Humpyard.config.locales.each do |locale|
add_to_sitemap xml, base_url, locale, [{
:index => true,
:url => root_page.human_url(:locale => locale),
:lastmod => root_page.last_modified,
:children => []
}] + root_page.child_pages(:single_root => true).map{|p| p.content_data.site_map(locale)}
end
end
end
render :xml => xml.target!
end | [
"def",
"sitemap",
"require",
"'builder'",
"xml",
"=",
"::",
"Builder",
"::",
"XmlMarkup",
".",
"new",
":indent",
"=>",
"2",
"xml",
".",
"instruct!",
"xml",
".",
"tag!",
":urlset",
",",
"{",
"'xmlns'",
"=>",
"\"http://www.sitemaps.org/schemas/sitemap/0.9\"",
",",
"'xmlns:xsi'",
"=>",
"\"http://www.w3.org/2001/XMLSchema-instance\"",
",",
"'xsi:schemaLocation'",
"=>",
"\"http://www.sitemaps.org/schemas/sitemap/0.9\\nhttp://www.sitemaps.org/schemas/sitemap/0.9/sitemap.xsd\"",
"}",
"do",
"base_url",
"=",
"\"#{request.protocol}#{request.host}#{request.port==80 ? '' : \":#{request.port}\"}\"",
"if",
"root_page",
"=",
"Page",
".",
"root_page",
"Humpyard",
".",
"config",
".",
"locales",
".",
"each",
"do",
"|",
"locale",
"|",
"add_to_sitemap",
"xml",
",",
"base_url",
",",
"locale",
",",
"[",
"{",
":index",
"=>",
"true",
",",
":url",
"=>",
"root_page",
".",
"human_url",
"(",
":locale",
"=>",
"locale",
")",
",",
":lastmod",
"=>",
"root_page",
".",
"last_modified",
",",
":children",
"=>",
"[",
"]",
"}",
"]",
"+",
"root_page",
".",
"child_pages",
"(",
":single_root",
"=>",
"true",
")",
".",
"map",
"{",
"|",
"p",
"|",
"p",
".",
"content_data",
".",
"site_map",
"(",
"locale",
")",
"}",
"end",
"end",
"end",
"render",
":xml",
"=>",
"xml",
".",
"target!",
"end"
] | Render the sitemap.xml for robots | [
"Render",
"the",
"sitemap",
".",
"xml",
"for",
"robots"
] | f344ab851f1dfd824c1e4cb4b92f7c62ac0acefd | https://github.com/humpyard/humpyard/blob/f344ab851f1dfd824c1e4cb4b92f7c62ac0acefd/app/controllers/humpyard/pages_controller.rb#L290-L315 | train |
ideonetwork/lato-blog | app/models/lato_blog/post_field.rb | LatoBlog.PostField.update_child_visibility | def update_child_visibility
return if meta_visible == meta_visible_was
post_fields.map { |pf| pf.update(meta_visible: meta_visible) }
end | ruby | def update_child_visibility
return if meta_visible == meta_visible_was
post_fields.map { |pf| pf.update(meta_visible: meta_visible) }
end | [
"def",
"update_child_visibility",
"return",
"if",
"meta_visible",
"==",
"meta_visible_was",
"post_fields",
".",
"map",
"{",
"|",
"pf",
"|",
"pf",
".",
"update",
"(",
"meta_visible",
":",
"meta_visible",
")",
"}",
"end"
] | This functions update all post fields child visibility with the current
post field visibility. | [
"This",
"functions",
"update",
"all",
"post",
"fields",
"child",
"visibility",
"with",
"the",
"current",
"post",
"field",
"visibility",
"."
] | a0d92de299a0e285851743b9d4a902f611187cba | https://github.com/ideonetwork/lato-blog/blob/a0d92de299a0e285851743b9d4a902f611187cba/app/models/lato_blog/post_field.rb#L43-L46 | train |
jeremyvdw/disqussion | lib/disqussion/client/posts.rb | Disqussion.Posts.vote | def vote(*args)
options = args.last.is_a?(Hash) ? args.pop : {}
if args.length == 2
options.merge!(:vote => args[0])
options.merge!(:post => args[1])
response = post('posts/vote', options)
else
puts "#{Kernel.caller.first}: posts.vote expects 2 arguments: vote([-1..1]), posts ID"
end
end | ruby | def vote(*args)
options = args.last.is_a?(Hash) ? args.pop : {}
if args.length == 2
options.merge!(:vote => args[0])
options.merge!(:post => args[1])
response = post('posts/vote', options)
else
puts "#{Kernel.caller.first}: posts.vote expects 2 arguments: vote([-1..1]), posts ID"
end
end | [
"def",
"vote",
"(",
"*",
"args",
")",
"options",
"=",
"args",
".",
"last",
".",
"is_a?",
"(",
"Hash",
")",
"?",
"args",
".",
"pop",
":",
"{",
"}",
"if",
"args",
".",
"length",
"==",
"2",
"options",
".",
"merge!",
"(",
":vote",
"=>",
"args",
"[",
"0",
"]",
")",
"options",
".",
"merge!",
"(",
":post",
"=>",
"args",
"[",
"1",
"]",
")",
"response",
"=",
"post",
"(",
"'posts/vote'",
",",
"options",
")",
"else",
"puts",
"\"#{Kernel.caller.first}: posts.vote expects 2 arguments: vote([-1..1]), posts ID\"",
"end",
"end"
] | Register a vote for a post.
@accessibility: public key, secret key
@methods: POST
@format: json, jsonp
@authenticated: true
@limited: false
@param vote [Integer] Choices: -1, 0, 1
@param post [Integer] Looks up a post by ID.
@return [Hashie::Rash] Details on the post.
@example Vote for post ID 12345678
Disqussion::Client.posts.vote(1, 12345678)
@see: http://disqus.com/api/3.0/posts/vote.json | [
"Register",
"a",
"vote",
"for",
"a",
"post",
"."
] | 5ad1b0325b7630daf41eb59fc8acbcb785cbc387 | https://github.com/jeremyvdw/disqussion/blob/5ad1b0325b7630daf41eb59fc8acbcb785cbc387/lib/disqussion/client/posts.rb#L275-L284 | train |
tmcarthur/DAF | lib/daf/datasources/yaml_data_source.rb | DAF.YAMLDataSource.action_options | def action_options
# Attempt resolution to outputs of monitor
return @action_options unless @monitor_class.outputs.length > 0
action_options = @action_options.clone
@monitor_class.outputs.each do |output, _type|
action_options.each do |option_key, option_value|
action_options[option_key] =
option_value.gsub("{{#{output}}}", @monitor.send(output).to_s)
end
end
action_options
end | ruby | def action_options
# Attempt resolution to outputs of monitor
return @action_options unless @monitor_class.outputs.length > 0
action_options = @action_options.clone
@monitor_class.outputs.each do |output, _type|
action_options.each do |option_key, option_value|
action_options[option_key] =
option_value.gsub("{{#{output}}}", @monitor.send(output).to_s)
end
end
action_options
end | [
"def",
"action_options",
"# Attempt resolution to outputs of monitor",
"return",
"@action_options",
"unless",
"@monitor_class",
".",
"outputs",
".",
"length",
">",
"0",
"action_options",
"=",
"@action_options",
".",
"clone",
"@monitor_class",
".",
"outputs",
".",
"each",
"do",
"|",
"output",
",",
"_type",
"|",
"action_options",
".",
"each",
"do",
"|",
"option_key",
",",
"option_value",
"|",
"action_options",
"[",
"option_key",
"]",
"=",
"option_value",
".",
"gsub",
"(",
"\"{{#{output}}}\"",
",",
"@monitor",
".",
"send",
"(",
"output",
")",
".",
"to_s",
")",
"end",
"end",
"action_options",
"end"
] | Accepts the path of the YAML file to be parsed into
commands - will throw a CommandException should it have
invalid parameters
@param filePath [String] Path for YAML file | [
"Accepts",
"the",
"path",
"of",
"the",
"YAML",
"file",
"to",
"be",
"parsed",
"into",
"commands",
"-",
"will",
"throw",
"a",
"CommandException",
"should",
"it",
"have",
"invalid",
"parameters"
] | e88d67ec123cc911131dbc74d33735378224703b | https://github.com/tmcarthur/DAF/blob/e88d67ec123cc911131dbc74d33735378224703b/lib/daf/datasources/yaml_data_source.rb#L24-L35 | train |
deepfryed/pony-express | lib/pony-express.rb | PonyExpress.Mail.remove | def remove keys
keys = keys.map(&:to_sym)
@options.reject! {|k, v| keys.include?(k) }
end | ruby | def remove keys
keys = keys.map(&:to_sym)
@options.reject! {|k, v| keys.include?(k) }
end | [
"def",
"remove",
"keys",
"keys",
"=",
"keys",
".",
"map",
"(",
":to_sym",
")",
"@options",
".",
"reject!",
"{",
"|",
"k",
",",
"v",
"|",
"keys",
".",
"include?",
"(",
"k",
")",
"}",
"end"
] | Remove an option.
@example remove.
require "pony-express"
mail = PonyExpress::Mail.new
mail.add to: "[email protected]", cc: "[email protected]"
mail.remove :cc | [
"Remove",
"an",
"option",
"."
] | adedc87a6d47591a56dd2c4fc69339274a754754 | https://github.com/deepfryed/pony-express/blob/adedc87a6d47591a56dd2c4fc69339274a754754/lib/pony-express.rb#L128-L131 | train |
rubiii/ambience | lib/ambience/config.rb | Ambience.Config.to_hash | def to_hash
config = load_base_config
config = config.deep_merge(load_env_config)
config.deep_merge(load_jvm_config)
end | ruby | def to_hash
config = load_base_config
config = config.deep_merge(load_env_config)
config.deep_merge(load_jvm_config)
end | [
"def",
"to_hash",
"config",
"=",
"load_base_config",
"config",
"=",
"config",
".",
"deep_merge",
"(",
"load_env_config",
")",
"config",
".",
"deep_merge",
"(",
"load_jvm_config",
")",
"end"
] | Returns the Ambience config as a Hash. | [
"Returns",
"the",
"Ambience",
"config",
"as",
"a",
"Hash",
"."
] | 25f6e4a94cbed60c719307616fa37a23ecd0fbc2 | https://github.com/rubiii/ambience/blob/25f6e4a94cbed60c719307616fa37a23ecd0fbc2/lib/ambience/config.rb#L38-L42 | train |
rubiii/ambience | lib/ambience/config.rb | Ambience.Config.hash_from_property | def hash_from_property(property, value)
property.split(".").reverse.inject(value) { |value, item| { item => value } }
end | ruby | def hash_from_property(property, value)
property.split(".").reverse.inject(value) { |value, item| { item => value } }
end | [
"def",
"hash_from_property",
"(",
"property",
",",
"value",
")",
"property",
".",
"split",
"(",
"\".\"",
")",
".",
"reverse",
".",
"inject",
"(",
"value",
")",
"{",
"|",
"value",
",",
"item",
"|",
"{",
"item",
"=>",
"value",
"}",
"}",
"end"
] | Returns a Hash generated from a JVM +property+ and its +value+.
==== Example:
hash_from_property "webservice.auth.address", "http://auth.example.com"
# => { "webservice" => { "auth" => { "address" => "http://auth.example.com" } } } | [
"Returns",
"a",
"Hash",
"generated",
"from",
"a",
"JVM",
"+",
"property",
"+",
"and",
"its",
"+",
"value",
"+",
"."
] | 25f6e4a94cbed60c719307616fa37a23ecd0fbc2 | https://github.com/rubiii/ambience/blob/25f6e4a94cbed60c719307616fa37a23ecd0fbc2/lib/ambience/config.rb#L85-L87 | train |
acnalesso/anagram_solver | lib/anagram_solver/permutator.rb | AnagramSolver.Permutator.precompute_old | def precompute_old
warn "This method should not be used, please use precompute instead."
word_list.rewind.each do |line|
word = line.chomp
precomputed_list_old[word.split('').sort.join.freeze] += [word]
end
end | ruby | def precompute_old
warn "This method should not be used, please use precompute instead."
word_list.rewind.each do |line|
word = line.chomp
precomputed_list_old[word.split('').sort.join.freeze] += [word]
end
end | [
"def",
"precompute_old",
"warn",
"\"This method should not be used, please use precompute instead.\"",
"word_list",
".",
"rewind",
".",
"each",
"do",
"|",
"line",
"|",
"word",
"=",
"line",
".",
"chomp",
"precomputed_list_old",
"[",
"word",
".",
"split",
"(",
"''",
")",
".",
"sort",
".",
"join",
".",
"freeze",
"]",
"+=",
"[",
"word",
"]",
"end",
"end"
] | Initializes word_list instance variable, precomputed_list
assigning it a hash whose default values is an empty array.
Precomputes word_list in underneath the hood. (i.e A in-process
thread that AsyncConsumer offers. )
Used for benchmarking | [
"Initializes",
"word_list",
"instance",
"variable",
"precomputed_list",
"assigning",
"it",
"a",
"hash",
"whose",
"default",
"values",
"is",
"an",
"empty",
"array",
"."
] | edb228d8472e898ff06360cfc098d80a43e7d0ea | https://github.com/acnalesso/anagram_solver/blob/edb228d8472e898ff06360cfc098d80a43e7d0ea/lib/anagram_solver/permutator.rb#L36-L42 | train |
cbrumelle/blueprintr | lib/blueprint-css/lib/blueprint/compressor.rb | Blueprint.Compressor.initialize_project_from_yaml | def initialize_project_from_yaml(project_name = nil)
# ensures project_name is set and settings.yml is present
return unless (project_name && File.exist?(@settings_file))
# loads yaml into hash
projects = YAML::load(File.path_to_string(@settings_file))
if (project = projects[project_name]) # checks to see if project info is present
self.namespace = project['namespace'] || ""
self.destination_path = (self.destination_path == Blueprint::BLUEPRINT_ROOT_PATH ? project['path'] : self.destination_path) || Blueprint::BLUEPRINT_ROOT_PATH
self.custom_css = project['custom_css'] || {}
self.semantic_classes = project['semantic_classes'] || {}
self.plugins = project['plugins'] || []
if (layout = project['custom_layout'])
self.custom_layout = CustomLayout.new(:column_count => layout['column_count'], :column_width => layout['column_width'], :gutter_width => layout['gutter_width'], :input_padding => layout['input_padding'], :input_border => layout['input_border'])
end
@loaded_from_settings = true
end
end | ruby | def initialize_project_from_yaml(project_name = nil)
# ensures project_name is set and settings.yml is present
return unless (project_name && File.exist?(@settings_file))
# loads yaml into hash
projects = YAML::load(File.path_to_string(@settings_file))
if (project = projects[project_name]) # checks to see if project info is present
self.namespace = project['namespace'] || ""
self.destination_path = (self.destination_path == Blueprint::BLUEPRINT_ROOT_PATH ? project['path'] : self.destination_path) || Blueprint::BLUEPRINT_ROOT_PATH
self.custom_css = project['custom_css'] || {}
self.semantic_classes = project['semantic_classes'] || {}
self.plugins = project['plugins'] || []
if (layout = project['custom_layout'])
self.custom_layout = CustomLayout.new(:column_count => layout['column_count'], :column_width => layout['column_width'], :gutter_width => layout['gutter_width'], :input_padding => layout['input_padding'], :input_border => layout['input_border'])
end
@loaded_from_settings = true
end
end | [
"def",
"initialize_project_from_yaml",
"(",
"project_name",
"=",
"nil",
")",
"# ensures project_name is set and settings.yml is present",
"return",
"unless",
"(",
"project_name",
"&&",
"File",
".",
"exist?",
"(",
"@settings_file",
")",
")",
"# loads yaml into hash",
"projects",
"=",
"YAML",
"::",
"load",
"(",
"File",
".",
"path_to_string",
"(",
"@settings_file",
")",
")",
"if",
"(",
"project",
"=",
"projects",
"[",
"project_name",
"]",
")",
"# checks to see if project info is present",
"self",
".",
"namespace",
"=",
"project",
"[",
"'namespace'",
"]",
"||",
"\"\"",
"self",
".",
"destination_path",
"=",
"(",
"self",
".",
"destination_path",
"==",
"Blueprint",
"::",
"BLUEPRINT_ROOT_PATH",
"?",
"project",
"[",
"'path'",
"]",
":",
"self",
".",
"destination_path",
")",
"||",
"Blueprint",
"::",
"BLUEPRINT_ROOT_PATH",
"self",
".",
"custom_css",
"=",
"project",
"[",
"'custom_css'",
"]",
"||",
"{",
"}",
"self",
".",
"semantic_classes",
"=",
"project",
"[",
"'semantic_classes'",
"]",
"||",
"{",
"}",
"self",
".",
"plugins",
"=",
"project",
"[",
"'plugins'",
"]",
"||",
"[",
"]",
"if",
"(",
"layout",
"=",
"project",
"[",
"'custom_layout'",
"]",
")",
"self",
".",
"custom_layout",
"=",
"CustomLayout",
".",
"new",
"(",
":column_count",
"=>",
"layout",
"[",
"'column_count'",
"]",
",",
":column_width",
"=>",
"layout",
"[",
"'column_width'",
"]",
",",
":gutter_width",
"=>",
"layout",
"[",
"'gutter_width'",
"]",
",",
":input_padding",
"=>",
"layout",
"[",
"'input_padding'",
"]",
",",
":input_border",
"=>",
"layout",
"[",
"'input_border'",
"]",
")",
"end",
"@loaded_from_settings",
"=",
"true",
"end",
"end"
] | attempts to load output settings from settings.yml | [
"attempts",
"to",
"load",
"output",
"settings",
"from",
"settings",
".",
"yml"
] | b414436f614a8d97d77b47b588ddcf3f5e61b6bd | https://github.com/cbrumelle/blueprintr/blob/b414436f614a8d97d77b47b588ddcf3f5e61b6bd/lib/blueprint-css/lib/blueprint/compressor.rb#L77-L96 | train |
bradfeehan/derelict | lib/derelict/executer.rb | Derelict.Executer.execute | def execute(command, &block)
logger.info "Executing command '#{command}'"
reset
pid, stdin, stdout_stream, stderr_stream = Open4::popen4(command)
@pid = pid
stdin.close rescue nil
save_exit_status(pid)
forward_signals_to(pid) do
handle_streams stdout_stream, stderr_stream, &block
end
self
ensure
logger.debug "Closing stdout and stderr streams for process"
stdout.close rescue nil
stderr.close rescue nil
end | ruby | def execute(command, &block)
logger.info "Executing command '#{command}'"
reset
pid, stdin, stdout_stream, stderr_stream = Open4::popen4(command)
@pid = pid
stdin.close rescue nil
save_exit_status(pid)
forward_signals_to(pid) do
handle_streams stdout_stream, stderr_stream, &block
end
self
ensure
logger.debug "Closing stdout and stderr streams for process"
stdout.close rescue nil
stderr.close rescue nil
end | [
"def",
"execute",
"(",
"command",
",",
"&",
"block",
")",
"logger",
".",
"info",
"\"Executing command '#{command}'\"",
"reset",
"pid",
",",
"stdin",
",",
"stdout_stream",
",",
"stderr_stream",
"=",
"Open4",
"::",
"popen4",
"(",
"command",
")",
"@pid",
"=",
"pid",
"stdin",
".",
"close",
"rescue",
"nil",
"save_exit_status",
"(",
"pid",
")",
"forward_signals_to",
"(",
"pid",
")",
"do",
"handle_streams",
"stdout_stream",
",",
"stderr_stream",
",",
"block",
"end",
"self",
"ensure",
"logger",
".",
"debug",
"\"Closing stdout and stderr streams for process\"",
"stdout",
".",
"close",
"rescue",
"nil",
"stderr",
".",
"close",
"rescue",
"nil",
"end"
] | Initializes an Executer instance with particular options
* options: A hash of options, with the following (symbol) keys:
* :mode: Controls how the process' output is given to
the block, one of :chars (pass each character
one by one, retrieved with getc), or :lines
(pass only whole lines, retrieved with gets).
(optional, defaults to :lines)
* :no_buffer: If true, the process' stdout and stderr won't
be collected in the stdout and stderr
properties, and will only be passed to the
block (optional, defaults to false)
Executes <tt>command</tt> and returns after execution
* command: A string containing the command to run
* block: Gets passed stdout and stderr every time the process
outputs to each stream (first parameter is stdout,
second parameter is stderr; only one will contain
data, the other will be nil) | [
"Initializes",
"an",
"Executer",
"instance",
"with",
"particular",
"options"
] | c9d70f04562280a34083dd060b0e4099e6f32d8d | https://github.com/bradfeehan/derelict/blob/c9d70f04562280a34083dd060b0e4099e6f32d8d/lib/derelict/executer.rb#L68-L85 | train |
bradfeehan/derelict | lib/derelict/executer.rb | Derelict.Executer.forward_signals_to | def forward_signals_to(pid, signals = %w[INT])
# Set up signal handlers
logger.debug "Setting up signal handlers for #{signals.inspect}"
signal_count = 0
signals.each do |signal|
Signal.trap(signal) do
Process.kill signal, pid rescue nil
# If this is the second time we've received and forwarded
# on the signal, make sure next time we just give up.
reset_handlers_for signals if ++signal_count >= 2
end
end
# Run the block now that the signals are being forwarded
yield
ensure
# Always good to make sure we clean up after ourselves
reset_handlers_for signals
end | ruby | def forward_signals_to(pid, signals = %w[INT])
# Set up signal handlers
logger.debug "Setting up signal handlers for #{signals.inspect}"
signal_count = 0
signals.each do |signal|
Signal.trap(signal) do
Process.kill signal, pid rescue nil
# If this is the second time we've received and forwarded
# on the signal, make sure next time we just give up.
reset_handlers_for signals if ++signal_count >= 2
end
end
# Run the block now that the signals are being forwarded
yield
ensure
# Always good to make sure we clean up after ourselves
reset_handlers_for signals
end | [
"def",
"forward_signals_to",
"(",
"pid",
",",
"signals",
"=",
"%w[",
"INT",
"]",
")",
"# Set up signal handlers",
"logger",
".",
"debug",
"\"Setting up signal handlers for #{signals.inspect}\"",
"signal_count",
"=",
"0",
"signals",
".",
"each",
"do",
"|",
"signal",
"|",
"Signal",
".",
"trap",
"(",
"signal",
")",
"do",
"Process",
".",
"kill",
"signal",
",",
"pid",
"rescue",
"nil",
"# If this is the second time we've received and forwarded",
"# on the signal, make sure next time we just give up.",
"reset_handlers_for",
"signals",
"if",
"+",
"+",
"signal_count",
">=",
"2",
"end",
"end",
"# Run the block now that the signals are being forwarded",
"yield",
"ensure",
"# Always good to make sure we clean up after ourselves",
"reset_handlers_for",
"signals",
"end"
] | Forward signals to a process while running the given block
* pid: The process ID to forward signals to
* signals: The names of the signals to handle (optional,
defaults to SIGINT only) | [
"Forward",
"signals",
"to",
"a",
"process",
"while",
"running",
"the",
"given",
"block"
] | c9d70f04562280a34083dd060b0e4099e6f32d8d | https://github.com/bradfeehan/derelict/blob/c9d70f04562280a34083dd060b0e4099e6f32d8d/lib/derelict/executer.rb#L129-L148 | train |
bradfeehan/derelict | lib/derelict/executer.rb | Derelict.Executer.reset_handlers_for | def reset_handlers_for(signals)
logger.debug "Resetting signal handlers for #{signals.inspect}"
signals.each {|signal| Signal.trap signal, "DEFAULT" }
end | ruby | def reset_handlers_for(signals)
logger.debug "Resetting signal handlers for #{signals.inspect}"
signals.each {|signal| Signal.trap signal, "DEFAULT" }
end | [
"def",
"reset_handlers_for",
"(",
"signals",
")",
"logger",
".",
"debug",
"\"Resetting signal handlers for #{signals.inspect}\"",
"signals",
".",
"each",
"{",
"|",
"signal",
"|",
"Signal",
".",
"trap",
"signal",
",",
"\"DEFAULT\"",
"}",
"end"
] | Resets the handlers for particular signals to the default
* signals: An array of signal names to reset the handlers for | [
"Resets",
"the",
"handlers",
"for",
"particular",
"signals",
"to",
"the",
"default"
] | c9d70f04562280a34083dd060b0e4099e6f32d8d | https://github.com/bradfeehan/derelict/blob/c9d70f04562280a34083dd060b0e4099e6f32d8d/lib/derelict/executer.rb#L153-L156 | train |
bradfeehan/derelict | lib/derelict/executer.rb | Derelict.Executer.handle_streams | def handle_streams(stdout_stream, stderr_stream, &block)
logger.debug "Monitoring stdout/stderr streams for output"
streams = [stdout_stream, stderr_stream]
until streams.empty?
# Find which streams are ready for reading, timeout 0.1s
selected, = select(streams, nil, nil, 0.1)
# Try again if none were ready
next if selected.nil? or selected.empty?
selected.each do |stream|
if stream.eof?
logger.debug "Stream reached end-of-file"
if @success.nil?
logger.debug "Process hasn't finished, keeping stream"
else
logger.debug "Removing stream"
streams.delete(stream)
end
next
end
while data = @reader.call(stream)
data = ((@options[:mode] == :chars) ? data.chr : data)
stream_name = (stream == stdout_stream) ? :stdout : :stderr
output data, stream_name, &block unless block.nil?
buffer data, stream_name unless @options[:no_buffer]
end
end
end
end | ruby | def handle_streams(stdout_stream, stderr_stream, &block)
logger.debug "Monitoring stdout/stderr streams for output"
streams = [stdout_stream, stderr_stream]
until streams.empty?
# Find which streams are ready for reading, timeout 0.1s
selected, = select(streams, nil, nil, 0.1)
# Try again if none were ready
next if selected.nil? or selected.empty?
selected.each do |stream|
if stream.eof?
logger.debug "Stream reached end-of-file"
if @success.nil?
logger.debug "Process hasn't finished, keeping stream"
else
logger.debug "Removing stream"
streams.delete(stream)
end
next
end
while data = @reader.call(stream)
data = ((@options[:mode] == :chars) ? data.chr : data)
stream_name = (stream == stdout_stream) ? :stdout : :stderr
output data, stream_name, &block unless block.nil?
buffer data, stream_name unless @options[:no_buffer]
end
end
end
end | [
"def",
"handle_streams",
"(",
"stdout_stream",
",",
"stderr_stream",
",",
"&",
"block",
")",
"logger",
".",
"debug",
"\"Monitoring stdout/stderr streams for output\"",
"streams",
"=",
"[",
"stdout_stream",
",",
"stderr_stream",
"]",
"until",
"streams",
".",
"empty?",
"# Find which streams are ready for reading, timeout 0.1s",
"selected",
",",
"=",
"select",
"(",
"streams",
",",
"nil",
",",
"nil",
",",
"0.1",
")",
"# Try again if none were ready",
"next",
"if",
"selected",
".",
"nil?",
"or",
"selected",
".",
"empty?",
"selected",
".",
"each",
"do",
"|",
"stream",
"|",
"if",
"stream",
".",
"eof?",
"logger",
".",
"debug",
"\"Stream reached end-of-file\"",
"if",
"@success",
".",
"nil?",
"logger",
".",
"debug",
"\"Process hasn't finished, keeping stream\"",
"else",
"logger",
".",
"debug",
"\"Removing stream\"",
"streams",
".",
"delete",
"(",
"stream",
")",
"end",
"next",
"end",
"while",
"data",
"=",
"@reader",
".",
"call",
"(",
"stream",
")",
"data",
"=",
"(",
"(",
"@options",
"[",
":mode",
"]",
"==",
":chars",
")",
"?",
"data",
".",
"chr",
":",
"data",
")",
"stream_name",
"=",
"(",
"stream",
"==",
"stdout_stream",
")",
"?",
":stdout",
":",
":stderr",
"output",
"data",
",",
"stream_name",
",",
"block",
"unless",
"block",
".",
"nil?",
"buffer",
"data",
",",
"stream_name",
"unless",
"@options",
"[",
":no_buffer",
"]",
"end",
"end",
"end",
"end"
] | Manages reading from the stdout and stderr streams
* stdout_stream: The process' stdout stream
* stderr_stream: The process' stderr stream
* block: The block to pass output to (optional) | [
"Manages",
"reading",
"from",
"the",
"stdout",
"and",
"stderr",
"streams"
] | c9d70f04562280a34083dd060b0e4099e6f32d8d | https://github.com/bradfeehan/derelict/blob/c9d70f04562280a34083dd060b0e4099e6f32d8d/lib/derelict/executer.rb#L163-L193 | train |
bradfeehan/derelict | lib/derelict/executer.rb | Derelict.Executer.output | def output(data, stream_name = :stdout, &block)
# Pass the output to the block
if block.arity == 2
args = [nil, nil]
if stream_name == :stdout
args[0] = data
else
args[1] = data
end
block.call(*args)
else
yield data if stream_name == :stdout
end
end | ruby | def output(data, stream_name = :stdout, &block)
# Pass the output to the block
if block.arity == 2
args = [nil, nil]
if stream_name == :stdout
args[0] = data
else
args[1] = data
end
block.call(*args)
else
yield data if stream_name == :stdout
end
end | [
"def",
"output",
"(",
"data",
",",
"stream_name",
"=",
":stdout",
",",
"&",
"block",
")",
"# Pass the output to the block",
"if",
"block",
".",
"arity",
"==",
"2",
"args",
"=",
"[",
"nil",
",",
"nil",
"]",
"if",
"stream_name",
"==",
":stdout",
"args",
"[",
"0",
"]",
"=",
"data",
"else",
"args",
"[",
"1",
"]",
"=",
"data",
"end",
"block",
".",
"call",
"(",
"args",
")",
"else",
"yield",
"data",
"if",
"stream_name",
"==",
":stdout",
"end",
"end"
] | Outputs data to the block
* data: The data that needs to be passed to the block
* stream_name: The stream data came from (:stdout or :stderr)
* block: The block to pass the data to | [
"Outputs",
"data",
"to",
"the",
"block"
] | c9d70f04562280a34083dd060b0e4099e6f32d8d | https://github.com/bradfeehan/derelict/blob/c9d70f04562280a34083dd060b0e4099e6f32d8d/lib/derelict/executer.rb#L200-L213 | train |
tmcarthur/DAF | lib/daf/command.rb | DAF.Command.execute | def execute
@thread = Thread.new do
if Thread.current != Thread.main
loop do
@datasource.monitor.on_trigger do
@datasource.action.activate(@datasource.action_options)
end
end
end
end
end | ruby | def execute
@thread = Thread.new do
if Thread.current != Thread.main
loop do
@datasource.monitor.on_trigger do
@datasource.action.activate(@datasource.action_options)
end
end
end
end
end | [
"def",
"execute",
"@thread",
"=",
"Thread",
".",
"new",
"do",
"if",
"Thread",
".",
"current",
"!=",
"Thread",
".",
"main",
"loop",
"do",
"@datasource",
".",
"monitor",
".",
"on_trigger",
"do",
"@datasource",
".",
"action",
".",
"activate",
"(",
"@datasource",
".",
"action_options",
")",
"end",
"end",
"end",
"end",
"end"
] | Create a new command object from a data source
@param datasource [CommandDataSource] The data source to use to initialize
command object
Begins executing the command by starting the monitor specified in
the data source - will return immediately | [
"Create",
"a",
"new",
"command",
"object",
"from",
"a",
"data",
"source"
] | e88d67ec123cc911131dbc74d33735378224703b | https://github.com/tmcarthur/DAF/blob/e88d67ec123cc911131dbc74d33735378224703b/lib/daf/command.rb#L21-L31 | train |
sugaryourcoffee/syclink | lib/syclink/link_checker.rb | SycLink.LinkChecker.response_of_uri | def response_of_uri(uri)
begin
Net::HTTP.start(uri.host, uri.port) do |http|
http.head(uri.path.size > 0 ? uri.path : "/").code
end
rescue Exception => e
"Error"
end
end | ruby | def response_of_uri(uri)
begin
Net::HTTP.start(uri.host, uri.port) do |http|
http.head(uri.path.size > 0 ? uri.path : "/").code
end
rescue Exception => e
"Error"
end
end | [
"def",
"response_of_uri",
"(",
"uri",
")",
"begin",
"Net",
"::",
"HTTP",
".",
"start",
"(",
"uri",
".",
"host",
",",
"uri",
".",
"port",
")",
"do",
"|",
"http",
"|",
"http",
".",
"head",
"(",
"uri",
".",
"path",
".",
"size",
">",
"0",
"?",
"uri",
".",
"path",
":",
"\"/\"",
")",
".",
"code",
"end",
"rescue",
"Exception",
"=>",
"e",
"\"Error\"",
"end",
"end"
] | Checks whether the uri is reachable. If so it returns '200' otherwise
'Error'. uri has to have a host, that is uri.host should not be nil | [
"Checks",
"whether",
"the",
"uri",
"is",
"reachable",
".",
"If",
"so",
"it",
"returns",
"200",
"otherwise",
"Error",
".",
"uri",
"has",
"to",
"have",
"a",
"host",
"that",
"is",
"uri",
".",
"host",
"should",
"not",
"be",
"nil"
] | 941ee2045c946daa1e0db394eb643aa82c1254cc | https://github.com/sugaryourcoffee/syclink/blob/941ee2045c946daa1e0db394eb643aa82c1254cc/lib/syclink/link_checker.rb#L20-L28 | train |
celldee/ffi-rxs | lib/ffi-rxs/poll.rb | XS.Poller.register | def register sock, events = XS::POLLIN | XS::POLLOUT, fd = 0
return false if (sock.nil? && fd.zero?) || events.zero?
item = @items.get(@sockets.index(sock))
unless item
@sockets << sock
item = LibXS::PollItem.new
if sock.kind_of?(XS::Socket) || sock.kind_of?(Socket)
item[:socket] = sock.socket
item[:fd] = 0
else
item[:socket] = FFI::MemoryPointer.new(0)
item[:fd] = fd
end
@raw_to_socket[item.socket.address] = sock
@items << item
end
item[:events] |= events
end | ruby | def register sock, events = XS::POLLIN | XS::POLLOUT, fd = 0
return false if (sock.nil? && fd.zero?) || events.zero?
item = @items.get(@sockets.index(sock))
unless item
@sockets << sock
item = LibXS::PollItem.new
if sock.kind_of?(XS::Socket) || sock.kind_of?(Socket)
item[:socket] = sock.socket
item[:fd] = 0
else
item[:socket] = FFI::MemoryPointer.new(0)
item[:fd] = fd
end
@raw_to_socket[item.socket.address] = sock
@items << item
end
item[:events] |= events
end | [
"def",
"register",
"sock",
",",
"events",
"=",
"XS",
"::",
"POLLIN",
"|",
"XS",
"::",
"POLLOUT",
",",
"fd",
"=",
"0",
"return",
"false",
"if",
"(",
"sock",
".",
"nil?",
"&&",
"fd",
".",
"zero?",
")",
"||",
"events",
".",
"zero?",
"item",
"=",
"@items",
".",
"get",
"(",
"@sockets",
".",
"index",
"(",
"sock",
")",
")",
"unless",
"item",
"@sockets",
"<<",
"sock",
"item",
"=",
"LibXS",
"::",
"PollItem",
".",
"new",
"if",
"sock",
".",
"kind_of?",
"(",
"XS",
"::",
"Socket",
")",
"||",
"sock",
".",
"kind_of?",
"(",
"Socket",
")",
"item",
"[",
":socket",
"]",
"=",
"sock",
".",
"socket",
"item",
"[",
":fd",
"]",
"=",
"0",
"else",
"item",
"[",
":socket",
"]",
"=",
"FFI",
"::",
"MemoryPointer",
".",
"new",
"(",
"0",
")",
"item",
"[",
":fd",
"]",
"=",
"fd",
"end",
"@raw_to_socket",
"[",
"item",
".",
"socket",
".",
"address",
"]",
"=",
"sock",
"@items",
"<<",
"item",
"end",
"item",
"[",
":events",
"]",
"|=",
"events",
"end"
] | Register the +sock+ for +events+. This method is idempotent meaning
it can be called multiple times with the same data and the socket
will only get registered at most once. Calling multiple times with
different values for +events+ will OR the event information together.
@param socket
@param events
One of @XS::POLLIN@ and @XS::POLLOUT@
@return true if successful
@return false if not | [
"Register",
"the",
"+",
"sock",
"+",
"for",
"+",
"events",
"+",
".",
"This",
"method",
"is",
"idempotent",
"meaning",
"it",
"can",
"be",
"called",
"multiple",
"times",
"with",
"the",
"same",
"data",
"and",
"the",
"socket",
"will",
"only",
"get",
"registered",
"at",
"most",
"once",
".",
"Calling",
"multiple",
"times",
"with",
"different",
"values",
"for",
"+",
"events",
"+",
"will",
"OR",
"the",
"event",
"information",
"together",
"."
] | 95378f3a5e5b5b3f1f726a9a1620f41ab4ee7f0e | https://github.com/celldee/ffi-rxs/blob/95378f3a5e5b5b3f1f726a9a1620f41ab4ee7f0e/lib/ffi-rxs/poll.rb#L75-L96 | train |
celldee/ffi-rxs | lib/ffi-rxs/poll.rb | XS.Poller.deregister | def deregister sock, events, fd = 0
return unless sock || !fd.zero?
item = @items.get(@sockets.index(sock))
if item && (item[:events] & events) > 0
# change the value in place
item[:events] ^= events
delete sock if item[:events].zero?
true
else
false
end
end | ruby | def deregister sock, events, fd = 0
return unless sock || !fd.zero?
item = @items.get(@sockets.index(sock))
if item && (item[:events] & events) > 0
# change the value in place
item[:events] ^= events
delete sock if item[:events].zero?
true
else
false
end
end | [
"def",
"deregister",
"sock",
",",
"events",
",",
"fd",
"=",
"0",
"return",
"unless",
"sock",
"||",
"!",
"fd",
".",
"zero?",
"item",
"=",
"@items",
".",
"get",
"(",
"@sockets",
".",
"index",
"(",
"sock",
")",
")",
"if",
"item",
"&&",
"(",
"item",
"[",
":events",
"]",
"&",
"events",
")",
">",
"0",
"# change the value in place",
"item",
"[",
":events",
"]",
"^=",
"events",
"delete",
"sock",
"if",
"item",
"[",
":events",
"]",
".",
"zero?",
"true",
"else",
"false",
"end",
"end"
] | Deregister the +sock+ for +events+. When there are no events left,
this also deletes the socket from the poll items.
@param socket
@param events
One of @XS::POLLIN@ and @XS::POLLOUT@
@return true if successful
@return false if not | [
"Deregister",
"the",
"+",
"sock",
"+",
"for",
"+",
"events",
"+",
".",
"When",
"there",
"are",
"no",
"events",
"left",
"this",
"also",
"deletes",
"the",
"socket",
"from",
"the",
"poll",
"items",
"."
] | 95378f3a5e5b5b3f1f726a9a1620f41ab4ee7f0e | https://github.com/celldee/ffi-rxs/blob/95378f3a5e5b5b3f1f726a9a1620f41ab4ee7f0e/lib/ffi-rxs/poll.rb#L107-L121 | train |
celldee/ffi-rxs | lib/ffi-rxs/poll.rb | XS.Poller.delete | def delete sock
unless (size = @sockets.size).zero?
@sockets.delete_if { |socket| socket.socket.address == sock.socket.address }
socket_deleted = size != @sockets.size
item_deleted = @items.delete sock
raw_deleted = @raw_to_socket.delete(sock.socket.address)
socket_deleted && item_deleted && raw_deleted
else
false
end
end | ruby | def delete sock
unless (size = @sockets.size).zero?
@sockets.delete_if { |socket| socket.socket.address == sock.socket.address }
socket_deleted = size != @sockets.size
item_deleted = @items.delete sock
raw_deleted = @raw_to_socket.delete(sock.socket.address)
socket_deleted && item_deleted && raw_deleted
else
false
end
end | [
"def",
"delete",
"sock",
"unless",
"(",
"size",
"=",
"@sockets",
".",
"size",
")",
".",
"zero?",
"@sockets",
".",
"delete_if",
"{",
"|",
"socket",
"|",
"socket",
".",
"socket",
".",
"address",
"==",
"sock",
".",
"socket",
".",
"address",
"}",
"socket_deleted",
"=",
"size",
"!=",
"@sockets",
".",
"size",
"item_deleted",
"=",
"@items",
".",
"delete",
"sock",
"raw_deleted",
"=",
"@raw_to_socket",
".",
"delete",
"(",
"sock",
".",
"socket",
".",
"address",
")",
"socket_deleted",
"&&",
"item_deleted",
"&&",
"raw_deleted",
"else",
"false",
"end",
"end"
] | Deletes the +sock+ for all subscribed events. Called internally
when a socket has been deregistered and has no more events
registered anywhere.
Can also be called directly to remove the socket from the polling
array.
@param socket
@return true if successful
@return false if not | [
"Deletes",
"the",
"+",
"sock",
"+",
"for",
"all",
"subscribed",
"events",
".",
"Called",
"internally",
"when",
"a",
"socket",
"has",
"been",
"deregistered",
"and",
"has",
"no",
"more",
"events",
"registered",
"anywhere",
"."
] | 95378f3a5e5b5b3f1f726a9a1620f41ab4ee7f0e | https://github.com/celldee/ffi-rxs/blob/95378f3a5e5b5b3f1f726a9a1620f41ab4ee7f0e/lib/ffi-rxs/poll.rb#L174-L188 | train |
celldee/ffi-rxs | lib/ffi-rxs/poll.rb | XS.Poller.update_selectables | def update_selectables
@readables.clear
@writables.clear
@items.each do |poll_item|
#FIXME: spec for sockets *and* file descriptors
if poll_item.readable?
@readables << (poll_item.socket.address.zero? ? poll_item.fd : @raw_to_socket[poll_item.socket.address])
end
if poll_item.writable?
@writables << (poll_item.socket.address.zero? ? poll_item.fd : @raw_to_socket[poll_item.socket.address])
end
end
end | ruby | def update_selectables
@readables.clear
@writables.clear
@items.each do |poll_item|
#FIXME: spec for sockets *and* file descriptors
if poll_item.readable?
@readables << (poll_item.socket.address.zero? ? poll_item.fd : @raw_to_socket[poll_item.socket.address])
end
if poll_item.writable?
@writables << (poll_item.socket.address.zero? ? poll_item.fd : @raw_to_socket[poll_item.socket.address])
end
end
end | [
"def",
"update_selectables",
"@readables",
".",
"clear",
"@writables",
".",
"clear",
"@items",
".",
"each",
"do",
"|",
"poll_item",
"|",
"#FIXME: spec for sockets *and* file descriptors",
"if",
"poll_item",
".",
"readable?",
"@readables",
"<<",
"(",
"poll_item",
".",
"socket",
".",
"address",
".",
"zero?",
"?",
"poll_item",
".",
"fd",
":",
"@raw_to_socket",
"[",
"poll_item",
".",
"socket",
".",
"address",
"]",
")",
"end",
"if",
"poll_item",
".",
"writable?",
"@writables",
"<<",
"(",
"poll_item",
".",
"socket",
".",
"address",
".",
"zero?",
"?",
"poll_item",
".",
"fd",
":",
"@raw_to_socket",
"[",
"poll_item",
".",
"socket",
".",
"address",
"]",
")",
"end",
"end",
"end"
] | Update readables and writeables | [
"Update",
"readables",
"and",
"writeables"
] | 95378f3a5e5b5b3f1f726a9a1620f41ab4ee7f0e | https://github.com/celldee/ffi-rxs/blob/95378f3a5e5b5b3f1f726a9a1620f41ab4ee7f0e/lib/ffi-rxs/poll.rb#L216-L230 | train |
hybridgroup/taskmapper-bugzilla | lib/provider/bugzilla.rb | TaskMapper::Provider.Bugzilla.authorize | def authorize(auth = {})
@authentication ||= TaskMapper::Authenticator.new(auth)
auth = @authentication
if (auth.username.nil? || auth.url.nil? || auth.password.nil?)
raise "Please provide username, password and url"
end
url = auth.url.gsub(/\/$/,'')
unless url.split('/').last == 'xmlrpc.cgi'
auth.url = url+'/xmlrpc.cgi'
end
@bugzilla = Rubyzilla::Bugzilla.new(auth.url)
begin
@bugzilla.login(auth.username,auth.password)
rescue
warn 'Authentication was invalid'
end
end | ruby | def authorize(auth = {})
@authentication ||= TaskMapper::Authenticator.new(auth)
auth = @authentication
if (auth.username.nil? || auth.url.nil? || auth.password.nil?)
raise "Please provide username, password and url"
end
url = auth.url.gsub(/\/$/,'')
unless url.split('/').last == 'xmlrpc.cgi'
auth.url = url+'/xmlrpc.cgi'
end
@bugzilla = Rubyzilla::Bugzilla.new(auth.url)
begin
@bugzilla.login(auth.username,auth.password)
rescue
warn 'Authentication was invalid'
end
end | [
"def",
"authorize",
"(",
"auth",
"=",
"{",
"}",
")",
"@authentication",
"||=",
"TaskMapper",
"::",
"Authenticator",
".",
"new",
"(",
"auth",
")",
"auth",
"=",
"@authentication",
"if",
"(",
"auth",
".",
"username",
".",
"nil?",
"||",
"auth",
".",
"url",
".",
"nil?",
"||",
"auth",
".",
"password",
".",
"nil?",
")",
"raise",
"\"Please provide username, password and url\"",
"end",
"url",
"=",
"auth",
".",
"url",
".",
"gsub",
"(",
"/",
"\\/",
"/",
",",
"''",
")",
"unless",
"url",
".",
"split",
"(",
"'/'",
")",
".",
"last",
"==",
"'xmlrpc.cgi'",
"auth",
".",
"url",
"=",
"url",
"+",
"'/xmlrpc.cgi'",
"end",
"@bugzilla",
"=",
"Rubyzilla",
"::",
"Bugzilla",
".",
"new",
"(",
"auth",
".",
"url",
")",
"begin",
"@bugzilla",
".",
"login",
"(",
"auth",
".",
"username",
",",
"auth",
".",
"password",
")",
"rescue",
"warn",
"'Authentication was invalid'",
"end",
"end"
] | declare needed overloaded methods here | [
"declare",
"needed",
"overloaded",
"methods",
"here"
] | 2eb871742418206bbe9fe683e5bc20831e1eb236 | https://github.com/hybridgroup/taskmapper-bugzilla/blob/2eb871742418206bbe9fe683e5bc20831e1eb236/lib/provider/bugzilla.rb#L15-L31 | train |
fuCtor/mswallet | lib/mswallet/pass.rb | Mswallet.Pass.file | def file(options = {})
options[:file_name] ||= 'pass.mswallet'
temp_file = Tempfile.new(options[:file_name])
temp_file.write self.stream.string
temp_file.close
temp_file
end | ruby | def file(options = {})
options[:file_name] ||= 'pass.mswallet'
temp_file = Tempfile.new(options[:file_name])
temp_file.write self.stream.string
temp_file.close
temp_file
end | [
"def",
"file",
"(",
"options",
"=",
"{",
"}",
")",
"options",
"[",
":file_name",
"]",
"||=",
"'pass.mswallet'",
"temp_file",
"=",
"Tempfile",
".",
"new",
"(",
"options",
"[",
":file_name",
"]",
")",
"temp_file",
".",
"write",
"self",
".",
"stream",
".",
"string",
"temp_file",
".",
"close",
"temp_file",
"end"
] | Return a Tempfile containing our ZipStream | [
"Return",
"a",
"Tempfile",
"containing",
"our",
"ZipStream"
] | 684475989c0936f2654e3f040d56aa58fa94e22a | https://github.com/fuCtor/mswallet/blob/684475989c0936f2654e3f040d56aa58fa94e22a/lib/mswallet/pass.rb#L39-L45 | train |
colstrom/ezmq | lib/ezmq/request.rb | EZMQ.Client.request | def request(message, **options)
send message, options
if block_given?
yield receive options
else
receive options
end
end | ruby | def request(message, **options)
send message, options
if block_given?
yield receive options
else
receive options
end
end | [
"def",
"request",
"(",
"message",
",",
"**",
"options",
")",
"send",
"message",
",",
"options",
"if",
"block_given?",
"yield",
"receive",
"options",
"else",
"receive",
"options",
"end",
"end"
] | Creates a new Client socket.
@param [:bind, :connect] mode (:connect) a mode for the socket.
@param [Hash] options optional parameters.
@see EZMQ::Socket EZMQ::Socket for optional parameters.
@return [Client] a new instance of Client.
Sends a message and waits to receive a response.
@param [String] message the message to send.
@param [Hash] options optional parameters.
@option options [lambda] encode how to encode the message.
@option options [lambda] decode how to decode the message.
@return [void] the decoded response message. | [
"Creates",
"a",
"new",
"Client",
"socket",
"."
] | cd7f9f256d6c3f7a844871a3a77a89d7122d5836 | https://github.com/colstrom/ezmq/blob/cd7f9f256d6c3f7a844871a3a77a89d7122d5836/lib/ezmq/request.rb#L28-L35 | train |
Subsets and Splits