id
int32
0
24.9k
repo
stringlengths
5
58
path
stringlengths
9
168
func_name
stringlengths
9
130
original_string
stringlengths
66
10.5k
language
stringclasses
1 value
code
stringlengths
66
10.5k
code_tokens
sequence
docstring
stringlengths
8
16k
docstring_tokens
sequence
sha
stringlengths
40
40
url
stringlengths
94
266
1,100
logicminds/rubyipmi
lib/rubyipmi/ipmitool/commands/basecommand.rb
Rubyipmi::Ipmitool.BaseCommand.find_fix
def find_fix(result) return unless result # The errorcode code hash contains the fix begin fix = ErrorCodes.search(result) @options.merge_notify!(fix) rescue raise "Could not find fix for error code: \n#{result}" end end
ruby
def find_fix(result) return unless result # The errorcode code hash contains the fix begin fix = ErrorCodes.search(result) @options.merge_notify!(fix) rescue raise "Could not find fix for error code: \n#{result}" end end
[ "def", "find_fix", "(", "result", ")", "return", "unless", "result", "# The errorcode code hash contains the fix", "begin", "fix", "=", "ErrorCodes", ".", "search", "(", "result", ")", "@options", ".", "merge_notify!", "(", "fix", ")", "rescue", "raise", "\"Could not find fix for error code: \\n#{result}\"", "end", "end" ]
The findfix method acts like a recursive method and applies fixes defined in the errorcodes If a fix is found it is applied to the options hash, and then the last run command is retried until all the fixes are exhausted or a error not defined in the errorcodes is found
[ "The", "findfix", "method", "acts", "like", "a", "recursive", "method", "and", "applies", "fixes", "defined", "in", "the", "errorcodes", "If", "a", "fix", "is", "found", "it", "is", "applied", "to", "the", "options", "hash", "and", "then", "the", "last", "run", "command", "is", "retried", "until", "all", "the", "fixes", "are", "exhausted", "or", "a", "error", "not", "defined", "in", "the", "errorcodes", "is", "found" ]
516dfb0d5f8aa126159a5f5c25d60ab5c98f862f
https://github.com/logicminds/rubyipmi/blob/516dfb0d5f8aa126159a5f5c25d60ab5c98f862f/lib/rubyipmi/ipmitool/commands/basecommand.rb#L36-L46
1,101
logicminds/rubyipmi
lib/rubyipmi/freeipmi/commands/chassis.rb
Rubyipmi::Freeipmi.Chassis.bootdevice
def bootdevice(device, reboot = false, persistent = false) if config.bootdevices.include?(device) bootstatus = config.bootdevice(device, persistent) power.cycle if reboot && bootstatus else logger.error("Device with name: #{device} is not a valid boot device for host #{options['hostname']}") if logger raise "Device with name: #{device} is not a valid boot device for host #{options['hostname']}" end end
ruby
def bootdevice(device, reboot = false, persistent = false) if config.bootdevices.include?(device) bootstatus = config.bootdevice(device, persistent) power.cycle if reboot && bootstatus else logger.error("Device with name: #{device} is not a valid boot device for host #{options['hostname']}") if logger raise "Device with name: #{device} is not a valid boot device for host #{options['hostname']}" end end
[ "def", "bootdevice", "(", "device", ",", "reboot", "=", "false", ",", "persistent", "=", "false", ")", "if", "config", ".", "bootdevices", ".", "include?", "(", "device", ")", "bootstatus", "=", "config", ".", "bootdevice", "(", "device", ",", "persistent", ")", "power", ".", "cycle", "if", "reboot", "&&", "bootstatus", "else", "logger", ".", "error", "(", "\"Device with name: #{device} is not a valid boot device for host #{options['hostname']}\"", ")", "if", "logger", "raise", "\"Device with name: #{device} is not a valid boot device for host #{options['hostname']}\"", "end", "end" ]
set boot device from given boot device
[ "set", "boot", "device", "from", "given", "boot", "device" ]
516dfb0d5f8aa126159a5f5c25d60ab5c98f862f
https://github.com/logicminds/rubyipmi/blob/516dfb0d5f8aa126159a5f5c25d60ab5c98f862f/lib/rubyipmi/freeipmi/commands/chassis.rb#L35-L43
1,102
logicminds/rubyipmi
lib/rubyipmi/freeipmi/commands/chassis.rb
Rubyipmi::Freeipmi.Chassis.bootpxe
def bootpxe(reboot = false, persistent = false) bootstatus = config.bootpxe(persistent) # Only reboot if setting the boot flag was successful power.cycle if reboot && bootstatus end
ruby
def bootpxe(reboot = false, persistent = false) bootstatus = config.bootpxe(persistent) # Only reboot if setting the boot flag was successful power.cycle if reboot && bootstatus end
[ "def", "bootpxe", "(", "reboot", "=", "false", ",", "persistent", "=", "false", ")", "bootstatus", "=", "config", ".", "bootpxe", "(", "persistent", ")", "# Only reboot if setting the boot flag was successful", "power", ".", "cycle", "if", "reboot", "&&", "bootstatus", "end" ]
set boot device to pxe with option to reboot
[ "set", "boot", "device", "to", "pxe", "with", "option", "to", "reboot" ]
516dfb0d5f8aa126159a5f5c25d60ab5c98f862f
https://github.com/logicminds/rubyipmi/blob/516dfb0d5f8aa126159a5f5c25d60ab5c98f862f/lib/rubyipmi/freeipmi/commands/chassis.rb#L46-L50
1,103
logicminds/rubyipmi
lib/rubyipmi/freeipmi/commands/chassis.rb
Rubyipmi::Freeipmi.Chassis.bootdisk
def bootdisk(reboot = false, persistent = false) bootstatus = config.bootdisk(persistent) # Only reboot if setting the boot flag was successful power.cycle if reboot && bootstatus end
ruby
def bootdisk(reboot = false, persistent = false) bootstatus = config.bootdisk(persistent) # Only reboot if setting the boot flag was successful power.cycle if reboot && bootstatus end
[ "def", "bootdisk", "(", "reboot", "=", "false", ",", "persistent", "=", "false", ")", "bootstatus", "=", "config", ".", "bootdisk", "(", "persistent", ")", "# Only reboot if setting the boot flag was successful", "power", ".", "cycle", "if", "reboot", "&&", "bootstatus", "end" ]
set boot device to disk with option to reboot
[ "set", "boot", "device", "to", "disk", "with", "option", "to", "reboot" ]
516dfb0d5f8aa126159a5f5c25d60ab5c98f862f
https://github.com/logicminds/rubyipmi/blob/516dfb0d5f8aa126159a5f5c25d60ab5c98f862f/lib/rubyipmi/freeipmi/commands/chassis.rb#L53-L57
1,104
logicminds/rubyipmi
lib/rubyipmi/freeipmi/commands/chassis.rb
Rubyipmi::Freeipmi.Chassis.bootcdrom
def bootcdrom(reboot = false, persistent = false) bootstatus = config.bootcdrom(persistent) # Only reboot if setting the boot flag was successful power.cycle if reboot && bootstatus end
ruby
def bootcdrom(reboot = false, persistent = false) bootstatus = config.bootcdrom(persistent) # Only reboot if setting the boot flag was successful power.cycle if reboot && bootstatus end
[ "def", "bootcdrom", "(", "reboot", "=", "false", ",", "persistent", "=", "false", ")", "bootstatus", "=", "config", ".", "bootcdrom", "(", "persistent", ")", "# Only reboot if setting the boot flag was successful", "power", ".", "cycle", "if", "reboot", "&&", "bootstatus", "end" ]
set boot device to cdrom with option to reboot
[ "set", "boot", "device", "to", "cdrom", "with", "option", "to", "reboot" ]
516dfb0d5f8aa126159a5f5c25d60ab5c98f862f
https://github.com/logicminds/rubyipmi/blob/516dfb0d5f8aa126159a5f5c25d60ab5c98f862f/lib/rubyipmi/freeipmi/commands/chassis.rb#L60-L64
1,105
logicminds/rubyipmi
lib/rubyipmi/ipmitool/commands/chassis.rb
Rubyipmi::Ipmitool.Chassis.bootbios
def bootbios(reboot = false, persistent = false) bootstatus = config.bootbios(persistent) # Only reboot if setting the boot flag was successful power.cycle if reboot && bootstatus bootstatus end
ruby
def bootbios(reboot = false, persistent = false) bootstatus = config.bootbios(persistent) # Only reboot if setting the boot flag was successful power.cycle if reboot && bootstatus bootstatus end
[ "def", "bootbios", "(", "reboot", "=", "false", ",", "persistent", "=", "false", ")", "bootstatus", "=", "config", ".", "bootbios", "(", "persistent", ")", "# Only reboot if setting the boot flag was successful", "power", ".", "cycle", "if", "reboot", "&&", "bootstatus", "bootstatus", "end" ]
boot into bios setup with option to reboot
[ "boot", "into", "bios", "setup", "with", "option", "to", "reboot" ]
516dfb0d5f8aa126159a5f5c25d60ab5c98f862f
https://github.com/logicminds/rubyipmi/blob/516dfb0d5f8aa126159a5f5c25d60ab5c98f862f/lib/rubyipmi/ipmitool/commands/chassis.rb#L72-L77
1,106
logicminds/rubyipmi
lib/rubyipmi/ipmitool/commands/chassis.rb
Rubyipmi::Ipmitool.Chassis.identifystatus
def identifystatus options["cmdargs"] = "chassis identify status" value = runcmd options.delete_notify("cmdargs") @result.chomp.split(":").last.strip if value end
ruby
def identifystatus options["cmdargs"] = "chassis identify status" value = runcmd options.delete_notify("cmdargs") @result.chomp.split(":").last.strip if value end
[ "def", "identifystatus", "options", "[", "\"cmdargs\"", "]", "=", "\"chassis identify status\"", "value", "=", "runcmd", "options", ".", "delete_notify", "(", "\"cmdargs\"", ")", "@result", ".", "chomp", ".", "split", "(", "\":\"", ")", ".", "last", ".", "strip", "if", "value", "end" ]
A currently unsupported method to retrieve the led status
[ "A", "currently", "unsupported", "method", "to", "retrieve", "the", "led", "status" ]
516dfb0d5f8aa126159a5f5c25d60ab5c98f862f
https://github.com/logicminds/rubyipmi/blob/516dfb0d5f8aa126159a5f5c25d60ab5c98f862f/lib/rubyipmi/ipmitool/commands/chassis.rb#L87-L92
1,107
logicminds/rubyipmi
lib/rubyipmi/freeipmi/commands/fru.rb
Rubyipmi::Freeipmi.FruData.parse
def parse(data) return unless data data.each do |line| key, value = line.split(':', 2) if key =~ /^FRU.*/ if value =~ /([\w\s]*)\(.*\)/ self[:name] = $~[1].strip.gsub(/\ /, '_').downcase end else key = key.strip.gsub(/\ /, '_').downcase.gsub(/fru_/, '') self[key] = value.strip unless value.nil? end end end
ruby
def parse(data) return unless data data.each do |line| key, value = line.split(':', 2) if key =~ /^FRU.*/ if value =~ /([\w\s]*)\(.*\)/ self[:name] = $~[1].strip.gsub(/\ /, '_').downcase end else key = key.strip.gsub(/\ /, '_').downcase.gsub(/fru_/, '') self[key] = value.strip unless value.nil? end end end
[ "def", "parse", "(", "data", ")", "return", "unless", "data", "data", ".", "each", "do", "|", "line", "|", "key", ",", "value", "=", "line", ".", "split", "(", "':'", ",", "2", ")", "if", "key", "=~", "/", "/", "if", "value", "=~", "/", "\\w", "\\s", "\\(", "\\)", "/", "self", "[", ":name", "]", "=", "$~", "[", "1", "]", ".", "strip", ".", "gsub", "(", "/", "\\ ", "/", ",", "'_'", ")", ".", "downcase", "end", "else", "key", "=", "key", ".", "strip", ".", "gsub", "(", "/", "\\ ", "/", ",", "'_'", ")", ".", "downcase", ".", "gsub", "(", "/", "/", ",", "''", ")", "self", "[", "key", "]", "=", "value", ".", "strip", "unless", "value", ".", "nil?", "end", "end", "end" ]
parse the fru information that should be an array of lines
[ "parse", "the", "fru", "information", "that", "should", "be", "an", "array", "of", "lines" ]
516dfb0d5f8aa126159a5f5c25d60ab5c98f862f
https://github.com/logicminds/rubyipmi/blob/516dfb0d5f8aa126159a5f5c25d60ab5c98f862f/lib/rubyipmi/freeipmi/commands/fru.rb#L112-L125
1,108
dmarcotte/github-markdown-preview
lib/github-markdown-preview/html_preview.rb
GithubMarkdownPreview.HtmlPreview.pipeline_filters
def pipeline_filters(options) filters = [ HTML::Pipeline::MarkdownFilter, HTML::Pipeline::SanitizationFilter, HTML::Pipeline::ImageMaxWidthFilter, HTML::Pipeline::HttpsFilter, HTML::Pipeline::EmojiFilter, GithubMarkdownPreview::Pipeline::TaskListFilter ] if HtmlPreview::SYNTAX_HIGHLIGHTS filters << HTML::Pipeline::SyntaxHighlightFilter end if options[:comment_mode] filters << HTML::Pipeline::MentionFilter else filters << HTML::Pipeline::TableOfContentsFilter end filters end
ruby
def pipeline_filters(options) filters = [ HTML::Pipeline::MarkdownFilter, HTML::Pipeline::SanitizationFilter, HTML::Pipeline::ImageMaxWidthFilter, HTML::Pipeline::HttpsFilter, HTML::Pipeline::EmojiFilter, GithubMarkdownPreview::Pipeline::TaskListFilter ] if HtmlPreview::SYNTAX_HIGHLIGHTS filters << HTML::Pipeline::SyntaxHighlightFilter end if options[:comment_mode] filters << HTML::Pipeline::MentionFilter else filters << HTML::Pipeline::TableOfContentsFilter end filters end
[ "def", "pipeline_filters", "(", "options", ")", "filters", "=", "[", "HTML", "::", "Pipeline", "::", "MarkdownFilter", ",", "HTML", "::", "Pipeline", "::", "SanitizationFilter", ",", "HTML", "::", "Pipeline", "::", "ImageMaxWidthFilter", ",", "HTML", "::", "Pipeline", "::", "HttpsFilter", ",", "HTML", "::", "Pipeline", "::", "EmojiFilter", ",", "GithubMarkdownPreview", "::", "Pipeline", "::", "TaskListFilter", "]", "if", "HtmlPreview", "::", "SYNTAX_HIGHLIGHTS", "filters", "<<", "HTML", "::", "Pipeline", "::", "SyntaxHighlightFilter", "end", "if", "options", "[", ":comment_mode", "]", "filters", "<<", "HTML", "::", "Pipeline", "::", "MentionFilter", "else", "filters", "<<", "HTML", "::", "Pipeline", "::", "TableOfContentsFilter", "end", "filters", "end" ]
Compute the filters to use in the html-pipeline based on the given options
[ "Compute", "the", "filters", "to", "use", "in", "the", "html", "-", "pipeline", "based", "on", "the", "given", "options" ]
88ea17d08a563fe7e2e867cd1e3f27ca4a2a7d00
https://github.com/dmarcotte/github-markdown-preview/blob/88ea17d08a563fe7e2e867cd1e3f27ca4a2a7d00/lib/github-markdown-preview/html_preview.rb#L68-L89
1,109
dmarcotte/github-markdown-preview
lib/github-markdown-preview/html_preview.rb
GithubMarkdownPreview.HtmlPreview.update
def update unless File.exist?(@source_file) raise FileNotFoundError.new("Source file deleted") end markdown_render = @preview_pipeline.call(IO.read(@source_file), @pipeline_context, {})[:output].to_s preview_html = wrap_preview(markdown_render) File.open(@preview_file, 'w') do |f| f.write(preview_html) end @update_callbacks.each { |callback| callback.call } end
ruby
def update unless File.exist?(@source_file) raise FileNotFoundError.new("Source file deleted") end markdown_render = @preview_pipeline.call(IO.read(@source_file), @pipeline_context, {})[:output].to_s preview_html = wrap_preview(markdown_render) File.open(@preview_file, 'w') do |f| f.write(preview_html) end @update_callbacks.each { |callback| callback.call } end
[ "def", "update", "unless", "File", ".", "exist?", "(", "@source_file", ")", "raise", "FileNotFoundError", ".", "new", "(", "\"Source file deleted\"", ")", "end", "markdown_render", "=", "@preview_pipeline", ".", "call", "(", "IO", ".", "read", "(", "@source_file", ")", ",", "@pipeline_context", ",", "{", "}", ")", "[", ":output", "]", ".", "to_s", "preview_html", "=", "wrap_preview", "(", "markdown_render", ")", "File", ".", "open", "(", "@preview_file", ",", "'w'", ")", "do", "|", "f", "|", "f", ".", "write", "(", "preview_html", ")", "end", "@update_callbacks", ".", "each", "{", "|", "callback", "|", "callback", ".", "call", "}", "end" ]
Update the preview file
[ "Update", "the", "preview", "file" ]
88ea17d08a563fe7e2e867cd1e3f27ca4a2a7d00
https://github.com/dmarcotte/github-markdown-preview/blob/88ea17d08a563fe7e2e867cd1e3f27ca4a2a7d00/lib/github-markdown-preview/html_preview.rb#L93-L106
1,110
logicminds/rubyipmi
lib/rubyipmi/freeipmi/commands/bmcdevice.rb
Rubyipmi::Freeipmi.BmcDevice.reset
def reset(type = 'cold') if ['cold', 'warm'].include?(type) key = "#{type}-reset" command(key) else logger.error("reset type: #{type} is not a valid choice, use warm or cold") if logger raise "reset type: #{type} is not a valid choice, use warm or cold" end end
ruby
def reset(type = 'cold') if ['cold', 'warm'].include?(type) key = "#{type}-reset" command(key) else logger.error("reset type: #{type} is not a valid choice, use warm or cold") if logger raise "reset type: #{type} is not a valid choice, use warm or cold" end end
[ "def", "reset", "(", "type", "=", "'cold'", ")", "if", "[", "'cold'", ",", "'warm'", "]", ".", "include?", "(", "type", ")", "key", "=", "\"#{type}-reset\"", "command", "(", "key", ")", "else", "logger", ".", "error", "(", "\"reset type: #{type} is not a valid choice, use warm or cold\"", ")", "if", "logger", "raise", "\"reset type: #{type} is not a valid choice, use warm or cold\"", "end", "end" ]
reset the bmc device, useful for debugging and troubleshooting
[ "reset", "the", "bmc", "device", "useful", "for", "debugging", "and", "troubleshooting" ]
516dfb0d5f8aa126159a5f5c25d60ab5c98f862f
https://github.com/logicminds/rubyipmi/blob/516dfb0d5f8aa126159a5f5c25d60ab5c98f862f/lib/rubyipmi/freeipmi/commands/bmcdevice.rb#L16-L24
1,111
logicminds/rubyipmi
lib/rubyipmi/ipmitool/commands/bmc.rb
Rubyipmi::Ipmitool.Bmc.reset
def reset(type = 'cold') if ['cold', 'warm'].include?(type) @options["cmdargs"] = "bmc reset #{type}" value = runcmd @options.delete_notify("cmdargs") return value else logger.error("reset type: #{type} is not a valid choice, use warm or cold") if logger raise "reset type: #{type} is not a valid choice, use warm or cold" end end
ruby
def reset(type = 'cold') if ['cold', 'warm'].include?(type) @options["cmdargs"] = "bmc reset #{type}" value = runcmd @options.delete_notify("cmdargs") return value else logger.error("reset type: #{type} is not a valid choice, use warm or cold") if logger raise "reset type: #{type} is not a valid choice, use warm or cold" end end
[ "def", "reset", "(", "type", "=", "'cold'", ")", "if", "[", "'cold'", ",", "'warm'", "]", ".", "include?", "(", "type", ")", "@options", "[", "\"cmdargs\"", "]", "=", "\"bmc reset #{type}\"", "value", "=", "runcmd", "@options", ".", "delete_notify", "(", "\"cmdargs\"", ")", "return", "value", "else", "logger", ".", "error", "(", "\"reset type: #{type} is not a valid choice, use warm or cold\"", ")", "if", "logger", "raise", "\"reset type: #{type} is not a valid choice, use warm or cold\"", "end", "end" ]
reset the bmc device, useful for troubleshooting
[ "reset", "the", "bmc", "device", "useful", "for", "troubleshooting" ]
516dfb0d5f8aa126159a5f5c25d60ab5c98f862f
https://github.com/logicminds/rubyipmi/blob/516dfb0d5f8aa126159a5f5c25d60ab5c98f862f/lib/rubyipmi/ipmitool/commands/bmc.rb#L30-L40
1,112
logicminds/rubyipmi
lib/rubyipmi/ipmitool/commands/bmc.rb
Rubyipmi::Ipmitool.Bmc.retrieve
def retrieve @options["cmdargs"] = "bmc info" status = runcmd @options.delete_notify("cmdargs") subkey = nil if !status raise @result else @result.lines.each do |line| # clean up the data from spaces item = line.split(':') key = item.first.strip value = item.last.strip # if the following condition is met we have subvalues if value.empty? subkey = key @bmcinfo[subkey] = [] elsif key == value && subkey # subvalue found @bmcinfo[subkey] << value else # Normal key/value pair with no subkeys subkey = nil @bmcinfo[key] = value end end return @bmcinfo end end
ruby
def retrieve @options["cmdargs"] = "bmc info" status = runcmd @options.delete_notify("cmdargs") subkey = nil if !status raise @result else @result.lines.each do |line| # clean up the data from spaces item = line.split(':') key = item.first.strip value = item.last.strip # if the following condition is met we have subvalues if value.empty? subkey = key @bmcinfo[subkey] = [] elsif key == value && subkey # subvalue found @bmcinfo[subkey] << value else # Normal key/value pair with no subkeys subkey = nil @bmcinfo[key] = value end end return @bmcinfo end end
[ "def", "retrieve", "@options", "[", "\"cmdargs\"", "]", "=", "\"bmc info\"", "status", "=", "runcmd", "@options", ".", "delete_notify", "(", "\"cmdargs\"", ")", "subkey", "=", "nil", "if", "!", "status", "raise", "@result", "else", "@result", ".", "lines", ".", "each", "do", "|", "line", "|", "# clean up the data from spaces", "item", "=", "line", ".", "split", "(", "':'", ")", "key", "=", "item", ".", "first", ".", "strip", "value", "=", "item", ".", "last", ".", "strip", "# if the following condition is met we have subvalues", "if", "value", ".", "empty?", "subkey", "=", "key", "@bmcinfo", "[", "subkey", "]", "=", "[", "]", "elsif", "key", "==", "value", "&&", "subkey", "# subvalue found", "@bmcinfo", "[", "subkey", "]", "<<", "value", "else", "# Normal key/value pair with no subkeys", "subkey", "=", "nil", "@bmcinfo", "[", "key", "]", "=", "value", "end", "end", "return", "@bmcinfo", "end", "end" ]
This function will get the bmcinfo and return a hash of each item in the info
[ "This", "function", "will", "get", "the", "bmcinfo", "and", "return", "a", "hash", "of", "each", "item", "in", "the", "info" ]
516dfb0d5f8aa126159a5f5c25d60ab5c98f862f
https://github.com/logicminds/rubyipmi/blob/516dfb0d5f8aa126159a5f5c25d60ab5c98f862f/lib/rubyipmi/ipmitool/commands/bmc.rb#L54-L82
1,113
logicminds/rubyipmi
lib/rubyipmi/commands/mixins/sensors_mixin.rb
Rubyipmi.SensorsMixin.fanlist
def fanlist(refreshdata = false) refresh if refreshdata list.each_with_object({}) { |(name, sensor), flist| flist[name] = sensor if name =~ /.*fan.*/ } end
ruby
def fanlist(refreshdata = false) refresh if refreshdata list.each_with_object({}) { |(name, sensor), flist| flist[name] = sensor if name =~ /.*fan.*/ } end
[ "def", "fanlist", "(", "refreshdata", "=", "false", ")", "refresh", "if", "refreshdata", "list", ".", "each_with_object", "(", "{", "}", ")", "{", "|", "(", "name", ",", "sensor", ")", ",", "flist", "|", "flist", "[", "name", "]", "=", "sensor", "if", "name", "=~", "/", "/", "}", "end" ]
returns a hash of fan sensors where the key is fan name and value is the sensor
[ "returns", "a", "hash", "of", "fan", "sensors", "where", "the", "key", "is", "fan", "name", "and", "value", "is", "the", "sensor" ]
516dfb0d5f8aa126159a5f5c25d60ab5c98f862f
https://github.com/logicminds/rubyipmi/blob/516dfb0d5f8aa126159a5f5c25d60ab5c98f862f/lib/rubyipmi/commands/mixins/sensors_mixin.rb#L21-L24
1,114
logicminds/rubyipmi
lib/rubyipmi/commands/mixins/sensors_mixin.rb
Rubyipmi.SensorsMixin.templist
def templist(refreshdata = false) refresh if refreshdata list.each_with_object({}) do |(name, sensor), tlist| tlist[name] = sensor if (sensor[:unit] =~ /.*degree.*/ || name =~ /.*temp.*/) end end
ruby
def templist(refreshdata = false) refresh if refreshdata list.each_with_object({}) do |(name, sensor), tlist| tlist[name] = sensor if (sensor[:unit] =~ /.*degree.*/ || name =~ /.*temp.*/) end end
[ "def", "templist", "(", "refreshdata", "=", "false", ")", "refresh", "if", "refreshdata", "list", ".", "each_with_object", "(", "{", "}", ")", "do", "|", "(", "name", ",", "sensor", ")", ",", "tlist", "|", "tlist", "[", "name", "]", "=", "sensor", "if", "(", "sensor", "[", ":unit", "]", "=~", "/", "/", "||", "name", "=~", "/", "/", ")", "end", "end" ]
returns a hash of sensors where each key is the name of the sensor and the value is the sensor
[ "returns", "a", "hash", "of", "sensors", "where", "each", "key", "is", "the", "name", "of", "the", "sensor", "and", "the", "value", "is", "the", "sensor" ]
516dfb0d5f8aa126159a5f5c25d60ab5c98f862f
https://github.com/logicminds/rubyipmi/blob/516dfb0d5f8aa126159a5f5c25d60ab5c98f862f/lib/rubyipmi/commands/mixins/sensors_mixin.rb#L27-L32
1,115
logicminds/rubyipmi
lib/rubyipmi/freeipmi/commands/chassisconfig.rb
Rubyipmi::Freeipmi.ChassisConfig.checkout
def checkout(section = nil) @options["checkout"] = false @options["section"] = section if section value = runcmd @options.delete_notify("checkout") @options.delete_notify("section") if section value end
ruby
def checkout(section = nil) @options["checkout"] = false @options["section"] = section if section value = runcmd @options.delete_notify("checkout") @options.delete_notify("section") if section value end
[ "def", "checkout", "(", "section", "=", "nil", ")", "@options", "[", "\"checkout\"", "]", "=", "false", "@options", "[", "\"section\"", "]", "=", "section", "if", "section", "value", "=", "runcmd", "@options", ".", "delete_notify", "(", "\"checkout\"", ")", "@options", ".", "delete_notify", "(", "\"section\"", ")", "if", "section", "value", "end" ]
This is the raw command to get the entire ipmi chassis configuration If you pass in a section you will get just the section
[ "This", "is", "the", "raw", "command", "to", "get", "the", "entire", "ipmi", "chassis", "configuration", "If", "you", "pass", "in", "a", "section", "you", "will", "get", "just", "the", "section" ]
516dfb0d5f8aa126159a5f5c25d60ab5c98f862f
https://github.com/logicminds/rubyipmi/blob/516dfb0d5f8aa126159a5f5c25d60ab5c98f862f/lib/rubyipmi/freeipmi/commands/chassisconfig.rb#L17-L24
1,116
logicminds/rubyipmi
lib/rubyipmi/ipmitool/commands/fru.rb
Rubyipmi::Ipmitool.Fru.parse
def parse(data) return unless data parsed_data = [] data.lines.each do |line| if line =~ /^FRU.*/ # this is the either the first line of of the fru or another fru if parsed_data.count != 0 # we have reached a new fru device so lets record the previous fru new_fru = FruData.new(parsed_data) parsed_data = [] @list[new_fru[:name]] = new_fru end end parsed_data << line end # process the last fru return if parsed_data.count == 0 # we have reached a new fru device so lets record the previous fru new_fru = FruData.new(parsed_data) parsed_data = [] @list[new_fru[:name]] = new_fru end
ruby
def parse(data) return unless data parsed_data = [] data.lines.each do |line| if line =~ /^FRU.*/ # this is the either the first line of of the fru or another fru if parsed_data.count != 0 # we have reached a new fru device so lets record the previous fru new_fru = FruData.new(parsed_data) parsed_data = [] @list[new_fru[:name]] = new_fru end end parsed_data << line end # process the last fru return if parsed_data.count == 0 # we have reached a new fru device so lets record the previous fru new_fru = FruData.new(parsed_data) parsed_data = [] @list[new_fru[:name]] = new_fru end
[ "def", "parse", "(", "data", ")", "return", "unless", "data", "parsed_data", "=", "[", "]", "data", ".", "lines", ".", "each", "do", "|", "line", "|", "if", "line", "=~", "/", "/", "# this is the either the first line of of the fru or another fru", "if", "parsed_data", ".", "count", "!=", "0", "# we have reached a new fru device so lets record the previous fru", "new_fru", "=", "FruData", ".", "new", "(", "parsed_data", ")", "parsed_data", "=", "[", "]", "@list", "[", "new_fru", "[", ":name", "]", "]", "=", "new_fru", "end", "end", "parsed_data", "<<", "line", "end", "# process the last fru", "return", "if", "parsed_data", ".", "count", "==", "0", "# we have reached a new fru device so lets record the previous fru", "new_fru", "=", "FruData", ".", "new", "(", "parsed_data", ")", "parsed_data", "=", "[", "]", "@list", "[", "new_fru", "[", ":name", "]", "]", "=", "new_fru", "end" ]
parse the fru information
[ "parse", "the", "fru", "information" ]
516dfb0d5f8aa126159a5f5c25d60ab5c98f862f
https://github.com/logicminds/rubyipmi/blob/516dfb0d5f8aa126159a5f5c25d60ab5c98f862f/lib/rubyipmi/ipmitool/commands/fru.rb#L61-L83
1,117
seratch/rspec-kickstarter
lib/rspec_kickstarter/generator.rb
RSpecKickstarter.Generator.write_spec
def write_spec(file_path, force_write = false, dry_run = false, rails_mode = false) class_or_module = RSpecKickstarter::RDocFactory.get_rdoc_class_or_module(file_path) if class_or_module spec_path = get_spec_path(file_path) if force_write && File.exist?(spec_path) append_to_existing_spec(class_or_module, dry_run, rails_mode, spec_path) else create_new_spec(class_or_module, dry_run, rails_mode, file_path, spec_path) end else puts "#{file_path} skipped (Class/Module not found)." end end
ruby
def write_spec(file_path, force_write = false, dry_run = false, rails_mode = false) class_or_module = RSpecKickstarter::RDocFactory.get_rdoc_class_or_module(file_path) if class_or_module spec_path = get_spec_path(file_path) if force_write && File.exist?(spec_path) append_to_existing_spec(class_or_module, dry_run, rails_mode, spec_path) else create_new_spec(class_or_module, dry_run, rails_mode, file_path, spec_path) end else puts "#{file_path} skipped (Class/Module not found)." end end
[ "def", "write_spec", "(", "file_path", ",", "force_write", "=", "false", ",", "dry_run", "=", "false", ",", "rails_mode", "=", "false", ")", "class_or_module", "=", "RSpecKickstarter", "::", "RDocFactory", ".", "get_rdoc_class_or_module", "(", "file_path", ")", "if", "class_or_module", "spec_path", "=", "get_spec_path", "(", "file_path", ")", "if", "force_write", "&&", "File", ".", "exist?", "(", "spec_path", ")", "append_to_existing_spec", "(", "class_or_module", ",", "dry_run", ",", "rails_mode", ",", "spec_path", ")", "else", "create_new_spec", "(", "class_or_module", ",", "dry_run", ",", "rails_mode", ",", "file_path", ",", "spec_path", ")", "end", "else", "puts", "\"#{file_path} skipped (Class/Module not found).\"", "end", "end" ]
Writes new spec or appends to the existing spec.
[ "Writes", "new", "spec", "or", "appends", "to", "the", "existing", "spec", "." ]
969d85fb9d702908ab0c6f2acc014b72a91c17e9
https://github.com/seratch/rspec-kickstarter/blob/969d85fb9d702908ab0c6f2acc014b72a91c17e9/lib/rspec_kickstarter/generator.rb#L27-L39
1,118
seratch/rspec-kickstarter
lib/rspec_kickstarter/generator.rb
RSpecKickstarter.Generator.create_new_spec
def create_new_spec(class_or_module, dry_run, rails_mode, file_path, spec_path) # These names are used in ERB template, don't delete. # rubocop:disable Lint/UselessAssignment methods_to_generate = class_or_module.method_list.select { |m| m.visibility == :public } c = class_or_module self_path = to_string_value_to_require(file_path) # rubocop:enable Lint/UselessAssignment erb = RSpecKickstarter::ERBFactory.new(@full_template).get_instance_for_new_spec(rails_mode, file_path) code = erb.result(binding) if dry_run puts "----- #{spec_path} -----" puts code else if File.exist?(spec_path) puts "#{spec_path} already exists." else FileUtils.mkdir_p(File.dirname(spec_path)) File.open(spec_path, 'w') { |f| f.write(code) } puts "#{spec_path} created." end end end
ruby
def create_new_spec(class_or_module, dry_run, rails_mode, file_path, spec_path) # These names are used in ERB template, don't delete. # rubocop:disable Lint/UselessAssignment methods_to_generate = class_or_module.method_list.select { |m| m.visibility == :public } c = class_or_module self_path = to_string_value_to_require(file_path) # rubocop:enable Lint/UselessAssignment erb = RSpecKickstarter::ERBFactory.new(@full_template).get_instance_for_new_spec(rails_mode, file_path) code = erb.result(binding) if dry_run puts "----- #{spec_path} -----" puts code else if File.exist?(spec_path) puts "#{spec_path} already exists." else FileUtils.mkdir_p(File.dirname(spec_path)) File.open(spec_path, 'w') { |f| f.write(code) } puts "#{spec_path} created." end end end
[ "def", "create_new_spec", "(", "class_or_module", ",", "dry_run", ",", "rails_mode", ",", "file_path", ",", "spec_path", ")", "# These names are used in ERB template, don't delete.", "# rubocop:disable Lint/UselessAssignment", "methods_to_generate", "=", "class_or_module", ".", "method_list", ".", "select", "{", "|", "m", "|", "m", ".", "visibility", "==", ":public", "}", "c", "=", "class_or_module", "self_path", "=", "to_string_value_to_require", "(", "file_path", ")", "# rubocop:enable Lint/UselessAssignment", "erb", "=", "RSpecKickstarter", "::", "ERBFactory", ".", "new", "(", "@full_template", ")", ".", "get_instance_for_new_spec", "(", "rails_mode", ",", "file_path", ")", "code", "=", "erb", ".", "result", "(", "binding", ")", "if", "dry_run", "puts", "\"----- #{spec_path} -----\"", "puts", "code", "else", "if", "File", ".", "exist?", "(", "spec_path", ")", "puts", "\"#{spec_path} already exists.\"", "else", "FileUtils", ".", "mkdir_p", "(", "File", ".", "dirname", "(", "spec_path", ")", ")", "File", ".", "open", "(", "spec_path", ",", "'w'", ")", "{", "|", "f", "|", "f", ".", "write", "(", "code", ")", "}", "puts", "\"#{spec_path} created.\"", "end", "end", "end" ]
Creates new spec. rubocop:disable Metrics/AbcSize
[ "Creates", "new", "spec", "." ]
969d85fb9d702908ab0c6f2acc014b72a91c17e9
https://github.com/seratch/rspec-kickstarter/blob/969d85fb9d702908ab0c6f2acc014b72a91c17e9/lib/rspec_kickstarter/generator.rb#L104-L127
1,119
seratch/rspec-kickstarter
lib/rspec_kickstarter/erb_factory.rb
RSpecKickstarter.ERBFactory.get_instance_for_new_spec
def get_instance_for_new_spec(rails_mode, target_path) template = get_erb_template(@custom_template, true, rails_mode, target_path) ERB.new(template, nil, '-', '_new_spec_code') end
ruby
def get_instance_for_new_spec(rails_mode, target_path) template = get_erb_template(@custom_template, true, rails_mode, target_path) ERB.new(template, nil, '-', '_new_spec_code') end
[ "def", "get_instance_for_new_spec", "(", "rails_mode", ",", "target_path", ")", "template", "=", "get_erb_template", "(", "@custom_template", ",", "true", ",", "rails_mode", ",", "target_path", ")", "ERB", ".", "new", "(", "template", ",", "nil", ",", "'-'", ",", "'_new_spec_code'", ")", "end" ]
Returns ERB instance for creating new spec
[ "Returns", "ERB", "instance", "for", "creating", "new", "spec" ]
969d85fb9d702908ab0c6f2acc014b72a91c17e9
https://github.com/seratch/rspec-kickstarter/blob/969d85fb9d702908ab0c6f2acc014b72a91c17e9/lib/rspec_kickstarter/erb_factory.rb#L20-L23
1,120
seratch/rspec-kickstarter
lib/rspec_kickstarter/erb_factory.rb
RSpecKickstarter.ERBFactory.get_instance_for_appending
def get_instance_for_appending(rails_mode, target_path) template = get_erb_template(@custom_template, false, rails_mode, target_path) ERB.new(template, nil, '-', '_additional_spec_code') end
ruby
def get_instance_for_appending(rails_mode, target_path) template = get_erb_template(@custom_template, false, rails_mode, target_path) ERB.new(template, nil, '-', '_additional_spec_code') end
[ "def", "get_instance_for_appending", "(", "rails_mode", ",", "target_path", ")", "template", "=", "get_erb_template", "(", "@custom_template", ",", "false", ",", "rails_mode", ",", "target_path", ")", "ERB", ".", "new", "(", "template", ",", "nil", ",", "'-'", ",", "'_additional_spec_code'", ")", "end" ]
Returns ERB instance for appeding lacking tests
[ "Returns", "ERB", "instance", "for", "appeding", "lacking", "tests" ]
969d85fb9d702908ab0c6f2acc014b72a91c17e9
https://github.com/seratch/rspec-kickstarter/blob/969d85fb9d702908ab0c6f2acc014b72a91c17e9/lib/rspec_kickstarter/erb_factory.rb#L28-L31
1,121
seratch/rspec-kickstarter
lib/rspec_kickstarter/erb_factory.rb
RSpecKickstarter.ERBFactory.get_erb_template
def get_erb_template(custom_template, is_full, rails_mode, target_path) if custom_template custom_template elsif rails_mode && target_path.match(/controllers/) get_rails_controller_template(is_full) elsif rails_mode && target_path.match(/helpers/) get_rails_helper_template(is_full) else get_basic_template(is_full) end end
ruby
def get_erb_template(custom_template, is_full, rails_mode, target_path) if custom_template custom_template elsif rails_mode && target_path.match(/controllers/) get_rails_controller_template(is_full) elsif rails_mode && target_path.match(/helpers/) get_rails_helper_template(is_full) else get_basic_template(is_full) end end
[ "def", "get_erb_template", "(", "custom_template", ",", "is_full", ",", "rails_mode", ",", "target_path", ")", "if", "custom_template", "custom_template", "elsif", "rails_mode", "&&", "target_path", ".", "match", "(", "/", "/", ")", "get_rails_controller_template", "(", "is_full", ")", "elsif", "rails_mode", "&&", "target_path", ".", "match", "(", "/", "/", ")", "get_rails_helper_template", "(", "is_full", ")", "else", "get_basic_template", "(", "is_full", ")", "end", "end" ]
Returns ERB template
[ "Returns", "ERB", "template" ]
969d85fb9d702908ab0c6f2acc014b72a91c17e9
https://github.com/seratch/rspec-kickstarter/blob/969d85fb9d702908ab0c6f2acc014b72a91c17e9/lib/rspec_kickstarter/erb_factory.rb#L38-L48
1,122
redbooth/departure
lib/active_record/connection_adapters/percona_adapter.rb
ActiveRecord.ConnectionHandling.percona_connection
def percona_connection(config) mysql2_connection = mysql2_connection(config) config[:username] = 'root' if config[:username].nil? connection_details = Departure::ConnectionDetails.new(config) verbose = ActiveRecord::Migration.verbose sanitizers = [ Departure::LogSanitizers::PasswordSanitizer.new(connection_details) ] percona_logger = Departure::LoggerFactory.build(sanitizers: sanitizers, verbose: verbose) cli_generator = Departure::CliGenerator.new(connection_details) runner = Departure::Runner.new( percona_logger, cli_generator, mysql2_connection ) connection_options = { mysql_adapter: mysql2_connection } ConnectionAdapters::DepartureAdapter.new( runner, logger, connection_options, config ) end
ruby
def percona_connection(config) mysql2_connection = mysql2_connection(config) config[:username] = 'root' if config[:username].nil? connection_details = Departure::ConnectionDetails.new(config) verbose = ActiveRecord::Migration.verbose sanitizers = [ Departure::LogSanitizers::PasswordSanitizer.new(connection_details) ] percona_logger = Departure::LoggerFactory.build(sanitizers: sanitizers, verbose: verbose) cli_generator = Departure::CliGenerator.new(connection_details) runner = Departure::Runner.new( percona_logger, cli_generator, mysql2_connection ) connection_options = { mysql_adapter: mysql2_connection } ConnectionAdapters::DepartureAdapter.new( runner, logger, connection_options, config ) end
[ "def", "percona_connection", "(", "config", ")", "mysql2_connection", "=", "mysql2_connection", "(", "config", ")", "config", "[", ":username", "]", "=", "'root'", "if", "config", "[", ":username", "]", ".", "nil?", "connection_details", "=", "Departure", "::", "ConnectionDetails", ".", "new", "(", "config", ")", "verbose", "=", "ActiveRecord", "::", "Migration", ".", "verbose", "sanitizers", "=", "[", "Departure", "::", "LogSanitizers", "::", "PasswordSanitizer", ".", "new", "(", "connection_details", ")", "]", "percona_logger", "=", "Departure", "::", "LoggerFactory", ".", "build", "(", "sanitizers", ":", "sanitizers", ",", "verbose", ":", "verbose", ")", "cli_generator", "=", "Departure", "::", "CliGenerator", ".", "new", "(", "connection_details", ")", "runner", "=", "Departure", "::", "Runner", ".", "new", "(", "percona_logger", ",", "cli_generator", ",", "mysql2_connection", ")", "connection_options", "=", "{", "mysql_adapter", ":", "mysql2_connection", "}", "ConnectionAdapters", "::", "DepartureAdapter", ".", "new", "(", "runner", ",", "logger", ",", "connection_options", ",", "config", ")", "end" ]
Establishes a connection to the database that's used by all Active Record objects.
[ "Establishes", "a", "connection", "to", "the", "database", "that", "s", "used", "by", "all", "Active", "Record", "objects", "." ]
6ffaf1c298a741d10c2832dfbc5a1f62a39a7695
https://github.com/redbooth/departure/blob/6ffaf1c298a741d10c2832dfbc5a1f62a39a7695/lib/active_record/connection_adapters/percona_adapter.rb#L11-L38
1,123
redbooth/departure
lib/lhm/adapter.rb
Lhm.Adapter.add_index
def add_index(columns, index_name = nil) options = { name: index_name } if index_name migration.add_index(table_name, columns, options || {}) end
ruby
def add_index(columns, index_name = nil) options = { name: index_name } if index_name migration.add_index(table_name, columns, options || {}) end
[ "def", "add_index", "(", "columns", ",", "index_name", "=", "nil", ")", "options", "=", "{", "name", ":", "index_name", "}", "if", "index_name", "migration", ".", "add_index", "(", "table_name", ",", "columns", ",", "options", "||", "{", "}", ")", "end" ]
Adds an index in the specified columns through ActiveRecord. Note you can provide a name as well @param columns [Array<String>, Array<Symbol>, String, Symbol] @param index_name [String]
[ "Adds", "an", "index", "in", "the", "specified", "columns", "through", "ActiveRecord", ".", "Note", "you", "can", "provide", "a", "name", "as", "well" ]
6ffaf1c298a741d10c2832dfbc5a1f62a39a7695
https://github.com/redbooth/departure/blob/6ffaf1c298a741d10c2832dfbc5a1f62a39a7695/lib/lhm/adapter.rb#L39-L42
1,124
redbooth/departure
lib/lhm/adapter.rb
Lhm.Adapter.remove_index
def remove_index(columns, index_name = nil) options = if index_name { name: index_name } else { column: columns } end migration.remove_index(table_name, options) end
ruby
def remove_index(columns, index_name = nil) options = if index_name { name: index_name } else { column: columns } end migration.remove_index(table_name, options) end
[ "def", "remove_index", "(", "columns", ",", "index_name", "=", "nil", ")", "options", "=", "if", "index_name", "{", "name", ":", "index_name", "}", "else", "{", "column", ":", "columns", "}", "end", "migration", ".", "remove_index", "(", "table_name", ",", "options", ")", "end" ]
Removes the index in the given columns or by its name @param columns [Array<String>, Array<Symbol>, String, Symbol] @param index_name [String]
[ "Removes", "the", "index", "in", "the", "given", "columns", "or", "by", "its", "name" ]
6ffaf1c298a741d10c2832dfbc5a1f62a39a7695
https://github.com/redbooth/departure/blob/6ffaf1c298a741d10c2832dfbc5a1f62a39a7695/lib/lhm/adapter.rb#L48-L55
1,125
redbooth/departure
lib/lhm/adapter.rb
Lhm.Adapter.change_column
def change_column(column_name, definition) attributes = column_attributes(column_name, definition) migration.change_column(*attributes) end
ruby
def change_column(column_name, definition) attributes = column_attributes(column_name, definition) migration.change_column(*attributes) end
[ "def", "change_column", "(", "column_name", ",", "definition", ")", "attributes", "=", "column_attributes", "(", "column_name", ",", "definition", ")", "migration", ".", "change_column", "(", "attributes", ")", "end" ]
Change the column to use the provided definition, through ActiveRecord @param column_name [String, Symbol] @param definition [String, Symbol]
[ "Change", "the", "column", "to", "use", "the", "provided", "definition", "through", "ActiveRecord" ]
6ffaf1c298a741d10c2832dfbc5a1f62a39a7695
https://github.com/redbooth/departure/blob/6ffaf1c298a741d10c2832dfbc5a1f62a39a7695/lib/lhm/adapter.rb#L61-L64
1,126
redbooth/departure
lib/lhm/adapter.rb
Lhm.Adapter.add_unique_index
def add_unique_index(columns, index_name = nil) options = { unique: true } options.merge!(name: index_name) if index_name # rubocop:disable Performance/RedundantMerge migration.add_index(table_name, columns, options) end
ruby
def add_unique_index(columns, index_name = nil) options = { unique: true } options.merge!(name: index_name) if index_name # rubocop:disable Performance/RedundantMerge migration.add_index(table_name, columns, options) end
[ "def", "add_unique_index", "(", "columns", ",", "index_name", "=", "nil", ")", "options", "=", "{", "unique", ":", "true", "}", "options", ".", "merge!", "(", "name", ":", "index_name", ")", "if", "index_name", "# rubocop:disable Performance/RedundantMerge", "migration", ".", "add_index", "(", "table_name", ",", "columns", ",", "options", ")", "end" ]
Adds a unique index on the given columns, with the provided name if passed @param columns [Array<String>, Array<Symbol>, String, Symbol] @param index_name [String]
[ "Adds", "a", "unique", "index", "on", "the", "given", "columns", "with", "the", "provided", "name", "if", "passed" ]
6ffaf1c298a741d10c2832dfbc5a1f62a39a7695
https://github.com/redbooth/departure/blob/6ffaf1c298a741d10c2832dfbc5a1f62a39a7695/lib/lhm/adapter.rb#L78-L83
1,127
redbooth/departure
lib/lhm/adapter.rb
Lhm.Adapter.column
def column(name, definition) @column ||= if definition.is_a?(Symbol) ColumnWithType.new(name, definition) else ColumnWithSql.new(name, definition) end end
ruby
def column(name, definition) @column ||= if definition.is_a?(Symbol) ColumnWithType.new(name, definition) else ColumnWithSql.new(name, definition) end end
[ "def", "column", "(", "name", ",", "definition", ")", "@column", "||=", "if", "definition", ".", "is_a?", "(", "Symbol", ")", "ColumnWithType", ".", "new", "(", "name", ",", "definition", ")", "else", "ColumnWithSql", ".", "new", "(", "name", ",", "definition", ")", "end", "end" ]
Returns the instance of ActiveRecord column with the given name and definition @param name [String, Symbol] @param definition [String]
[ "Returns", "the", "instance", "of", "ActiveRecord", "column", "with", "the", "given", "name", "and", "definition" ]
6ffaf1c298a741d10c2832dfbc5a1f62a39a7695
https://github.com/redbooth/departure/blob/6ffaf1c298a741d10c2832dfbc5a1f62a39a7695/lib/lhm/adapter.rb#L94-L100
1,128
redbooth/departure
lib/lhm/column_with_sql.rb
Lhm.ColumnWithSql.column
def column cast_type = ActiveRecord::Base.connection.lookup_cast_type(definition) @column ||= self.class.column_factory.new( name, default_value, cast_type, definition, null_value ) end
ruby
def column cast_type = ActiveRecord::Base.connection.lookup_cast_type(definition) @column ||= self.class.column_factory.new( name, default_value, cast_type, definition, null_value ) end
[ "def", "column", "cast_type", "=", "ActiveRecord", "::", "Base", ".", "connection", ".", "lookup_cast_type", "(", "definition", ")", "@column", "||=", "self", ".", "class", ".", "column_factory", ".", "new", "(", "name", ",", "default_value", ",", "cast_type", ",", "definition", ",", "null_value", ")", "end" ]
Returns the column instance with the provided data @return [column_factory]
[ "Returns", "the", "column", "instance", "with", "the", "provided", "data" ]
6ffaf1c298a741d10c2832dfbc5a1f62a39a7695
https://github.com/redbooth/departure/blob/6ffaf1c298a741d10c2832dfbc5a1f62a39a7695/lib/lhm/column_with_sql.rb#L54-L63
1,129
redbooth/departure
lib/lhm/column_with_sql.rb
Lhm.ColumnWithSql.default_value
def default_value match = if definition =~ /timestamp|datetime/i /default '?(.+[^'])'?/i.match(definition) else /default '?(\w+)'?/i.match(definition) end return unless match match[1].downcase != 'null' ? match[1] : nil end
ruby
def default_value match = if definition =~ /timestamp|datetime/i /default '?(.+[^'])'?/i.match(definition) else /default '?(\w+)'?/i.match(definition) end return unless match match[1].downcase != 'null' ? match[1] : nil end
[ "def", "default_value", "match", "=", "if", "definition", "=~", "/", "/i", "/", "/i", ".", "match", "(", "definition", ")", "else", "/", "\\w", "/i", ".", "match", "(", "definition", ")", "end", "return", "unless", "match", "match", "[", "1", "]", ".", "downcase", "!=", "'null'", "?", "match", "[", "1", "]", ":", "nil", "end" ]
Gets the DEFAULT value the column takes as specified in the definition, if any @return [String, NilClass]
[ "Gets", "the", "DEFAULT", "value", "the", "column", "takes", "as", "specified", "in", "the", "definition", "if", "any" ]
6ffaf1c298a741d10c2832dfbc5a1f62a39a7695
https://github.com/redbooth/departure/blob/6ffaf1c298a741d10c2832dfbc5a1f62a39a7695/lib/lhm/column_with_sql.rb#L69-L79
1,130
redbooth/departure
lib/lhm/column_with_sql.rb
Lhm.ColumnWithSql.null_value
def null_value match = /((\w*) NULL)/i.match(definition) return true unless match match[2].downcase == 'not' ? false : true end
ruby
def null_value match = /((\w*) NULL)/i.match(definition) return true unless match match[2].downcase == 'not' ? false : true end
[ "def", "null_value", "match", "=", "/", "\\w", "/i", ".", "match", "(", "definition", ")", "return", "true", "unless", "match", "match", "[", "2", "]", ".", "downcase", "==", "'not'", "?", "false", ":", "true", "end" ]
Checks whether the column accepts NULL as specified in the definition @return [Boolean]
[ "Checks", "whether", "the", "column", "accepts", "NULL", "as", "specified", "in", "the", "definition" ]
6ffaf1c298a741d10c2832dfbc5a1f62a39a7695
https://github.com/redbooth/departure/blob/6ffaf1c298a741d10c2832dfbc5a1f62a39a7695/lib/lhm/column_with_sql.rb#L84-L89
1,131
redbooth/departure
lib/departure/command.rb
Departure.Command.run_in_process
def run_in_process Open3.popen3(full_command) do |_stdin, stdout, _stderr, waith_thr| begin loop do IO.select([stdout]) data = stdout.read_nonblock(8) logger.write_no_newline(data) end rescue EOFError # rubocop:disable Lint/HandleExceptions # noop ensure @status = waith_thr.value end end end
ruby
def run_in_process Open3.popen3(full_command) do |_stdin, stdout, _stderr, waith_thr| begin loop do IO.select([stdout]) data = stdout.read_nonblock(8) logger.write_no_newline(data) end rescue EOFError # rubocop:disable Lint/HandleExceptions # noop ensure @status = waith_thr.value end end end
[ "def", "run_in_process", "Open3", ".", "popen3", "(", "full_command", ")", "do", "|", "_stdin", ",", "stdout", ",", "_stderr", ",", "waith_thr", "|", "begin", "loop", "do", "IO", ".", "select", "(", "[", "stdout", "]", ")", "data", "=", "stdout", ".", "read_nonblock", "(", "8", ")", "logger", ".", "write_no_newline", "(", "data", ")", "end", "rescue", "EOFError", "# rubocop:disable Lint/HandleExceptions", "# noop", "ensure", "@status", "=", "waith_thr", ".", "value", "end", "end", "end" ]
Runs the command in a separate process, capturing its stdout and execution status
[ "Runs", "the", "command", "in", "a", "separate", "process", "capturing", "its", "stdout", "and", "execution", "status" ]
6ffaf1c298a741d10c2832dfbc5a1f62a39a7695
https://github.com/redbooth/departure/blob/6ffaf1c298a741d10c2832dfbc5a1f62a39a7695/lib/departure/command.rb#L42-L56
1,132
redbooth/departure
lib/departure/command.rb
Departure.Command.validate_status!
def validate_status! raise SignalError.new(status) if status.signaled? # rubocop:disable Style/RaiseArgs raise CommandNotFoundError if status.exitstatus == COMMAND_NOT_FOUND raise Error, error_message unless status.success? end
ruby
def validate_status! raise SignalError.new(status) if status.signaled? # rubocop:disable Style/RaiseArgs raise CommandNotFoundError if status.exitstatus == COMMAND_NOT_FOUND raise Error, error_message unless status.success? end
[ "def", "validate_status!", "raise", "SignalError", ".", "new", "(", "status", ")", "if", "status", ".", "signaled?", "# rubocop:disable Style/RaiseArgs", "raise", "CommandNotFoundError", "if", "status", ".", "exitstatus", "==", "COMMAND_NOT_FOUND", "raise", "Error", ",", "error_message", "unless", "status", ".", "success?", "end" ]
Validates the status of the execution @raise [NoStatusError] if the spawned process' status can't be retrieved @raise [SignalError] if the spawned process received a signal @raise [CommandNotFoundError] if pt-online-schema-change can't be found
[ "Validates", "the", "status", "of", "the", "execution" ]
6ffaf1c298a741d10c2832dfbc5a1f62a39a7695
https://github.com/redbooth/departure/blob/6ffaf1c298a741d10c2832dfbc5a1f62a39a7695/lib/departure/command.rb#L71-L75
1,133
redbooth/departure
lib/departure/cli_generator.rb
Departure.CliGenerator.all_options
def all_options env_variable_options = UserOptions.new global_configuration_options = UserOptions.new(Departure.configuration.global_percona_args) options = env_variable_options.merge(global_configuration_options).merge(DEFAULT_OPTIONS) options.to_a.join(' ') end
ruby
def all_options env_variable_options = UserOptions.new global_configuration_options = UserOptions.new(Departure.configuration.global_percona_args) options = env_variable_options.merge(global_configuration_options).merge(DEFAULT_OPTIONS) options.to_a.join(' ') end
[ "def", "all_options", "env_variable_options", "=", "UserOptions", ".", "new", "global_configuration_options", "=", "UserOptions", ".", "new", "(", "Departure", ".", "configuration", ".", "global_percona_args", ")", "options", "=", "env_variable_options", ".", "merge", "(", "global_configuration_options", ")", ".", "merge", "(", "DEFAULT_OPTIONS", ")", "options", ".", "to_a", ".", "join", "(", "' '", ")", "end" ]
Returns all the arguments to execute pt-online-schema-change with @return [String]
[ "Returns", "all", "the", "arguments", "to", "execute", "pt", "-", "online", "-", "schema", "-", "change", "with" ]
6ffaf1c298a741d10c2832dfbc5a1f62a39a7695
https://github.com/redbooth/departure/blob/6ffaf1c298a741d10c2832dfbc5a1f62a39a7695/lib/departure/cli_generator.rb#L77-L82
1,134
mmriis/simpleidn
lib/simpleidn.rb
SimpleIDN.Punycode.adapt
def adapt(delta, numpoints, firsttime) delta = firsttime ? (delta / DAMP) : (delta >> 1) delta += (delta / numpoints) k = 0 while delta > (((BASE - TMIN) * TMAX) / 2) delta /= BASE - TMIN k += BASE end k + (BASE - TMIN + 1) * delta / (delta + SKEW) end
ruby
def adapt(delta, numpoints, firsttime) delta = firsttime ? (delta / DAMP) : (delta >> 1) delta += (delta / numpoints) k = 0 while delta > (((BASE - TMIN) * TMAX) / 2) delta /= BASE - TMIN k += BASE end k + (BASE - TMIN + 1) * delta / (delta + SKEW) end
[ "def", "adapt", "(", "delta", ",", "numpoints", ",", "firsttime", ")", "delta", "=", "firsttime", "?", "(", "delta", "/", "DAMP", ")", ":", "(", "delta", ">>", "1", ")", "delta", "+=", "(", "delta", "/", "numpoints", ")", "k", "=", "0", "while", "delta", ">", "(", "(", "(", "BASE", "-", "TMIN", ")", "*", "TMAX", ")", "/", "2", ")", "delta", "/=", "BASE", "-", "TMIN", "k", "+=", "BASE", "end", "k", "+", "(", "BASE", "-", "TMIN", "+", "1", ")", "*", "delta", "/", "(", "delta", "+", "SKEW", ")", "end" ]
Bias adaptation function
[ "Bias", "adaptation", "function" ]
1b3accb22c4afc88257af1d08dd0a0920f13f88f
https://github.com/mmriis/simpleidn/blob/1b3accb22c4afc88257af1d08dd0a0920f13f88f/lib/simpleidn.rb#L44-L54
1,135
mmriis/simpleidn
lib/simpleidn.rb
SimpleIDN.Punycode.encode
def encode(input) input_encoding = input.encoding input = input.encode(Encoding::UTF_8).codepoints.to_a output = [] # Initialize the state: n = INITIAL_N delta = 0 bias = INITIAL_BIAS # Handle the basic code points: output = input.select { |char| char <= ASCII_MAX } h = b = output.length # h is the number of code points that have been handled, b is the # number of basic code points output << DELIMITER if b > 0 # Main encoding loop: while h < input.length # All non-basic code points < n have been # handled already. Find the next larger one: m = MAXINT input.each do |char| m = char if char >= n && char < m end # Increase delta enough to advance the decoder's # <n,i> state to <m,0>, but guard against overflow: raise(ConversionError, "punycode_overflow (1)") if m - n > ((MAXINT - delta) / (h + 1)).floor delta += (m - n) * (h + 1) n = m input.each_with_index do |char, _| if char < n delta += 1 raise(ConversionError, "punycode_overflow(2)") if delta > MAXINT end next unless char == n # Represent delta as a generalized variable-length integer: q = delta k = BASE loop do t = k <= bias ? TMIN : k >= bias + TMAX ? TMAX : k - bias break if q < t output << encode_digit(t + (q - t) % (BASE - t)) q = ((q - t) / (BASE - t)).floor k += BASE end output << encode_digit(q) bias = adapt(delta, h + 1, h == b) delta = 0 h += 1 end delta += 1 n += 1 end output.collect {|c| c.chr(Encoding::UTF_8)}.join(EMPTY).encode(input_encoding) end
ruby
def encode(input) input_encoding = input.encoding input = input.encode(Encoding::UTF_8).codepoints.to_a output = [] # Initialize the state: n = INITIAL_N delta = 0 bias = INITIAL_BIAS # Handle the basic code points: output = input.select { |char| char <= ASCII_MAX } h = b = output.length # h is the number of code points that have been handled, b is the # number of basic code points output << DELIMITER if b > 0 # Main encoding loop: while h < input.length # All non-basic code points < n have been # handled already. Find the next larger one: m = MAXINT input.each do |char| m = char if char >= n && char < m end # Increase delta enough to advance the decoder's # <n,i> state to <m,0>, but guard against overflow: raise(ConversionError, "punycode_overflow (1)") if m - n > ((MAXINT - delta) / (h + 1)).floor delta += (m - n) * (h + 1) n = m input.each_with_index do |char, _| if char < n delta += 1 raise(ConversionError, "punycode_overflow(2)") if delta > MAXINT end next unless char == n # Represent delta as a generalized variable-length integer: q = delta k = BASE loop do t = k <= bias ? TMIN : k >= bias + TMAX ? TMAX : k - bias break if q < t output << encode_digit(t + (q - t) % (BASE - t)) q = ((q - t) / (BASE - t)).floor k += BASE end output << encode_digit(q) bias = adapt(delta, h + 1, h == b) delta = 0 h += 1 end delta += 1 n += 1 end output.collect {|c| c.chr(Encoding::UTF_8)}.join(EMPTY).encode(input_encoding) end
[ "def", "encode", "(", "input", ")", "input_encoding", "=", "input", ".", "encoding", "input", "=", "input", ".", "encode", "(", "Encoding", "::", "UTF_8", ")", ".", "codepoints", ".", "to_a", "output", "=", "[", "]", "# Initialize the state:", "n", "=", "INITIAL_N", "delta", "=", "0", "bias", "=", "INITIAL_BIAS", "# Handle the basic code points:", "output", "=", "input", ".", "select", "{", "|", "char", "|", "char", "<=", "ASCII_MAX", "}", "h", "=", "b", "=", "output", ".", "length", "# h is the number of code points that have been handled, b is the", "# number of basic code points", "output", "<<", "DELIMITER", "if", "b", ">", "0", "# Main encoding loop:", "while", "h", "<", "input", ".", "length", "# All non-basic code points < n have been", "# handled already. Find the next larger one:", "m", "=", "MAXINT", "input", ".", "each", "do", "|", "char", "|", "m", "=", "char", "if", "char", ">=", "n", "&&", "char", "<", "m", "end", "# Increase delta enough to advance the decoder's", "# <n,i> state to <m,0>, but guard against overflow:", "raise", "(", "ConversionError", ",", "\"punycode_overflow (1)\"", ")", "if", "m", "-", "n", ">", "(", "(", "MAXINT", "-", "delta", ")", "/", "(", "h", "+", "1", ")", ")", ".", "floor", "delta", "+=", "(", "m", "-", "n", ")", "*", "(", "h", "+", "1", ")", "n", "=", "m", "input", ".", "each_with_index", "do", "|", "char", ",", "_", "|", "if", "char", "<", "n", "delta", "+=", "1", "raise", "(", "ConversionError", ",", "\"punycode_overflow(2)\"", ")", "if", "delta", ">", "MAXINT", "end", "next", "unless", "char", "==", "n", "# Represent delta as a generalized variable-length integer:", "q", "=", "delta", "k", "=", "BASE", "loop", "do", "t", "=", "k", "<=", "bias", "?", "TMIN", ":", "k", ">=", "bias", "+", "TMAX", "?", "TMAX", ":", "k", "-", "bias", "break", "if", "q", "<", "t", "output", "<<", "encode_digit", "(", "t", "+", "(", "q", "-", "t", ")", "%", "(", "BASE", "-", "t", ")", ")", "q", "=", "(", "(", "q", "-", "t", ")", "/", "(", "BASE", "-", "t", ")", ")", ".", "floor", "k", "+=", "BASE", "end", "output", "<<", "encode_digit", "(", "q", ")", "bias", "=", "adapt", "(", "delta", ",", "h", "+", "1", ",", "h", "==", "b", ")", "delta", "=", "0", "h", "+=", "1", "end", "delta", "+=", "1", "n", "+=", "1", "end", "output", ".", "collect", "{", "|", "c", "|", "c", ".", "chr", "(", "Encoding", "::", "UTF_8", ")", "}", ".", "join", "(", "EMPTY", ")", ".", "encode", "(", "input_encoding", ")", "end" ]
Main encode function
[ "Main", "encode", "function" ]
1b3accb22c4afc88257af1d08dd0a0920f13f88f
https://github.com/mmriis/simpleidn/blob/1b3accb22c4afc88257af1d08dd0a0920f13f88f/lib/simpleidn.rb#L129-L196
1,136
savonrb/akami
lib/akami/wsse.rb
Akami.WSSE.to_xml
def to_xml if signature? and signature.have_document? Gyoku.xml wsse_signature.merge!(hash) elsif username_token? && timestamp? Gyoku.xml wsse_username_token.merge!(wsu_timestamp) { |key, v1, v2| v1.merge!(v2) { |key, v1, v2| v1.merge!(v2) } } elsif username_token? Gyoku.xml wsse_username_token.merge!(hash) elsif timestamp? Gyoku.xml wsu_timestamp.merge!(hash) else "" end end
ruby
def to_xml if signature? and signature.have_document? Gyoku.xml wsse_signature.merge!(hash) elsif username_token? && timestamp? Gyoku.xml wsse_username_token.merge!(wsu_timestamp) { |key, v1, v2| v1.merge!(v2) { |key, v1, v2| v1.merge!(v2) } } elsif username_token? Gyoku.xml wsse_username_token.merge!(hash) elsif timestamp? Gyoku.xml wsu_timestamp.merge!(hash) else "" end end
[ "def", "to_xml", "if", "signature?", "and", "signature", ".", "have_document?", "Gyoku", ".", "xml", "wsse_signature", ".", "merge!", "(", "hash", ")", "elsif", "username_token?", "&&", "timestamp?", "Gyoku", ".", "xml", "wsse_username_token", ".", "merge!", "(", "wsu_timestamp", ")", "{", "|", "key", ",", "v1", ",", "v2", "|", "v1", ".", "merge!", "(", "v2", ")", "{", "|", "key", ",", "v1", ",", "v2", "|", "v1", ".", "merge!", "(", "v2", ")", "}", "}", "elsif", "username_token?", "Gyoku", ".", "xml", "wsse_username_token", ".", "merge!", "(", "hash", ")", "elsif", "timestamp?", "Gyoku", ".", "xml", "wsu_timestamp", ".", "merge!", "(", "hash", ")", "else", "\"\"", "end", "end" ]
Returns the XML for a WSSE header.
[ "Returns", "the", "XML", "for", "a", "WSSE", "header", "." ]
e2f21b05eb6661bbd4faf04a481511e6a53ff510
https://github.com/savonrb/akami/blob/e2f21b05eb6661bbd4faf04a481511e6a53ff510/lib/akami/wsse.rb#L93-L109
1,137
savonrb/akami
lib/akami/wsse.rb
Akami.WSSE.digest_password
def digest_password token = nonce + timestamp + password Base64.encode64(Digest::SHA1.digest(token)).chomp! end
ruby
def digest_password token = nonce + timestamp + password Base64.encode64(Digest::SHA1.digest(token)).chomp! end
[ "def", "digest_password", "token", "=", "nonce", "+", "timestamp", "+", "password", "Base64", ".", "encode64", "(", "Digest", "::", "SHA1", ".", "digest", "(", "token", ")", ")", ".", "chomp!", "end" ]
Returns the WSSE password, encrypted for digest authentication.
[ "Returns", "the", "WSSE", "password", "encrypted", "for", "digest", "authentication", "." ]
e2f21b05eb6661bbd4faf04a481511e6a53ff510
https://github.com/savonrb/akami/blob/e2f21b05eb6661bbd4faf04a481511e6a53ff510/lib/akami/wsse.rb#L175-L178
1,138
phallguy/shog
lib/shog/formatter.rb
Shog.Formatter.call
def call( severity, time, progname, msg ) return if msg.blank? || _silence?( msg ) msg = [ _tagged( time, :timestamp ), _tagged( progname, :progname ), formatted_severity_tag( severity ), formatted_message( severity, msg ) ].compact.join(" ") super severity, time, progname, msg end
ruby
def call( severity, time, progname, msg ) return if msg.blank? || _silence?( msg ) msg = [ _tagged( time, :timestamp ), _tagged( progname, :progname ), formatted_severity_tag( severity ), formatted_message( severity, msg ) ].compact.join(" ") super severity, time, progname, msg end
[ "def", "call", "(", "severity", ",", "time", ",", "progname", ",", "msg", ")", "return", "if", "msg", ".", "blank?", "||", "_silence?", "(", "msg", ")", "msg", "=", "[", "_tagged", "(", "time", ",", ":timestamp", ")", ",", "_tagged", "(", "progname", ",", ":progname", ")", ",", "formatted_severity_tag", "(", "severity", ")", ",", "formatted_message", "(", "severity", ",", "msg", ")", "]", ".", "compact", ".", "join", "(", "\" \"", ")", "super", "severity", ",", "time", ",", "progname", ",", "msg", "end" ]
Called by the logger to prepare a message for output. @return [String]
[ "Called", "by", "the", "logger", "to", "prepare", "a", "message", "for", "output", "." ]
294637aa2103d93a82e6f1df74ea35deb0dc04eb
https://github.com/phallguy/shog/blob/294637aa2103d93a82e6f1df74ea35deb0dc04eb/lib/shog/formatter.rb#L21-L32
1,139
phallguy/shog
lib/shog/formatter.rb
Shog.Formatter.formatted_severity_tag
def formatted_severity_tag( severity ) length = configuration[:severity_tags][:_length] ||= begin configuration[:severity_tags].reduce(0){ |l,(k,_)| [k.length,l].max } end return if length == 0 padded_severity = severity.ljust length formatted = if proc = configuration[:severity_tags][severity] proc.call padded_severity else padded_severity end _tagged formatted, :severity_tags end
ruby
def formatted_severity_tag( severity ) length = configuration[:severity_tags][:_length] ||= begin configuration[:severity_tags].reduce(0){ |l,(k,_)| [k.length,l].max } end return if length == 0 padded_severity = severity.ljust length formatted = if proc = configuration[:severity_tags][severity] proc.call padded_severity else padded_severity end _tagged formatted, :severity_tags end
[ "def", "formatted_severity_tag", "(", "severity", ")", "length", "=", "configuration", "[", ":severity_tags", "]", "[", ":_length", "]", "||=", "begin", "configuration", "[", ":severity_tags", "]", ".", "reduce", "(", "0", ")", "{", "|", "l", ",", "(", "k", ",", "_", ")", "|", "[", "k", ".", "length", ",", "l", "]", ".", "max", "}", "end", "return", "if", "length", "==", "0", "padded_severity", "=", "severity", ".", "ljust", "length", "formatted", "=", "if", "proc", "=", "configuration", "[", ":severity_tags", "]", "[", "severity", "]", "proc", ".", "call", "padded_severity", "else", "padded_severity", "end", "_tagged", "formatted", ",", ":severity_tags", "end" ]
Formats the severity indicator prefixed before each line when writing to the log. @param [String] the severity of the message (ex DEBUG, WARN, etc.) @return [String] formatted version of the severity
[ "Formats", "the", "severity", "indicator", "prefixed", "before", "each", "line", "when", "writing", "to", "the", "log", "." ]
294637aa2103d93a82e6f1df74ea35deb0dc04eb
https://github.com/phallguy/shog/blob/294637aa2103d93a82e6f1df74ea35deb0dc04eb/lib/shog/formatter.rb#L55-L70
1,140
phallguy/shog
lib/shog/formatter.rb
Shog.Formatter.format_time
def format_time( time, expected = 30 ) timef = time.uncolorize.to_f case when timef > expected * 2 then time.to_s.uncolorize.red when timef > expected then time.to_s.uncolorize.yellow else time end end
ruby
def format_time( time, expected = 30 ) timef = time.uncolorize.to_f case when timef > expected * 2 then time.to_s.uncolorize.red when timef > expected then time.to_s.uncolorize.yellow else time end end
[ "def", "format_time", "(", "time", ",", "expected", "=", "30", ")", "timef", "=", "time", ".", "uncolorize", ".", "to_f", "case", "when", "timef", ">", "expected", "*", "2", "then", "time", ".", "to_s", ".", "uncolorize", ".", "red", "when", "timef", ">", "expected", "then", "time", ".", "to_s", ".", "uncolorize", ".", "yellow", "else", "time", "end", "end" ]
Formats a time value expressed in ms, adding color to highlight times outside the expected range. If `time` is more than `expected` it's highlighted yellow. If it's more than double it's highlighted red. @param [String] time in ms. @param [Float] expected maximum amount of time it should have taken. @return [String] the formatted time.
[ "Formats", "a", "time", "value", "expressed", "in", "ms", "adding", "color", "to", "highlight", "times", "outside", "the", "expected", "range", "." ]
294637aa2103d93a82e6f1df74ea35deb0dc04eb
https://github.com/phallguy/shog/blob/294637aa2103d93a82e6f1df74ea35deb0dc04eb/lib/shog/formatter.rb#L81-L88
1,141
c7/hazel
lib/hazel/cli.rb
Hazel.CLI.create_empty_directories
def create_empty_directories %w{config/initializers lib spec}.each do |dir| empty_directory File.join(@app_path, dir) end empty_directory File.join(@app_path, 'db/migrate') unless @database.empty? create_file File.join(@app_path, "lib", ".gitkeep") end
ruby
def create_empty_directories %w{config/initializers lib spec}.each do |dir| empty_directory File.join(@app_path, dir) end empty_directory File.join(@app_path, 'db/migrate') unless @database.empty? create_file File.join(@app_path, "lib", ".gitkeep") end
[ "def", "create_empty_directories", "%w{", "config/initializers", "lib", "spec", "}", ".", "each", "do", "|", "dir", "|", "empty_directory", "File", ".", "join", "(", "@app_path", ",", "dir", ")", "end", "empty_directory", "File", ".", "join", "(", "@app_path", ",", "'db/migrate'", ")", "unless", "@database", ".", "empty?", "create_file", "File", ".", "join", "(", "@app_path", ",", "\"lib\"", ",", "\".gitkeep\"", ")", "end" ]
Create empty directories
[ "Create", "empty", "directories" ]
51de275b8066371f460a499eb2f1c5a1ea7cfc9c
https://github.com/c7/hazel/blob/51de275b8066371f460a499eb2f1c5a1ea7cfc9c/lib/hazel/cli.rb#L34-L42
1,142
pboling/gem_bench
lib/gem_bench/gemfile_line_tokenizer.rb
GemBench.GemfileLineTokenizer.following_non_gem_lines
def following_non_gem_lines all_lines[(index+1)..(-1)]. reject {|x| x.strip.empty? || x.match(GemBench::TRASH_REGEX) }. map(&:strip). inject([]) do |following_lines, next_line| break following_lines if next_line.match(GEM_REGEX) following_lines << next_line end end
ruby
def following_non_gem_lines all_lines[(index+1)..(-1)]. reject {|x| x.strip.empty? || x.match(GemBench::TRASH_REGEX) }. map(&:strip). inject([]) do |following_lines, next_line| break following_lines if next_line.match(GEM_REGEX) following_lines << next_line end end
[ "def", "following_non_gem_lines", "all_lines", "[", "(", "index", "+", "1", ")", "..", "(", "-", "1", ")", "]", ".", "reject", "{", "|", "x", "|", "x", ".", "strip", ".", "empty?", "||", "x", ".", "match", "(", "GemBench", "::", "TRASH_REGEX", ")", "}", ".", "map", "(", ":strip", ")", ".", "inject", "(", "[", "]", ")", "do", "|", "following_lines", ",", "next_line", "|", "break", "following_lines", "if", "next_line", ".", "match", "(", "GEM_REGEX", ")", "following_lines", "<<", "next_line", "end", "end" ]
returns an array with each line following the current line, which is not a gem line
[ "returns", "an", "array", "with", "each", "line", "following", "the", "current", "line", "which", "is", "not", "a", "gem", "line" ]
b686b1517187a5beecd1d4ac63417b91bd2929cc
https://github.com/pboling/gem_bench/blob/b686b1517187a5beecd1d4ac63417b91bd2929cc/lib/gem_bench/gemfile_line_tokenizer.rb#L164-L172
1,143
yaauie/cliver
lib/cliver/filter.rb
Cliver.Filter.requirements
def requirements(requirements) requirements.map do |requirement| req_parts = requirement.split(/\b(?=\d)/, 2) version = req_parts.last version.replace apply(version) req_parts.join end end
ruby
def requirements(requirements) requirements.map do |requirement| req_parts = requirement.split(/\b(?=\d)/, 2) version = req_parts.last version.replace apply(version) req_parts.join end end
[ "def", "requirements", "(", "requirements", ")", "requirements", ".", "map", "do", "|", "requirement", "|", "req_parts", "=", "requirement", ".", "split", "(", "/", "\\b", "\\d", "/", ",", "2", ")", "version", "=", "req_parts", ".", "last", "version", ".", "replace", "apply", "(", "version", ")", "req_parts", ".", "join", "end", "end" ]
Apply to a list of requirements @param requirements [Array<String>] @return [Array<String>]
[ "Apply", "to", "a", "list", "of", "requirements" ]
3d72e99af19c273a3f88adcd4b96c4b65b1b6d4b
https://github.com/yaauie/cliver/blob/3d72e99af19c273a3f88adcd4b96c4b65b1b6d4b/lib/cliver/filter.rb#L12-L19
1,144
yaauie/cliver
lib/cliver/dependency.rb
Cliver.Dependency.installed_versions
def installed_versions return enum_for(:installed_versions) unless block_given? find_executables.each do |executable_path| version = detect_version(executable_path) break(2) if yield(executable_path, version) end end
ruby
def installed_versions return enum_for(:installed_versions) unless block_given? find_executables.each do |executable_path| version = detect_version(executable_path) break(2) if yield(executable_path, version) end end
[ "def", "installed_versions", "return", "enum_for", "(", ":installed_versions", ")", "unless", "block_given?", "find_executables", ".", "each", "do", "|", "executable_path", "|", "version", "=", "detect_version", "(", "executable_path", ")", "break", "(", "2", ")", "if", "yield", "(", "executable_path", ",", "version", ")", "end", "end" ]
Get all the installed versions of the api-compatible executables. If a block is given, it yields once per found executable, lazily. @yieldparam executable_path [String] @yieldparam version [String] @yieldreturn [Boolean] - true if search should stop. @return [Hash<String,String>] executable_path, version
[ "Get", "all", "the", "installed", "versions", "of", "the", "api", "-", "compatible", "executables", ".", "If", "a", "block", "is", "given", "it", "yields", "once", "per", "found", "executable", "lazily", "." ]
3d72e99af19c273a3f88adcd4b96c4b65b1b6d4b
https://github.com/yaauie/cliver/blob/3d72e99af19c273a3f88adcd4b96c4b65b1b6d4b/lib/cliver/dependency.rb#L83-L91
1,145
yaauie/cliver
lib/cliver/dependency.rb
Cliver.Dependency.detect!
def detect! installed = {} installed_versions.each do |path, version| installed[path] = version return path if ENV['CLIVER_NO_VERIFY'] return path if requirement_satisfied_by?(version) strict? end # dependency not met. raise the appropriate error. raise_not_found! if installed.empty? raise_version_mismatch!(installed) end
ruby
def detect! installed = {} installed_versions.each do |path, version| installed[path] = version return path if ENV['CLIVER_NO_VERIFY'] return path if requirement_satisfied_by?(version) strict? end # dependency not met. raise the appropriate error. raise_not_found! if installed.empty? raise_version_mismatch!(installed) end
[ "def", "detect!", "installed", "=", "{", "}", "installed_versions", ".", "each", "do", "|", "path", ",", "version", "|", "installed", "[", "path", "]", "=", "version", "return", "path", "if", "ENV", "[", "'CLIVER_NO_VERIFY'", "]", "return", "path", "if", "requirement_satisfied_by?", "(", "version", ")", "strict?", "end", "# dependency not met. raise the appropriate error.", "raise_not_found!", "if", "installed", ".", "empty?", "raise_version_mismatch!", "(", "installed", ")", "end" ]
Detects an installed version of the executable that matches the requirements. @return [String] path to an executable that meets the requirements @raise [Cliver::Dependency::NotMet] if no match found
[ "Detects", "an", "installed", "version", "of", "the", "executable", "that", "matches", "the", "requirements", "." ]
3d72e99af19c273a3f88adcd4b96c4b65b1b6d4b
https://github.com/yaauie/cliver/blob/3d72e99af19c273a3f88adcd4b96c4b65b1b6d4b/lib/cliver/dependency.rb#L106-L118
1,146
shortdudey123/yamllint
lib/yamllint/linter.rb
YamlLint.Linter.check
def check(path) raise FileNotFoundError, "#{path}: no such file" unless File.exist?(path) valid = false unless disable_extension_check unless check_filename(path) errors[path] = ['File extension must be .yaml or .yml'] return valid end end File.open(path, 'r') do |f| error_array = [] valid = check_data(f.read, error_array) errors[path] = error_array unless error_array.empty? end valid end
ruby
def check(path) raise FileNotFoundError, "#{path}: no such file" unless File.exist?(path) valid = false unless disable_extension_check unless check_filename(path) errors[path] = ['File extension must be .yaml or .yml'] return valid end end File.open(path, 'r') do |f| error_array = [] valid = check_data(f.read, error_array) errors[path] = error_array unless error_array.empty? end valid end
[ "def", "check", "(", "path", ")", "raise", "FileNotFoundError", ",", "\"#{path}: no such file\"", "unless", "File", ".", "exist?", "(", "path", ")", "valid", "=", "false", "unless", "disable_extension_check", "unless", "check_filename", "(", "path", ")", "errors", "[", "path", "]", "=", "[", "'File extension must be .yaml or .yml'", "]", "return", "valid", "end", "end", "File", ".", "open", "(", "path", ",", "'r'", ")", "do", "|", "f", "|", "error_array", "=", "[", "]", "valid", "=", "check_data", "(", "f", ".", "read", ",", "error_array", ")", "errors", "[", "path", "]", "=", "error_array", "unless", "error_array", ".", "empty?", "end", "valid", "end" ]
Check a single file
[ "Check", "a", "single", "file" ]
aa8e0538882eddcd2996f6f62fabaafda3fdb942
https://github.com/shortdudey123/yamllint/blob/aa8e0538882eddcd2996f6f62fabaafda3fdb942/lib/yamllint/linter.rb#L35-L53
1,147
shortdudey123/yamllint
lib/yamllint/linter.rb
YamlLint.Linter.check_stream
def check_stream(io_stream) yaml_data = io_stream.read error_array = [] valid = check_data(yaml_data, error_array) errors[''] = error_array unless error_array.empty? valid end
ruby
def check_stream(io_stream) yaml_data = io_stream.read error_array = [] valid = check_data(yaml_data, error_array) errors[''] = error_array unless error_array.empty? valid end
[ "def", "check_stream", "(", "io_stream", ")", "yaml_data", "=", "io_stream", ".", "read", "error_array", "=", "[", "]", "valid", "=", "check_data", "(", "yaml_data", ",", "error_array", ")", "errors", "[", "''", "]", "=", "error_array", "unless", "error_array", ".", "empty?", "valid", "end" ]
Check an IO stream
[ "Check", "an", "IO", "stream" ]
aa8e0538882eddcd2996f6f62fabaafda3fdb942
https://github.com/shortdudey123/yamllint/blob/aa8e0538882eddcd2996f6f62fabaafda3fdb942/lib/yamllint/linter.rb#L56-L64
1,148
shortdudey123/yamllint
lib/yamllint/linter.rb
YamlLint.Linter.display_errors
def display_errors errors.each do |path, errors| puts path errors.each do |err| puts " #{err}" end end end
ruby
def display_errors errors.each do |path, errors| puts path errors.each do |err| puts " #{err}" end end end
[ "def", "display_errors", "errors", ".", "each", "do", "|", "path", ",", "errors", "|", "puts", "path", "errors", ".", "each", "do", "|", "err", "|", "puts", "\" #{err}\"", "end", "end", "end" ]
Output the lint errors
[ "Output", "the", "lint", "errors" ]
aa8e0538882eddcd2996f6f62fabaafda3fdb942
https://github.com/shortdudey123/yamllint/blob/aa8e0538882eddcd2996f6f62fabaafda3fdb942/lib/yamllint/linter.rb#L77-L84
1,149
shortdudey123/yamllint
lib/yamllint/linter.rb
YamlLint.Linter.check_filename
def check_filename(filename) extension = filename.split('.').last return true if valid_extensions.include?(extension) false end
ruby
def check_filename(filename) extension = filename.split('.').last return true if valid_extensions.include?(extension) false end
[ "def", "check_filename", "(", "filename", ")", "extension", "=", "filename", ".", "split", "(", "'.'", ")", ".", "last", "return", "true", "if", "valid_extensions", ".", "include?", "(", "extension", ")", "false", "end" ]
Check file extension
[ "Check", "file", "extension" ]
aa8e0538882eddcd2996f6f62fabaafda3fdb942
https://github.com/shortdudey123/yamllint/blob/aa8e0538882eddcd2996f6f62fabaafda3fdb942/lib/yamllint/linter.rb#L89-L93
1,150
shortdudey123/yamllint
lib/yamllint/linter.rb
YamlLint.Linter.check_data
def check_data(yaml_data, errors_array) valid = check_not_empty?(yaml_data, errors_array) valid &&= check_syntax_valid?(yaml_data, errors_array) valid &&= check_overlapping_keys?(yaml_data, errors_array) valid end
ruby
def check_data(yaml_data, errors_array) valid = check_not_empty?(yaml_data, errors_array) valid &&= check_syntax_valid?(yaml_data, errors_array) valid &&= check_overlapping_keys?(yaml_data, errors_array) valid end
[ "def", "check_data", "(", "yaml_data", ",", "errors_array", ")", "valid", "=", "check_not_empty?", "(", "yaml_data", ",", "errors_array", ")", "valid", "&&=", "check_syntax_valid?", "(", "yaml_data", ",", "errors_array", ")", "valid", "&&=", "check_overlapping_keys?", "(", "yaml_data", ",", "errors_array", ")", "valid", "end" ]
Check the data in the file or stream
[ "Check", "the", "data", "in", "the", "file", "or", "stream" ]
aa8e0538882eddcd2996f6f62fabaafda3fdb942
https://github.com/shortdudey123/yamllint/blob/aa8e0538882eddcd2996f6f62fabaafda3fdb942/lib/yamllint/linter.rb#L96-L102
1,151
shortdudey123/yamllint
lib/yamllint/linter.rb
YamlLint.Linter.check_not_empty?
def check_not_empty?(yaml_data, errors_array) if yaml_data.empty? errors_array << 'The YAML should not be an empty string' false elsif yaml_data.strip.empty? errors_array << 'The YAML should not just be spaces' false else true end end
ruby
def check_not_empty?(yaml_data, errors_array) if yaml_data.empty? errors_array << 'The YAML should not be an empty string' false elsif yaml_data.strip.empty? errors_array << 'The YAML should not just be spaces' false else true end end
[ "def", "check_not_empty?", "(", "yaml_data", ",", "errors_array", ")", "if", "yaml_data", ".", "empty?", "errors_array", "<<", "'The YAML should not be an empty string'", "false", "elsif", "yaml_data", ".", "strip", ".", "empty?", "errors_array", "<<", "'The YAML should not just be spaces'", "false", "else", "true", "end", "end" ]
Check that the data is not empty
[ "Check", "that", "the", "data", "is", "not", "empty" ]
aa8e0538882eddcd2996f6f62fabaafda3fdb942
https://github.com/shortdudey123/yamllint/blob/aa8e0538882eddcd2996f6f62fabaafda3fdb942/lib/yamllint/linter.rb#L105-L115
1,152
shortdudey123/yamllint
lib/yamllint/linter.rb
YamlLint.Linter.check_syntax_valid?
def check_syntax_valid?(yaml_data, errors_array) YAML.safe_load(yaml_data) true rescue YAML::SyntaxError => e errors_array << e.message false end
ruby
def check_syntax_valid?(yaml_data, errors_array) YAML.safe_load(yaml_data) true rescue YAML::SyntaxError => e errors_array << e.message false end
[ "def", "check_syntax_valid?", "(", "yaml_data", ",", "errors_array", ")", "YAML", ".", "safe_load", "(", "yaml_data", ")", "true", "rescue", "YAML", "::", "SyntaxError", "=>", "e", "errors_array", "<<", "e", ".", "message", "false", "end" ]
Check that the data is valid YAML
[ "Check", "that", "the", "data", "is", "valid", "YAML" ]
aa8e0538882eddcd2996f6f62fabaafda3fdb942
https://github.com/shortdudey123/yamllint/blob/aa8e0538882eddcd2996f6f62fabaafda3fdb942/lib/yamllint/linter.rb#L118-L124
1,153
shortdudey123/yamllint
lib/yamllint/linter.rb
YamlLint.Linter.check_overlapping_keys?
def check_overlapping_keys?(yaml_data, errors_array) overlap_detector = KeyOverlapDetector.new data = Psych.parser.parse(yaml_data) overlap_detector.parse(data) overlap_detector.overlapping_keys.each do |key| err_meg = "The same key is defined more than once: #{key.join('.')}" errors_array << err_meg end overlap_detector.overlapping_keys.empty? end
ruby
def check_overlapping_keys?(yaml_data, errors_array) overlap_detector = KeyOverlapDetector.new data = Psych.parser.parse(yaml_data) overlap_detector.parse(data) overlap_detector.overlapping_keys.each do |key| err_meg = "The same key is defined more than once: #{key.join('.')}" errors_array << err_meg end overlap_detector.overlapping_keys.empty? end
[ "def", "check_overlapping_keys?", "(", "yaml_data", ",", "errors_array", ")", "overlap_detector", "=", "KeyOverlapDetector", ".", "new", "data", "=", "Psych", ".", "parser", ".", "parse", "(", "yaml_data", ")", "overlap_detector", ".", "parse", "(", "data", ")", "overlap_detector", ".", "overlapping_keys", ".", "each", "do", "|", "key", "|", "err_meg", "=", "\"The same key is defined more than once: #{key.join('.')}\"", "errors_array", "<<", "err_meg", "end", "overlap_detector", ".", "overlapping_keys", ".", "empty?", "end" ]
Check if there is overlapping key
[ "Check", "if", "there", "is", "overlapping", "key" ]
aa8e0538882eddcd2996f6f62fabaafda3fdb942
https://github.com/shortdudey123/yamllint/blob/aa8e0538882eddcd2996f6f62fabaafda3fdb942/lib/yamllint/linter.rb#L258-L270
1,154
flori/term-ansicolor
lib/term/ansicolor.rb
Term.ANSIColor.uncolor
def uncolor(string = nil) # :yields: if block_given? yield.to_str.gsub(COLORED_REGEXP, '') elsif string.respond_to?(:to_str) string.to_str.gsub(COLORED_REGEXP, '') elsif respond_to?(:to_str) to_str.gsub(COLORED_REGEXP, '') else '' end.extend(Term::ANSIColor) end
ruby
def uncolor(string = nil) # :yields: if block_given? yield.to_str.gsub(COLORED_REGEXP, '') elsif string.respond_to?(:to_str) string.to_str.gsub(COLORED_REGEXP, '') elsif respond_to?(:to_str) to_str.gsub(COLORED_REGEXP, '') else '' end.extend(Term::ANSIColor) end
[ "def", "uncolor", "(", "string", "=", "nil", ")", "# :yields:", "if", "block_given?", "yield", ".", "to_str", ".", "gsub", "(", "COLORED_REGEXP", ",", "''", ")", "elsif", "string", ".", "respond_to?", "(", ":to_str", ")", "string", ".", "to_str", ".", "gsub", "(", "COLORED_REGEXP", ",", "''", ")", "elsif", "respond_to?", "(", ":to_str", ")", "to_str", ".", "gsub", "(", "COLORED_REGEXP", ",", "''", ")", "else", "''", "end", ".", "extend", "(", "Term", "::", "ANSIColor", ")", "end" ]
Returns an uncolored version of the string, that is all ANSI-Attributes are stripped from the string.
[ "Returns", "an", "uncolored", "version", "of", "the", "string", "that", "is", "all", "ANSI", "-", "Attributes", "are", "stripped", "from", "the", "string", "." ]
678eaee3e72bf51a02385fa27890e88175670dc0
https://github.com/flori/term-ansicolor/blob/678eaee3e72bf51a02385fa27890e88175670dc0/lib/term/ansicolor.rb#L70-L80
1,155
flori/term-ansicolor
lib/term/ansicolor.rb
Term.ANSIColor.color
def color(name, string = nil, &block) attribute = Attribute[name] or raise ArgumentError, "unknown attribute #{name.inspect}" result = '' result << "\e[#{attribute.code}m" if Term::ANSIColor.coloring? if block_given? result << yield.to_s elsif string.respond_to?(:to_str) result << string.to_str elsif respond_to?(:to_str) result << to_str else return result #only switch on end result << "\e[0m" if Term::ANSIColor.coloring? result.extend(Term::ANSIColor) end
ruby
def color(name, string = nil, &block) attribute = Attribute[name] or raise ArgumentError, "unknown attribute #{name.inspect}" result = '' result << "\e[#{attribute.code}m" if Term::ANSIColor.coloring? if block_given? result << yield.to_s elsif string.respond_to?(:to_str) result << string.to_str elsif respond_to?(:to_str) result << to_str else return result #only switch on end result << "\e[0m" if Term::ANSIColor.coloring? result.extend(Term::ANSIColor) end
[ "def", "color", "(", "name", ",", "string", "=", "nil", ",", "&", "block", ")", "attribute", "=", "Attribute", "[", "name", "]", "or", "raise", "ArgumentError", ",", "\"unknown attribute #{name.inspect}\"", "result", "=", "''", "result", "<<", "\"\\e[#{attribute.code}m\"", "if", "Term", "::", "ANSIColor", ".", "coloring?", "if", "block_given?", "result", "<<", "yield", ".", "to_s", "elsif", "string", ".", "respond_to?", "(", ":to_str", ")", "result", "<<", "string", ".", "to_str", "elsif", "respond_to?", "(", ":to_str", ")", "result", "<<", "to_str", "else", "return", "result", "#only switch on", "end", "result", "<<", "\"\\e[0m\"", "if", "Term", "::", "ANSIColor", ".", "coloring?", "result", ".", "extend", "(", "Term", "::", "ANSIColor", ")", "end" ]
Return +string+ or the result string of the given +block+ colored with color +name+. If string isn't a string only the escape sequence to switch on the color +name+ is returned.
[ "Return", "+", "string", "+", "or", "the", "result", "string", "of", "the", "given", "+", "block", "+", "colored", "with", "color", "+", "name", "+", ".", "If", "string", "isn", "t", "a", "string", "only", "the", "escape", "sequence", "to", "switch", "on", "the", "color", "+", "name", "+", "is", "returned", "." ]
678eaee3e72bf51a02385fa27890e88175670dc0
https://github.com/flori/term-ansicolor/blob/678eaee3e72bf51a02385fa27890e88175670dc0/lib/term/ansicolor.rb#L87-L102
1,156
shortdudey123/yamllint
lib/yamllint/cli.rb
YamlLint.CLI.execute!
def execute! files_to_check = parse_options.leftovers YamlLint.logger.level = Logger::DEBUG if opts.debug no_yamls_to_check_msg = "Error: need at least one YAML file to check.\n"\ 'Try --help for help.' abort(no_yamls_to_check_msg) if files_to_check.empty? lint(files_to_check) end
ruby
def execute! files_to_check = parse_options.leftovers YamlLint.logger.level = Logger::DEBUG if opts.debug no_yamls_to_check_msg = "Error: need at least one YAML file to check.\n"\ 'Try --help for help.' abort(no_yamls_to_check_msg) if files_to_check.empty? lint(files_to_check) end
[ "def", "execute!", "files_to_check", "=", "parse_options", ".", "leftovers", "YamlLint", ".", "logger", ".", "level", "=", "Logger", "::", "DEBUG", "if", "opts", ".", "debug", "no_yamls_to_check_msg", "=", "\"Error: need at least one YAML file to check.\\n\"", "'Try --help for help.'", "abort", "(", "no_yamls_to_check_msg", ")", "if", "files_to_check", ".", "empty?", "lint", "(", "files_to_check", ")", "end" ]
setup CLI options Run the CLI command
[ "setup", "CLI", "options", "Run", "the", "CLI", "command" ]
aa8e0538882eddcd2996f6f62fabaafda3fdb942
https://github.com/shortdudey123/yamllint/blob/aa8e0538882eddcd2996f6f62fabaafda3fdb942/lib/yamllint/cli.rb#L22-L31
1,157
yaauie/cliver
lib/cliver/detector.rb
Cliver.Detector.detect_version
def detect_version(executable_path) capture = ShellCapture.new(version_command(executable_path)) unless capture.command_found raise Cliver::Dependency::NotFound.new( "Could not find an executable at given path '#{executable_path}'." + "If this path was not specified explicitly, it is probably a " + "bug in [Cliver](https://github.com/yaauie/cliver/issues)." ) end capture.stdout[version_pattern] || capture.stderr[version_pattern] end
ruby
def detect_version(executable_path) capture = ShellCapture.new(version_command(executable_path)) unless capture.command_found raise Cliver::Dependency::NotFound.new( "Could not find an executable at given path '#{executable_path}'." + "If this path was not specified explicitly, it is probably a " + "bug in [Cliver](https://github.com/yaauie/cliver/issues)." ) end capture.stdout[version_pattern] || capture.stderr[version_pattern] end
[ "def", "detect_version", "(", "executable_path", ")", "capture", "=", "ShellCapture", ".", "new", "(", "version_command", "(", "executable_path", ")", ")", "unless", "capture", ".", "command_found", "raise", "Cliver", "::", "Dependency", "::", "NotFound", ".", "new", "(", "\"Could not find an executable at given path '#{executable_path}'.\"", "+", "\"If this path was not specified explicitly, it is probably a \"", "+", "\"bug in [Cliver](https://github.com/yaauie/cliver/issues).\"", ")", "end", "capture", ".", "stdout", "[", "version_pattern", "]", "||", "capture", ".", "stderr", "[", "version_pattern", "]", "end" ]
Forgiving input, allows either argument if only one supplied. @overload initialize(*command_args) @param command_args [Array<String>] @overload initialize(version_pattern) @param version_pattern [Regexp] @overload initialize(*command_args, version_pattern) @param command_args [Array<String>] @param version_pattern [Regexp] @param executable_path [String] - the path to the executable to test @return [String] - should be contain {Gem::Version}-parsable version number.
[ "Forgiving", "input", "allows", "either", "argument", "if", "only", "one", "supplied", "." ]
3d72e99af19c273a3f88adcd4b96c4b65b1b6d4b
https://github.com/yaauie/cliver/blob/3d72e99af19c273a3f88adcd4b96c4b65b1b6d4b/lib/cliver/detector.rb#L42-L52
1,158
fusioncharts/rails-wrapper
samples/lib/fusioncharts/rails/chart.rb
Fusioncharts.Chart.render
def render config = json_escape JSON.generate(self.options) if @timeSeriesSource config.gsub! '"__DataSource__"', json_escape(@timeSeriesSource) end dataUrlFormat = self.jsonUrl? ? "json" : ( self.xmlUrl ? "xml" : nil ) template = File.read(File.expand_path("../../../templates/chart.erb", __FILE__)) renderer = ERB.new(template) return raw renderer.result(binding) end
ruby
def render config = json_escape JSON.generate(self.options) if @timeSeriesSource config.gsub! '"__DataSource__"', json_escape(@timeSeriesSource) end dataUrlFormat = self.jsonUrl? ? "json" : ( self.xmlUrl ? "xml" : nil ) template = File.read(File.expand_path("../../../templates/chart.erb", __FILE__)) renderer = ERB.new(template) return raw renderer.result(binding) end
[ "def", "render", "config", "=", "json_escape", "JSON", ".", "generate", "(", "self", ".", "options", ")", "if", "@timeSeriesSource", "config", ".", "gsub!", "'\"__DataSource__\"'", ",", "json_escape", "(", "@timeSeriesSource", ")", "end", "dataUrlFormat", "=", "self", ".", "jsonUrl?", "?", "\"json\"", ":", "(", "self", ".", "xmlUrl", "?", "\"xml\"", ":", "nil", ")", "template", "=", "File", ".", "read", "(", "File", ".", "expand_path", "(", "\"../../../templates/chart.erb\"", ",", "__FILE__", ")", ")", "renderer", "=", "ERB", ".", "new", "(", "template", ")", "return", "raw", "renderer", ".", "result", "(", "binding", ")", "end" ]
Render the chart
[ "Render", "the", "chart" ]
277c20fe97b29f94c64e31345c36eb4e0715c93f
https://github.com/fusioncharts/rails-wrapper/blob/277c20fe97b29f94c64e31345c36eb4e0715c93f/samples/lib/fusioncharts/rails/chart.rb#L102-L111
1,159
fusioncharts/rails-wrapper
samples/lib/fusioncharts/rails/chart.rb
Fusioncharts.Chart.parse_options
def parse_options newOptions = nil @options.each do |key, value| if key.downcase.to_s.eql? "timeseries" @timeSeriesData = value.GetDataStore() @timeSeriesSource = value.GetDataSource() newOptions = {} newOptions['dataSource'] = "__DataSource__" @options.delete(key) end end if newOptions @options.merge!(newOptions) end keys = @options.keys keys.each{ |k| instance_variable_set "@#{k}".to_sym, @options[k] if self.respond_to? k } #parse_datasource_json end
ruby
def parse_options newOptions = nil @options.each do |key, value| if key.downcase.to_s.eql? "timeseries" @timeSeriesData = value.GetDataStore() @timeSeriesSource = value.GetDataSource() newOptions = {} newOptions['dataSource'] = "__DataSource__" @options.delete(key) end end if newOptions @options.merge!(newOptions) end keys = @options.keys keys.each{ |k| instance_variable_set "@#{k}".to_sym, @options[k] if self.respond_to? k } #parse_datasource_json end
[ "def", "parse_options", "newOptions", "=", "nil", "@options", ".", "each", "do", "|", "key", ",", "value", "|", "if", "key", ".", "downcase", ".", "to_s", ".", "eql?", "\"timeseries\"", "@timeSeriesData", "=", "value", ".", "GetDataStore", "(", ")", "@timeSeriesSource", "=", "value", ".", "GetDataSource", "(", ")", "newOptions", "=", "{", "}", "newOptions", "[", "'dataSource'", "]", "=", "\"__DataSource__\"", "@options", ".", "delete", "(", "key", ")", "end", "end", "if", "newOptions", "@options", ".", "merge!", "(", "newOptions", ")", "end", "keys", "=", "@options", ".", "keys", "keys", ".", "each", "{", "|", "k", "|", "instance_variable_set", "\"@#{k}\"", ".", "to_sym", ",", "@options", "[", "k", "]", "if", "self", ".", "respond_to?", "k", "}", "#parse_datasource_json", "end" ]
Helper method that converts the constructor params into instance variables
[ "Helper", "method", "that", "converts", "the", "constructor", "params", "into", "instance", "variables" ]
277c20fe97b29f94c64e31345c36eb4e0715c93f
https://github.com/fusioncharts/rails-wrapper/blob/277c20fe97b29f94c64e31345c36eb4e0715c93f/samples/lib/fusioncharts/rails/chart.rb#L133-L151
1,160
dougfales/gpx
lib/gpx/segment.rb
GPX.Segment.smooth_location_by_average
def smooth_location_by_average(opts = {}) seconds_either_side = opts[:averaging_window] || 20 # calculate the first and last points to which the smoothing should be applied earliest = (find_point_by_time_or_offset(opts[:start]) || @earliest_point).time latest = (find_point_by_time_or_offset(opts[:end]) || @latest_point).time tmp_points = [] @points.each do |point| if point.time > latest || point.time < earliest tmp_points.push point # add the point unaltered next end lat_av = 0.to_f lon_av = 0.to_f alt_av = 0.to_f n = 0 # k ranges from the time of the current point +/- 20s (-1 * seconds_either_side..seconds_either_side).each do |k| # find the point nearest to the time offset indicated by k contributing_point = closest_point(point.time + k) # sum up the contributions to the average lat_av += contributing_point.lat lon_av += contributing_point.lon alt_av += contributing_point.elevation n += 1 end # calculate the averages tmp_point = point.clone tmp_point.lon = (lon_av / n).round(7) tmp_point.elevation = (alt_av / n).round(2) tmp_point.lat = (lat_av / n).round(7) tmp_points.push tmp_point end @points.clear reset_meta_data # now commit the averages back and recalculate the distances tmp_points.each do |point| append_point(point) end end
ruby
def smooth_location_by_average(opts = {}) seconds_either_side = opts[:averaging_window] || 20 # calculate the first and last points to which the smoothing should be applied earliest = (find_point_by_time_or_offset(opts[:start]) || @earliest_point).time latest = (find_point_by_time_or_offset(opts[:end]) || @latest_point).time tmp_points = [] @points.each do |point| if point.time > latest || point.time < earliest tmp_points.push point # add the point unaltered next end lat_av = 0.to_f lon_av = 0.to_f alt_av = 0.to_f n = 0 # k ranges from the time of the current point +/- 20s (-1 * seconds_either_side..seconds_either_side).each do |k| # find the point nearest to the time offset indicated by k contributing_point = closest_point(point.time + k) # sum up the contributions to the average lat_av += contributing_point.lat lon_av += contributing_point.lon alt_av += contributing_point.elevation n += 1 end # calculate the averages tmp_point = point.clone tmp_point.lon = (lon_av / n).round(7) tmp_point.elevation = (alt_av / n).round(2) tmp_point.lat = (lat_av / n).round(7) tmp_points.push tmp_point end @points.clear reset_meta_data # now commit the averages back and recalculate the distances tmp_points.each do |point| append_point(point) end end
[ "def", "smooth_location_by_average", "(", "opts", "=", "{", "}", ")", "seconds_either_side", "=", "opts", "[", ":averaging_window", "]", "||", "20", "# calculate the first and last points to which the smoothing should be applied", "earliest", "=", "(", "find_point_by_time_or_offset", "(", "opts", "[", ":start", "]", ")", "||", "@earliest_point", ")", ".", "time", "latest", "=", "(", "find_point_by_time_or_offset", "(", "opts", "[", ":end", "]", ")", "||", "@latest_point", ")", ".", "time", "tmp_points", "=", "[", "]", "@points", ".", "each", "do", "|", "point", "|", "if", "point", ".", "time", ">", "latest", "||", "point", ".", "time", "<", "earliest", "tmp_points", ".", "push", "point", "# add the point unaltered", "next", "end", "lat_av", "=", "0", ".", "to_f", "lon_av", "=", "0", ".", "to_f", "alt_av", "=", "0", ".", "to_f", "n", "=", "0", "# k ranges from the time of the current point +/- 20s", "(", "-", "1", "*", "seconds_either_side", "..", "seconds_either_side", ")", ".", "each", "do", "|", "k", "|", "# find the point nearest to the time offset indicated by k", "contributing_point", "=", "closest_point", "(", "point", ".", "time", "+", "k", ")", "# sum up the contributions to the average", "lat_av", "+=", "contributing_point", ".", "lat", "lon_av", "+=", "contributing_point", ".", "lon", "alt_av", "+=", "contributing_point", ".", "elevation", "n", "+=", "1", "end", "# calculate the averages", "tmp_point", "=", "point", ".", "clone", "tmp_point", ".", "lon", "=", "(", "lon_av", "/", "n", ")", ".", "round", "(", "7", ")", "tmp_point", ".", "elevation", "=", "(", "alt_av", "/", "n", ")", ".", "round", "(", "2", ")", "tmp_point", ".", "lat", "=", "(", "lat_av", "/", "n", ")", ".", "round", "(", "7", ")", "tmp_points", ".", "push", "tmp_point", "end", "@points", ".", "clear", "reset_meta_data", "# now commit the averages back and recalculate the distances", "tmp_points", ".", "each", "do", "|", "point", "|", "append_point", "(", "point", ")", "end", "end" ]
smooths the location data in the segment (by recalculating the location as an average of 20 neighbouring points. Useful for removing noise from GPS traces.
[ "smooths", "the", "location", "data", "in", "the", "segment", "(", "by", "recalculating", "the", "location", "as", "an", "average", "of", "20", "neighbouring", "points", ".", "Useful", "for", "removing", "noise", "from", "GPS", "traces", "." ]
632fcda922488ca410aabce451871755ef2b544c
https://github.com/dougfales/gpx/blob/632fcda922488ca410aabce451871755ef2b544c/lib/gpx/segment.rb#L132-L173
1,161
dougfales/gpx
lib/gpx/gpx_file.rb
GPX.GPXFile.crop
def crop(area) reset_meta_data keep_tracks = [] tracks.each do |trk| trk.crop(area) unless trk.empty? update_meta_data(trk) keep_tracks << trk end end @tracks = keep_tracks routes.each { |rte| rte.crop(area) } waypoints.each { |wpt| wpt.crop(area) } end
ruby
def crop(area) reset_meta_data keep_tracks = [] tracks.each do |trk| trk.crop(area) unless trk.empty? update_meta_data(trk) keep_tracks << trk end end @tracks = keep_tracks routes.each { |rte| rte.crop(area) } waypoints.each { |wpt| wpt.crop(area) } end
[ "def", "crop", "(", "area", ")", "reset_meta_data", "keep_tracks", "=", "[", "]", "tracks", ".", "each", "do", "|", "trk", "|", "trk", ".", "crop", "(", "area", ")", "unless", "trk", ".", "empty?", "update_meta_data", "(", "trk", ")", "keep_tracks", "<<", "trk", "end", "end", "@tracks", "=", "keep_tracks", "routes", ".", "each", "{", "|", "rte", "|", "rte", ".", "crop", "(", "area", ")", "}", "waypoints", ".", "each", "{", "|", "wpt", "|", "wpt", ".", "crop", "(", "area", ")", "}", "end" ]
Crops any points falling within a rectangular area. Identical to the delete_area method in every respect except that the points outside of the given area are deleted. Note that this method automatically causes the meta data to be updated after deletion.
[ "Crops", "any", "points", "falling", "within", "a", "rectangular", "area", ".", "Identical", "to", "the", "delete_area", "method", "in", "every", "respect", "except", "that", "the", "points", "outside", "of", "the", "given", "area", "are", "deleted", ".", "Note", "that", "this", "method", "automatically", "causes", "the", "meta", "data", "to", "be", "updated", "after", "deletion", "." ]
632fcda922488ca410aabce451871755ef2b544c
https://github.com/dougfales/gpx/blob/632fcda922488ca410aabce451871755ef2b544c/lib/gpx/gpx_file.rb#L145-L158
1,162
dougfales/gpx
lib/gpx/gpx_file.rb
GPX.GPXFile.calculate_duration
def calculate_duration @duration = 0 if @tracks.nil? || @tracks.size.zero? || @tracks[0].segments.nil? || @tracks[0].segments.size.zero? return @duration end @duration = (@tracks[-1].segments[-1].points[-1].time - @tracks.first.segments.first.points.first.time) rescue StandardError @duration = 0 end
ruby
def calculate_duration @duration = 0 if @tracks.nil? || @tracks.size.zero? || @tracks[0].segments.nil? || @tracks[0].segments.size.zero? return @duration end @duration = (@tracks[-1].segments[-1].points[-1].time - @tracks.first.segments.first.points.first.time) rescue StandardError @duration = 0 end
[ "def", "calculate_duration", "@duration", "=", "0", "if", "@tracks", ".", "nil?", "||", "@tracks", ".", "size", ".", "zero?", "||", "@tracks", "[", "0", "]", ".", "segments", ".", "nil?", "||", "@tracks", "[", "0", "]", ".", "segments", ".", "size", ".", "zero?", "return", "@duration", "end", "@duration", "=", "(", "@tracks", "[", "-", "1", "]", ".", "segments", "[", "-", "1", "]", ".", "points", "[", "-", "1", "]", ".", "time", "-", "@tracks", ".", "first", ".", "segments", ".", "first", ".", "points", ".", "first", ".", "time", ")", "rescue", "StandardError", "@duration", "=", "0", "end" ]
Calculates and sets the duration attribute by subtracting the time on the very first point from the time on the very last point.
[ "Calculates", "and", "sets", "the", "duration", "attribute", "by", "subtracting", "the", "time", "on", "the", "very", "first", "point", "from", "the", "time", "on", "the", "very", "last", "point", "." ]
632fcda922488ca410aabce451871755ef2b544c
https://github.com/dougfales/gpx/blob/632fcda922488ca410aabce451871755ef2b544c/lib/gpx/gpx_file.rb#L342-L350
1,163
dougfales/gpx
lib/gpx/bounds.rb
GPX.Bounds.contains?
def contains?(pt) ((pt.lat >= min_lat) && (pt.lat <= max_lat) && (pt.lon >= min_lon) && (pt.lon <= max_lon)) end
ruby
def contains?(pt) ((pt.lat >= min_lat) && (pt.lat <= max_lat) && (pt.lon >= min_lon) && (pt.lon <= max_lon)) end
[ "def", "contains?", "(", "pt", ")", "(", "(", "pt", ".", "lat", ">=", "min_lat", ")", "&&", "(", "pt", ".", "lat", "<=", "max_lat", ")", "&&", "(", "pt", ".", "lon", ">=", "min_lon", ")", "&&", "(", "pt", ".", "lon", "<=", "max_lon", ")", ")", "end" ]
Returns true if the pt is within these bounds.
[ "Returns", "true", "if", "the", "pt", "is", "within", "these", "bounds", "." ]
632fcda922488ca410aabce451871755ef2b544c
https://github.com/dougfales/gpx/blob/632fcda922488ca410aabce451871755ef2b544c/lib/gpx/bounds.rb#L27-L29
1,164
dougfales/gpx
lib/gpx/track.rb
GPX.Track.contains_time?
def contains_time?(time) segments.each do |seg| return true if seg.contains_time?(time) end false end
ruby
def contains_time?(time) segments.each do |seg| return true if seg.contains_time?(time) end false end
[ "def", "contains_time?", "(", "time", ")", "segments", ".", "each", "do", "|", "seg", "|", "return", "true", "if", "seg", ".", "contains_time?", "(", "time", ")", "end", "false", "end" ]
Returns true if the given time occurs within any of the segments of this track.
[ "Returns", "true", "if", "the", "given", "time", "occurs", "within", "any", "of", "the", "segments", "of", "this", "track", "." ]
632fcda922488ca410aabce451871755ef2b544c
https://github.com/dougfales/gpx/blob/632fcda922488ca410aabce451871755ef2b544c/lib/gpx/track.rb#L52-L57
1,165
dougfales/gpx
lib/gpx/track.rb
GPX.Track.delete_area
def delete_area(area) reset_meta_data segments.each do |seg| seg.delete_area(area) update_meta_data(seg) unless seg.empty? end segments.delete_if(&:empty?) end
ruby
def delete_area(area) reset_meta_data segments.each do |seg| seg.delete_area(area) update_meta_data(seg) unless seg.empty? end segments.delete_if(&:empty?) end
[ "def", "delete_area", "(", "area", ")", "reset_meta_data", "segments", ".", "each", "do", "|", "seg", "|", "seg", ".", "delete_area", "(", "area", ")", "update_meta_data", "(", "seg", ")", "unless", "seg", ".", "empty?", "end", "segments", ".", "delete_if", "(", ":empty?", ")", "end" ]
Deletes all points within a given area and updates the meta data.
[ "Deletes", "all", "points", "within", "a", "given", "area", "and", "updates", "the", "meta", "data", "." ]
632fcda922488ca410aabce451871755ef2b544c
https://github.com/dougfales/gpx/blob/632fcda922488ca410aabce451871755ef2b544c/lib/gpx/track.rb#L79-L86
1,166
elucid/resque-delayed
lib/resque-delayed/worker.rb
Resque::Delayed.Worker.work
def work(interval = 5.0) interval = Float(interval) $0 = "resque-delayed: harvesting" startup loop do break if shutdown? # harvest delayed jobs while they are available while job = Resque::Delayed.next do log "got: #{job.inspect}" queue, klass, *args = job Resque::Job.create(queue, klass, *args) end break if interval.zero? log! "Sleeping for #{interval} seconds" sleep interval end end
ruby
def work(interval = 5.0) interval = Float(interval) $0 = "resque-delayed: harvesting" startup loop do break if shutdown? # harvest delayed jobs while they are available while job = Resque::Delayed.next do log "got: #{job.inspect}" queue, klass, *args = job Resque::Job.create(queue, klass, *args) end break if interval.zero? log! "Sleeping for #{interval} seconds" sleep interval end end
[ "def", "work", "(", "interval", "=", "5.0", ")", "interval", "=", "Float", "(", "interval", ")", "$0", "=", "\"resque-delayed: harvesting\"", "startup", "loop", "do", "break", "if", "shutdown?", "# harvest delayed jobs while they are available", "while", "job", "=", "Resque", "::", "Delayed", ".", "next", "do", "log", "\"got: #{job.inspect}\"", "queue", ",", "klass", ",", "*", "args", "=", "job", "Resque", "::", "Job", ".", "create", "(", "queue", ",", "klass", ",", "args", ")", "end", "break", "if", "interval", ".", "zero?", "log!", "\"Sleeping for #{interval} seconds\"", "sleep", "interval", "end", "end" ]
Can be passed a float representing the polling frequency. The default is 5 seconds, but for a semi-active site you may want to use a smaller value.
[ "Can", "be", "passed", "a", "float", "representing", "the", "polling", "frequency", ".", "The", "default", "is", "5", "seconds", "but", "for", "a", "semi", "-", "active", "site", "you", "may", "want", "to", "use", "a", "smaller", "value", "." ]
3b93fb8252cdc443250ba0c640f458634c9515d6
https://github.com/elucid/resque-delayed/blob/3b93fb8252cdc443250ba0c640f458634c9515d6/lib/resque-delayed/worker.rb#L19-L38
1,167
elucid/resque-delayed
lib/resque-delayed/worker.rb
Resque::Delayed.Worker.log
def log(message) if verbose puts "*** #{message}" elsif very_verbose time = Time.now.strftime('%H:%M:%S %Y-%m-%d') puts "** [#{time}] #$$: #{message}" end end
ruby
def log(message) if verbose puts "*** #{message}" elsif very_verbose time = Time.now.strftime('%H:%M:%S %Y-%m-%d') puts "** [#{time}] #$$: #{message}" end end
[ "def", "log", "(", "message", ")", "if", "verbose", "puts", "\"*** #{message}\"", "elsif", "very_verbose", "time", "=", "Time", ".", "now", ".", "strftime", "(", "'%H:%M:%S %Y-%m-%d'", ")", "puts", "\"** [#{time}] #$$: #{message}\"", "end", "end" ]
Log a message to STDOUT if we are verbose or very_verbose.
[ "Log", "a", "message", "to", "STDOUT", "if", "we", "are", "verbose", "or", "very_verbose", "." ]
3b93fb8252cdc443250ba0c640f458634c9515d6
https://github.com/elucid/resque-delayed/blob/3b93fb8252cdc443250ba0c640f458634c9515d6/lib/resque-delayed/worker.rb#L106-L113
1,168
myles/jekyll-typogrify
lib/jekyll/typogrify.rb
Jekyll.TypogrifyFilter.custom_caps
def custom_caps(text) # $1 and $2 are excluded HTML tags, $3 is the part before the caps and $4 is the caps match text.gsub(%r{ (<[^/][^>]*?>)| # Ignore any opening tag, so we don't mess up attribute values (\s|&nbsp;|^|'|"|>|) # Make sure our capture is preceded by whitespace or quotes ([A-Z\d](?:(\.|'|-|&|&amp;|&\#38;)?[A-Z\d][\.']?){1,}) # Capture capital words, with optional dots, numbers or ampersands in between (?!\w) # ...which must not be followed by a word character. }x) do |str| tag, before, caps = $1, $2, $3 # Do nothing with the contents if ignored tags, the inside of an opening HTML element # so we don't mess up attribute values, or if our capture is only digits. if tag || caps =~ /^\d+\.?$/ str elsif $3 =~ /^[\d\.]+$/ before + caps else before + '<span class="caps">' + caps + '</span>' end end end
ruby
def custom_caps(text) # $1 and $2 are excluded HTML tags, $3 is the part before the caps and $4 is the caps match text.gsub(%r{ (<[^/][^>]*?>)| # Ignore any opening tag, so we don't mess up attribute values (\s|&nbsp;|^|'|"|>|) # Make sure our capture is preceded by whitespace or quotes ([A-Z\d](?:(\.|'|-|&|&amp;|&\#38;)?[A-Z\d][\.']?){1,}) # Capture capital words, with optional dots, numbers or ampersands in between (?!\w) # ...which must not be followed by a word character. }x) do |str| tag, before, caps = $1, $2, $3 # Do nothing with the contents if ignored tags, the inside of an opening HTML element # so we don't mess up attribute values, or if our capture is only digits. if tag || caps =~ /^\d+\.?$/ str elsif $3 =~ /^[\d\.]+$/ before + caps else before + '<span class="caps">' + caps + '</span>' end end end
[ "def", "custom_caps", "(", "text", ")", "# $1 and $2 are excluded HTML tags, $3 is the part before the caps and $4 is the caps match", "text", ".", "gsub", "(", "%r{", "\\s", "\\d", "\\.", "\\#", "\\d", "\\.", "\\w", "}x", ")", "do", "|", "str", "|", "tag", ",", "before", ",", "caps", "=", "$1", ",", "$2", ",", "$3", "# Do nothing with the contents if ignored tags, the inside of an opening HTML element", "# so we don't mess up attribute values, or if our capture is only digits.", "if", "tag", "||", "caps", "=~", "/", "\\d", "\\.", "/", "str", "elsif", "$3", "=~", "/", "\\d", "\\.", "/", "before", "+", "caps", "else", "before", "+", "'<span class=\"caps\">'", "+", "caps", "+", "'</span>'", "end", "end", "end" ]
custom modules to jekyll-typogrify surrounds two or more consecutive capital letters, perhaps with interspersed digits and periods in a span with a styled class. @param [String] text input text @return [String] input text with caps wrapped
[ "custom", "modules", "to", "jekyll", "-", "typogrify", "surrounds", "two", "or", "more", "consecutive", "capital", "letters", "perhaps", "with", "interspersed", "digits", "and", "periods", "in", "a", "span", "with", "a", "styled", "class", "." ]
edfebe97d029682d71d19741c2bf52e741e8b252
https://github.com/myles/jekyll-typogrify/blob/edfebe97d029682d71d19741c2bf52e741e8b252/lib/jekyll/typogrify.rb#L124-L144
1,169
take-five/activerecord-hierarchical_query
lib/active_record/hierarchical_query.rb
ActiveRecord.HierarchicalQuery.join_recursive
def join_recursive(join_options = {}, &block) raise ArgumentError, 'block expected' unless block_given? query = Query.new(klass) if block.arity == 0 query.instance_eval(&block) else block.call(query) end query.join_to(self, join_options) end
ruby
def join_recursive(join_options = {}, &block) raise ArgumentError, 'block expected' unless block_given? query = Query.new(klass) if block.arity == 0 query.instance_eval(&block) else block.call(query) end query.join_to(self, join_options) end
[ "def", "join_recursive", "(", "join_options", "=", "{", "}", ",", "&", "block", ")", "raise", "ArgumentError", ",", "'block expected'", "unless", "block_given?", "query", "=", "Query", ".", "new", "(", "klass", ")", "if", "block", ".", "arity", "==", "0", "query", ".", "instance_eval", "(", "block", ")", "else", "block", ".", "call", "(", "query", ")", "end", "query", ".", "join_to", "(", "self", ",", "join_options", ")", "end" ]
Performs a join to recursive subquery which should be built within a block. @example MyModel.join_recursive do |query| query.start_with(parent_id: nil) .connect_by(id: :parent_id) .where('depth < ?', 5) .order_siblings(name: :desc) end @param [Hash] join_options @option join_options [String, Symbol] :as aliased name of joined table (`%table_name%__recursive` by default) @yield [query] @yieldparam [ActiveRecord::HierarchicalQuery::Query] query Hierarchical query @raise [ArgumentError] if block is omitted
[ "Performs", "a", "join", "to", "recursive", "subquery", "which", "should", "be", "built", "within", "a", "block", "." ]
8adb826d35e39640641397bccd21468b3443d026
https://github.com/take-five/activerecord-hierarchical_query/blob/8adb826d35e39640641397bccd21468b3443d026/lib/active_record/hierarchical_query.rb#L31-L43
1,170
harley/auditable
lib/auditable/auditing.rb
Auditable.Auditing.audit_tag_with
def audit_tag_with(tag) if audit = last_audit audit.update_attribute(:tag, tag) # Force the trigger of a reload if audited_version is used. Happens automatically otherwise audits.reload if self.class.audited_version else self.audit_tag = tag snap! end end
ruby
def audit_tag_with(tag) if audit = last_audit audit.update_attribute(:tag, tag) # Force the trigger of a reload if audited_version is used. Happens automatically otherwise audits.reload if self.class.audited_version else self.audit_tag = tag snap! end end
[ "def", "audit_tag_with", "(", "tag", ")", "if", "audit", "=", "last_audit", "audit", ".", "update_attribute", "(", ":tag", ",", "tag", ")", "# Force the trigger of a reload if audited_version is used. Happens automatically otherwise", "audits", ".", "reload", "if", "self", ".", "class", ".", "audited_version", "else", "self", ".", "audit_tag", "=", "tag", "snap!", "end", "end" ]
Mark the latest record with a tag in order to easily find and perform diff against later If there are no audits for this record, create a new audit with this tag
[ "Mark", "the", "latest", "record", "with", "a", "tag", "in", "order", "to", "easily", "find", "and", "perform", "diff", "against", "later", "If", "there", "are", "no", "audits", "for", "this", "record", "create", "a", "new", "audit", "with", "this", "tag" ]
c309fa345864719718045e9b4f13a0e87a8597a2
https://github.com/harley/auditable/blob/c309fa345864719718045e9b4f13a0e87a8597a2/lib/auditable/auditing.rb#L196-L206
1,171
harley/auditable
lib/auditable/auditing.rb
Auditable.Auditing.snap
def snap serialize_attribute = lambda do |attribute| # If a proc, do nothing, cannot be serialized # XXX: raise warning on passing in a proc? if attribute.is_a? Proc # noop # Is an ActiveRecord, serialize as hash instead of serializing the object elsif attribute.class.ancestors.include?(ActiveRecord::Base) attribute.serializable_hash # If an array, such as from an association, serialize the elements in the array elsif attribute.is_a?(Array) || attribute.is_a?(ActiveRecord::Associations::CollectionProxy) attribute.map { |element| serialize_attribute.call(element) } # otherwise, return val else attribute end end {}.tap do |s| self.class.audited_attributes.each do |attr| val = self.send attr s[attr.to_s] = serialize_attribute.call(val) end end end
ruby
def snap serialize_attribute = lambda do |attribute| # If a proc, do nothing, cannot be serialized # XXX: raise warning on passing in a proc? if attribute.is_a? Proc # noop # Is an ActiveRecord, serialize as hash instead of serializing the object elsif attribute.class.ancestors.include?(ActiveRecord::Base) attribute.serializable_hash # If an array, such as from an association, serialize the elements in the array elsif attribute.is_a?(Array) || attribute.is_a?(ActiveRecord::Associations::CollectionProxy) attribute.map { |element| serialize_attribute.call(element) } # otherwise, return val else attribute end end {}.tap do |s| self.class.audited_attributes.each do |attr| val = self.send attr s[attr.to_s] = serialize_attribute.call(val) end end end
[ "def", "snap", "serialize_attribute", "=", "lambda", "do", "|", "attribute", "|", "# If a proc, do nothing, cannot be serialized", "# XXX: raise warning on passing in a proc?", "if", "attribute", ".", "is_a?", "Proc", "# noop", "# Is an ActiveRecord, serialize as hash instead of serializing the object", "elsif", "attribute", ".", "class", ".", "ancestors", ".", "include?", "(", "ActiveRecord", "::", "Base", ")", "attribute", ".", "serializable_hash", "# If an array, such as from an association, serialize the elements in the array", "elsif", "attribute", ".", "is_a?", "(", "Array", ")", "||", "attribute", ".", "is_a?", "(", "ActiveRecord", "::", "Associations", "::", "CollectionProxy", ")", "attribute", ".", "map", "{", "|", "element", "|", "serialize_attribute", ".", "call", "(", "element", ")", "}", "# otherwise, return val", "else", "attribute", "end", "end", "{", "}", ".", "tap", "do", "|", "s", "|", "self", ".", "class", ".", "audited_attributes", ".", "each", "do", "|", "attr", "|", "val", "=", "self", ".", "send", "attr", "s", "[", "attr", ".", "to_s", "]", "=", "serialize_attribute", ".", "call", "(", "val", ")", "end", "end", "end" ]
Take a snapshot of the current state of the audited record's audited attributes
[ "Take", "a", "snapshot", "of", "the", "current", "state", "of", "the", "audited", "record", "s", "audited", "attributes" ]
c309fa345864719718045e9b4f13a0e87a8597a2
https://github.com/harley/auditable/blob/c309fa345864719718045e9b4f13a0e87a8597a2/lib/auditable/auditing.rb#L209-L236
1,172
harley/auditable
lib/auditable/auditing.rb
Auditable.Auditing.snap!
def snap!(options = {}) data = options.merge(:modifications => self.snap) data[:tag] = self.audit_tag if self.audit_tag data[:action] = self.audit_action if self.audit_action data[:changed_by] = self.audit_changed_by if self.audit_changed_by self.save_audit( data ) end
ruby
def snap!(options = {}) data = options.merge(:modifications => self.snap) data[:tag] = self.audit_tag if self.audit_tag data[:action] = self.audit_action if self.audit_action data[:changed_by] = self.audit_changed_by if self.audit_changed_by self.save_audit( data ) end
[ "def", "snap!", "(", "options", "=", "{", "}", ")", "data", "=", "options", ".", "merge", "(", ":modifications", "=>", "self", ".", "snap", ")", "data", "[", ":tag", "]", "=", "self", ".", "audit_tag", "if", "self", ".", "audit_tag", "data", "[", ":action", "]", "=", "self", ".", "audit_action", "if", "self", ".", "audit_action", "data", "[", ":changed_by", "]", "=", "self", ".", "audit_changed_by", "if", "self", ".", "audit_changed_by", "self", ".", "save_audit", "(", "data", ")", "end" ]
Take a snapshot of and save the current state of the audited record's audited attributes Accept values for :tag, :action and :user in the argument hash. However, these are overridden by the values set by the auditable record's virtual attributes (#audit_tag, #audit_action, #changed_by) if defined
[ "Take", "a", "snapshot", "of", "and", "save", "the", "current", "state", "of", "the", "audited", "record", "s", "audited", "attributes" ]
c309fa345864719718045e9b4f13a0e87a8597a2
https://github.com/harley/auditable/blob/c309fa345864719718045e9b4f13a0e87a8597a2/lib/auditable/auditing.rb#L241-L249
1,173
harley/auditable
lib/auditable/auditing.rb
Auditable.Auditing.last_change_of
def last_change_of(attribute) raise "#{attribute} is not audited for model #{self.class}. Audited attributes: #{self.class.audited_attributes}" unless self.class.audited_attributes.include? attribute.to_sym attribute = attribute.to_s # support symbol as well last = audits.size - 1 last.downto(1) do |i| if audits[i].modifications[attribute] != audits[i-1].modifications[attribute] return audits[i].diff(audits[i-1])[attribute] end end nil end
ruby
def last_change_of(attribute) raise "#{attribute} is not audited for model #{self.class}. Audited attributes: #{self.class.audited_attributes}" unless self.class.audited_attributes.include? attribute.to_sym attribute = attribute.to_s # support symbol as well last = audits.size - 1 last.downto(1) do |i| if audits[i].modifications[attribute] != audits[i-1].modifications[attribute] return audits[i].diff(audits[i-1])[attribute] end end nil end
[ "def", "last_change_of", "(", "attribute", ")", "raise", "\"#{attribute} is not audited for model #{self.class}. Audited attributes: #{self.class.audited_attributes}\"", "unless", "self", ".", "class", ".", "audited_attributes", ".", "include?", "attribute", ".", "to_sym", "attribute", "=", "attribute", ".", "to_s", "# support symbol as well", "last", "=", "audits", ".", "size", "-", "1", "last", ".", "downto", "(", "1", ")", "do", "|", "i", "|", "if", "audits", "[", "i", "]", ".", "modifications", "[", "attribute", "]", "!=", "audits", "[", "i", "-", "1", "]", ".", "modifications", "[", "attribute", "]", "return", "audits", "[", "i", "]", ".", "diff", "(", "audits", "[", "i", "-", "1", "]", ")", "[", "attribute", "]", "end", "end", "nil", "end" ]
Return last attribute's change This method may be slow and inefficient on model with lots of audit objects. Go through each audit in the reverse order and find the first occurrence when audit.modifications[attribute] changed
[ "Return", "last", "attribute", "s", "change" ]
c309fa345864719718045e9b4f13a0e87a8597a2
https://github.com/harley/auditable/blob/c309fa345864719718045e9b4f13a0e87a8597a2/lib/auditable/auditing.rb#L291-L301
1,174
harley/auditable
lib/auditable/base.rb
Auditable.Base.diff
def diff(other_audit) other_modifications = other_audit ? other_audit.modifications : {} {}.tap do |d| # find keys present only in this audit (self.modifications.keys - other_modifications.keys).each do |k| d[k] = [nil, self.modifications[k]] if self.modifications[k] end # find keys present only in other audit (other_modifications.keys - self.modifications.keys).each do |k| d[k] = [other_modifications[k], nil] if other_modifications[k] end # find common keys and diff values self.modifications.keys.each do |k| if self.modifications[k] != other_modifications[k] d[k] = [other_modifications[k], self.modifications[k]] end end end end
ruby
def diff(other_audit) other_modifications = other_audit ? other_audit.modifications : {} {}.tap do |d| # find keys present only in this audit (self.modifications.keys - other_modifications.keys).each do |k| d[k] = [nil, self.modifications[k]] if self.modifications[k] end # find keys present only in other audit (other_modifications.keys - self.modifications.keys).each do |k| d[k] = [other_modifications[k], nil] if other_modifications[k] end # find common keys and diff values self.modifications.keys.each do |k| if self.modifications[k] != other_modifications[k] d[k] = [other_modifications[k], self.modifications[k]] end end end end
[ "def", "diff", "(", "other_audit", ")", "other_modifications", "=", "other_audit", "?", "other_audit", ".", "modifications", ":", "{", "}", "{", "}", ".", "tap", "do", "|", "d", "|", "# find keys present only in this audit", "(", "self", ".", "modifications", ".", "keys", "-", "other_modifications", ".", "keys", ")", ".", "each", "do", "|", "k", "|", "d", "[", "k", "]", "=", "[", "nil", ",", "self", ".", "modifications", "[", "k", "]", "]", "if", "self", ".", "modifications", "[", "k", "]", "end", "# find keys present only in other audit", "(", "other_modifications", ".", "keys", "-", "self", ".", "modifications", ".", "keys", ")", ".", "each", "do", "|", "k", "|", "d", "[", "k", "]", "=", "[", "other_modifications", "[", "k", "]", ",", "nil", "]", "if", "other_modifications", "[", "k", "]", "end", "# find common keys and diff values", "self", ".", "modifications", ".", "keys", ".", "each", "do", "|", "k", "|", "if", "self", ".", "modifications", "[", "k", "]", "!=", "other_modifications", "[", "k", "]", "d", "[", "k", "]", "=", "[", "other_modifications", "[", "k", "]", ",", "self", ".", "modifications", "[", "k", "]", "]", "end", "end", "end", "end" ]
Diffing two audits' modifications Returns a hash containing arrays of the form { :key_1 => [<value_in_other_audit>, <value_in_this_audit>], :key_2 => [<value_in_other_audit>, <value_in_this_audit>], :other_audit_own_key => [<value_in_other_audit>, nil], :this_audio_own_key => [nil, <value_in_this_audit>] }
[ "Diffing", "two", "audits", "modifications" ]
c309fa345864719718045e9b4f13a0e87a8597a2
https://github.com/harley/auditable/blob/c309fa345864719718045e9b4f13a0e87a8597a2/lib/auditable/base.rb#L22-L43
1,175
harley/auditable
lib/auditable/base.rb
Auditable.Base.diff_since
def diff_since(time) other_audit = auditable.audits.where("created_at <= ? AND id != ?", time, id).order("id DESC").limit(1).first diff(other_audit) end
ruby
def diff_since(time) other_audit = auditable.audits.where("created_at <= ? AND id != ?", time, id).order("id DESC").limit(1).first diff(other_audit) end
[ "def", "diff_since", "(", "time", ")", "other_audit", "=", "auditable", ".", "audits", ".", "where", "(", "\"created_at <= ? AND id != ?\"", ",", "time", ",", "id", ")", ".", "order", "(", "\"id DESC\"", ")", ".", "limit", "(", "1", ")", ".", "first", "diff", "(", "other_audit", ")", "end" ]
Diff this audit with the latest audit created before the `time` variable passed
[ "Diff", "this", "audit", "with", "the", "latest", "audit", "created", "before", "the", "time", "variable", "passed" ]
c309fa345864719718045e9b4f13a0e87a8597a2
https://github.com/harley/auditable/blob/c309fa345864719718045e9b4f13a0e87a8597a2/lib/auditable/base.rb#L72-L76
1,176
harley/auditable
lib/auditable/base.rb
Auditable.Base.diff_since_version
def diff_since_version(version) other_audit = auditable.audits.where("version <= ? AND id != ?", version, id).order("version DESC").limit(1).first diff(other_audit) end
ruby
def diff_since_version(version) other_audit = auditable.audits.where("version <= ? AND id != ?", version, id).order("version DESC").limit(1).first diff(other_audit) end
[ "def", "diff_since_version", "(", "version", ")", "other_audit", "=", "auditable", ".", "audits", ".", "where", "(", "\"version <= ? AND id != ?\"", ",", "version", ",", "id", ")", ".", "order", "(", "\"version DESC\"", ")", ".", "limit", "(", "1", ")", ".", "first", "diff", "(", "other_audit", ")", "end" ]
Diff this audit with the latest audit created before this version
[ "Diff", "this", "audit", "with", "the", "latest", "audit", "created", "before", "this", "version" ]
c309fa345864719718045e9b4f13a0e87a8597a2
https://github.com/harley/auditable/blob/c309fa345864719718045e9b4f13a0e87a8597a2/lib/auditable/base.rb#L79-L83
1,177
pjotrp/bioruby-vcf
lib/bio-vcf/vcfheader.rb
BioVcf.VcfHeader.tag
def tag h h2 = h.dup [:show_help,:skip_header,:verbose,:quiet,:debug].each { |key| h2.delete(key) } info = h2.map { |k,v| k.to_s.capitalize+'='+'"'+v.to_s+'"' }.join(',') line = '##BioVcf=<'+info+'>' @lines.insert(-2,line) line end
ruby
def tag h h2 = h.dup [:show_help,:skip_header,:verbose,:quiet,:debug].each { |key| h2.delete(key) } info = h2.map { |k,v| k.to_s.capitalize+'='+'"'+v.to_s+'"' }.join(',') line = '##BioVcf=<'+info+'>' @lines.insert(-2,line) line end
[ "def", "tag", "h", "h2", "=", "h", ".", "dup", "[", ":show_help", ",", ":skip_header", ",", ":verbose", ",", ":quiet", ",", ":debug", "]", ".", "each", "{", "|", "key", "|", "h2", ".", "delete", "(", "key", ")", "}", "info", "=", "h2", ".", "map", "{", "|", "k", ",", "v", "|", "k", ".", "to_s", ".", "capitalize", "+", "'='", "+", "'\"'", "+", "v", ".", "to_s", "+", "'\"'", "}", ".", "join", "(", "','", ")", "line", "=", "'##BioVcf=<'", "+", "info", "+", "'>'", "@lines", ".", "insert", "(", "-", "2", ",", "line", ")", "line", "end" ]
Push a special key value list to the header
[ "Push", "a", "special", "key", "value", "list", "to", "the", "header" ]
bb9a3f9c10ffbd0304690bbca001ad775f6ea54e
https://github.com/pjotrp/bioruby-vcf/blob/bb9a3f9c10ffbd0304690bbca001ad775f6ea54e/lib/bio-vcf/vcfheader.rb#L51-L58
1,178
pjotrp/bioruby-vcf
lib/bio-vcf/vcfrecord.rb
BioVcf.VcfRecord.method_missing
def method_missing(m, *args, &block) name = m.to_s if name =~ /\?$/ # Query for empty sample name @sample_index ||= @header.sample_index return !VcfSample::empty?(@fields[@sample_index[name.chop]]) else sample[name] end end
ruby
def method_missing(m, *args, &block) name = m.to_s if name =~ /\?$/ # Query for empty sample name @sample_index ||= @header.sample_index return !VcfSample::empty?(@fields[@sample_index[name.chop]]) else sample[name] end end
[ "def", "method_missing", "(", "m", ",", "*", "args", ",", "&", "block", ")", "name", "=", "m", ".", "to_s", "if", "name", "=~", "/", "\\?", "/", "# Query for empty sample name", "@sample_index", "||=", "@header", ".", "sample_index", "return", "!", "VcfSample", "::", "empty?", "(", "@fields", "[", "@sample_index", "[", "name", ".", "chop", "]", "]", ")", "else", "sample", "[", "name", "]", "end", "end" ]
Return the sample
[ "Return", "the", "sample" ]
bb9a3f9c10ffbd0304690bbca001ad775f6ea54e
https://github.com/pjotrp/bioruby-vcf/blob/bb9a3f9c10ffbd0304690bbca001ad775f6ea54e/lib/bio-vcf/vcfrecord.rb#L314-L323
1,179
pjotrp/bioruby-vcf
lib/bio-vcf/vcffile.rb
BioVcf.VCFfile.each
def each return enum_for(:each) unless block_given? io = nil if @is_gz infile = open(@file) io = Zlib::GzipReader.new(infile) else io = File.open(@file) end header = BioVcf::VcfHeader.new io.each_line do |line| line.chomp! if line =~ /^##fileformat=/ header.add(line) next end if line =~ /^#/ header.add(line) next end fields = BioVcf::VcfLine.parse(line) rec = BioVcf::VcfRecord.new(fields,header) yield rec end end
ruby
def each return enum_for(:each) unless block_given? io = nil if @is_gz infile = open(@file) io = Zlib::GzipReader.new(infile) else io = File.open(@file) end header = BioVcf::VcfHeader.new io.each_line do |line| line.chomp! if line =~ /^##fileformat=/ header.add(line) next end if line =~ /^#/ header.add(line) next end fields = BioVcf::VcfLine.parse(line) rec = BioVcf::VcfRecord.new(fields,header) yield rec end end
[ "def", "each", "return", "enum_for", "(", ":each", ")", "unless", "block_given?", "io", "=", "nil", "if", "@is_gz", "infile", "=", "open", "(", "@file", ")", "io", "=", "Zlib", "::", "GzipReader", ".", "new", "(", "infile", ")", "else", "io", "=", "File", ".", "open", "(", "@file", ")", "end", "header", "=", "BioVcf", "::", "VcfHeader", ".", "new", "io", ".", "each_line", "do", "|", "line", "|", "line", ".", "chomp!", "if", "line", "=~", "/", "/", "header", ".", "add", "(", "line", ")", "next", "end", "if", "line", "=~", "/", "/", "header", ".", "add", "(", "line", ")", "next", "end", "fields", "=", "BioVcf", "::", "VcfLine", ".", "parse", "(", "line", ")", "rec", "=", "BioVcf", "::", "VcfRecord", ".", "new", "(", "fields", ",", "header", ")", "yield", "rec", "end", "end" ]
Returns an enum that can be used as an iterator.
[ "Returns", "an", "enum", "that", "can", "be", "used", "as", "an", "iterator", "." ]
bb9a3f9c10ffbd0304690bbca001ad775f6ea54e
https://github.com/pjotrp/bioruby-vcf/blob/bb9a3f9c10ffbd0304690bbca001ad775f6ea54e/lib/bio-vcf/vcffile.rb#L19-L44
1,180
pjotrp/bioruby-vcf
lib/bio-vcf/vcfgenotypefield.rb
BioVcf.VcfGenotypeField.method_missing
def method_missing(m, *args, &block) return nil if @is_empty if m =~ /\?$/ # query if a value exists, e.g., r.info.dp? or s.dp? v = values[fetch(m.to_s.upcase.chop)] return (not VcfValue::empty?(v)) else v = values[fetch(m.to_s.upcase)] return nil if VcfValue::empty?(v) v = v.to_i if v =~ /^\d+$/ v = v.to_f if v =~ /^\d+\.\d+$/ v end end
ruby
def method_missing(m, *args, &block) return nil if @is_empty if m =~ /\?$/ # query if a value exists, e.g., r.info.dp? or s.dp? v = values[fetch(m.to_s.upcase.chop)] return (not VcfValue::empty?(v)) else v = values[fetch(m.to_s.upcase)] return nil if VcfValue::empty?(v) v = v.to_i if v =~ /^\d+$/ v = v.to_f if v =~ /^\d+\.\d+$/ v end end
[ "def", "method_missing", "(", "m", ",", "*", "args", ",", "&", "block", ")", "return", "nil", "if", "@is_empty", "if", "m", "=~", "/", "\\?", "/", "# query if a value exists, e.g., r.info.dp? or s.dp?", "v", "=", "values", "[", "fetch", "(", "m", ".", "to_s", ".", "upcase", ".", "chop", ")", "]", "return", "(", "not", "VcfValue", "::", "empty?", "(", "v", ")", ")", "else", "v", "=", "values", "[", "fetch", "(", "m", ".", "to_s", ".", "upcase", ")", "]", "return", "nil", "if", "VcfValue", "::", "empty?", "(", "v", ")", "v", "=", "v", ".", "to_i", "if", "v", "=~", "/", "\\d", "/", "v", "=", "v", ".", "to_f", "if", "v", "=~", "/", "\\d", "\\.", "\\d", "/", "v", "end", "end" ]
Returns the value of a field
[ "Returns", "the", "value", "of", "a", "field" ]
bb9a3f9c10ffbd0304690bbca001ad775f6ea54e
https://github.com/pjotrp/bioruby-vcf/blob/bb9a3f9c10ffbd0304690bbca001ad775f6ea54e/lib/bio-vcf/vcfgenotypefield.rb#L172-L185
1,181
pjotrp/bioruby-vcf
lib/bio-vcf/vcfgenotypefield.rb
BioVcf.VcfGenotypeField.ilist
def ilist name v = fetch_value(name) return nil if not v v.split(',').map{|i| i.to_i} end
ruby
def ilist name v = fetch_value(name) return nil if not v v.split(',').map{|i| i.to_i} end
[ "def", "ilist", "name", "v", "=", "fetch_value", "(", "name", ")", "return", "nil", "if", "not", "v", "v", ".", "split", "(", "','", ")", ".", "map", "{", "|", "i", "|", "i", ".", "to_i", "}", "end" ]
Return an integer list
[ "Return", "an", "integer", "list" ]
bb9a3f9c10ffbd0304690bbca001ad775f6ea54e
https://github.com/pjotrp/bioruby-vcf/blob/bb9a3f9c10ffbd0304690bbca001ad775f6ea54e/lib/bio-vcf/vcfgenotypefield.rb#L200-L204
1,182
zverok/saharspec
lib/saharspec/matchers/be_json.rb
RSpec.Matchers.be_json
def be_json(expected = Saharspec::Matchers::BeJson::NONE) Saharspec::Matchers::BeJson.new(expected) end
ruby
def be_json(expected = Saharspec::Matchers::BeJson::NONE) Saharspec::Matchers::BeJson.new(expected) end
[ "def", "be_json", "(", "expected", "=", "Saharspec", "::", "Matchers", "::", "BeJson", "::", "NONE", ")", "Saharspec", "::", "Matchers", "::", "BeJson", ".", "new", "(", "expected", ")", "end" ]
`be_json` checks if provided value is JSON, and optionally checks it contents. If you need to check against some hashes, it is more convenient to use `be_json_sym`, which parses JSON with `symbolize_names: true`. @example expect('{}').to be_json # ok expect('garbage').to be_json # expected value to be a valid JSON string but failed: 765: unexpected token at 'garbage' expect('{"foo": "bar"}').to be_json('foo' => 'bar') # ok expect('{"foo": "bar"}').to be_json_sym(foo: 'bar') # more convenient expect('{"foo": [1, 2, 3]').to be_json_sym(foo: array_including(3)) # nested matchers work expect(something_large).to be_json_sym(include(meta: include(next_page: Integer))) @param expected Value or matcher to check JSON against. It should implement `#===` method, so all standard and custom RSpec matchers work.
[ "be_json", "checks", "if", "provided", "value", "is", "JSON", "and", "optionally", "checks", "it", "contents", "." ]
6b014308a5399059284f9f24a1acfc6e7df96e30
https://github.com/zverok/saharspec/blob/6b014308a5399059284f9f24a1acfc6e7df96e30/lib/saharspec/matchers/be_json.rb#L84-L86
1,183
estum/growlyflash
lib/growlyflash/controller_additions.rb
Growlyflash.ControllerAdditions.flash_to_headers
def flash_to_headers if response.xhr? && growlyhash(true).size > 0 response.headers['X-Message'] = URI.escape(growlyhash.to_json) growlyhash.each_key { |k| flash.discard(k) } end end
ruby
def flash_to_headers if response.xhr? && growlyhash(true).size > 0 response.headers['X-Message'] = URI.escape(growlyhash.to_json) growlyhash.each_key { |k| flash.discard(k) } end end
[ "def", "flash_to_headers", "if", "response", ".", "xhr?", "&&", "growlyhash", "(", "true", ")", ".", "size", ">", "0", "response", ".", "headers", "[", "'X-Message'", "]", "=", "URI", ".", "escape", "(", "growlyhash", ".", "to_json", ")", "growlyhash", ".", "each_key", "{", "|", "k", "|", "flash", ".", "discard", "(", "k", ")", "}", "end", "end" ]
Dumps available messages to headers and discards them to prevent appear it again after refreshing a page
[ "Dumps", "available", "messages", "to", "headers", "and", "discards", "them", "to", "prevent", "appear", "it", "again", "after", "refreshing", "a", "page" ]
21028453f23e2acc0a270ebe65700c645e4f97bc
https://github.com/estum/growlyflash/blob/21028453f23e2acc0a270ebe65700c645e4f97bc/lib/growlyflash/controller_additions.rb#L28-L33
1,184
estum/growlyflash
lib/growlyflash/controller_additions.rb
Growlyflash.ControllerAdditions.growlyflash_static_notices
def growlyflash_static_notices(js_var = 'window.flashes') return if flash.empty? script = "#{js_var} = #{growlyhash.to_json.html_safe};".freeze view_context.javascript_tag(script, defer: 'defer') end
ruby
def growlyflash_static_notices(js_var = 'window.flashes') return if flash.empty? script = "#{js_var} = #{growlyhash.to_json.html_safe};".freeze view_context.javascript_tag(script, defer: 'defer') end
[ "def", "growlyflash_static_notices", "(", "js_var", "=", "'window.flashes'", ")", "return", "if", "flash", ".", "empty?", "script", "=", "\"#{js_var} = #{growlyhash.to_json.html_safe};\"", ".", "freeze", "view_context", ".", "javascript_tag", "(", "script", ",", "defer", ":", "'defer'", ")", "end" ]
View helper method which renders flash messages to js variable if they weren't dumped to headers with XHR request
[ "View", "helper", "method", "which", "renders", "flash", "messages", "to", "js", "variable", "if", "they", "weren", "t", "dumped", "to", "headers", "with", "XHR", "request" ]
21028453f23e2acc0a270ebe65700c645e4f97bc
https://github.com/estum/growlyflash/blob/21028453f23e2acc0a270ebe65700c645e4f97bc/lib/growlyflash/controller_additions.rb#L37-L41
1,185
estum/growlyflash
lib/growlyflash/controller_additions.rb
Growlyflash.ControllerAdditions.growlyhash
def growlyhash(force = false) @growlyhash = nil if force @growlyhash ||= flash.to_hash.select { |k, v| v.is_a? String } end
ruby
def growlyhash(force = false) @growlyhash = nil if force @growlyhash ||= flash.to_hash.select { |k, v| v.is_a? String } end
[ "def", "growlyhash", "(", "force", "=", "false", ")", "@growlyhash", "=", "nil", "if", "force", "@growlyhash", "||=", "flash", ".", "to_hash", ".", "select", "{", "|", "k", ",", "v", "|", "v", ".", "is_a?", "String", "}", "end" ]
Hash with available growl flash messages which contains a string object.
[ "Hash", "with", "available", "growl", "flash", "messages", "which", "contains", "a", "string", "object", "." ]
21028453f23e2acc0a270ebe65700c645e4f97bc
https://github.com/estum/growlyflash/blob/21028453f23e2acc0a270ebe65700c645e4f97bc/lib/growlyflash/controller_additions.rb#L54-L57
1,186
celsodantas/protokoll
lib/protokoll/protokoll.rb
Protokoll.ClassMethods.protokoll
def protokoll(column, _options = {}) options = { :pattern => "%Y%m#####", :number_symbol => "#", :column => column, :start => 0, :scope_by => nil } options.merge!(_options) raise ArgumentError.new("pattern can't be nil!") if options[:pattern].nil? raise ArgumentError.new("pattern requires at least one counter symbol #{options[:number_symbol]}") unless pattern_includes_symbols?(options) # Defining custom method send :define_method, "reserve_#{options[:column]}!".to_sym do self[column] = Counter.next(self, options) end # Signing before_create before_create do |record| unless record[column].present? record[column] = Counter.next(self, options) end end end
ruby
def protokoll(column, _options = {}) options = { :pattern => "%Y%m#####", :number_symbol => "#", :column => column, :start => 0, :scope_by => nil } options.merge!(_options) raise ArgumentError.new("pattern can't be nil!") if options[:pattern].nil? raise ArgumentError.new("pattern requires at least one counter symbol #{options[:number_symbol]}") unless pattern_includes_symbols?(options) # Defining custom method send :define_method, "reserve_#{options[:column]}!".to_sym do self[column] = Counter.next(self, options) end # Signing before_create before_create do |record| unless record[column].present? record[column] = Counter.next(self, options) end end end
[ "def", "protokoll", "(", "column", ",", "_options", "=", "{", "}", ")", "options", "=", "{", ":pattern", "=>", "\"%Y%m#####\"", ",", ":number_symbol", "=>", "\"#\"", ",", ":column", "=>", "column", ",", ":start", "=>", "0", ",", ":scope_by", "=>", "nil", "}", "options", ".", "merge!", "(", "_options", ")", "raise", "ArgumentError", ".", "new", "(", "\"pattern can't be nil!\"", ")", "if", "options", "[", ":pattern", "]", ".", "nil?", "raise", "ArgumentError", ".", "new", "(", "\"pattern requires at least one counter symbol #{options[:number_symbol]}\"", ")", "unless", "pattern_includes_symbols?", "(", "options", ")", "# Defining custom method", "send", ":define_method", ",", "\"reserve_#{options[:column]}!\"", ".", "to_sym", "do", "self", "[", "column", "]", "=", "Counter", ".", "next", "(", "self", ",", "options", ")", "end", "# Signing before_create", "before_create", "do", "|", "record", "|", "unless", "record", "[", "column", "]", ".", "present?", "record", "[", "column", "]", "=", "Counter", ".", "next", "(", "self", ",", "options", ")", "end", "end", "end" ]
Class method available in models == Example class Order < ActiveRecord::Base protokoll :number end
[ "Class", "method", "available", "in", "models" ]
6f4e72aebbb239b30d9cc6b34db87881a3f83d64
https://github.com/celsodantas/protokoll/blob/6f4e72aebbb239b30d9cc6b34db87881a3f83d64/lib/protokoll/protokoll.rb#L13-L35
1,187
piotrmurach/lex
lib/lex/lexer.rb
Lex.Lexer.lex
def lex(input) @input = input return enum_for(:lex, input) unless block_given? if debug logger.info "lex: tokens = #{@dsl.lex_tokens}" logger.info "lex: states = #{@dsl.state_info}" logger.info "lex: ignore = #{@dsl.state_ignore}" logger.info "lex: error = #{@dsl.state_error}" end stream_tokens(input) do |token| yield token end end
ruby
def lex(input) @input = input return enum_for(:lex, input) unless block_given? if debug logger.info "lex: tokens = #{@dsl.lex_tokens}" logger.info "lex: states = #{@dsl.state_info}" logger.info "lex: ignore = #{@dsl.state_ignore}" logger.info "lex: error = #{@dsl.state_error}" end stream_tokens(input) do |token| yield token end end
[ "def", "lex", "(", "input", ")", "@input", "=", "input", "return", "enum_for", "(", ":lex", ",", "input", ")", "unless", "block_given?", "if", "debug", "logger", ".", "info", "\"lex: tokens = #{@dsl.lex_tokens}\"", "logger", ".", "info", "\"lex: states = #{@dsl.state_info}\"", "logger", ".", "info", "\"lex: ignore = #{@dsl.state_ignore}\"", "logger", ".", "info", "\"lex: error = #{@dsl.state_error}\"", "end", "stream_tokens", "(", "input", ")", "do", "|", "token", "|", "yield", "token", "end", "end" ]
Tokenizes input and returns all tokens @param [String] input @return [Enumerator] the tokens found @api public
[ "Tokenizes", "input", "and", "returns", "all", "tokens" ]
28460ecafb8b92cf9a31e821f9f088c8f7573665
https://github.com/piotrmurach/lex/blob/28460ecafb8b92cf9a31e821f9f088c8f7573665/lib/lex/lexer.rb#L51-L66
1,188
piotrmurach/lex
lib/lex/lexer.rb
Lex.Lexer.stream_tokens
def stream_tokens(input, &block) scanner = StringScanner.new(input) while !scanner.eos? current_char = scanner.peek(1) if @dsl.state_ignore[current_state].include?(current_char) scanner.pos += current_char.size @char_pos_in_line += current_char.size next end if debug logger.info "lex: [#{current_state}]: lexemes = #{@dsl.state_lexemes[current_state].map(&:name)}" end # Look for regex match longest_token = nil @dsl.state_lexemes[current_state].each do |lexeme| match = lexeme.match(scanner) next if match.nil? longest_token = match if longest_token.nil? next if longest_token.value.length >= match.value.length longest_token = match end if longest_token if longest_token.action new_token = longest_token.action.call(self, longest_token) # No value returned from action move to the next token if new_token.nil? || !new_token.is_a?(Token) chars_to_skip = longest_token.value.to_s.length scanner.pos += chars_to_skip unless longest_token.name == :newline @char_pos_in_line += chars_to_skip end next end end move_by = longest_token.value.to_s.length start_char_pos_in_token = @char_pos_in_line + current_char.size longest_token.update_line(current_line, start_char_pos_in_token) advance_column(move_by) scanner.pos += move_by end # No match if longest_token.nil? # Check in errors if @dsl.state_error[current_state] token = Token.new(:error, current_char) start_char_pos_in_token = @char_pos_in_line + current_char.size token.update_line(current_line, start_char_pos_in_token) new_token = @dsl.state_error[current_state].call(self, token) advance_column(current_char.length) scanner.pos += current_char.length if new_token.is_a?(Token) || !new_token.nil? longest_token = new_token else next end end if longest_token.nil? complain("Illegal character `#{current_char}`") end end logger.info "lex: #{longest_token}" if debug block.call(longest_token) end end
ruby
def stream_tokens(input, &block) scanner = StringScanner.new(input) while !scanner.eos? current_char = scanner.peek(1) if @dsl.state_ignore[current_state].include?(current_char) scanner.pos += current_char.size @char_pos_in_line += current_char.size next end if debug logger.info "lex: [#{current_state}]: lexemes = #{@dsl.state_lexemes[current_state].map(&:name)}" end # Look for regex match longest_token = nil @dsl.state_lexemes[current_state].each do |lexeme| match = lexeme.match(scanner) next if match.nil? longest_token = match if longest_token.nil? next if longest_token.value.length >= match.value.length longest_token = match end if longest_token if longest_token.action new_token = longest_token.action.call(self, longest_token) # No value returned from action move to the next token if new_token.nil? || !new_token.is_a?(Token) chars_to_skip = longest_token.value.to_s.length scanner.pos += chars_to_skip unless longest_token.name == :newline @char_pos_in_line += chars_to_skip end next end end move_by = longest_token.value.to_s.length start_char_pos_in_token = @char_pos_in_line + current_char.size longest_token.update_line(current_line, start_char_pos_in_token) advance_column(move_by) scanner.pos += move_by end # No match if longest_token.nil? # Check in errors if @dsl.state_error[current_state] token = Token.new(:error, current_char) start_char_pos_in_token = @char_pos_in_line + current_char.size token.update_line(current_line, start_char_pos_in_token) new_token = @dsl.state_error[current_state].call(self, token) advance_column(current_char.length) scanner.pos += current_char.length if new_token.is_a?(Token) || !new_token.nil? longest_token = new_token else next end end if longest_token.nil? complain("Illegal character `#{current_char}`") end end logger.info "lex: #{longest_token}" if debug block.call(longest_token) end end
[ "def", "stream_tokens", "(", "input", ",", "&", "block", ")", "scanner", "=", "StringScanner", ".", "new", "(", "input", ")", "while", "!", "scanner", ".", "eos?", "current_char", "=", "scanner", ".", "peek", "(", "1", ")", "if", "@dsl", ".", "state_ignore", "[", "current_state", "]", ".", "include?", "(", "current_char", ")", "scanner", ".", "pos", "+=", "current_char", ".", "size", "@char_pos_in_line", "+=", "current_char", ".", "size", "next", "end", "if", "debug", "logger", ".", "info", "\"lex: [#{current_state}]: lexemes = #{@dsl.state_lexemes[current_state].map(&:name)}\"", "end", "# Look for regex match", "longest_token", "=", "nil", "@dsl", ".", "state_lexemes", "[", "current_state", "]", ".", "each", "do", "|", "lexeme", "|", "match", "=", "lexeme", ".", "match", "(", "scanner", ")", "next", "if", "match", ".", "nil?", "longest_token", "=", "match", "if", "longest_token", ".", "nil?", "next", "if", "longest_token", ".", "value", ".", "length", ">=", "match", ".", "value", ".", "length", "longest_token", "=", "match", "end", "if", "longest_token", "if", "longest_token", ".", "action", "new_token", "=", "longest_token", ".", "action", ".", "call", "(", "self", ",", "longest_token", ")", "# No value returned from action move to the next token", "if", "new_token", ".", "nil?", "||", "!", "new_token", ".", "is_a?", "(", "Token", ")", "chars_to_skip", "=", "longest_token", ".", "value", ".", "to_s", ".", "length", "scanner", ".", "pos", "+=", "chars_to_skip", "unless", "longest_token", ".", "name", "==", ":newline", "@char_pos_in_line", "+=", "chars_to_skip", "end", "next", "end", "end", "move_by", "=", "longest_token", ".", "value", ".", "to_s", ".", "length", "start_char_pos_in_token", "=", "@char_pos_in_line", "+", "current_char", ".", "size", "longest_token", ".", "update_line", "(", "current_line", ",", "start_char_pos_in_token", ")", "advance_column", "(", "move_by", ")", "scanner", ".", "pos", "+=", "move_by", "end", "# No match", "if", "longest_token", ".", "nil?", "# Check in errors", "if", "@dsl", ".", "state_error", "[", "current_state", "]", "token", "=", "Token", ".", "new", "(", ":error", ",", "current_char", ")", "start_char_pos_in_token", "=", "@char_pos_in_line", "+", "current_char", ".", "size", "token", ".", "update_line", "(", "current_line", ",", "start_char_pos_in_token", ")", "new_token", "=", "@dsl", ".", "state_error", "[", "current_state", "]", ".", "call", "(", "self", ",", "token", ")", "advance_column", "(", "current_char", ".", "length", ")", "scanner", ".", "pos", "+=", "current_char", ".", "length", "if", "new_token", ".", "is_a?", "(", "Token", ")", "||", "!", "new_token", ".", "nil?", "longest_token", "=", "new_token", "else", "next", "end", "end", "if", "longest_token", ".", "nil?", "complain", "(", "\"Illegal character `#{current_char}`\"", ")", "end", "end", "logger", ".", "info", "\"lex: #{longest_token}\"", "if", "debug", "block", ".", "call", "(", "longest_token", ")", "end", "end" ]
Advances through input and streams tokens @param [String] input @yield [Lex::Token] @api public
[ "Advances", "through", "input", "and", "streams", "tokens" ]
28460ecafb8b92cf9a31e821f9f088c8f7573665
https://github.com/piotrmurach/lex/blob/28460ecafb8b92cf9a31e821f9f088c8f7573665/lib/lex/lexer.rb#L75-L143
1,189
leishman/kraken_ruby
lib/kraken_ruby/client.rb
Kraken.Client.add_order
def add_order(opts={}) required_opts = %w{ pair type ordertype volume } leftover = required_opts - opts.keys.map(&:to_s) if leftover.length > 0 raise ArgumentError.new("Required options, not given. Input must include #{leftover}") end post_private 'AddOrder', opts end
ruby
def add_order(opts={}) required_opts = %w{ pair type ordertype volume } leftover = required_opts - opts.keys.map(&:to_s) if leftover.length > 0 raise ArgumentError.new("Required options, not given. Input must include #{leftover}") end post_private 'AddOrder', opts end
[ "def", "add_order", "(", "opts", "=", "{", "}", ")", "required_opts", "=", "%w{", "pair", "type", "ordertype", "volume", "}", "leftover", "=", "required_opts", "-", "opts", ".", "keys", ".", "map", "(", ":to_s", ")", "if", "leftover", ".", "length", ">", "0", "raise", "ArgumentError", ".", "new", "(", "\"Required options, not given. Input must include #{leftover}\"", ")", "end", "post_private", "'AddOrder'", ",", "opts", "end" ]
Private User Trading
[ "Private", "User", "Trading" ]
bce2daad1f5fd761c5b07c018c5a911c3922d66d
https://github.com/leishman/kraken_ruby/blob/bce2daad1f5fd761c5b07c018c5a911c3922d66d/lib/kraken_ruby/client.rb#L115-L122
1,190
sosedoff/xml-sitemap
lib/xml-sitemap/render_engine.rb
XmlSitemap.RenderEngine.render_nokogiri
def render_nokogiri unless defined? Nokogiri raise ArgumentError, "Nokogiri not found!" end builder = Nokogiri::XML::Builder.new(:encoding => "UTF-8") do |xml| xml.urlset(XmlSitemap::MAP_SCHEMA_OPTIONS) { |s| @items.each do |item| s.url do |u| u.loc item.target # Format and image tag specifications found at http://support.google.com/webmasters/bin/answer.py?hl=en&answer=178636 if item.image_location u["image"].image do |a| a["image"].loc item.image_location a["image"].caption item.image_caption if item.image_caption a["image"].title item.image_title if item.image_title a["image"].license item.image_license if item.image_license a["image"].geo_location item.image_geolocation if item.image_geolocation end end # Format and video tag specifications found at http://support.google.com/webmasters/bin/answer.py?hl=en&answer=80472&topic=10079&ctx=topic#2 if item.video_thumbnail_location && item.video_title && item.video_description && (item.video_content_location || item.video_player_location) u["video"].video do |a| a["video"].thumbnail_loc item.video_thumbnail_location a["video"].title item.video_title a["video"].description item.video_description a["video"].content_loc item.video_content_location if item.video_content_location a["video"].player_loc item.video_player_location if item.video_player_location a["video"].duration item.video_duration.to_s if item.video_duration a["video"].expiration_date item.video_expiration_date_value if item.video_expiration_date a["video"].rating item.video_rating.to_s if item.video_rating a["video"].view_count item.video_view_count.to_s if item.video_view_count a["video"].publication_date item.video_publication_date_value if item.video_publication_date a["video"].family_friendly item.video_family_friendly if item.video_family_friendly a["video"].category item.video_category if item.video_category a["video"].restriction item.video_restriction, :relationship => "allow" if item.video_restriction a["video"].gallery_loc item.video_gallery_location if item.video_gallery_location a["video"].price item.video_price.to_s, :currency => "USD" if item.video_price a["video"].requires_subscription item.video_requires_subscription if item.video_requires_subscription a["video"].uploader item.video_uploader if item.video_uploader a["video"].platform item.video_platform, :relationship => "allow" if item.video_platform a["video"].live item.video_live if item.video_live end end u.lastmod item.lastmod_value u.changefreq item.changefreq.to_s if item.changefreq u.priority item.priority.to_s if item.priority end end } end builder.to_xml end
ruby
def render_nokogiri unless defined? Nokogiri raise ArgumentError, "Nokogiri not found!" end builder = Nokogiri::XML::Builder.new(:encoding => "UTF-8") do |xml| xml.urlset(XmlSitemap::MAP_SCHEMA_OPTIONS) { |s| @items.each do |item| s.url do |u| u.loc item.target # Format and image tag specifications found at http://support.google.com/webmasters/bin/answer.py?hl=en&answer=178636 if item.image_location u["image"].image do |a| a["image"].loc item.image_location a["image"].caption item.image_caption if item.image_caption a["image"].title item.image_title if item.image_title a["image"].license item.image_license if item.image_license a["image"].geo_location item.image_geolocation if item.image_geolocation end end # Format and video tag specifications found at http://support.google.com/webmasters/bin/answer.py?hl=en&answer=80472&topic=10079&ctx=topic#2 if item.video_thumbnail_location && item.video_title && item.video_description && (item.video_content_location || item.video_player_location) u["video"].video do |a| a["video"].thumbnail_loc item.video_thumbnail_location a["video"].title item.video_title a["video"].description item.video_description a["video"].content_loc item.video_content_location if item.video_content_location a["video"].player_loc item.video_player_location if item.video_player_location a["video"].duration item.video_duration.to_s if item.video_duration a["video"].expiration_date item.video_expiration_date_value if item.video_expiration_date a["video"].rating item.video_rating.to_s if item.video_rating a["video"].view_count item.video_view_count.to_s if item.video_view_count a["video"].publication_date item.video_publication_date_value if item.video_publication_date a["video"].family_friendly item.video_family_friendly if item.video_family_friendly a["video"].category item.video_category if item.video_category a["video"].restriction item.video_restriction, :relationship => "allow" if item.video_restriction a["video"].gallery_loc item.video_gallery_location if item.video_gallery_location a["video"].price item.video_price.to_s, :currency => "USD" if item.video_price a["video"].requires_subscription item.video_requires_subscription if item.video_requires_subscription a["video"].uploader item.video_uploader if item.video_uploader a["video"].platform item.video_platform, :relationship => "allow" if item.video_platform a["video"].live item.video_live if item.video_live end end u.lastmod item.lastmod_value u.changefreq item.changefreq.to_s if item.changefreq u.priority item.priority.to_s if item.priority end end } end builder.to_xml end
[ "def", "render_nokogiri", "unless", "defined?", "Nokogiri", "raise", "ArgumentError", ",", "\"Nokogiri not found!\"", "end", "builder", "=", "Nokogiri", "::", "XML", "::", "Builder", ".", "new", "(", ":encoding", "=>", "\"UTF-8\"", ")", "do", "|", "xml", "|", "xml", ".", "urlset", "(", "XmlSitemap", "::", "MAP_SCHEMA_OPTIONS", ")", "{", "|", "s", "|", "@items", ".", "each", "do", "|", "item", "|", "s", ".", "url", "do", "|", "u", "|", "u", ".", "loc", "item", ".", "target", "# Format and image tag specifications found at http://support.google.com/webmasters/bin/answer.py?hl=en&answer=178636", "if", "item", ".", "image_location", "u", "[", "\"image\"", "]", ".", "image", "do", "|", "a", "|", "a", "[", "\"image\"", "]", ".", "loc", "item", ".", "image_location", "a", "[", "\"image\"", "]", ".", "caption", "item", ".", "image_caption", "if", "item", ".", "image_caption", "a", "[", "\"image\"", "]", ".", "title", "item", ".", "image_title", "if", "item", ".", "image_title", "a", "[", "\"image\"", "]", ".", "license", "item", ".", "image_license", "if", "item", ".", "image_license", "a", "[", "\"image\"", "]", ".", "geo_location", "item", ".", "image_geolocation", "if", "item", ".", "image_geolocation", "end", "end", "# Format and video tag specifications found at http://support.google.com/webmasters/bin/answer.py?hl=en&answer=80472&topic=10079&ctx=topic#2", "if", "item", ".", "video_thumbnail_location", "&&", "item", ".", "video_title", "&&", "item", ".", "video_description", "&&", "(", "item", ".", "video_content_location", "||", "item", ".", "video_player_location", ")", "u", "[", "\"video\"", "]", ".", "video", "do", "|", "a", "|", "a", "[", "\"video\"", "]", ".", "thumbnail_loc", "item", ".", "video_thumbnail_location", "a", "[", "\"video\"", "]", ".", "title", "item", ".", "video_title", "a", "[", "\"video\"", "]", ".", "description", "item", ".", "video_description", "a", "[", "\"video\"", "]", ".", "content_loc", "item", ".", "video_content_location", "if", "item", ".", "video_content_location", "a", "[", "\"video\"", "]", ".", "player_loc", "item", ".", "video_player_location", "if", "item", ".", "video_player_location", "a", "[", "\"video\"", "]", ".", "duration", "item", ".", "video_duration", ".", "to_s", "if", "item", ".", "video_duration", "a", "[", "\"video\"", "]", ".", "expiration_date", "item", ".", "video_expiration_date_value", "if", "item", ".", "video_expiration_date", "a", "[", "\"video\"", "]", ".", "rating", "item", ".", "video_rating", ".", "to_s", "if", "item", ".", "video_rating", "a", "[", "\"video\"", "]", ".", "view_count", "item", ".", "video_view_count", ".", "to_s", "if", "item", ".", "video_view_count", "a", "[", "\"video\"", "]", ".", "publication_date", "item", ".", "video_publication_date_value", "if", "item", ".", "video_publication_date", "a", "[", "\"video\"", "]", ".", "family_friendly", "item", ".", "video_family_friendly", "if", "item", ".", "video_family_friendly", "a", "[", "\"video\"", "]", ".", "category", "item", ".", "video_category", "if", "item", ".", "video_category", "a", "[", "\"video\"", "]", ".", "restriction", "item", ".", "video_restriction", ",", ":relationship", "=>", "\"allow\"", "if", "item", ".", "video_restriction", "a", "[", "\"video\"", "]", ".", "gallery_loc", "item", ".", "video_gallery_location", "if", "item", ".", "video_gallery_location", "a", "[", "\"video\"", "]", ".", "price", "item", ".", "video_price", ".", "to_s", ",", ":currency", "=>", "\"USD\"", "if", "item", ".", "video_price", "a", "[", "\"video\"", "]", ".", "requires_subscription", "item", ".", "video_requires_subscription", "if", "item", ".", "video_requires_subscription", "a", "[", "\"video\"", "]", ".", "uploader", "item", ".", "video_uploader", "if", "item", ".", "video_uploader", "a", "[", "\"video\"", "]", ".", "platform", "item", ".", "video_platform", ",", ":relationship", "=>", "\"allow\"", "if", "item", ".", "video_platform", "a", "[", "\"video\"", "]", ".", "live", "item", ".", "video_live", "if", "item", ".", "video_live", "end", "end", "u", ".", "lastmod", "item", ".", "lastmod_value", "u", ".", "changefreq", "item", ".", "changefreq", ".", "to_s", "if", "item", ".", "changefreq", "u", ".", "priority", "item", ".", "priority", ".", "to_s", "if", "item", ".", "priority", "end", "end", "}", "end", "builder", ".", "to_xml", "end" ]
Render with Nokogiri gem
[ "Render", "with", "Nokogiri", "gem" ]
a9b510d49297d219c5b19a9c778cb8c6f0f1ae16
https://github.com/sosedoff/xml-sitemap/blob/a9b510d49297d219c5b19a9c778cb8c6f0f1ae16/lib/xml-sitemap/render_engine.rb#L7-L62
1,191
sosedoff/xml-sitemap
lib/xml-sitemap/render_engine.rb
XmlSitemap.RenderEngine.render_string
def render_string result = '<?xml version="1.0" encoding="UTF-8"?>' + "\n<urlset" XmlSitemap::MAP_SCHEMA_OPTIONS.each do |key, val| result << ' ' + key + '="' + val + '"' end result << ">\n" item_results = [] @items.each do |item| item_string = " <url>\n" item_string << " <loc>#{CGI::escapeHTML(item.target)}</loc>\n" # Format and image tag specifications found at http://support.google.com/webmasters/bin/answer.py?hl=en&answer=178636 if item.image_location item_string << " <image:image>\n" item_string << " <image:loc>#{CGI::escapeHTML(item.image_location)}</image:loc>\n" item_string << " <image:caption>#{CGI::escapeHTML(item.image_caption)}</image:caption>\n" if item.image_caption item_string << " <image:title>#{CGI::escapeHTML(item.image_title)}</image:title>\n" if item.image_title item_string << " <image:license>#{CGI::escapeHTML(item.image_license)}</image:license>\n" if item.image_license item_string << " <image:geo_location>#{CGI::escapeHTML(item.image_geolocation)}</image:geo_location>\n" if item.image_geolocation item_string << " </image:image>\n" end # Format and video tag specifications found at http://support.google.com/webmasters/bin/answer.py?hl=en&answer=80472&topic=10079&ctx=topic#2 if item.video_thumbnail_location && item.video_title && item.video_description && (item.video_content_location || item.video_player_location) item_string << " <video:video>\n" item_string << " <video:thumbnail_loc>#{CGI::escapeHTML(item.video_thumbnail_location)}</video:thumbnail_loc>\n" item_string << " <video:title>#{CGI::escapeHTML(item.video_title)}</video:title>\n" item_string << " <video:description>#{CGI::escapeHTML(item.video_description)}</video:description>\n" item_string << " <video:content_loc>#{CGI::escapeHTML(item.video_content_location)}</video:content_loc>\n" if item.video_content_location item_string << " <video:player_loc>#{CGI::escapeHTML(item.video_player_location)}</video:player_loc>\n" if item.video_player_location item_string << " <video:duration>#{CGI::escapeHTML(item.video_duration.to_s)}</video:duration>\n" if item.video_duration item_string << " <video:expiration_date>#{item.video_expiration_date_value}</video:expiration_date>\n" if item.video_expiration_date item_string << " <video:rating>#{CGI::escapeHTML(item.video_rating.to_s)}</video:rating>\n" if item.video_rating item_string << " <video:view_count>#{CGI::escapeHTML(item.video_view_count.to_s)}</video:view_count>\n" if item.video_view_count item_string << " <video:publication_date>#{item.video_publication_date_value}</video:publication_date>\n" if item.video_publication_date item_string << " <video:family_friendly>#{CGI::escapeHTML(item.video_family_friendly)}</video:family_friendly>\n" if item.video_family_friendly item_string << " <video:category>#{CGI::escapeHTML(item.video_category)}</video:category>\n" if item.video_category item_string << " <video:restriction relationship=\"allow\">#{CGI::escapeHTML(item.video_restriction)}</video:restriction>\n" if item.video_restriction item_string << " <video:gallery_loc>#{CGI::escapeHTML(item.video_gallery_location)}</video:gallery_loc>\n" if item.video_gallery_location item_string << " <video:price currency=\"USD\">#{CGI::escapeHTML(item.video_price.to_s)}</video:price>\n" if item.video_price item_string << " <video:requires_subscription>#{CGI::escapeHTML(item.video_requires_subscription)}</video:requires_subscription>\n" if item.video_requires_subscription item_string << " <video:uploader>#{CGI::escapeHTML(item.video_uploader)}</video:uploader>\n" if item.video_uploader item_string << " <video:platform relationship=\"allow\">#{CGI::escapeHTML(item.video_platform)}</video:platform>\n" if item.video_platform item_string << " <video:live>#{CGI::escapeHTML(item.video_live)}</video:live>\n" if item.video_live item_string << " </video:video>\n" end item_string << " <lastmod>#{item.lastmod_value}</lastmod>\n" item_string << " <changefreq>#{item.changefreq}</changefreq>\n" if item.changefreq item_string << " <priority>#{item.priority}</priority>\n" if item.priority item_string << " </url>\n" item_results << item_string end result << item_results.join("") result << "</urlset>\n" result end
ruby
def render_string result = '<?xml version="1.0" encoding="UTF-8"?>' + "\n<urlset" XmlSitemap::MAP_SCHEMA_OPTIONS.each do |key, val| result << ' ' + key + '="' + val + '"' end result << ">\n" item_results = [] @items.each do |item| item_string = " <url>\n" item_string << " <loc>#{CGI::escapeHTML(item.target)}</loc>\n" # Format and image tag specifications found at http://support.google.com/webmasters/bin/answer.py?hl=en&answer=178636 if item.image_location item_string << " <image:image>\n" item_string << " <image:loc>#{CGI::escapeHTML(item.image_location)}</image:loc>\n" item_string << " <image:caption>#{CGI::escapeHTML(item.image_caption)}</image:caption>\n" if item.image_caption item_string << " <image:title>#{CGI::escapeHTML(item.image_title)}</image:title>\n" if item.image_title item_string << " <image:license>#{CGI::escapeHTML(item.image_license)}</image:license>\n" if item.image_license item_string << " <image:geo_location>#{CGI::escapeHTML(item.image_geolocation)}</image:geo_location>\n" if item.image_geolocation item_string << " </image:image>\n" end # Format and video tag specifications found at http://support.google.com/webmasters/bin/answer.py?hl=en&answer=80472&topic=10079&ctx=topic#2 if item.video_thumbnail_location && item.video_title && item.video_description && (item.video_content_location || item.video_player_location) item_string << " <video:video>\n" item_string << " <video:thumbnail_loc>#{CGI::escapeHTML(item.video_thumbnail_location)}</video:thumbnail_loc>\n" item_string << " <video:title>#{CGI::escapeHTML(item.video_title)}</video:title>\n" item_string << " <video:description>#{CGI::escapeHTML(item.video_description)}</video:description>\n" item_string << " <video:content_loc>#{CGI::escapeHTML(item.video_content_location)}</video:content_loc>\n" if item.video_content_location item_string << " <video:player_loc>#{CGI::escapeHTML(item.video_player_location)}</video:player_loc>\n" if item.video_player_location item_string << " <video:duration>#{CGI::escapeHTML(item.video_duration.to_s)}</video:duration>\n" if item.video_duration item_string << " <video:expiration_date>#{item.video_expiration_date_value}</video:expiration_date>\n" if item.video_expiration_date item_string << " <video:rating>#{CGI::escapeHTML(item.video_rating.to_s)}</video:rating>\n" if item.video_rating item_string << " <video:view_count>#{CGI::escapeHTML(item.video_view_count.to_s)}</video:view_count>\n" if item.video_view_count item_string << " <video:publication_date>#{item.video_publication_date_value}</video:publication_date>\n" if item.video_publication_date item_string << " <video:family_friendly>#{CGI::escapeHTML(item.video_family_friendly)}</video:family_friendly>\n" if item.video_family_friendly item_string << " <video:category>#{CGI::escapeHTML(item.video_category)}</video:category>\n" if item.video_category item_string << " <video:restriction relationship=\"allow\">#{CGI::escapeHTML(item.video_restriction)}</video:restriction>\n" if item.video_restriction item_string << " <video:gallery_loc>#{CGI::escapeHTML(item.video_gallery_location)}</video:gallery_loc>\n" if item.video_gallery_location item_string << " <video:price currency=\"USD\">#{CGI::escapeHTML(item.video_price.to_s)}</video:price>\n" if item.video_price item_string << " <video:requires_subscription>#{CGI::escapeHTML(item.video_requires_subscription)}</video:requires_subscription>\n" if item.video_requires_subscription item_string << " <video:uploader>#{CGI::escapeHTML(item.video_uploader)}</video:uploader>\n" if item.video_uploader item_string << " <video:platform relationship=\"allow\">#{CGI::escapeHTML(item.video_platform)}</video:platform>\n" if item.video_platform item_string << " <video:live>#{CGI::escapeHTML(item.video_live)}</video:live>\n" if item.video_live item_string << " </video:video>\n" end item_string << " <lastmod>#{item.lastmod_value}</lastmod>\n" item_string << " <changefreq>#{item.changefreq}</changefreq>\n" if item.changefreq item_string << " <priority>#{item.priority}</priority>\n" if item.priority item_string << " </url>\n" item_results << item_string end result << item_results.join("") result << "</urlset>\n" result end
[ "def", "render_string", "result", "=", "'<?xml version=\"1.0\" encoding=\"UTF-8\"?>'", "+", "\"\\n<urlset\"", "XmlSitemap", "::", "MAP_SCHEMA_OPTIONS", ".", "each", "do", "|", "key", ",", "val", "|", "result", "<<", "' '", "+", "key", "+", "'=\"'", "+", "val", "+", "'\"'", "end", "result", "<<", "\">\\n\"", "item_results", "=", "[", "]", "@items", ".", "each", "do", "|", "item", "|", "item_string", "=", "\" <url>\\n\"", "item_string", "<<", "\" <loc>#{CGI::escapeHTML(item.target)}</loc>\\n\"", "# Format and image tag specifications found at http://support.google.com/webmasters/bin/answer.py?hl=en&answer=178636", "if", "item", ".", "image_location", "item_string", "<<", "\" <image:image>\\n\"", "item_string", "<<", "\" <image:loc>#{CGI::escapeHTML(item.image_location)}</image:loc>\\n\"", "item_string", "<<", "\" <image:caption>#{CGI::escapeHTML(item.image_caption)}</image:caption>\\n\"", "if", "item", ".", "image_caption", "item_string", "<<", "\" <image:title>#{CGI::escapeHTML(item.image_title)}</image:title>\\n\"", "if", "item", ".", "image_title", "item_string", "<<", "\" <image:license>#{CGI::escapeHTML(item.image_license)}</image:license>\\n\"", "if", "item", ".", "image_license", "item_string", "<<", "\" <image:geo_location>#{CGI::escapeHTML(item.image_geolocation)}</image:geo_location>\\n\"", "if", "item", ".", "image_geolocation", "item_string", "<<", "\" </image:image>\\n\"", "end", "# Format and video tag specifications found at http://support.google.com/webmasters/bin/answer.py?hl=en&answer=80472&topic=10079&ctx=topic#2", "if", "item", ".", "video_thumbnail_location", "&&", "item", ".", "video_title", "&&", "item", ".", "video_description", "&&", "(", "item", ".", "video_content_location", "||", "item", ".", "video_player_location", ")", "item_string", "<<", "\" <video:video>\\n\"", "item_string", "<<", "\" <video:thumbnail_loc>#{CGI::escapeHTML(item.video_thumbnail_location)}</video:thumbnail_loc>\\n\"", "item_string", "<<", "\" <video:title>#{CGI::escapeHTML(item.video_title)}</video:title>\\n\"", "item_string", "<<", "\" <video:description>#{CGI::escapeHTML(item.video_description)}</video:description>\\n\"", "item_string", "<<", "\" <video:content_loc>#{CGI::escapeHTML(item.video_content_location)}</video:content_loc>\\n\"", "if", "item", ".", "video_content_location", "item_string", "<<", "\" <video:player_loc>#{CGI::escapeHTML(item.video_player_location)}</video:player_loc>\\n\"", "if", "item", ".", "video_player_location", "item_string", "<<", "\" <video:duration>#{CGI::escapeHTML(item.video_duration.to_s)}</video:duration>\\n\"", "if", "item", ".", "video_duration", "item_string", "<<", "\" <video:expiration_date>#{item.video_expiration_date_value}</video:expiration_date>\\n\"", "if", "item", ".", "video_expiration_date", "item_string", "<<", "\" <video:rating>#{CGI::escapeHTML(item.video_rating.to_s)}</video:rating>\\n\"", "if", "item", ".", "video_rating", "item_string", "<<", "\" <video:view_count>#{CGI::escapeHTML(item.video_view_count.to_s)}</video:view_count>\\n\"", "if", "item", ".", "video_view_count", "item_string", "<<", "\" <video:publication_date>#{item.video_publication_date_value}</video:publication_date>\\n\"", "if", "item", ".", "video_publication_date", "item_string", "<<", "\" <video:family_friendly>#{CGI::escapeHTML(item.video_family_friendly)}</video:family_friendly>\\n\"", "if", "item", ".", "video_family_friendly", "item_string", "<<", "\" <video:category>#{CGI::escapeHTML(item.video_category)}</video:category>\\n\"", "if", "item", ".", "video_category", "item_string", "<<", "\" <video:restriction relationship=\\\"allow\\\">#{CGI::escapeHTML(item.video_restriction)}</video:restriction>\\n\"", "if", "item", ".", "video_restriction", "item_string", "<<", "\" <video:gallery_loc>#{CGI::escapeHTML(item.video_gallery_location)}</video:gallery_loc>\\n\"", "if", "item", ".", "video_gallery_location", "item_string", "<<", "\" <video:price currency=\\\"USD\\\">#{CGI::escapeHTML(item.video_price.to_s)}</video:price>\\n\"", "if", "item", ".", "video_price", "item_string", "<<", "\" <video:requires_subscription>#{CGI::escapeHTML(item.video_requires_subscription)}</video:requires_subscription>\\n\"", "if", "item", ".", "video_requires_subscription", "item_string", "<<", "\" <video:uploader>#{CGI::escapeHTML(item.video_uploader)}</video:uploader>\\n\"", "if", "item", ".", "video_uploader", "item_string", "<<", "\" <video:platform relationship=\\\"allow\\\">#{CGI::escapeHTML(item.video_platform)}</video:platform>\\n\"", "if", "item", ".", "video_platform", "item_string", "<<", "\" <video:live>#{CGI::escapeHTML(item.video_live)}</video:live>\\n\"", "if", "item", ".", "video_live", "item_string", "<<", "\" </video:video>\\n\"", "end", "item_string", "<<", "\" <lastmod>#{item.lastmod_value}</lastmod>\\n\"", "item_string", "<<", "\" <changefreq>#{item.changefreq}</changefreq>\\n\"", "if", "item", ".", "changefreq", "item_string", "<<", "\" <priority>#{item.priority}</priority>\\n\"", "if", "item", ".", "priority", "item_string", "<<", "\" </url>\\n\"", "item_results", "<<", "item_string", "end", "result", "<<", "item_results", ".", "join", "(", "\"\"", ")", "result", "<<", "\"</urlset>\\n\"", "result", "end" ]
Render with plain strings
[ "Render", "with", "plain", "strings" ]
a9b510d49297d219c5b19a9c778cb8c6f0f1ae16
https://github.com/sosedoff/xml-sitemap/blob/a9b510d49297d219c5b19a9c778cb8c6f0f1ae16/lib/xml-sitemap/render_engine.rb#L121-L183
1,192
SimplyBuilt/SimonSays
lib/simon_says/authorizer.rb
SimonSays.Authorizer.find_resource
def find_resource(resource, options = {}) resource = resource.to_s scope, query = resource_scope_and_query(resource, options) through = options[:through] ? options[:through].to_s : nil assoc = through || (options[:from] ? resource.pluralize : nil) scope = scope.send(assoc) if assoc && scope.respond_to?(assoc) record = scope.where(query).first! if through instance_variable_set "@#{through.singularize}", record record = record.send(resource) end instance_variable_set "@#{resource}", record end
ruby
def find_resource(resource, options = {}) resource = resource.to_s scope, query = resource_scope_and_query(resource, options) through = options[:through] ? options[:through].to_s : nil assoc = through || (options[:from] ? resource.pluralize : nil) scope = scope.send(assoc) if assoc && scope.respond_to?(assoc) record = scope.where(query).first! if through instance_variable_set "@#{through.singularize}", record record = record.send(resource) end instance_variable_set "@#{resource}", record end
[ "def", "find_resource", "(", "resource", ",", "options", "=", "{", "}", ")", "resource", "=", "resource", ".", "to_s", "scope", ",", "query", "=", "resource_scope_and_query", "(", "resource", ",", "options", ")", "through", "=", "options", "[", ":through", "]", "?", "options", "[", ":through", "]", ".", "to_s", ":", "nil", "assoc", "=", "through", "||", "(", "options", "[", ":from", "]", "?", "resource", ".", "pluralize", ":", "nil", ")", "scope", "=", "scope", ".", "send", "(", "assoc", ")", "if", "assoc", "&&", "scope", ".", "respond_to?", "(", "assoc", ")", "record", "=", "scope", ".", "where", "(", "query", ")", ".", "first!", "if", "through", "instance_variable_set", "\"@#{through.singularize}\"", ",", "record", "record", "=", "record", ".", "send", "(", "resource", ")", "end", "instance_variable_set", "\"@#{resource}\"", ",", "record", "end" ]
Internal find_resource instance method @private @param [Symbol, String] resource name of resource to find @param [Hash] options finder options
[ "Internal", "find_resource", "instance", "method" ]
d3e937f49118c7b7a405fed806d043e412adac2b
https://github.com/SimplyBuilt/SimonSays/blob/d3e937f49118c7b7a405fed806d043e412adac2b/lib/simon_says/authorizer.rb#L123-L140
1,193
SimplyBuilt/SimonSays
lib/simon_says/authorizer.rb
SimonSays.Authorizer.authorize
def authorize(required = nil, options) if through = options[:through] name = through.to_s.singularize.to_sym else name = options[:resource] end record = instance_variable_get("@#{name}") if record.nil? # must be devise scope record = send("current_#{name}") send "authenticate_#{name}!" end role_attr = record.class.role_attribute_name actual = record.send(role_attr) required ||= options[role_attr] required = [required] unless Array === required # actual roles must have at least # one required role (array intersection) ((required & actual).size > 0).tap do |res| raise Denied.new(role_attr, required, actual) unless res end end
ruby
def authorize(required = nil, options) if through = options[:through] name = through.to_s.singularize.to_sym else name = options[:resource] end record = instance_variable_get("@#{name}") if record.nil? # must be devise scope record = send("current_#{name}") send "authenticate_#{name}!" end role_attr = record.class.role_attribute_name actual = record.send(role_attr) required ||= options[role_attr] required = [required] unless Array === required # actual roles must have at least # one required role (array intersection) ((required & actual).size > 0).tap do |res| raise Denied.new(role_attr, required, actual) unless res end end
[ "def", "authorize", "(", "required", "=", "nil", ",", "options", ")", "if", "through", "=", "options", "[", ":through", "]", "name", "=", "through", ".", "to_s", ".", "singularize", ".", "to_sym", "else", "name", "=", "options", "[", ":resource", "]", "end", "record", "=", "instance_variable_get", "(", "\"@#{name}\"", ")", "if", "record", ".", "nil?", "# must be devise scope", "record", "=", "send", "(", "\"current_#{name}\"", ")", "send", "\"authenticate_#{name}!\"", "end", "role_attr", "=", "record", ".", "class", ".", "role_attribute_name", "actual", "=", "record", ".", "send", "(", "role_attr", ")", "required", "||=", "options", "[", "role_attr", "]", "required", "=", "[", "required", "]", "unless", "Array", "===", "required", "# actual roles must have at least", "# one required role (array intersection)", "(", "(", "required", "&", "actual", ")", ".", "size", ">", "0", ")", ".", "tap", "do", "|", "res", "|", "raise", "Denied", ".", "new", "(", "role_attr", ",", "required", ",", "actual", ")", "unless", "res", "end", "end" ]
Internal authorize instance method @private @param [Symbol, String] one or more required roles @param [Hash] options authorizer options
[ "Internal", "authorize", "instance", "method" ]
d3e937f49118c7b7a405fed806d043e412adac2b
https://github.com/SimplyBuilt/SimonSays/blob/d3e937f49118c7b7a405fed806d043e412adac2b/lib/simon_says/authorizer.rb#L147-L172
1,194
sosedoff/xml-sitemap
lib/xml-sitemap/index.rb
XmlSitemap.Index.add
def add(map, use_offsets=true) raise ArgumentError, 'XmlSitemap::Map object required!' unless map.kind_of?(XmlSitemap::Map) raise ArgumentError, 'Map is empty!' if map.empty? @maps << { :loc => use_offsets ? map.index_url(@offsets[map.group], @secure) : map.plain_index_url(@secure), :lastmod => map.created_at.utc.iso8601 } @offsets[map.group] += 1 end
ruby
def add(map, use_offsets=true) raise ArgumentError, 'XmlSitemap::Map object required!' unless map.kind_of?(XmlSitemap::Map) raise ArgumentError, 'Map is empty!' if map.empty? @maps << { :loc => use_offsets ? map.index_url(@offsets[map.group], @secure) : map.plain_index_url(@secure), :lastmod => map.created_at.utc.iso8601 } @offsets[map.group] += 1 end
[ "def", "add", "(", "map", ",", "use_offsets", "=", "true", ")", "raise", "ArgumentError", ",", "'XmlSitemap::Map object required!'", "unless", "map", ".", "kind_of?", "(", "XmlSitemap", "::", "Map", ")", "raise", "ArgumentError", ",", "'Map is empty!'", "if", "map", ".", "empty?", "@maps", "<<", "{", ":loc", "=>", "use_offsets", "?", "map", ".", "index_url", "(", "@offsets", "[", "map", ".", "group", "]", ",", "@secure", ")", ":", "map", ".", "plain_index_url", "(", "@secure", ")", ",", ":lastmod", "=>", "map", ".", "created_at", ".", "utc", ".", "iso8601", "}", "@offsets", "[", "map", ".", "group", "]", "+=", "1", "end" ]
Initialize a new Index instance opts - Index options opts[:secure] - Force HTTPS for all items. (default: false) Add map object to index map - XmlSitemap::Map instance
[ "Initialize", "a", "new", "Index", "instance" ]
a9b510d49297d219c5b19a9c778cb8c6f0f1ae16
https://github.com/sosedoff/xml-sitemap/blob/a9b510d49297d219c5b19a9c778cb8c6f0f1ae16/lib/xml-sitemap/index.rb#L23-L32
1,195
sosedoff/xml-sitemap
lib/xml-sitemap/index.rb
XmlSitemap.Index.render
def render xml = Builder::XmlMarkup.new(:indent => 2) xml.instruct!(:xml, :version => '1.0', :encoding => 'UTF-8') xml.sitemapindex(XmlSitemap::INDEX_SCHEMA_OPTIONS) { |s| @maps.each do |item| s.sitemap do |m| m.loc item[:loc] m.lastmod item[:lastmod] end end }.to_s end
ruby
def render xml = Builder::XmlMarkup.new(:indent => 2) xml.instruct!(:xml, :version => '1.0', :encoding => 'UTF-8') xml.sitemapindex(XmlSitemap::INDEX_SCHEMA_OPTIONS) { |s| @maps.each do |item| s.sitemap do |m| m.loc item[:loc] m.lastmod item[:lastmod] end end }.to_s end
[ "def", "render", "xml", "=", "Builder", "::", "XmlMarkup", ".", "new", "(", ":indent", "=>", "2", ")", "xml", ".", "instruct!", "(", ":xml", ",", ":version", "=>", "'1.0'", ",", ":encoding", "=>", "'UTF-8'", ")", "xml", ".", "sitemapindex", "(", "XmlSitemap", "::", "INDEX_SCHEMA_OPTIONS", ")", "{", "|", "s", "|", "@maps", ".", "each", "do", "|", "item", "|", "s", ".", "sitemap", "do", "|", "m", "|", "m", ".", "loc", "item", "[", ":loc", "]", "m", ".", "lastmod", "item", "[", ":lastmod", "]", "end", "end", "}", ".", "to_s", "end" ]
Generate sitemap XML index
[ "Generate", "sitemap", "XML", "index" ]
a9b510d49297d219c5b19a9c778cb8c6f0f1ae16
https://github.com/sosedoff/xml-sitemap/blob/a9b510d49297d219c5b19a9c778cb8c6f0f1ae16/lib/xml-sitemap/index.rb#L36-L47
1,196
sosedoff/xml-sitemap
lib/xml-sitemap/index.rb
XmlSitemap.Index.render_to
def render_to(path, options={}) overwrite = options[:overwrite] || true path = File.expand_path(path) if File.exists?(path) && !overwrite raise RuntimeError, "File already exists and not overwritable!" end File.open(path, 'w') { |f| f.write(self.render) } end
ruby
def render_to(path, options={}) overwrite = options[:overwrite] || true path = File.expand_path(path) if File.exists?(path) && !overwrite raise RuntimeError, "File already exists and not overwritable!" end File.open(path, 'w') { |f| f.write(self.render) } end
[ "def", "render_to", "(", "path", ",", "options", "=", "{", "}", ")", "overwrite", "=", "options", "[", ":overwrite", "]", "||", "true", "path", "=", "File", ".", "expand_path", "(", "path", ")", "if", "File", ".", "exists?", "(", "path", ")", "&&", "!", "overwrite", "raise", "RuntimeError", ",", "\"File already exists and not overwritable!\"", "end", "File", ".", "open", "(", "path", ",", "'w'", ")", "{", "|", "f", "|", "f", ".", "write", "(", "self", ".", "render", ")", "}", "end" ]
Render XML sitemap index into the file path - Output filename options - Options hash options[:ovewrite] - Overwrite file contents (default: true)
[ "Render", "XML", "sitemap", "index", "into", "the", "file" ]
a9b510d49297d219c5b19a9c778cb8c6f0f1ae16
https://github.com/sosedoff/xml-sitemap/blob/a9b510d49297d219c5b19a9c778cb8c6f0f1ae16/lib/xml-sitemap/index.rb#L56-L65
1,197
sosedoff/xml-sitemap
lib/xml-sitemap/map.rb
XmlSitemap.Map.add
def add(target, opts={}) raise RuntimeError, 'Only up to 50k records allowed!' if @items.size > 50000 raise ArgumentError, 'Target required!' if target.nil? raise ArgumentError, 'Target is empty!' if target.to_s.strip.empty? url = process_target(target) if url.length > 2048 raise ArgumentError, "Target can't be longer than 2,048 characters!" end opts[:updated] = @created_at unless opts.key?(:updated) item = XmlSitemap::Item.new(url, opts) @items << item item end
ruby
def add(target, opts={}) raise RuntimeError, 'Only up to 50k records allowed!' if @items.size > 50000 raise ArgumentError, 'Target required!' if target.nil? raise ArgumentError, 'Target is empty!' if target.to_s.strip.empty? url = process_target(target) if url.length > 2048 raise ArgumentError, "Target can't be longer than 2,048 characters!" end opts[:updated] = @created_at unless opts.key?(:updated) item = XmlSitemap::Item.new(url, opts) @items << item item end
[ "def", "add", "(", "target", ",", "opts", "=", "{", "}", ")", "raise", "RuntimeError", ",", "'Only up to 50k records allowed!'", "if", "@items", ".", "size", ">", "50000", "raise", "ArgumentError", ",", "'Target required!'", "if", "target", ".", "nil?", "raise", "ArgumentError", ",", "'Target is empty!'", "if", "target", ".", "to_s", ".", "strip", ".", "empty?", "url", "=", "process_target", "(", "target", ")", "if", "url", ".", "length", ">", "2048", "raise", "ArgumentError", ",", "\"Target can't be longer than 2,048 characters!\"", "end", "opts", "[", ":updated", "]", "=", "@created_at", "unless", "opts", ".", "key?", "(", ":updated", ")", "item", "=", "XmlSitemap", "::", "Item", ".", "new", "(", "url", ",", "opts", ")", "@items", "<<", "item", "item", "end" ]
Initializa a new Map instance domain - Primary domain for the map (required) opts - Map options opts[:home] - Automatic homepage creation. To disable set to false. (default: true) opts[:secure] - Force HTTPS for all items. (default: false) opts[:time] - Set default lastmod timestamp for items (default: current time) opts[:group] - Group name for sitemap index. (default: sitemap) opts[:root] - Force all links to fall under the main domain. You can add full urls (not paths) if set to false. (default: true) Adds a new item to the map target - Path or url opts - Item options opts[:updated] - Lastmod property of the item opts[:period] - Update frequency. opts[:priority] - Item priority. opts[:validate_time] - Skip time validation if want to insert raw strings.
[ "Initializa", "a", "new", "Map", "instance" ]
a9b510d49297d219c5b19a9c778cb8c6f0f1ae16
https://github.com/sosedoff/xml-sitemap/blob/a9b510d49297d219c5b19a9c778cb8c6f0f1ae16/lib/xml-sitemap/map.rb#L49-L64
1,198
sosedoff/xml-sitemap
lib/xml-sitemap/map.rb
XmlSitemap.Map.render_to
def render_to(path, options={}) overwrite = options[:overwrite] == true || true compress = options[:gzip] == true || false path = File.expand_path(path) path << ".gz" unless path =~ /\.gz\z/i if compress if File.exists?(path) && !overwrite raise RuntimeError, "File already exists and not overwritable!" end File.open(path, 'wb') do |f| unless compress f.write(self.render) else gz = Zlib::GzipWriter.new(f) gz.write(self.render) gz.close end end end
ruby
def render_to(path, options={}) overwrite = options[:overwrite] == true || true compress = options[:gzip] == true || false path = File.expand_path(path) path << ".gz" unless path =~ /\.gz\z/i if compress if File.exists?(path) && !overwrite raise RuntimeError, "File already exists and not overwritable!" end File.open(path, 'wb') do |f| unless compress f.write(self.render) else gz = Zlib::GzipWriter.new(f) gz.write(self.render) gz.close end end end
[ "def", "render_to", "(", "path", ",", "options", "=", "{", "}", ")", "overwrite", "=", "options", "[", ":overwrite", "]", "==", "true", "||", "true", "compress", "=", "options", "[", ":gzip", "]", "==", "true", "||", "false", "path", "=", "File", ".", "expand_path", "(", "path", ")", "path", "<<", "\".gz\"", "unless", "path", "=~", "/", "\\.", "\\z", "/i", "if", "compress", "if", "File", ".", "exists?", "(", "path", ")", "&&", "!", "overwrite", "raise", "RuntimeError", ",", "\"File already exists and not overwritable!\"", "end", "File", ".", "open", "(", "path", ",", "'wb'", ")", "do", "|", "f", "|", "unless", "compress", "f", ".", "write", "(", "self", ".", "render", ")", "else", "gz", "=", "Zlib", "::", "GzipWriter", ".", "new", "(", "f", ")", "gz", ".", "write", "(", "self", ".", "render", ")", "gz", ".", "close", "end", "end", "end" ]
Render XML sitemap into the file path - Output filename options - Options hash options[:overwrite] - Overwrite the file contents (default: true) options[:gzip] - Gzip file contents (default: false)
[ "Render", "XML", "sitemap", "into", "the", "file" ]
a9b510d49297d219c5b19a9c778cb8c6f0f1ae16
https://github.com/sosedoff/xml-sitemap/blob/a9b510d49297d219c5b19a9c778cb8c6f0f1ae16/lib/xml-sitemap/map.rb#L118-L138
1,199
sosedoff/xml-sitemap
lib/xml-sitemap/map.rb
XmlSitemap.Map.process_target
def process_target(str) if @root == true url(str =~ /^\// ? str : "/#{str}") else str =~ /^(http|https)/i ? str : url(str =~ /^\// ? str : "/#{str}") end end
ruby
def process_target(str) if @root == true url(str =~ /^\// ? str : "/#{str}") else str =~ /^(http|https)/i ? str : url(str =~ /^\// ? str : "/#{str}") end end
[ "def", "process_target", "(", "str", ")", "if", "@root", "==", "true", "url", "(", "str", "=~", "/", "\\/", "/", "?", "str", ":", "\"/#{str}\"", ")", "else", "str", "=~", "/", "/i", "?", "str", ":", "url", "(", "str", "=~", "/", "\\/", "/", "?", "str", ":", "\"/#{str}\"", ")", "end", "end" ]
Process target path or url
[ "Process", "target", "path", "or", "url" ]
a9b510d49297d219c5b19a9c778cb8c6f0f1ae16
https://github.com/sosedoff/xml-sitemap/blob/a9b510d49297d219c5b19a9c778cb8c6f0f1ae16/lib/xml-sitemap/map.rb#L144-L150