id
int32
0
24.9k
repo
stringlengths
5
58
path
stringlengths
9
168
func_name
stringlengths
9
130
original_string
stringlengths
66
10.5k
language
stringclasses
1 value
code
stringlengths
66
10.5k
code_tokens
list
docstring
stringlengths
8
16k
docstring_tokens
list
sha
stringlengths
40
40
url
stringlengths
94
266
9,800
ideonetwork/lato-blog
app/controllers/lato_blog/back/tags_controller.rb
LatoBlog.Back::TagsController.edit
def edit core__set_header_active_page_title(LANGUAGES[:lato_blog][:pages][:tags_edit]) @tag = LatoBlog::Tag.find_by(id: params[:id]) return unless check_tag_presence if @tag.meta_language != cookies[:lato_blog__current_language] set_current_language @tag.meta_language end end
ruby
def edit core__set_header_active_page_title(LANGUAGES[:lato_blog][:pages][:tags_edit]) @tag = LatoBlog::Tag.find_by(id: params[:id]) return unless check_tag_presence if @tag.meta_language != cookies[:lato_blog__current_language] set_current_language @tag.meta_language end end
[ "def", "edit", "core__set_header_active_page_title", "(", "LANGUAGES", "[", ":lato_blog", "]", "[", ":pages", "]", "[", ":tags_edit", "]", ")", "@tag", "=", "LatoBlog", "::", "Tag", ".", "find_by", "(", "id", ":", "params", "[", ":id", "]", ")", "return", "unless", "check_tag_presence", "if", "@tag", ".", "meta_language", "!=", "cookies", "[", ":lato_blog__current_language", "]", "set_current_language", "@tag", ".", "meta_language", "end", "end" ]
This function show the view to edit a tag.
[ "This", "function", "show", "the", "view", "to", "edit", "a", "tag", "." ]
a0d92de299a0e285851743b9d4a902f611187cba
https://github.com/ideonetwork/lato-blog/blob/a0d92de299a0e285851743b9d4a902f611187cba/app/controllers/lato_blog/back/tags_controller.rb#L55-L63
9,801
ideonetwork/lato-blog
app/controllers/lato_blog/back/tags_controller.rb
LatoBlog.Back::TagsController.update
def update @tag = LatoBlog::Tag.find_by(id: params[:id]) return unless check_tag_presence if [email protected](edit_tag_params) flash[:danger] = @tag.errors.full_messages.to_sentence redirect_to lato_blog.edit_tag_path(@tag.id) return end flash[:success] = LANGUAGES[:lato_blog][:flashes][:tag_update_success] redirect_to lato_blog.tag_path(@tag.id) end
ruby
def update @tag = LatoBlog::Tag.find_by(id: params[:id]) return unless check_tag_presence if [email protected](edit_tag_params) flash[:danger] = @tag.errors.full_messages.to_sentence redirect_to lato_blog.edit_tag_path(@tag.id) return end flash[:success] = LANGUAGES[:lato_blog][:flashes][:tag_update_success] redirect_to lato_blog.tag_path(@tag.id) end
[ "def", "update", "@tag", "=", "LatoBlog", "::", "Tag", ".", "find_by", "(", "id", ":", "params", "[", ":id", "]", ")", "return", "unless", "check_tag_presence", "if", "!", "@tag", ".", "update", "(", "edit_tag_params", ")", "flash", "[", ":danger", "]", "=", "@tag", ".", "errors", ".", "full_messages", ".", "to_sentence", "redirect_to", "lato_blog", ".", "edit_tag_path", "(", "@tag", ".", "id", ")", "return", "end", "flash", "[", ":success", "]", "=", "LANGUAGES", "[", ":lato_blog", "]", "[", ":flashes", "]", "[", ":tag_update_success", "]", "redirect_to", "lato_blog", ".", "tag_path", "(", "@tag", ".", "id", ")", "end" ]
This function updates a tag.
[ "This", "function", "updates", "a", "tag", "." ]
a0d92de299a0e285851743b9d4a902f611187cba
https://github.com/ideonetwork/lato-blog/blob/a0d92de299a0e285851743b9d4a902f611187cba/app/controllers/lato_blog/back/tags_controller.rb#L66-L78
9,802
ideonetwork/lato-blog
app/controllers/lato_blog/back/tags_controller.rb
LatoBlog.Back::TagsController.destroy
def destroy @tag = LatoBlog::Tag.find_by(id: params[:id]) return unless check_tag_presence if [email protected] flash[:danger] = @tag.tag_parent.errors.full_messages.to_sentence redirect_to lato_blog.edit_tag_path(@tag.id) return end flash[:success] = LANGUAGES[:lato_blog][:flashes][:tag_destroy_success] redirect_to lato_blog.categories_path(status: 'deleted') end
ruby
def destroy @tag = LatoBlog::Tag.find_by(id: params[:id]) return unless check_tag_presence if [email protected] flash[:danger] = @tag.tag_parent.errors.full_messages.to_sentence redirect_to lato_blog.edit_tag_path(@tag.id) return end flash[:success] = LANGUAGES[:lato_blog][:flashes][:tag_destroy_success] redirect_to lato_blog.categories_path(status: 'deleted') end
[ "def", "destroy", "@tag", "=", "LatoBlog", "::", "Tag", ".", "find_by", "(", "id", ":", "params", "[", ":id", "]", ")", "return", "unless", "check_tag_presence", "if", "!", "@tag", ".", "destroy", "flash", "[", ":danger", "]", "=", "@tag", ".", "tag_parent", ".", "errors", ".", "full_messages", ".", "to_sentence", "redirect_to", "lato_blog", ".", "edit_tag_path", "(", "@tag", ".", "id", ")", "return", "end", "flash", "[", ":success", "]", "=", "LANGUAGES", "[", ":lato_blog", "]", "[", ":flashes", "]", "[", ":tag_destroy_success", "]", "redirect_to", "lato_blog", ".", "categories_path", "(", "status", ":", "'deleted'", ")", "end" ]
This function destroyes a tag.
[ "This", "function", "destroyes", "a", "tag", "." ]
a0d92de299a0e285851743b9d4a902f611187cba
https://github.com/ideonetwork/lato-blog/blob/a0d92de299a0e285851743b9d4a902f611187cba/app/controllers/lato_blog/back/tags_controller.rb#L81-L93
9,803
mixflame/Hokkaido
lib/gem_modifier.rb
Hokkaido.GemModifier.parse_gem
def parse_gem(init_lib) # puts "Processing: #{init_lib}" # don't ask init_path = init_lib init_file = File.read(init_lib) current_file = "" init_file.each_line do |line| if line.strip =~ /^require/ parser = RubyParser.new sexp = parser.parse(line) call = sexp[2] unless call == :require # WEIRD SHIT IS HAPPENING current_file += line next end require_type = sexp[3][1][0] library = sexp[3][1][1] #p library if require_type == :str && library.match(@gem_name) # fold in full_rb_path = File.join([@lib_folder, "#{library}.rb"]) unless @require_libs.include?(full_rb_path) file_index = @require_libs.index(init_lib) insert_index = file_index @require_libs.insert insert_index, full_rb_path parse_gem(full_rb_path) end else current_file += "# FIXME: #require is not supported in RubyMotion\n" current_file += "# #{line}" next end # comment it out current_file += "# #{line}" next elsif line.strip =~ /^autoload/ # same as require parser = RubyParser.new sexp = parser.parse(line) call = sexp[2] unless call == :autoload # WEIRD SHIT IS HAPPENING current_file += line next end require_type = sexp[3][2][0] library = sexp[3][2][1] full_rb_path = File.join([@lib_folder, "#{library}.rb"]) unless @require_libs.include?(full_rb_path) file_index = @require_libs.index(init_lib) insert_index = file_index @require_libs.insert insert_index, full_rb_path parse_gem(full_rb_path) end # comment it out current_file += "# #{line}" next elsif line.strip =~ /^eval/ # reprint as a block # parser = RubyParser.new # sexp = parser.parse(line) # code_str = sexp[3][1][1] # new_eval = "eval do\n #{code_str}\nend\n" # current_file += "#{new_eval}" # next # produce a fixme current_file += "# FIXME: Cannot eval strings in RubyMotion. \n" current_file += "# Rewrite to use a block.. inbuilt hack will run \n" current_file += "# Change this: \n" current_file += "# eval %Q{ \n" current_file += '# def #{c}(string = nil) ' + "\n" current_file += "# To this \n" current_file += "# eval do \n" current_file += "# define_method(c) do |string| \n" current_file += "#{line}" next elsif line.strip =~ /^binding/ current_file += "# FIXME: binding is not supported in RubyMotion.\n" current_file += "#{line}" next end # dont intefere current_file += line end # replace file File.open(init_lib, 'w') {|f| f.write(current_file) } #unless TEST_MODE end
ruby
def parse_gem(init_lib) # puts "Processing: #{init_lib}" # don't ask init_path = init_lib init_file = File.read(init_lib) current_file = "" init_file.each_line do |line| if line.strip =~ /^require/ parser = RubyParser.new sexp = parser.parse(line) call = sexp[2] unless call == :require # WEIRD SHIT IS HAPPENING current_file += line next end require_type = sexp[3][1][0] library = sexp[3][1][1] #p library if require_type == :str && library.match(@gem_name) # fold in full_rb_path = File.join([@lib_folder, "#{library}.rb"]) unless @require_libs.include?(full_rb_path) file_index = @require_libs.index(init_lib) insert_index = file_index @require_libs.insert insert_index, full_rb_path parse_gem(full_rb_path) end else current_file += "# FIXME: #require is not supported in RubyMotion\n" current_file += "# #{line}" next end # comment it out current_file += "# #{line}" next elsif line.strip =~ /^autoload/ # same as require parser = RubyParser.new sexp = parser.parse(line) call = sexp[2] unless call == :autoload # WEIRD SHIT IS HAPPENING current_file += line next end require_type = sexp[3][2][0] library = sexp[3][2][1] full_rb_path = File.join([@lib_folder, "#{library}.rb"]) unless @require_libs.include?(full_rb_path) file_index = @require_libs.index(init_lib) insert_index = file_index @require_libs.insert insert_index, full_rb_path parse_gem(full_rb_path) end # comment it out current_file += "# #{line}" next elsif line.strip =~ /^eval/ # reprint as a block # parser = RubyParser.new # sexp = parser.parse(line) # code_str = sexp[3][1][1] # new_eval = "eval do\n #{code_str}\nend\n" # current_file += "#{new_eval}" # next # produce a fixme current_file += "# FIXME: Cannot eval strings in RubyMotion. \n" current_file += "# Rewrite to use a block.. inbuilt hack will run \n" current_file += "# Change this: \n" current_file += "# eval %Q{ \n" current_file += '# def #{c}(string = nil) ' + "\n" current_file += "# To this \n" current_file += "# eval do \n" current_file += "# define_method(c) do |string| \n" current_file += "#{line}" next elsif line.strip =~ /^binding/ current_file += "# FIXME: binding is not supported in RubyMotion.\n" current_file += "#{line}" next end # dont intefere current_file += line end # replace file File.open(init_lib, 'w') {|f| f.write(current_file) } #unless TEST_MODE end
[ "def", "parse_gem", "(", "init_lib", ")", "# puts \"Processing: #{init_lib}\"", "# don't ask", "init_path", "=", "init_lib", "init_file", "=", "File", ".", "read", "(", "init_lib", ")", "current_file", "=", "\"\"", "init_file", ".", "each_line", "do", "|", "line", "|", "if", "line", ".", "strip", "=~", "/", "/", "parser", "=", "RubyParser", ".", "new", "sexp", "=", "parser", ".", "parse", "(", "line", ")", "call", "=", "sexp", "[", "2", "]", "unless", "call", "==", ":require", "# WEIRD SHIT IS HAPPENING", "current_file", "+=", "line", "next", "end", "require_type", "=", "sexp", "[", "3", "]", "[", "1", "]", "[", "0", "]", "library", "=", "sexp", "[", "3", "]", "[", "1", "]", "[", "1", "]", "#p library", "if", "require_type", "==", ":str", "&&", "library", ".", "match", "(", "@gem_name", ")", "# fold in", "full_rb_path", "=", "File", ".", "join", "(", "[", "@lib_folder", ",", "\"#{library}.rb\"", "]", ")", "unless", "@require_libs", ".", "include?", "(", "full_rb_path", ")", "file_index", "=", "@require_libs", ".", "index", "(", "init_lib", ")", "insert_index", "=", "file_index", "@require_libs", ".", "insert", "insert_index", ",", "full_rb_path", "parse_gem", "(", "full_rb_path", ")", "end", "else", "current_file", "+=", "\"# FIXME: #require is not supported in RubyMotion\\n\"", "current_file", "+=", "\"# #{line}\"", "next", "end", "# comment it out", "current_file", "+=", "\"# #{line}\"", "next", "elsif", "line", ".", "strip", "=~", "/", "/", "# same as require", "parser", "=", "RubyParser", ".", "new", "sexp", "=", "parser", ".", "parse", "(", "line", ")", "call", "=", "sexp", "[", "2", "]", "unless", "call", "==", ":autoload", "# WEIRD SHIT IS HAPPENING", "current_file", "+=", "line", "next", "end", "require_type", "=", "sexp", "[", "3", "]", "[", "2", "]", "[", "0", "]", "library", "=", "sexp", "[", "3", "]", "[", "2", "]", "[", "1", "]", "full_rb_path", "=", "File", ".", "join", "(", "[", "@lib_folder", ",", "\"#{library}.rb\"", "]", ")", "unless", "@require_libs", ".", "include?", "(", "full_rb_path", ")", "file_index", "=", "@require_libs", ".", "index", "(", "init_lib", ")", "insert_index", "=", "file_index", "@require_libs", ".", "insert", "insert_index", ",", "full_rb_path", "parse_gem", "(", "full_rb_path", ")", "end", "# comment it out", "current_file", "+=", "\"# #{line}\"", "next", "elsif", "line", ".", "strip", "=~", "/", "/", "# reprint as a block", "# parser = RubyParser.new", "# sexp = parser.parse(line)", "# code_str = sexp[3][1][1]", "# new_eval = \"eval do\\n #{code_str}\\nend\\n\"", "# current_file += \"#{new_eval}\"", "# next", "# produce a fixme", "current_file", "+=", "\"# FIXME: Cannot eval strings in RubyMotion. \\n\"", "current_file", "+=", "\"# Rewrite to use a block.. inbuilt hack will run \\n\"", "current_file", "+=", "\"# Change this: \\n\"", "current_file", "+=", "\"# eval %Q{ \\n\"", "current_file", "+=", "'# def #{c}(string = nil) '", "+", "\"\\n\"", "current_file", "+=", "\"# To this \\n\"", "current_file", "+=", "\"# eval do \\n\"", "current_file", "+=", "\"# define_method(c) do |string| \\n\"", "current_file", "+=", "\"#{line}\"", "next", "elsif", "line", ".", "strip", "=~", "/", "/", "current_file", "+=", "\"# FIXME: binding is not supported in RubyMotion.\\n\"", "current_file", "+=", "\"#{line}\"", "next", "end", "# dont intefere", "current_file", "+=", "line", "end", "# replace file", "File", ".", "open", "(", "init_lib", ",", "'w'", ")", "{", "|", "f", "|", "f", ".", "write", "(", "current_file", ")", "}", "#unless TEST_MODE", "end" ]
def simulate! puts "simulator not implemented..." end
[ "def", "simulate!", "puts", "simulator", "not", "implemented", "...", "end" ]
bf21e7915044576ef74495ccd70d7ff5ee1bcd4b
https://github.com/mixflame/Hokkaido/blob/bf21e7915044576ef74495ccd70d7ff5ee1bcd4b/lib/gem_modifier.rb#L54-L156
9,804
ashiksp/smart_que
lib/smart_que/consumers/base.rb
Consumers.Base.start
def start channel.prefetch(10) queue.subscribe(manual_ack: true, exclusive: false) do |delivery_info, metadata, payload| begin body = JSON.parse(payload).with_indifferent_access status = run(body) rescue => e status = :error end if status == :ok channel.ack(delivery_info.delivery_tag) elsif status == :retry channel.reject(delivery_info.delivery_tag, true) else # :error, nil etc channel.reject(delivery_info.delivery_tag, false) end end wait_for_threads end
ruby
def start channel.prefetch(10) queue.subscribe(manual_ack: true, exclusive: false) do |delivery_info, metadata, payload| begin body = JSON.parse(payload).with_indifferent_access status = run(body) rescue => e status = :error end if status == :ok channel.ack(delivery_info.delivery_tag) elsif status == :retry channel.reject(delivery_info.delivery_tag, true) else # :error, nil etc channel.reject(delivery_info.delivery_tag, false) end end wait_for_threads end
[ "def", "start", "channel", ".", "prefetch", "(", "10", ")", "queue", ".", "subscribe", "(", "manual_ack", ":", "true", ",", "exclusive", ":", "false", ")", "do", "|", "delivery_info", ",", "metadata", ",", "payload", "|", "begin", "body", "=", "JSON", ".", "parse", "(", "payload", ")", ".", "with_indifferent_access", "status", "=", "run", "(", "body", ")", "rescue", "=>", "e", "status", "=", ":error", "end", "if", "status", "==", ":ok", "channel", ".", "ack", "(", "delivery_info", ".", "delivery_tag", ")", "elsif", "status", "==", ":retry", "channel", ".", "reject", "(", "delivery_info", ".", "delivery_tag", ",", "true", ")", "else", "# :error, nil etc", "channel", ".", "reject", "(", "delivery_info", ".", "delivery_tag", ",", "false", ")", "end", "end", "wait_for_threads", "end" ]
Method which kick start the consumer process thread
[ "Method", "which", "kick", "start", "the", "consumer", "process", "thread" ]
3b16451e38c430f05c0ac5fb111cfc96e4dc34b8
https://github.com/ashiksp/smart_que/blob/3b16451e38c430f05c0ac5fb111cfc96e4dc34b8/lib/smart_que/consumers/base.rb#L40-L60
9,805
tmcarthur/DAF
lib/daf/configurable.rb
DAF.Configurable.process_options
def process_options(options) options.each do |key, value| key = key.to_s fail OptionException, "No Option #{key}" unless self.class.options[key] opt = send("#{key}") opt.value = value fail OptionException, "Bad value for option #{key}" unless opt.valid? end validate_required_options end
ruby
def process_options(options) options.each do |key, value| key = key.to_s fail OptionException, "No Option #{key}" unless self.class.options[key] opt = send("#{key}") opt.value = value fail OptionException, "Bad value for option #{key}" unless opt.valid? end validate_required_options end
[ "def", "process_options", "(", "options", ")", "options", ".", "each", "do", "|", "key", ",", "value", "|", "key", "=", "key", ".", "to_s", "fail", "OptionException", ",", "\"No Option #{key}\"", "unless", "self", ".", "class", ".", "options", "[", "key", "]", "opt", "=", "send", "(", "\"#{key}\"", ")", "opt", ".", "value", "=", "value", "fail", "OptionException", ",", "\"Bad value for option #{key}\"", "unless", "opt", ".", "valid?", "end", "validate_required_options", "end" ]
Processes given parameter into the defined options previously declared includes validation for types and any custom validators delcared @param [Hash<String,Object>] Hash of option name/value pairs, values must conform to validation rules for options or exception will be raised
[ "Processes", "given", "parameter", "into", "the", "defined", "options", "previously", "declared", "includes", "validation", "for", "types", "and", "any", "custom", "validators", "delcared" ]
e88d67ec123cc911131dbc74d33735378224703b
https://github.com/tmcarthur/DAF/blob/e88d67ec123cc911131dbc74d33735378224703b/lib/daf/configurable.rb#L13-L22
9,806
PeterCamilleri/pause_output
lib/pause_output/output_pager.rb
PauseOutput.OutputPager.write
def write(str) while !str.empty? pre,mid,str = str.partition("\n") write_str(pre) unless pre.empty? writeln unless mid.empty? end end
ruby
def write(str) while !str.empty? pre,mid,str = str.partition("\n") write_str(pre) unless pre.empty? writeln unless mid.empty? end end
[ "def", "write", "(", "str", ")", "while", "!", "str", ".", "empty?", "pre", ",", "mid", ",", "str", "=", "str", ".", "partition", "(", "\"\\n\"", ")", "write_str", "(", "pre", ")", "unless", "pre", ".", "empty?", "writeln", "unless", "mid", ".", "empty?", "end", "end" ]
Set up the initial values. Write out a general string with page pauses.
[ "Set", "up", "the", "initial", "values", ".", "Write", "out", "a", "general", "string", "with", "page", "pauses", "." ]
60bcf8e0f386543aba7f3274714d877168f7cf28
https://github.com/PeterCamilleri/pause_output/blob/60bcf8e0f386543aba7f3274714d877168f7cf28/lib/pause_output/output_pager.rb#L18-L24
9,807
PeterCamilleri/pause_output
lib/pause_output/output_pager.rb
PauseOutput.OutputPager.write_str
def write_str(str) loop do len = str.length if @chars + len < chars_per_line $pause_output_out.write(str) @chars += len return else tipping_point = chars_per_line - @chars $pause_output_out.write(str[0, tipping_point]) count_lines str = (str[tipping_point..-1]) end end end
ruby
def write_str(str) loop do len = str.length if @chars + len < chars_per_line $pause_output_out.write(str) @chars += len return else tipping_point = chars_per_line - @chars $pause_output_out.write(str[0, tipping_point]) count_lines str = (str[tipping_point..-1]) end end end
[ "def", "write_str", "(", "str", ")", "loop", "do", "len", "=", "str", ".", "length", "if", "@chars", "+", "len", "<", "chars_per_line", "$pause_output_out", ".", "write", "(", "str", ")", "@chars", "+=", "len", "return", "else", "tipping_point", "=", "chars_per_line", "-", "@chars", "$pause_output_out", ".", "write", "(", "str", "[", "0", ",", "tipping_point", "]", ")", "count_lines", "str", "=", "(", "str", "[", "tipping_point", "..", "-", "1", "]", ")", "end", "end", "end" ]
Write out a simple string with no embedded new-lines.
[ "Write", "out", "a", "simple", "string", "with", "no", "embedded", "new", "-", "lines", "." ]
60bcf8e0f386543aba7f3274714d877168f7cf28
https://github.com/PeterCamilleri/pause_output/blob/60bcf8e0f386543aba7f3274714d877168f7cf28/lib/pause_output/output_pager.rb#L34-L50
9,808
PeterCamilleri/pause_output
lib/pause_output/output_pager.rb
PauseOutput.OutputPager.pause
def pause msg = pause_message $pause_output_out.write(msg) MiniTerm.raw do |term| result = term.get_raw_char term.flush result end ensure $pause_output_out.write("\r" + " " * msg.length + "\r") end
ruby
def pause msg = pause_message $pause_output_out.write(msg) MiniTerm.raw do |term| result = term.get_raw_char term.flush result end ensure $pause_output_out.write("\r" + " " * msg.length + "\r") end
[ "def", "pause", "msg", "=", "pause_message", "$pause_output_out", ".", "write", "(", "msg", ")", "MiniTerm", ".", "raw", "do", "|", "term", "|", "result", "=", "term", ".", "get_raw_char", "term", ".", "flush", "result", "end", "ensure", "$pause_output_out", ".", "write", "(", "\"\\r\"", "+", "\" \"", "*", "msg", ".", "length", "+", "\"\\r\"", ")", "end" ]
Pause waiting for the user.
[ "Pause", "waiting", "for", "the", "user", "." ]
60bcf8e0f386543aba7f3274714d877168f7cf28
https://github.com/PeterCamilleri/pause_output/blob/60bcf8e0f386543aba7f3274714d877168f7cf28/lib/pause_output/output_pager.rb#L77-L89
9,809
evilmarty/internode.rb
lib/internode/account.rb
Internode.Account.concurrent_map
def concurrent_map threads = services.map{|s| Thread.new{ yield s } } threads.each(&:join) threads.map(&:value) end
ruby
def concurrent_map threads = services.map{|s| Thread.new{ yield s } } threads.each(&:join) threads.map(&:value) end
[ "def", "concurrent_map", "threads", "=", "services", ".", "map", "{", "|", "s", "|", "Thread", ".", "new", "{", "yield", "s", "}", "}", "threads", ".", "each", "(", ":join", ")", "threads", ".", "map", "(", ":value", ")", "end" ]
Used to allow performing API requests in parallal instead of series
[ "Used", "to", "allow", "performing", "API", "requests", "in", "parallal", "instead", "of", "series" ]
6107c4a3b5f7f05edf2fdfe5daa987113b2050a7
https://github.com/evilmarty/internode.rb/blob/6107c4a3b5f7f05edf2fdfe5daa987113b2050a7/lib/internode/account.rb#L28-L32
9,810
dlindahl/network_executive
lib/network_executive/program_schedule.rb
NetworkExecutive.ProgramSchedule.occurrence_at
def occurrence_at( time ) real_duration = duration - 1 range = [ time - real_duration, time ] start_time = proxy.occurrences_between( range[0], range[1] ).first end_time = start_time + real_duration Occurrence.new start_time, real_duration, end_time end
ruby
def occurrence_at( time ) real_duration = duration - 1 range = [ time - real_duration, time ] start_time = proxy.occurrences_between( range[0], range[1] ).first end_time = start_time + real_duration Occurrence.new start_time, real_duration, end_time end
[ "def", "occurrence_at", "(", "time", ")", "real_duration", "=", "duration", "-", "1", "range", "=", "[", "time", "-", "real_duration", ",", "time", "]", "start_time", "=", "proxy", ".", "occurrences_between", "(", "range", "[", "0", "]", ",", "range", "[", "1", "]", ")", ".", "first", "end_time", "=", "start_time", "+", "real_duration", "Occurrence", ".", "new", "start_time", ",", "real_duration", ",", "end_time", "end" ]
Returns the scheduled occurrence that matches the specified time
[ "Returns", "the", "scheduled", "occurrence", "that", "matches", "the", "specified", "time" ]
4802e8b20225d7058c82f5ded05bfa6c84918e3d
https://github.com/dlindahl/network_executive/blob/4802e8b20225d7058c82f5ded05bfa6c84918e3d/lib/network_executive/program_schedule.rb#L56-L65
9,811
Nauktis/nauktis_utils
lib/nauktis_utils/duplicate.rb
NauktisUtils.Duplicate.files_in
def files_in(directories) files = [] Find.find(*directories) do |path| unless File.directory?(path) or File.symlink?(path) files << File.expand_path(path) end end files.uniq end
ruby
def files_in(directories) files = [] Find.find(*directories) do |path| unless File.directory?(path) or File.symlink?(path) files << File.expand_path(path) end end files.uniq end
[ "def", "files_in", "(", "directories", ")", "files", "=", "[", "]", "Find", ".", "find", "(", "directories", ")", "do", "|", "path", "|", "unless", "File", ".", "directory?", "(", "path", ")", "or", "File", ".", "symlink?", "(", "path", ")", "files", "<<", "File", ".", "expand_path", "(", "path", ")", "end", "end", "files", ".", "uniq", "end" ]
Returns the list of files in the directories provided
[ "Returns", "the", "list", "of", "files", "in", "the", "directories", "provided" ]
10e2a8ae558484a95ab61b8ee0a15f3e68b94b1c
https://github.com/Nauktis/nauktis_utils/blob/10e2a8ae558484a95ab61b8ee0a15f3e68b94b1c/lib/nauktis_utils/duplicate.rb#L176-L184
9,812
Nauktis/nauktis_utils
lib/nauktis_utils/duplicate.rb
NauktisUtils.Duplicate.size_of
def size_of(directories) size = 0 files_in(directories).each do |f| size += File.size(f) end size end
ruby
def size_of(directories) size = 0 files_in(directories).each do |f| size += File.size(f) end size end
[ "def", "size_of", "(", "directories", ")", "size", "=", "0", "files_in", "(", "directories", ")", ".", "each", "do", "|", "f", "|", "size", "+=", "File", ".", "size", "(", "f", ")", "end", "size", "end" ]
Returns the total size of the directories provided
[ "Returns", "the", "total", "size", "of", "the", "directories", "provided" ]
10e2a8ae558484a95ab61b8ee0a15f3e68b94b1c
https://github.com/Nauktis/nauktis_utils/blob/10e2a8ae558484a95ab61b8ee0a15f3e68b94b1c/lib/nauktis_utils/duplicate.rb#L187-L193
9,813
jeremyd/virtualmonkey
lib/virtualmonkey/mysql.rb
VirtualMonkey.Mysql.setup_dns
def setup_dns(domain) # TODO should we just use the ID instead of the full href? [email protected] @dns = SharedDns.new(domain) raise "Unable to reserve DNS" unless @dns.reserve_dns(owner) @dns.set_dns_inputs(@deployment) end
ruby
def setup_dns(domain) # TODO should we just use the ID instead of the full href? [email protected] @dns = SharedDns.new(domain) raise "Unable to reserve DNS" unless @dns.reserve_dns(owner) @dns.set_dns_inputs(@deployment) end
[ "def", "setup_dns", "(", "domain", ")", "# TODO should we just use the ID instead of the full href?", "owner", "=", "@deployment", ".", "href", "@dns", "=", "SharedDns", ".", "new", "(", "domain", ")", "raise", "\"Unable to reserve DNS\"", "unless", "@dns", ".", "reserve_dns", "(", "owner", ")", "@dns", ".", "set_dns_inputs", "(", "@deployment", ")", "end" ]
uses SharedDns to find an available set of DNS records and sets them on the deployment
[ "uses", "SharedDns", "to", "find", "an", "available", "set", "of", "DNS", "records", "and", "sets", "them", "on", "the", "deployment" ]
b2c7255f20ac5ec881eb90afbb5e712160db0dcb
https://github.com/jeremyd/virtualmonkey/blob/b2c7255f20ac5ec881eb90afbb5e712160db0dcb/lib/virtualmonkey/mysql.rb#L113-L119
9,814
talyric/pvcglue
lib/pvcglue/cloud.rb
Pvcglue.Cloud.find_minion_by_name
def find_minion_by_name(minion_name, raise_error = true) # raise(Thor::Error, "Node not specified.") if node_name.nil? || node_name.empty? raise('Minion not specified.') if minion_name.nil? || minion_name.empty? return {minion_name => minions_filtered[minion_name]} if minions[minion_name] minions.each do |key, value| return {key => value} if key.start_with?(minion_name) end raise("Not found: #{minion_name} in #{stage_name}.") if raise_error # raise(Thor::Error, "Not found: #{node_name} in #{stage_name}.") nil end
ruby
def find_minion_by_name(minion_name, raise_error = true) # raise(Thor::Error, "Node not specified.") if node_name.nil? || node_name.empty? raise('Minion not specified.') if minion_name.nil? || minion_name.empty? return {minion_name => minions_filtered[minion_name]} if minions[minion_name] minions.each do |key, value| return {key => value} if key.start_with?(minion_name) end raise("Not found: #{minion_name} in #{stage_name}.") if raise_error # raise(Thor::Error, "Not found: #{node_name} in #{stage_name}.") nil end
[ "def", "find_minion_by_name", "(", "minion_name", ",", "raise_error", "=", "true", ")", "# raise(Thor::Error, \"Node not specified.\") if node_name.nil? || node_name.empty?", "raise", "(", "'Minion not specified.'", ")", "if", "minion_name", ".", "nil?", "||", "minion_name", ".", "empty?", "return", "{", "minion_name", "=>", "minions_filtered", "[", "minion_name", "]", "}", "if", "minions", "[", "minion_name", "]", "minions", ".", "each", "do", "|", "key", ",", "value", "|", "return", "{", "key", "=>", "value", "}", "if", "key", ".", "start_with?", "(", "minion_name", ")", "end", "raise", "(", "\"Not found: #{minion_name} in #{stage_name}.\"", ")", "if", "raise_error", "# raise(Thor::Error, \"Not found: #{node_name} in #{stage_name}.\")", "nil", "end" ]
find node by full node_name or by matching prefix of node_name
[ "find", "node", "by", "full", "node_name", "or", "by", "matching", "prefix", "of", "node_name" ]
c0f8c70d75fb34dd9ba0e186c355f25a9e165452
https://github.com/talyric/pvcglue/blob/c0f8c70d75fb34dd9ba0e186c355f25a9e165452/lib/pvcglue/cloud.rb#L91-L101
9,815
babausse/kharon
lib/kharon/validator.rb
Kharon.Validator.method_missing
def method_missing(name, *arguments, &block) if respond_to? name if arguments.count == 1 processors[name].process(arguments[0]) elsif arguments.count == 2 processors[name].process(arguments[0], arguments[1]) end else super end end
ruby
def method_missing(name, *arguments, &block) if respond_to? name if arguments.count == 1 processors[name].process(arguments[0]) elsif arguments.count == 2 processors[name].process(arguments[0], arguments[1]) end else super end end
[ "def", "method_missing", "(", "name", ",", "*", "arguments", ",", "&", "block", ")", "if", "respond_to?", "name", "if", "arguments", ".", "count", "==", "1", "processors", "[", "name", "]", ".", "process", "(", "arguments", "[", "0", "]", ")", "elsif", "arguments", ".", "count", "==", "2", "processors", "[", "name", "]", ".", "process", "(", "arguments", "[", "0", "]", ",", "arguments", "[", "1", "]", ")", "end", "else", "super", "end", "end" ]
Constructor of the classe, receiving the datas to validate and filter. @param [Hash] datas the datas to validate in the validator. @example create a new instance of validator. @validator = Kharon::Validator.new({key: "value"}) Method used to not directly define the different type validation methods, but instead to look for it in the processors list. @param [String] name the name of the not found method. @param [Array] arguments the arguments passed to the not found method when it's called. @param [Proc] block the block that might have been passed to the not found method when it's called.
[ "Constructor", "of", "the", "classe", "receiving", "the", "datas", "to", "validate", "and", "filter", "." ]
bfd3d90cbc229db70f2ed1762f5f1743259154cd
https://github.com/babausse/kharon/blob/bfd3d90cbc229db70f2ed1762f5f1743259154cd/lib/kharon/validator.rb#L38-L48
9,816
conversation/raca
lib/raca/http_client.rb
Raca.HttpClient.cloud_request
def cloud_request(request, &block) Net::HTTP.start(@hostname, 443, use_ssl: true, read_timeout: 120) do |http| request['X-Auth-Token'] = @account.auth_token request['User-Agent'] = "raca 0.4.4 (http://rubygems.org/gems/raca)" response = http.request(request, &block) if response.is_a?(Net::HTTPSuccess) response else raise_on_error(request, response) end end end
ruby
def cloud_request(request, &block) Net::HTTP.start(@hostname, 443, use_ssl: true, read_timeout: 120) do |http| request['X-Auth-Token'] = @account.auth_token request['User-Agent'] = "raca 0.4.4 (http://rubygems.org/gems/raca)" response = http.request(request, &block) if response.is_a?(Net::HTTPSuccess) response else raise_on_error(request, response) end end end
[ "def", "cloud_request", "(", "request", ",", "&", "block", ")", "Net", "::", "HTTP", ".", "start", "(", "@hostname", ",", "443", ",", "use_ssl", ":", "true", ",", "read_timeout", ":", "120", ")", "do", "|", "http", "|", "request", "[", "'X-Auth-Token'", "]", "=", "@account", ".", "auth_token", "request", "[", "'User-Agent'", "]", "=", "\"raca 0.4.4 (http://rubygems.org/gems/raca)\"", "response", "=", "http", ".", "request", "(", "request", ",", "block", ")", "if", "response", ".", "is_a?", "(", "Net", "::", "HTTPSuccess", ")", "response", "else", "raise_on_error", "(", "request", ",", "response", ")", "end", "end", "end" ]
perform an HTTP request to rackpsace. request is a Net::HTTP request object. This can be called with and without a block. Without a block, the response is returned as you'd expect response = http_client.cloud_request(request) With the block form, the response is yielded to the block: http_client.cloud_request(request) do |response| puts response end
[ "perform", "an", "HTTP", "request", "to", "rackpsace", "." ]
fa69dfde22359cc0e06f655055be4eadcc7019c0
https://github.com/conversation/raca/blob/fa69dfde22359cc0e06f655055be4eadcc7019c0/lib/raca/http_client.rb#L95-L106
9,817
ukparliament/gromnative
lib/grom_native/request.rb
GromNative.UrlRequest.method_missing
def method_missing(method, *params, &block) @endpoint_parts << method.to_s @endpoint_parts << params @endpoint_parts = @endpoint_parts.flatten! block&.call self || super end
ruby
def method_missing(method, *params, &block) @endpoint_parts << method.to_s @endpoint_parts << params @endpoint_parts = @endpoint_parts.flatten! block&.call self || super end
[ "def", "method_missing", "(", "method", ",", "*", "params", ",", "&", "block", ")", "@endpoint_parts", "<<", "method", ".", "to_s", "@endpoint_parts", "<<", "params", "@endpoint_parts", "=", "@endpoint_parts", ".", "flatten!", "block", "&.", "call", "self", "||", "super", "end" ]
Overrides ruby's method_missing to allow creation of URLs through method calls. @example Adding a simple URL part request = Parliament::Request::UrlRequest.new(base_url: 'http://example.com') # url: http://example.com/people request.people @example Adding a simple URL part with parameters request = Parliament::Request::UrlRequest.new(base_url: 'http://example.com') # url: http://example.com/people/123456 request.people('123456') @example Chaining URL parts and using hyphens request = Parliament::Request::UrlRequest.new(base_url: 'http://example.com') # url: http://example.com/people/123456/foo/bar/hello-world/7890 request.people('123456').foo.bar('hello-world', '7890') @param [Symbol] method the 'method' (url part) we are processing. @param [Array<Object>] params parameters passed to the specified method (url part). @param [Block] block additional block (kept for compatibility with method_missing API). @return [Parliament::Request::UrlRequest] self (this is to allow method chaining).
[ "Overrides", "ruby", "s", "method_missing", "to", "allow", "creation", "of", "URLs", "through", "method", "calls", "." ]
4b291e9e910699f7881316279ca787be6f1d5038
https://github.com/ukparliament/gromnative/blob/4b291e9e910699f7881316279ca787be6f1d5038/lib/grom_native/request.rb#L97-L106
9,818
traject/traject_sequel_writer
lib/traject/sequel_writer.rb
Traject.SequelWriter.output_value_to_column_value
def output_value_to_column_value(v) if v.kind_of?(Array) if v.length == 0 nil elsif v.length == 1 v.first elsif v.first.kind_of?(String) v.join(@internal_delimiter) else # Not a string? Um, raise for now? raise ArgumentError.new("Traject::SequelWriter, multiple non-String values provided: #{v}") end else v end end
ruby
def output_value_to_column_value(v) if v.kind_of?(Array) if v.length == 0 nil elsif v.length == 1 v.first elsif v.first.kind_of?(String) v.join(@internal_delimiter) else # Not a string? Um, raise for now? raise ArgumentError.new("Traject::SequelWriter, multiple non-String values provided: #{v}") end else v end end
[ "def", "output_value_to_column_value", "(", "v", ")", "if", "v", ".", "kind_of?", "(", "Array", ")", "if", "v", ".", "length", "==", "0", "nil", "elsif", "v", ".", "length", "==", "1", "v", ".", "first", "elsif", "v", ".", "first", ".", "kind_of?", "(", "String", ")", "v", ".", "join", "(", "@internal_delimiter", ")", "else", "# Not a string? Um, raise for now?", "raise", "ArgumentError", ".", "new", "(", "\"Traject::SequelWriter, multiple non-String values provided: #{v}\"", ")", "end", "else", "v", "end", "end" ]
Traject context.output_hash values are arrays. turn them into good column values, joining strings if needed. Single values also accepted, even though not traject standard, they will be passed through unchanged.
[ "Traject", "context", ".", "output_hash", "values", "are", "arrays", ".", "turn", "them", "into", "good", "column", "values", "joining", "strings", "if", "needed", "." ]
72c8b9c3d5cfc09fbcae4652826d7b9e0731b842
https://github.com/traject/traject_sequel_writer/blob/72c8b9c3d5cfc09fbcae4652826d7b9e0731b842/lib/traject/sequel_writer.rb#L152-L167
9,819
GoConflux/conify
lib/conify/command.rb
Conify.Command.run
def run(klass, method) # Get the command info for this method on this klass command_info_module = klass::CommandInfo.const_get(camelize(method)) # If seeking help for this command with --help or -h if seeking_command_help?(@current_args) puts "\nPurpose: #{command_description(command_info_module)}\n" # respond with command-specific help respond_with_command_help(command_info_module) return end # get the valid arguments defined for this comand valid_args = command_valid_args(command_info_module) if !valid_args?(valid_args) handle_invalid_args(command_info_module) return end klass.new(@current_args.dup).send(method) end
ruby
def run(klass, method) # Get the command info for this method on this klass command_info_module = klass::CommandInfo.const_get(camelize(method)) # If seeking help for this command with --help or -h if seeking_command_help?(@current_args) puts "\nPurpose: #{command_description(command_info_module)}\n" # respond with command-specific help respond_with_command_help(command_info_module) return end # get the valid arguments defined for this comand valid_args = command_valid_args(command_info_module) if !valid_args?(valid_args) handle_invalid_args(command_info_module) return end klass.new(@current_args.dup).send(method) end
[ "def", "run", "(", "klass", ",", "method", ")", "# Get the command info for this method on this klass", "command_info_module", "=", "klass", "::", "CommandInfo", ".", "const_get", "(", "camelize", "(", "method", ")", ")", "# If seeking help for this command with --help or -h", "if", "seeking_command_help?", "(", "@current_args", ")", "puts", "\"\\nPurpose: #{command_description(command_info_module)}\\n\"", "# respond with command-specific help", "respond_with_command_help", "(", "command_info_module", ")", "return", "end", "# get the valid arguments defined for this comand", "valid_args", "=", "command_valid_args", "(", "command_info_module", ")", "if", "!", "valid_args?", "(", "valid_args", ")", "handle_invalid_args", "(", "command_info_module", ")", "return", "end", "klass", ".", "new", "(", "@current_args", ".", "dup", ")", ".", "send", "(", "method", ")", "end" ]
Call a method on a klass with certain arguments. Will validate arguments first before calling method.
[ "Call", "a", "method", "on", "a", "klass", "with", "certain", "arguments", ".", "Will", "validate", "arguments", "first", "before", "calling", "method", "." ]
2232fa8a3b144566f4558ab888988559d4dff6bd
https://github.com/GoConflux/conify/blob/2232fa8a3b144566f4558ab888988559d4dff6bd/lib/conify/command.rb#L73-L95
9,820
GoConflux/conify
lib/conify/command.rb
Conify.Command.valid_args?
def valid_args?(accepted_arg_formats) valid_args = false accepted_arg_formats.each { |format| # if no arguments exist, and no arguments is an accepted format, args are valid. if format.empty? && @current_args.empty? valid_args = true else passed_in_args = @current_args.clone format.each_with_index { |arg, i| passed_in_args[i] = arg if CMD_BLACKLIST.include?(arg) } @invalid_args = passed_in_args - format - [nil] valid_args = true if passed_in_args == format end } valid_args end
ruby
def valid_args?(accepted_arg_formats) valid_args = false accepted_arg_formats.each { |format| # if no arguments exist, and no arguments is an accepted format, args are valid. if format.empty? && @current_args.empty? valid_args = true else passed_in_args = @current_args.clone format.each_with_index { |arg, i| passed_in_args[i] = arg if CMD_BLACKLIST.include?(arg) } @invalid_args = passed_in_args - format - [nil] valid_args = true if passed_in_args == format end } valid_args end
[ "def", "valid_args?", "(", "accepted_arg_formats", ")", "valid_args", "=", "false", "accepted_arg_formats", ".", "each", "{", "|", "format", "|", "# if no arguments exist, and no arguments is an accepted format, args are valid.", "if", "format", ".", "empty?", "&&", "@current_args", ".", "empty?", "valid_args", "=", "true", "else", "passed_in_args", "=", "@current_args", ".", "clone", "format", ".", "each_with_index", "{", "|", "arg", ",", "i", "|", "passed_in_args", "[", "i", "]", "=", "arg", "if", "CMD_BLACKLIST", ".", "include?", "(", "arg", ")", "}", "@invalid_args", "=", "passed_in_args", "-", "format", "-", "[", "nil", "]", "valid_args", "=", "true", "if", "passed_in_args", "==", "format", "end", "}", "valid_args", "end" ]
Check if passed-in arguments are valid for a specific format
[ "Check", "if", "passed", "-", "in", "arguments", "are", "valid", "for", "a", "specific", "format" ]
2232fa8a3b144566f4558ab888988559d4dff6bd
https://github.com/GoConflux/conify/blob/2232fa8a3b144566f4558ab888988559d4dff6bd/lib/conify/command.rb#L128-L149
9,821
GoConflux/conify
lib/conify/command.rb
Conify.Command.handle_invalid_args
def handle_invalid_args(command_info_module) if !@invalid_args.empty? message = 'Invalid argument' message += 's' if @invalid_args.length > 1 args = @invalid_args.map { |arg| "\"#{arg}\"" }.join(', ') puts " ! #{message}: #{args}" else puts " ! Invalid command usage" end respond_with_command_help(command_info_module) end
ruby
def handle_invalid_args(command_info_module) if !@invalid_args.empty? message = 'Invalid argument' message += 's' if @invalid_args.length > 1 args = @invalid_args.map { |arg| "\"#{arg}\"" }.join(', ') puts " ! #{message}: #{args}" else puts " ! Invalid command usage" end respond_with_command_help(command_info_module) end
[ "def", "handle_invalid_args", "(", "command_info_module", ")", "if", "!", "@invalid_args", ".", "empty?", "message", "=", "'Invalid argument'", "message", "+=", "'s'", "if", "@invalid_args", ".", "length", ">", "1", "args", "=", "@invalid_args", ".", "map", "{", "|", "arg", "|", "\"\\\"#{arg}\\\"\"", "}", ".", "join", "(", "', '", ")", "puts", "\" ! #{message}: #{args}\"", "else", "puts", "\" ! Invalid command usage\"", "end", "respond_with_command_help", "(", "command_info_module", ")", "end" ]
Respond to the user in the instance of invalid arguments.
[ "Respond", "to", "the", "user", "in", "the", "instance", "of", "invalid", "arguments", "." ]
2232fa8a3b144566f4558ab888988559d4dff6bd
https://github.com/GoConflux/conify/blob/2232fa8a3b144566f4558ab888988559d4dff6bd/lib/conify/command.rb#L152-L164
9,822
GoConflux/conify
lib/conify/command.rb
Conify.Command.create_commands_map
def create_commands_map # Require all the ruby command files command_file_paths.each do |file| require file # Get basename for the file without the extension basename = get_basename_from_file(file) # Camelcase the basename to be the klass name klass_name = camelize(basename) # return the command klass for this klass_name command_klass = Conify::Command.const_get(klass_name) # For each of the user-defined methods inside this class, create a command for it manually_added_methods(command_klass).each { |method| register_command(basename, method.to_s, command_klass, global: basename == 'global') } end end
ruby
def create_commands_map # Require all the ruby command files command_file_paths.each do |file| require file # Get basename for the file without the extension basename = get_basename_from_file(file) # Camelcase the basename to be the klass name klass_name = camelize(basename) # return the command klass for this klass_name command_klass = Conify::Command.const_get(klass_name) # For each of the user-defined methods inside this class, create a command for it manually_added_methods(command_klass).each { |method| register_command(basename, method.to_s, command_klass, global: basename == 'global') } end end
[ "def", "create_commands_map", "# Require all the ruby command files", "command_file_paths", ".", "each", "do", "|", "file", "|", "require", "file", "# Get basename for the file without the extension", "basename", "=", "get_basename_from_file", "(", "file", ")", "# Camelcase the basename to be the klass name", "klass_name", "=", "camelize", "(", "basename", ")", "# return the command klass for this klass_name", "command_klass", "=", "Conify", "::", "Command", ".", "const_get", "(", "klass_name", ")", "# For each of the user-defined methods inside this class, create a command for it", "manually_added_methods", "(", "command_klass", ")", ".", "each", "{", "|", "method", "|", "register_command", "(", "basename", ",", "method", ".", "to_s", ",", "command_klass", ",", "global", ":", "basename", "==", "'global'", ")", "}", "end", "end" ]
Create a commands map to respond to `conify help` with.
[ "Create", "a", "commands", "map", "to", "respond", "to", "conify", "help", "with", "." ]
2232fa8a3b144566f4558ab888988559d4dff6bd
https://github.com/GoConflux/conify/blob/2232fa8a3b144566f4558ab888988559d4dff6bd/lib/conify/command.rb#L196-L215
9,823
GoConflux/conify
lib/conify/command.rb
Conify.Command.usage_info
def usage_info(map) keys = map.keys commands_column_width = keys.max_by(&:length).length + 1 commands_column_width += 2 if commands_column_width < 12 # iterate through each of the commands, create an array # of strings in a `<command> # <description>` format. Sort # them alphabetically, and then join them with new lines. keys.map { |key| command = " #{key}" command += (' ' * (commands_column_width - key.length + 1)) command += "# #{map[key][:description]}" command }.sort_by{ |k| k.downcase }.join("\n") end
ruby
def usage_info(map) keys = map.keys commands_column_width = keys.max_by(&:length).length + 1 commands_column_width += 2 if commands_column_width < 12 # iterate through each of the commands, create an array # of strings in a `<command> # <description>` format. Sort # them alphabetically, and then join them with new lines. keys.map { |key| command = " #{key}" command += (' ' * (commands_column_width - key.length + 1)) command += "# #{map[key][:description]}" command }.sort_by{ |k| k.downcase }.join("\n") end
[ "def", "usage_info", "(", "map", ")", "keys", "=", "map", ".", "keys", "commands_column_width", "=", "keys", ".", "max_by", "(", ":length", ")", ".", "length", "+", "1", "commands_column_width", "+=", "2", "if", "commands_column_width", "<", "12", "# iterate through each of the commands, create an array", "# of strings in a `<command> # <description>` format. Sort", "# them alphabetically, and then join them with new lines.", "keys", ".", "map", "{", "|", "key", "|", "command", "=", "\" #{key}\"", "command", "+=", "(", "' '", "*", "(", "commands_column_width", "-", "key", ".", "length", "+", "1", ")", ")", "command", "+=", "\"# #{map[key][:description]}\"", "command", "}", ".", "sort_by", "{", "|", "k", "|", "k", ".", "downcase", "}", ".", "join", "(", "\"\\n\"", ")", "end" ]
Format a map of commands into help output format
[ "Format", "a", "map", "of", "commands", "into", "help", "output", "format" ]
2232fa8a3b144566f4558ab888988559d4dff6bd
https://github.com/GoConflux/conify/blob/2232fa8a3b144566f4558ab888988559d4dff6bd/lib/conify/command.rb#L218-L232
9,824
GoConflux/conify
lib/conify/command.rb
Conify.Command.get_basename_from_file
def get_basename_from_file(file) basename = Pathname.new(file).basename.to_s basename[0..(basename.rindex('.') - 1)] end
ruby
def get_basename_from_file(file) basename = Pathname.new(file).basename.to_s basename[0..(basename.rindex('.') - 1)] end
[ "def", "get_basename_from_file", "(", "file", ")", "basename", "=", "Pathname", ".", "new", "(", "file", ")", ".", "basename", ".", "to_s", "basename", "[", "0", "..", "(", "basename", ".", "rindex", "(", "'.'", ")", "-", "1", ")", "]", "end" ]
Return just the basename for a file, no extensions.
[ "Return", "just", "the", "basename", "for", "a", "file", "no", "extensions", "." ]
2232fa8a3b144566f4558ab888988559d4dff6bd
https://github.com/GoConflux/conify/blob/2232fa8a3b144566f4558ab888988559d4dff6bd/lib/conify/command.rb#L261-L264
9,825
GoConflux/conify
lib/conify/command.rb
Conify.Command.command_file_paths
def command_file_paths abstract_file = File.join(File.dirname(__FILE__), 'command', 'abstract_command.rb') Dir[File.join(File.dirname(__FILE__), 'command', '*.rb')] - [abstract_file] end
ruby
def command_file_paths abstract_file = File.join(File.dirname(__FILE__), 'command', 'abstract_command.rb') Dir[File.join(File.dirname(__FILE__), 'command', '*.rb')] - [abstract_file] end
[ "def", "command_file_paths", "abstract_file", "=", "File", ".", "join", "(", "File", ".", "dirname", "(", "__FILE__", ")", ",", "'command'", ",", "'abstract_command.rb'", ")", "Dir", "[", "File", ".", "join", "(", "File", ".", "dirname", "(", "__FILE__", ")", ",", "'command'", ",", "'*.rb'", ")", "]", "-", "[", "abstract_file", "]", "end" ]
Feturn an array of all command file paths, with the exception of abstract_command.rb
[ "Feturn", "an", "array", "of", "all", "command", "file", "paths", "with", "the", "exception", "of", "abstract_command", ".", "rb" ]
2232fa8a3b144566f4558ab888988559d4dff6bd
https://github.com/GoConflux/conify/blob/2232fa8a3b144566f4558ab888988559d4dff6bd/lib/conify/command.rb#L267-L270
9,826
GoConflux/conify
lib/conify/command.rb
Conify.Command.register_command
def register_command(basename, action, command_class, global: false) command = global ? action : (action == 'index' ? basename : "#{basename}:#{action}") command_info_module = command_class::CommandInfo.const_get(camelize(action)) commands[command] = { description: command_description(command_info_module) } end
ruby
def register_command(basename, action, command_class, global: false) command = global ? action : (action == 'index' ? basename : "#{basename}:#{action}") command_info_module = command_class::CommandInfo.const_get(camelize(action)) commands[command] = { description: command_description(command_info_module) } end
[ "def", "register_command", "(", "basename", ",", "action", ",", "command_class", ",", "global", ":", "false", ")", "command", "=", "global", "?", "action", ":", "(", "action", "==", "'index'", "?", "basename", ":", "\"#{basename}:#{action}\"", ")", "command_info_module", "=", "command_class", "::", "CommandInfo", ".", "const_get", "(", "camelize", "(", "action", ")", ")", "commands", "[", "command", "]", "=", "{", "description", ":", "command_description", "(", "command_info_module", ")", "}", "end" ]
register a command's info to the @@commands map - utilized when calling `conify help`
[ "register", "a", "command", "s", "info", "to", "the" ]
2232fa8a3b144566f4558ab888988559d4dff6bd
https://github.com/GoConflux/conify/blob/2232fa8a3b144566f4558ab888988559d4dff6bd/lib/conify/command.rb#L277-L283
9,827
psyho/prezio
lib/prezio/syntax_highlighter.rb
Prezio.SyntaxHighlighter.tableize_code
def tableize_code (str, lang = '') table = '<div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers">' code = '' str.lines.each_with_index do |line,index| table += "<span class='line-number'>#{index+1}</span>\n" code += "<span class='line'>#{line}</span>" end table += "</pre></td><td class='code'><pre><code class='#{lang}'>#{code}</code></pre></td></tr></table></div>" end
ruby
def tableize_code (str, lang = '') table = '<div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers">' code = '' str.lines.each_with_index do |line,index| table += "<span class='line-number'>#{index+1}</span>\n" code += "<span class='line'>#{line}</span>" end table += "</pre></td><td class='code'><pre><code class='#{lang}'>#{code}</code></pre></td></tr></table></div>" end
[ "def", "tableize_code", "(", "str", ",", "lang", "=", "''", ")", "table", "=", "'<div class=\"highlight\"><table><tr><td class=\"gutter\"><pre class=\"line-numbers\">'", "code", "=", "''", "str", ".", "lines", ".", "each_with_index", "do", "|", "line", ",", "index", "|", "table", "+=", "\"<span class='line-number'>#{index+1}</span>\\n\"", "code", "+=", "\"<span class='line'>#{line}</span>\"", "end", "table", "+=", "\"</pre></td><td class='code'><pre><code class='#{lang}'>#{code}</code></pre></td></tr></table></div>\"", "end" ]
taken from octopress
[ "taken", "from", "octopress" ]
201730e61665c985fda3acf35f3389dd1776de67
https://github.com/psyho/prezio/blob/201730e61665c985fda3acf35f3389dd1776de67/lib/prezio/syntax_highlighter.rb#L45-L53
9,828
nickcharlton/atlas-ruby
lib/atlas/box.rb
Atlas.Box.save
def save validate! body = { box: to_hash } # versions are saved seperately body[:box].delete(:versions) # update or create the box begin response = Atlas.client.put(url_builder.box_url, body: body) rescue Atlas::Errors::NotFoundError body[:box].replace_key!(:private, :is_private) response = Atlas.client.post("/boxes", body: body) end # trigger the same on versions versions.each(&:save) if versions update_with_response(response, [:versions]) end
ruby
def save validate! body = { box: to_hash } # versions are saved seperately body[:box].delete(:versions) # update or create the box begin response = Atlas.client.put(url_builder.box_url, body: body) rescue Atlas::Errors::NotFoundError body[:box].replace_key!(:private, :is_private) response = Atlas.client.post("/boxes", body: body) end # trigger the same on versions versions.each(&:save) if versions update_with_response(response, [:versions]) end
[ "def", "save", "validate!", "body", "=", "{", "box", ":", "to_hash", "}", "# versions are saved seperately", "body", "[", ":box", "]", ".", "delete", "(", ":versions", ")", "# update or create the box", "begin", "response", "=", "Atlas", ".", "client", ".", "put", "(", "url_builder", ".", "box_url", ",", "body", ":", "body", ")", "rescue", "Atlas", "::", "Errors", "::", "NotFoundError", "body", "[", ":box", "]", ".", "replace_key!", "(", ":private", ",", ":is_private", ")", "response", "=", "Atlas", ".", "client", ".", "post", "(", "\"/boxes\"", ",", "body", ":", "body", ")", "end", "# trigger the same on versions", "versions", ".", "each", "(", ":save", ")", "if", "versions", "update_with_response", "(", "response", ",", "[", ":versions", "]", ")", "end" ]
Save the box. @return [Hash] Atlas response object.
[ "Save", "the", "box", "." ]
2170c04496682e0d8e7c959bd9f267f62fa84c1d
https://github.com/nickcharlton/atlas-ruby/blob/2170c04496682e0d8e7c959bd9f267f62fa84c1d/lib/atlas/box.rb#L110-L131
9,829
rikas/bitwise_attribute
lib/bitwise_attribute.rb
BitwiseAttribute.ClassMethods.build_mapping
def build_mapping(values) {}.tap do |hash| values.each_with_index { |key, index| hash[key] = (0b1 << index) } end end
ruby
def build_mapping(values) {}.tap do |hash| values.each_with_index { |key, index| hash[key] = (0b1 << index) } end end
[ "def", "build_mapping", "(", "values", ")", "{", "}", ".", "tap", "do", "|", "hash", "|", "values", ".", "each_with_index", "{", "|", "key", ",", "index", "|", "hash", "[", "key", "]", "=", "(", "0b1", "<<", "index", ")", "}", "end", "end" ]
Builds internal bitwise key-value mapping it add a zero value, needed for bits operations. Each sym get a power of 2 value
[ "Builds", "internal", "bitwise", "key", "-", "value", "mapping", "it", "add", "a", "zero", "value", "needed", "for", "bits", "operations", ".", "Each", "sym", "get", "a", "power", "of", "2", "value" ]
b5a24fa843b6738ac7d83a01c73818bc75048021
https://github.com/rikas/bitwise_attribute/blob/b5a24fa843b6738ac7d83a01c73818bc75048021/lib/bitwise_attribute.rb#L60-L64
9,830
ariejan/firefly-client
lib/firefly/client.rb
Firefly.Client.shorten
def shorten(input) if input.is_a?(String) return create_url(input) elsif input.is_a?(Array) result = {} input.each do |inp| result[inp] = create_url(inp) end return result else raise ArgumentError.new('Shorten requires either a url or an array of urls') end end
ruby
def shorten(input) if input.is_a?(String) return create_url(input) elsif input.is_a?(Array) result = {} input.each do |inp| result[inp] = create_url(inp) end return result else raise ArgumentError.new('Shorten requires either a url or an array of urls') end end
[ "def", "shorten", "(", "input", ")", "if", "input", ".", "is_a?", "(", "String", ")", "return", "create_url", "(", "input", ")", "elsif", "input", ".", "is_a?", "(", "Array", ")", "result", "=", "{", "}", "input", ".", "each", "do", "|", "inp", "|", "result", "[", "inp", "]", "=", "create_url", "(", "inp", ")", "end", "return", "result", "else", "raise", "ArgumentError", ".", "new", "(", "'Shorten requires either a url or an array of urls'", ")", "end", "end" ]
Creates a new instance to shorten Firefly URLs +url+ is the URL to your Firefly server. E.g. "http://aj.gs". Note: do not include a trailing slash +api_key+ is your Firefly API Key. Shortens the given URL or array of URLs. shorten("http://google.com") => "http://aj.gs/7dZ" shorten(["http://google.com", "http://yahoo.com"]) => { "http://google.com/" => "http://aj.gs/7dZ", "http://yahoo.com/" => "http://aj.gs/8Yt" }
[ "Creates", "a", "new", "instance", "to", "shorten", "Firefly", "URLs" ]
217a37418e7eb1288626d4a4070e0ad2bc0effcc
https://github.com/ariejan/firefly-client/blob/217a37418e7eb1288626d4a4070e0ad2bc0effcc/lib/firefly/client.rb#L29-L41
9,831
ariejan/firefly-client
lib/firefly/client.rb
Firefly.Client.create_url
def create_url(long_url) begin options = { :query => { :url => long_url, :api_key => @api_key } } result = HTTParty.post(@firefly_url + '/api/add', options) if result =~ /Permission denied/i raise "Permission denied. Is your API Key set correctly?" if result.status = 401 else return result end end end
ruby
def create_url(long_url) begin options = { :query => { :url => long_url, :api_key => @api_key } } result = HTTParty.post(@firefly_url + '/api/add', options) if result =~ /Permission denied/i raise "Permission denied. Is your API Key set correctly?" if result.status = 401 else return result end end end
[ "def", "create_url", "(", "long_url", ")", "begin", "options", "=", "{", ":query", "=>", "{", ":url", "=>", "long_url", ",", ":api_key", "=>", "@api_key", "}", "}", "result", "=", "HTTParty", ".", "post", "(", "@firefly_url", "+", "'/api/add'", ",", "options", ")", "if", "result", "=~", "/", "/i", "raise", "\"Permission denied. Is your API Key set correctly?\"", "if", "result", ".", "status", "=", "401", "else", "return", "result", "end", "end", "end" ]
Shortend +long_url+ and returns the short_url on success
[ "Shortend", "+", "long_url", "+", "and", "returns", "the", "short_url", "on", "success" ]
217a37418e7eb1288626d4a4070e0ad2bc0effcc
https://github.com/ariejan/firefly-client/blob/217a37418e7eb1288626d4a4070e0ad2bc0effcc/lib/firefly/client.rb#L46-L57
9,832
buren/jsonapi_helpers
lib/jsonapi_helpers/support/key_transform.rb
JSONAPIHelpers.KeyTransform.camel
def camel(value) case value when Hash then value.deep_transform_keys! { |key| camel(key) } when Symbol then camel(value.to_s).to_sym when String then StringSupport.camel(value) else value end end
ruby
def camel(value) case value when Hash then value.deep_transform_keys! { |key| camel(key) } when Symbol then camel(value.to_s).to_sym when String then StringSupport.camel(value) else value end end
[ "def", "camel", "(", "value", ")", "case", "value", "when", "Hash", "then", "value", ".", "deep_transform_keys!", "{", "|", "key", "|", "camel", "(", "key", ")", "}", "when", "Symbol", "then", "camel", "(", "value", ".", "to_s", ")", ".", "to_sym", "when", "String", "then", "StringSupport", ".", "camel", "(", "value", ")", "else", "value", "end", "end" ]
Transforms values to UpperCamelCase or PascalCase. @example: "some_key" => "SomeKey",
[ "Transforms", "values", "to", "UpperCamelCase", "or", "PascalCase", "." ]
4a025a5f6ba3d6f01cd96e1776134d3aeb21e2a6
https://github.com/buren/jsonapi_helpers/blob/4a025a5f6ba3d6f01cd96e1776134d3aeb21e2a6/lib/jsonapi_helpers/support/key_transform.rb#L20-L27
9,833
buren/jsonapi_helpers
lib/jsonapi_helpers/support/key_transform.rb
JSONAPIHelpers.KeyTransform.camel_lower
def camel_lower(value) case value when Hash then value.deep_transform_keys! { |key| camel_lower(key) } when Symbol then camel_lower(value.to_s).to_sym when String then StringSupport.camel_lower(value) else value end end
ruby
def camel_lower(value) case value when Hash then value.deep_transform_keys! { |key| camel_lower(key) } when Symbol then camel_lower(value.to_s).to_sym when String then StringSupport.camel_lower(value) else value end end
[ "def", "camel_lower", "(", "value", ")", "case", "value", "when", "Hash", "then", "value", ".", "deep_transform_keys!", "{", "|", "key", "|", "camel_lower", "(", "key", ")", "}", "when", "Symbol", "then", "camel_lower", "(", "value", ".", "to_s", ")", ".", "to_sym", "when", "String", "then", "StringSupport", ".", "camel_lower", "(", "value", ")", "else", "value", "end", "end" ]
Transforms values to camelCase. @example: "some_key" => "someKey",
[ "Transforms", "values", "to", "camelCase", "." ]
4a025a5f6ba3d6f01cd96e1776134d3aeb21e2a6
https://github.com/buren/jsonapi_helpers/blob/4a025a5f6ba3d6f01cd96e1776134d3aeb21e2a6/lib/jsonapi_helpers/support/key_transform.rb#L33-L40
9,834
buren/jsonapi_helpers
lib/jsonapi_helpers/support/key_transform.rb
JSONAPIHelpers.KeyTransform.dash
def dash(value) case value when Hash then value.deep_transform_keys! { |key| dash(key) } when Symbol then dash(value.to_s).to_sym when String then StringSupport.dash(value) else value end end
ruby
def dash(value) case value when Hash then value.deep_transform_keys! { |key| dash(key) } when Symbol then dash(value.to_s).to_sym when String then StringSupport.dash(value) else value end end
[ "def", "dash", "(", "value", ")", "case", "value", "when", "Hash", "then", "value", ".", "deep_transform_keys!", "{", "|", "key", "|", "dash", "(", "key", ")", "}", "when", "Symbol", "then", "dash", "(", "value", ".", "to_s", ")", ".", "to_sym", "when", "String", "then", "StringSupport", ".", "dash", "(", "value", ")", "else", "value", "end", "end" ]
Transforms values to dashed-case. This is the default case for the JsonApi adapter. @example: "some_key" => "some-key",
[ "Transforms", "values", "to", "dashed", "-", "case", ".", "This", "is", "the", "default", "case", "for", "the", "JsonApi", "adapter", "." ]
4a025a5f6ba3d6f01cd96e1776134d3aeb21e2a6
https://github.com/buren/jsonapi_helpers/blob/4a025a5f6ba3d6f01cd96e1776134d3aeb21e2a6/lib/jsonapi_helpers/support/key_transform.rb#L47-L54
9,835
buren/jsonapi_helpers
lib/jsonapi_helpers/support/key_transform.rb
JSONAPIHelpers.KeyTransform.underscore
def underscore(value) case value when Hash then value.deep_transform_keys! { |key| underscore(key) } when Symbol then underscore(value.to_s).to_sym when String then StringSupport.underscore(value) else value end end
ruby
def underscore(value) case value when Hash then value.deep_transform_keys! { |key| underscore(key) } when Symbol then underscore(value.to_s).to_sym when String then StringSupport.underscore(value) else value end end
[ "def", "underscore", "(", "value", ")", "case", "value", "when", "Hash", "then", "value", ".", "deep_transform_keys!", "{", "|", "key", "|", "underscore", "(", "key", ")", "}", "when", "Symbol", "then", "underscore", "(", "value", ".", "to_s", ")", ".", "to_sym", "when", "String", "then", "StringSupport", ".", "underscore", "(", "value", ")", "else", "value", "end", "end" ]
Transforms values to underscore_case. This is the default case for deserialization in the JsonApi adapter. @example: "some-key" => "some_key",
[ "Transforms", "values", "to", "underscore_case", ".", "This", "is", "the", "default", "case", "for", "deserialization", "in", "the", "JsonApi", "adapter", "." ]
4a025a5f6ba3d6f01cd96e1776134d3aeb21e2a6
https://github.com/buren/jsonapi_helpers/blob/4a025a5f6ba3d6f01cd96e1776134d3aeb21e2a6/lib/jsonapi_helpers/support/key_transform.rb#L61-L68
9,836
ghn/swissforecast
lib/swissforecast.rb
Swissforecast.Client.find_by
def find_by(param) if param.key?(:city) perform(param[:city].sub(' ', '-')) elsif param.key?(:lat) && param.key?(:lng) perform("lat=#{param[:lat]}lng=#{param[:lng]}") end end
ruby
def find_by(param) if param.key?(:city) perform(param[:city].sub(' ', '-')) elsif param.key?(:lat) && param.key?(:lng) perform("lat=#{param[:lat]}lng=#{param[:lng]}") end end
[ "def", "find_by", "(", "param", ")", "if", "param", ".", "key?", "(", ":city", ")", "perform", "(", "param", "[", ":city", "]", ".", "sub", "(", "' '", ",", "'-'", ")", ")", "elsif", "param", ".", "key?", "(", ":lat", ")", "&&", "param", ".", "key?", "(", ":lng", ")", "perform", "(", "\"lat=#{param[:lat]}lng=#{param[:lng]}\"", ")", "end", "end" ]
=> find weather by city or by gps position
[ "=", ">", "find", "weather", "by", "city", "or", "by", "gps", "position" ]
aea52c3451002689a53a2cac63338a5409c445ec
https://github.com/ghn/swissforecast/blob/aea52c3451002689a53a2cac63338a5409c445ec/lib/swissforecast.rb#L13-L19
9,837
antonversal/fake_service
lib/fake_service/server.rb
FakeService.Server.right_header?
def right_header?(expected, actual) expected.inject(true) do |memo, (k, v)| memo && v == actual[k] end end
ruby
def right_header?(expected, actual) expected.inject(true) do |memo, (k, v)| memo && v == actual[k] end end
[ "def", "right_header?", "(", "expected", ",", "actual", ")", "expected", ".", "inject", "(", "true", ")", "do", "|", "memo", ",", "(", "k", ",", "v", ")", "|", "memo", "&&", "v", "==", "actual", "[", "k", "]", "end", "end" ]
Checks for request comes with right header.
[ "Checks", "for", "request", "comes", "with", "right", "header", "." ]
93a59f859447004bdea27b3b4226c4d73d197008
https://github.com/antonversal/fake_service/blob/93a59f859447004bdea27b3b4226c4d73d197008/lib/fake_service/server.rb#L19-L23
9,838
maxjacobson/todo_lint
lib/todo_lint/options.rb
TodoLint.Options.parse
def parse(args) @options = { :report => false } OptionParser.new do |parser| parser.banner = "Usage: todo_lint [options] [files]" add_config_options parser exclude_file_options parser include_extension_options parser report_version parser report_report_options parser end.parse!(args) # Any remaining arguments are assumed to be files options[:files] = args options end
ruby
def parse(args) @options = { :report => false } OptionParser.new do |parser| parser.banner = "Usage: todo_lint [options] [files]" add_config_options parser exclude_file_options parser include_extension_options parser report_version parser report_report_options parser end.parse!(args) # Any remaining arguments are assumed to be files options[:files] = args options end
[ "def", "parse", "(", "args", ")", "@options", "=", "{", ":report", "=>", "false", "}", "OptionParser", ".", "new", "do", "|", "parser", "|", "parser", ".", "banner", "=", "\"Usage: todo_lint [options] [files]\"", "add_config_options", "parser", "exclude_file_options", "parser", "include_extension_options", "parser", "report_version", "parser", "report_report_options", "parser", "end", ".", "parse!", "(", "args", ")", "# Any remaining arguments are assumed to be files", "options", "[", ":files", "]", "=", "args", "options", "end" ]
Parses command line options into an options hash @api public @example Options.new.parse("todo_lint -c app.rb") @param args [Array<String>] arguments passed via the command line @return [Hash] parsed options
[ "Parses", "command", "line", "options", "into", "an", "options", "hash" ]
0d1061383ea205ef4c74edc64568e308ac1af990
https://github.com/maxjacobson/todo_lint/blob/0d1061383ea205ef4c74edc64568e308ac1af990/lib/todo_lint/options.rb#L11-L27
9,839
maxjacobson/todo_lint
lib/todo_lint/options.rb
TodoLint.Options.exclude_file_options
def exclude_file_options(parser) parser.on("-e", "--exclude file1,...", Array, "List of file names to exclude") do |files_list| options[:excluded_files] = [] files_list.each do |short_file| options[:excluded_files] << File.expand_path(short_file) end end end
ruby
def exclude_file_options(parser) parser.on("-e", "--exclude file1,...", Array, "List of file names to exclude") do |files_list| options[:excluded_files] = [] files_list.each do |short_file| options[:excluded_files] << File.expand_path(short_file) end end end
[ "def", "exclude_file_options", "(", "parser", ")", "parser", ".", "on", "(", "\"-e\"", ",", "\"--exclude file1,...\"", ",", "Array", ",", "\"List of file names to exclude\"", ")", "do", "|", "files_list", "|", "options", "[", ":excluded_files", "]", "=", "[", "]", "files_list", ".", "each", "do", "|", "short_file", "|", "options", "[", ":excluded_files", "]", "<<", "File", ".", "expand_path", "(", "short_file", ")", "end", "end", "end" ]
Adds the excluded file options to the options hash @api private @return [Hash]
[ "Adds", "the", "excluded", "file", "options", "to", "the", "options", "hash" ]
0d1061383ea205ef4c74edc64568e308ac1af990
https://github.com/maxjacobson/todo_lint/blob/0d1061383ea205ef4c74edc64568e308ac1af990/lib/todo_lint/options.rb#L45-L53
9,840
kristianmandrup/cantango-config
lib/cantango/category.rb
CanTango.Category.has_any?
def has_any? subject, &block found = subjects.include? subject yield if found && block found end
ruby
def has_any? subject, &block found = subjects.include? subject yield if found && block found end
[ "def", "has_any?", "subject", ",", "&", "block", "found", "=", "subjects", ".", "include?", "subject", "yield", "if", "found", "&&", "block", "found", "end" ]
test if a particular category has a certain subject
[ "test", "if", "a", "particular", "category", "has", "a", "certain", "subject" ]
b3131f92c594cb5f085979c01699fe81fb3e724d
https://github.com/kristianmandrup/cantango-config/blob/b3131f92c594cb5f085979c01699fe81fb3e724d/lib/cantango/category.rb#L12-L16
9,841
caruby/scat
lib/scat/field.rb
Scat.Field.input_attributes
def input_attributes(value) params = {:id => input_id, :type => type, :name => name, :value => value } if type == 'checkbox' then params[:value] ||= self.value params[:checked] = true if default end params end
ruby
def input_attributes(value) params = {:id => input_id, :type => type, :name => name, :value => value } if type == 'checkbox' then params[:value] ||= self.value params[:checked] = true if default end params end
[ "def", "input_attributes", "(", "value", ")", "params", "=", "{", ":id", "=>", "input_id", ",", ":type", "=>", "type", ",", ":name", "=>", "name", ",", ":value", "=>", "value", "}", "if", "type", "==", "'checkbox'", "then", "params", "[", ":value", "]", "||=", "self", ".", "value", "params", "[", ":checked", "]", "=", "true", "if", "default", "end", "params", "end" ]
Parses the given field specification. @param [String] label the configuration field specification key @param [{String => String}] spec the configuration field specification value Returns this field's HTML input element attributes and target caTissue properties. The attributes are determined by the field configuration as follows: * +id+: this field's HTML input element id * +type+: this field's type * +checked+: +true+ if the field type is +checkbox+ and the field default is set * +name+: if the field type is not +checkbox+, then this field's name @param [String, nil] value the request parameter value @return [{Symbol => String}] the form input element attributes
[ "Parses", "the", "given", "field", "specification", "." ]
90291b317eb6b8ef8b0a4497622eadc15d3d9028
https://github.com/caruby/scat/blob/90291b317eb6b8ef8b0a4497622eadc15d3d9028/lib/scat/field.rb#L79-L86
9,842
26fe/sem4r
lib/sem4r/geo_location/geo_location_account_extension.rb
Sem4r.GeoLocationAccountExtension.geo_location
def geo_location(c1, c2 = nil , c3 = nil) if c1.class != GeoLocationSelector # TODO: raise wrong number of arguments if c2 or c3 are nil selector = GeoLocationSelector.new selector.address do address c1 city c2 country c3 end else selector = c1 end soap_message = service.geo_location.get(credentials, selector.to_xml) add_counters(soap_message.counters) end
ruby
def geo_location(c1, c2 = nil , c3 = nil) if c1.class != GeoLocationSelector # TODO: raise wrong number of arguments if c2 or c3 are nil selector = GeoLocationSelector.new selector.address do address c1 city c2 country c3 end else selector = c1 end soap_message = service.geo_location.get(credentials, selector.to_xml) add_counters(soap_message.counters) end
[ "def", "geo_location", "(", "c1", ",", "c2", "=", "nil", ",", "c3", "=", "nil", ")", "if", "c1", ".", "class", "!=", "GeoLocationSelector", "# TODO: raise wrong number of arguments if c2 or c3 are nil", "selector", "=", "GeoLocationSelector", ".", "new", "selector", ".", "address", "do", "address", "c1", "city", "c2", "country", "c3", "end", "else", "selector", "=", "c1", "end", "soap_message", "=", "service", ".", "geo_location", ".", "get", "(", "credentials", ",", "selector", ".", "to_xml", ")", "add_counters", "(", "soap_message", ".", "counters", ")", "end" ]
Call geo location adwords service @example account.geo_location("Via Conca del Naviglio", "Milano", "IT") account.geo_location( geoLocationSelector )
[ "Call", "geo", "location", "adwords", "service" ]
2326404f98b9c2833549fcfda078d39c9954a0fa
https://github.com/26fe/sem4r/blob/2326404f98b9c2833549fcfda078d39c9954a0fa/lib/sem4r/geo_location/geo_location_account_extension.rb#L35-L50
9,843
ktonon/code_node
spec/fixtures/activerecord/src/active_record/relation.rb
ActiveRecord.Relation.update_all
def update_all(updates, conditions = nil, options = {}) IdentityMap.repository[symbolized_base_class].clear if IdentityMap.enabled? if conditions || options.present? where(conditions).apply_finder_options(options.slice(:limit, :order)).update_all(updates) else stmt = Arel::UpdateManager.new(arel.engine) stmt.set Arel.sql(@klass.send(:sanitize_sql_for_assignment, updates)) stmt.table(table) stmt.key = table[primary_key] if joins_values.any? @klass.connection.join_to_update(stmt, arel) else stmt.take(arel.limit) stmt.order(*arel.orders) stmt.wheres = arel.constraints end @klass.connection.update stmt, 'SQL', bind_values end end
ruby
def update_all(updates, conditions = nil, options = {}) IdentityMap.repository[symbolized_base_class].clear if IdentityMap.enabled? if conditions || options.present? where(conditions).apply_finder_options(options.slice(:limit, :order)).update_all(updates) else stmt = Arel::UpdateManager.new(arel.engine) stmt.set Arel.sql(@klass.send(:sanitize_sql_for_assignment, updates)) stmt.table(table) stmt.key = table[primary_key] if joins_values.any? @klass.connection.join_to_update(stmt, arel) else stmt.take(arel.limit) stmt.order(*arel.orders) stmt.wheres = arel.constraints end @klass.connection.update stmt, 'SQL', bind_values end end
[ "def", "update_all", "(", "updates", ",", "conditions", "=", "nil", ",", "options", "=", "{", "}", ")", "IdentityMap", ".", "repository", "[", "symbolized_base_class", "]", ".", "clear", "if", "IdentityMap", ".", "enabled?", "if", "conditions", "||", "options", ".", "present?", "where", "(", "conditions", ")", ".", "apply_finder_options", "(", "options", ".", "slice", "(", ":limit", ",", ":order", ")", ")", ".", "update_all", "(", "updates", ")", "else", "stmt", "=", "Arel", "::", "UpdateManager", ".", "new", "(", "arel", ".", "engine", ")", "stmt", ".", "set", "Arel", ".", "sql", "(", "@klass", ".", "send", "(", ":sanitize_sql_for_assignment", ",", "updates", ")", ")", "stmt", ".", "table", "(", "table", ")", "stmt", ".", "key", "=", "table", "[", "primary_key", "]", "if", "joins_values", ".", "any?", "@klass", ".", "connection", ".", "join_to_update", "(", "stmt", ",", "arel", ")", "else", "stmt", ".", "take", "(", "arel", ".", "limit", ")", "stmt", ".", "order", "(", "arel", ".", "orders", ")", "stmt", ".", "wheres", "=", "arel", ".", "constraints", "end", "@klass", ".", "connection", ".", "update", "stmt", ",", "'SQL'", ",", "bind_values", "end", "end" ]
Updates all records with details given if they match a set of conditions supplied, limits and order can also be supplied. This method constructs a single SQL UPDATE statement and sends it straight to the database. It does not instantiate the involved models and it does not trigger Active Record callbacks or validations. ==== Parameters * +updates+ - A string, array, or hash representing the SET part of an SQL statement. * +conditions+ - A string, array, or hash representing the WHERE part of an SQL statement. See conditions in the intro. * +options+ - Additional options are <tt>:limit</tt> and <tt>:order</tt>, see the examples for usage. ==== Examples # Update all customers with the given attributes Customer.update_all :wants_email => true # Update all books with 'Rails' in their title Book.update_all "author = 'David'", "title LIKE '%Rails%'" # Update all avatars migrated more than a week ago Avatar.update_all ['migrated_at = ?', Time.now.utc], ['migrated_at > ?', 1.week.ago] # Update all books that match conditions, but limit it to 5 ordered by date Book.update_all "author = 'David'", "title LIKE '%Rails%'", :order => 'created_at', :limit => 5 # Conditions from the current relation also works Book.where('title LIKE ?', '%Rails%').update_all(:author => 'David') # The same idea applies to limit and order Book.where('title LIKE ?', '%Rails%').order(:created_at).limit(5).update_all(:author => 'David')
[ "Updates", "all", "records", "with", "details", "given", "if", "they", "match", "a", "set", "of", "conditions", "supplied", "limits", "and", "order", "can", "also", "be", "supplied", ".", "This", "method", "constructs", "a", "single", "SQL", "UPDATE", "statement", "and", "sends", "it", "straight", "to", "the", "database", ".", "It", "does", "not", "instantiate", "the", "involved", "models", "and", "it", "does", "not", "trigger", "Active", "Record", "callbacks", "or", "validations", "." ]
48d5d1a7442d9cade602be4fb782a1b56c7677f5
https://github.com/ktonon/code_node/blob/48d5d1a7442d9cade602be4fb782a1b56c7677f5/spec/fixtures/activerecord/src/active_record/relation.rb#L275-L296
9,844
wwidea/rexport
lib/rexport/data_fields.rb
Rexport.DataFields.export
def export(*methods) methods.flatten.map do |method| case value = (eval("self.#{method}", binding) rescue nil) when Date, Time value.strftime("%m/%d/%y") when TrueClass 'Y' when FalseClass 'N' else value.to_s end end end
ruby
def export(*methods) methods.flatten.map do |method| case value = (eval("self.#{method}", binding) rescue nil) when Date, Time value.strftime("%m/%d/%y") when TrueClass 'Y' when FalseClass 'N' else value.to_s end end end
[ "def", "export", "(", "*", "methods", ")", "methods", ".", "flatten", ".", "map", "do", "|", "method", "|", "case", "value", "=", "(", "eval", "(", "\"self.#{method}\"", ",", "binding", ")", "rescue", "nil", ")", "when", "Date", ",", "Time", "value", ".", "strftime", "(", "\"%m/%d/%y\"", ")", "when", "TrueClass", "'Y'", "when", "FalseClass", "'N'", "else", "value", ".", "to_s", "end", "end", "end" ]
Return an array of formatted export values for the passed methods
[ "Return", "an", "array", "of", "formatted", "export", "values", "for", "the", "passed", "methods" ]
f4f978dd0327ddba3a4318dd24090fbc6d4e4e59
https://github.com/wwidea/rexport/blob/f4f978dd0327ddba3a4318dd24090fbc6d4e4e59/lib/rexport/data_fields.rb#L100-L112
9,845
petebrowne/machined
lib/machined/environment.rb
Machined.Environment.reload
def reload # Make sure we have a fresh cache after we reload config.cache.clear if config.cache.respond_to?(:clear) # Reload dependencies as well, if necessary ActiveSupport::Dependencies.clear if defined?(ActiveSupport::Dependencies) # Use current configuration, but skip bundle and autoloading initializers current_config = config.marshal_dump.dup current_config.merge! :skip_bundle => true#, :skip_autoloading => true) initialize current_config end
ruby
def reload # Make sure we have a fresh cache after we reload config.cache.clear if config.cache.respond_to?(:clear) # Reload dependencies as well, if necessary ActiveSupport::Dependencies.clear if defined?(ActiveSupport::Dependencies) # Use current configuration, but skip bundle and autoloading initializers current_config = config.marshal_dump.dup current_config.merge! :skip_bundle => true#, :skip_autoloading => true) initialize current_config end
[ "def", "reload", "# Make sure we have a fresh cache after we reload", "config", ".", "cache", ".", "clear", "if", "config", ".", "cache", ".", "respond_to?", "(", ":clear", ")", "# Reload dependencies as well, if necessary", "ActiveSupport", "::", "Dependencies", ".", "clear", "if", "defined?", "(", "ActiveSupport", "::", "Dependencies", ")", "# Use current configuration, but skip bundle and autoloading initializers", "current_config", "=", "config", ".", "marshal_dump", ".", "dup", "current_config", ".", "merge!", ":skip_bundle", "=>", "true", "#, :skip_autoloading => true)", "initialize", "current_config", "end" ]
Reloads the environment. This will re-evaluate the config file & clear the current cache.
[ "Reloads", "the", "environment", ".", "This", "will", "re", "-", "evaluate", "the", "config", "file", "&", "clear", "the", "current", "cache", "." ]
4f3921bc5098104096474300e933f009f1b4f7dd
https://github.com/petebrowne/machined/blob/4f3921bc5098104096474300e933f009f1b4f7dd/lib/machined/environment.rb#L310-L322
9,846
petebrowne/machined
lib/machined/environment.rb
Machined.Environment.remove_sprocket
def remove_sprocket(name) if sprocket = get_sprocket(name) sprockets.delete sprocket set_sprocket(name, nil) end end
ruby
def remove_sprocket(name) if sprocket = get_sprocket(name) sprockets.delete sprocket set_sprocket(name, nil) end end
[ "def", "remove_sprocket", "(", "name", ")", "if", "sprocket", "=", "get_sprocket", "(", "name", ")", "sprockets", ".", "delete", "sprocket", "set_sprocket", "(", "name", ",", "nil", ")", "end", "end" ]
Removes the sprocket with the given name. This is useful if you don't need one of the default Sprockets.
[ "Removes", "the", "sprocket", "with", "the", "given", "name", ".", "This", "is", "useful", "if", "you", "don", "t", "need", "one", "of", "the", "default", "Sprockets", "." ]
4f3921bc5098104096474300e933f009f1b4f7dd
https://github.com/petebrowne/machined/blob/4f3921bc5098104096474300e933f009f1b4f7dd/lib/machined/environment.rb#L352-L357
9,847
petebrowne/machined
lib/machined/environment.rb
Machined.Environment.append_path
def append_path(sprocket, path) # :nodoc: path = Pathname.new(path).expand_path(root) sprocket.append_path(path) if path.exist? end
ruby
def append_path(sprocket, path) # :nodoc: path = Pathname.new(path).expand_path(root) sprocket.append_path(path) if path.exist? end
[ "def", "append_path", "(", "sprocket", ",", "path", ")", "# :nodoc:", "path", "=", "Pathname", ".", "new", "(", "path", ")", ".", "expand_path", "(", "root", ")", "sprocket", ".", "append_path", "(", "path", ")", "if", "path", ".", "exist?", "end" ]
Appends the given +path+ to the given +sprocket+ This makes sure the path is relative to the `root` path or an absolute path pointing somewhere else. It also checks if it exists before appending it.
[ "Appends", "the", "given", "+", "path", "+", "to", "the", "given", "+", "sprocket", "+", "This", "makes", "sure", "the", "path", "is", "relative", "to", "the", "root", "path", "or", "an", "absolute", "path", "pointing", "somewhere", "else", ".", "It", "also", "checks", "if", "it", "exists", "before", "appending", "it", "." ]
4f3921bc5098104096474300e933f009f1b4f7dd
https://github.com/petebrowne/machined/blob/4f3921bc5098104096474300e933f009f1b4f7dd/lib/machined/environment.rb#L420-L423
9,848
petebrowne/machined
lib/machined/environment.rb
Machined.Environment.append_paths
def append_paths(sprocket, paths) # :nodoc: paths or return paths.each do |path| append_path sprocket, path end end
ruby
def append_paths(sprocket, paths) # :nodoc: paths or return paths.each do |path| append_path sprocket, path end end
[ "def", "append_paths", "(", "sprocket", ",", "paths", ")", "# :nodoc:", "paths", "or", "return", "paths", ".", "each", "do", "|", "path", "|", "append_path", "sprocket", ",", "path", "end", "end" ]
Appends the given `Array` of +paths+ to the given +sprocket+.
[ "Appends", "the", "given", "Array", "of", "+", "paths", "+", "to", "the", "given", "+", "sprocket", "+", "." ]
4f3921bc5098104096474300e933f009f1b4f7dd
https://github.com/petebrowne/machined/blob/4f3921bc5098104096474300e933f009f1b4f7dd/lib/machined/environment.rb#L426-L431
9,849
petebrowne/machined
lib/machined/environment.rb
Machined.Environment.js_compressor
def js_compressor # :nodoc: case config.js_compressor when Crush::Engine config.js_compressor when Symbol, String JS_COMPRESSORS[config.js_compressor.to_sym] else Crush.register_js Tilt['js'] end end
ruby
def js_compressor # :nodoc: case config.js_compressor when Crush::Engine config.js_compressor when Symbol, String JS_COMPRESSORS[config.js_compressor.to_sym] else Crush.register_js Tilt['js'] end end
[ "def", "js_compressor", "# :nodoc:", "case", "config", ".", "js_compressor", "when", "Crush", "::", "Engine", "config", ".", "js_compressor", "when", "Symbol", ",", "String", "JS_COMPRESSORS", "[", "config", ".", "js_compressor", ".", "to_sym", "]", "else", "Crush", ".", "register_js", "Tilt", "[", "'js'", "]", "end", "end" ]
Returns the Javascript compression engine, based on what's set in `config.js_compressor`. If `config.js_compressor` is nil, let Tilt + Crush decide which one to use.
[ "Returns", "the", "Javascript", "compression", "engine", "based", "on", "what", "s", "set", "in", "config", ".", "js_compressor", ".", "If", "config", ".", "js_compressor", "is", "nil", "let", "Tilt", "+", "Crush", "decide", "which", "one", "to", "use", "." ]
4f3921bc5098104096474300e933f009f1b4f7dd
https://github.com/petebrowne/machined/blob/4f3921bc5098104096474300e933f009f1b4f7dd/lib/machined/environment.rb#L436-L446
9,850
petebrowne/machined
lib/machined/environment.rb
Machined.Environment.css_compressor
def css_compressor # :nodoc: case config.css_compressor when Crush::Engine config.css_compressor when Symbol, String CSS_COMPRESSORS[config.css_compressor.to_sym] else Crush.register_css Tilt['css'] end end
ruby
def css_compressor # :nodoc: case config.css_compressor when Crush::Engine config.css_compressor when Symbol, String CSS_COMPRESSORS[config.css_compressor.to_sym] else Crush.register_css Tilt['css'] end end
[ "def", "css_compressor", "# :nodoc:", "case", "config", ".", "css_compressor", "when", "Crush", "::", "Engine", "config", ".", "css_compressor", "when", "Symbol", ",", "String", "CSS_COMPRESSORS", "[", "config", ".", "css_compressor", ".", "to_sym", "]", "else", "Crush", ".", "register_css", "Tilt", "[", "'css'", "]", "end", "end" ]
Returns the CSS compression engine, based on what's set in `config.css_compressor`. If `config.css_compressor` is nil, let Tilt + Crush decide which one to use.
[ "Returns", "the", "CSS", "compression", "engine", "based", "on", "what", "s", "set", "in", "config", ".", "css_compressor", ".", "If", "config", ".", "css_compressor", "is", "nil", "let", "Tilt", "+", "Crush", "decide", "which", "one", "to", "use", "." ]
4f3921bc5098104096474300e933f009f1b4f7dd
https://github.com/petebrowne/machined/blob/4f3921bc5098104096474300e933f009f1b4f7dd/lib/machined/environment.rb#L451-L461
9,851
nsi-iff/nsivideogranulate-ruby
lib/nsivideogranulate/client.rb
NSIVideoGranulate.Client.granulate
def granulate(options = {}) @request_data = Hash.new if options[:video_link] insert_download_data options elsif options[:sam_uid] && options[:filename] file_data = {:video_uid => options[:sam_uid], :filename => options[:filename]} @request_data.merge! file_data elsif options[:file] && options[:filename] file_data = {:video => options[:file], :filename => options[:filename]} @request_data.merge! file_data else raise NSIVideoGranulate::Errors::Client::MissingParametersError end insert_callback_data options request = prepare_request :POST, @request_data.to_json execute_request(request) end
ruby
def granulate(options = {}) @request_data = Hash.new if options[:video_link] insert_download_data options elsif options[:sam_uid] && options[:filename] file_data = {:video_uid => options[:sam_uid], :filename => options[:filename]} @request_data.merge! file_data elsif options[:file] && options[:filename] file_data = {:video => options[:file], :filename => options[:filename]} @request_data.merge! file_data else raise NSIVideoGranulate::Errors::Client::MissingParametersError end insert_callback_data options request = prepare_request :POST, @request_data.to_json execute_request(request) end
[ "def", "granulate", "(", "options", "=", "{", "}", ")", "@request_data", "=", "Hash", ".", "new", "if", "options", "[", ":video_link", "]", "insert_download_data", "options", "elsif", "options", "[", ":sam_uid", "]", "&&", "options", "[", ":filename", "]", "file_data", "=", "{", ":video_uid", "=>", "options", "[", ":sam_uid", "]", ",", ":filename", "=>", "options", "[", ":filename", "]", "}", "@request_data", ".", "merge!", "file_data", "elsif", "options", "[", ":file", "]", "&&", "options", "[", ":filename", "]", "file_data", "=", "{", ":video", "=>", "options", "[", ":file", "]", ",", ":filename", "=>", "options", "[", ":filename", "]", "}", "@request_data", ".", "merge!", "file_data", "else", "raise", "NSIVideoGranulate", "::", "Errors", "::", "Client", "::", "MissingParametersError", "end", "insert_callback_data", "options", "request", "=", "prepare_request", ":POST", ",", "@request_data", ".", "to_json", "execute_request", "(", "request", ")", "end" ]
Initialize a client to a VideoGranulate node @param [Hash] options used to connect to the VideoGranulate node @options options [String] host to connect @options options [String] port to connect @options options [String] user to authenticatie with @options options [String] password to the refered user @return [Client] the object itself @example videogranulate = NSIVideoGranulate::Client.new host: 'localhost', port: '8886', user: 'test', password: 'test' @note if you had used the 'configure' method, you can use it without parameters and those you provided before will be used (see Client#configure) Send a video be granulated by a nsi.videogranulate node @param [Hash] options used to send a video to be graulated @option options [String] file the base64 encoded file to be granulated @option options [String] sam_uid the UID of a video at SAM @option options [String] filename the filename of the video @note the filename is very importante, the videogranulate node will use the proper coding/encoding option for the video type @option options [String] video_link link to the video that'll be granulated @note if provided both video_link and file options, file will be ignored and the client will download the video instead @option options [String] callback a callback url to the file granulation @option options [String] verb the callback request verb, when not provided, nsi.videogranulate defaults to POST @example A simple granulation require 'base64' video = Base64.encode64(File.new('video.ogv', 'r').read) response = nsivideogranulate.granulate(:file => video, :filename => 'video.ogv') nsivideogranulate.done(response["video_key"]) nsivideogranulate.grains_keys_for(response["video_key"]) @example Granulating from a SAM uid video = Base64.encode64(File.new('video.ogv', 'r').read) response = sam.store({:doc => doc}) video_key = response["key"] response = nsivideogranulate.granulate(:sam_uid => video_key, :filename => 'video.ogv') nsivideogranulate.done(response["video_key"]) nsivideogranulate.grains_keys_for(response["video_key"]) @example Downloading and granulating from web response = nsivideogranulate.granulate(:video_link => 'http://google.com/video.ogv') nsivideogranulate.done(response["video_key"]) nsivideogranulate.grains_keys_for(response["video_key"]) @example Sending a callback url video = Base64.encode64(File.new('video.ogv', 'r').read) nsivideogranulate.granulate(:file => video, :filename => 'video.ogv', :callback => 'http://google.com') nsivideogranulate.granulate(:video_link => 'http://google.com/video.ogv', :callback => 'http://google.com') @example Using a custom verb to the callback video = Base64.encode64(File.new('video.ogv', 'r').read) nsivideogranulate.granulate(:file => video, :filename => 'video.ogv', :callback => 'http://google.com', :verb => "PUT") nsivideogranulate.granulate(:video_link => 'http://google.com/video.ogv', :callback => 'http://google.com', :verb => "PUT") @return [Hash] response * "video_key" [String] the key to access the granulated video in the sam node it was stored @raise NSIVideoGranulate::Errors::Client::MissingParametersError when an invalid or incomplete set of parameters is provided @raise NSIVideoGranulate::Errors::Client::SAMConnectionError when cannot connect to the SAM node @raise NSIVideoGranulate::Errors::Client::AuthenticationError when invalids user and/or password are provided @raise NSIVideoGranulate::Errors::Client::KeyNotFoundError when an invalid sam_uid is provided
[ "Initialize", "a", "client", "to", "a", "VideoGranulate", "node" ]
794f44630ba6cac019a320288229ccccee00864d
https://github.com/nsi-iff/nsivideogranulate-ruby/blob/794f44630ba6cac019a320288229ccccee00864d/lib/nsivideogranulate/client.rb#L77-L93
9,852
nsi-iff/nsivideogranulate-ruby
lib/nsivideogranulate/client.rb
NSIVideoGranulate.Client.grains_keys_for
def grains_keys_for(video_key) request = prepare_request :GET, {:video_key => video_key, :grains => true}.to_json execute_request(request).select { |key| ['images', 'videos'].include? key } end
ruby
def grains_keys_for(video_key) request = prepare_request :GET, {:video_key => video_key, :grains => true}.to_json execute_request(request).select { |key| ['images', 'videos'].include? key } end
[ "def", "grains_keys_for", "(", "video_key", ")", "request", "=", "prepare_request", ":GET", ",", "{", ":video_key", "=>", "video_key", ",", ":grains", "=>", "true", "}", ".", "to_json", "execute_request", "(", "request", ")", ".", "select", "{", "|", "key", "|", "[", "'images'", ",", "'videos'", "]", ".", "include?", "key", "}", "end" ]
Return the keys of the grains of a video @param [String] key of the desired video @return [Hash] response * "images" [String] keys to the images grains of the video * "files" [String] keys to the files grains of the video @example nsivideogranulate.grains_keys_for("some key") @raise NSIVideoGranulate::Errors::Client::SAMConnectionError when cannot connect to the SAM node @raise NSIVideoGranulate::Errors::Client::AuthenticationError when invalids user and/or password are provided @raise NSIVideoGranulate::Errors::Client::KeyNotFoundError when an invalid key is provided
[ "Return", "the", "keys", "of", "the", "grains", "of", "a", "video" ]
794f44630ba6cac019a320288229ccccee00864d
https://github.com/nsi-iff/nsivideogranulate-ruby/blob/794f44630ba6cac019a320288229ccccee00864d/lib/nsivideogranulate/client.rb#L129-L132
9,853
0000marcell/simple_commander
lib/simple_commander/cli.rb
SimpleCommander.CLI.set_exec_path
def set_exec_path(path) yml = YAML.load_file(@config_file) yml[:exec_path] = File.expand_path(path) File.open(@config_file, 'w+'){|f| f.write(yml.to_yaml)} end
ruby
def set_exec_path(path) yml = YAML.load_file(@config_file) yml[:exec_path] = File.expand_path(path) File.open(@config_file, 'w+'){|f| f.write(yml.to_yaml)} end
[ "def", "set_exec_path", "(", "path", ")", "yml", "=", "YAML", ".", "load_file", "(", "@config_file", ")", "yml", "[", ":exec_path", "]", "=", "File", ".", "expand_path", "(", "path", ")", "File", ".", "open", "(", "@config_file", ",", "'w+'", ")", "{", "|", "f", "|", "f", ".", "write", "(", "yml", ".", "to_yaml", ")", "}", "end" ]
set exec path
[ "set", "exec", "path" ]
337c2e0d9926c643ce131b1a1ebd3740241e4424
https://github.com/0000marcell/simple_commander/blob/337c2e0d9926c643ce131b1a1ebd3740241e4424/lib/simple_commander/cli.rb#L99-L103
9,854
NUBIC/aker
lib/aker/rack/session_timer.rb
Aker::Rack.SessionTimer.call
def call(env) now = Time.now.to_i session = env['rack.session'] window_size = window_size(env) previous_timeout = session['aker.last_request_at'] return @app.call(env) unless window_size > 0 env['aker.timeout_at'] = now + window_size session['aker.last_request_at'] = now return @app.call(env) unless previous_timeout if now >= previous_timeout + window_size env['aker.session_expired'] = true env['warden'].logout end @app.call(env) end
ruby
def call(env) now = Time.now.to_i session = env['rack.session'] window_size = window_size(env) previous_timeout = session['aker.last_request_at'] return @app.call(env) unless window_size > 0 env['aker.timeout_at'] = now + window_size session['aker.last_request_at'] = now return @app.call(env) unless previous_timeout if now >= previous_timeout + window_size env['aker.session_expired'] = true env['warden'].logout end @app.call(env) end
[ "def", "call", "(", "env", ")", "now", "=", "Time", ".", "now", ".", "to_i", "session", "=", "env", "[", "'rack.session'", "]", "window_size", "=", "window_size", "(", "env", ")", "previous_timeout", "=", "session", "[", "'aker.last_request_at'", "]", "return", "@app", ".", "call", "(", "env", ")", "unless", "window_size", ">", "0", "env", "[", "'aker.timeout_at'", "]", "=", "now", "+", "window_size", "session", "[", "'aker.last_request_at'", "]", "=", "now", "return", "@app", ".", "call", "(", "env", ")", "unless", "previous_timeout", "if", "now", ">=", "previous_timeout", "+", "window_size", "env", "[", "'aker.session_expired'", "]", "=", "true", "env", "[", "'warden'", "]", ".", "logout", "end", "@app", ".", "call", "(", "env", ")", "end" ]
Determines whether the incoming request arrived within the timeout window. If it did, then the request is passed onto the rest of the Rack stack; otherwise, the user is redirected to the configured logout path.
[ "Determines", "whether", "the", "incoming", "request", "arrived", "within", "the", "timeout", "window", ".", "If", "it", "did", "then", "the", "request", "is", "passed", "onto", "the", "rest", "of", "the", "Rack", "stack", ";", "otherwise", "the", "user", "is", "redirected", "to", "the", "configured", "logout", "path", "." ]
ff43606a8812e38f96bbe71b46e7f631cbeacf1c
https://github.com/NUBIC/aker/blob/ff43606a8812e38f96bbe71b46e7f631cbeacf1c/lib/aker/rack/session_timer.rb#L69-L87
9,855
fanfilmu/conflow
lib/conflow/future.rb
Conflow.Future.build_promise
def build_promise(depending_job, param_key) Promise.new.tap do |promise| promise.assign_attributes(job_id: job.id, hash_field: param_key, result_key: result_key) depending_job.promise_ids << promise.id end end
ruby
def build_promise(depending_job, param_key) Promise.new.tap do |promise| promise.assign_attributes(job_id: job.id, hash_field: param_key, result_key: result_key) depending_job.promise_ids << promise.id end end
[ "def", "build_promise", "(", "depending_job", ",", "param_key", ")", "Promise", ".", "new", ".", "tap", "do", "|", "promise", "|", "promise", ".", "assign_attributes", "(", "job_id", ":", "job", ".", "id", ",", "hash_field", ":", "param_key", ",", "result_key", ":", "result_key", ")", "depending_job", ".", "promise_ids", "<<", "promise", ".", "id", "end", "end" ]
Builds promise from this future @api private @param depending_job [Conflow::Job] job which will use new promise @param param_key [Symbol, String] key in result hash that holds promised value @return [Conflow::Promise] promise object
[ "Builds", "promise", "from", "this", "future" ]
74b8fc2eb5a3a2a2a8918e1797d1e35c8ec9fdfb
https://github.com/fanfilmu/conflow/blob/74b8fc2eb5a3a2a2a8918e1797d1e35c8ec9fdfb/lib/conflow/future.rb#L46-L51
9,856
thriventures/storage_room_gem
lib/storage_room/accessors.rb
StorageRoom.Accessors.to_hash
def to_hash(args = {}) # :nodoc: args ||= {} hash = {} self.attributes.each do |name, value| hash[name] = if value.is_a?(::Array) value.map {|x| x.respond_to?(:to_hash) ? call_method_with_optional_parameters(x, :to_hash, :nested => true) : x} elsif value.respond_to?(:to_hash) call_method_with_optional_parameters(value, :to_hash, :nested => true) elsif value.respond_to?(:as_json) value.as_json(:nested => true) else value end end hash end
ruby
def to_hash(args = {}) # :nodoc: args ||= {} hash = {} self.attributes.each do |name, value| hash[name] = if value.is_a?(::Array) value.map {|x| x.respond_to?(:to_hash) ? call_method_with_optional_parameters(x, :to_hash, :nested => true) : x} elsif value.respond_to?(:to_hash) call_method_with_optional_parameters(value, :to_hash, :nested => true) elsif value.respond_to?(:as_json) value.as_json(:nested => true) else value end end hash end
[ "def", "to_hash", "(", "args", "=", "{", "}", ")", "# :nodoc:", "args", "||=", "{", "}", "hash", "=", "{", "}", "self", ".", "attributes", ".", "each", "do", "|", "name", ",", "value", "|", "hash", "[", "name", "]", "=", "if", "value", ".", "is_a?", "(", "::", "Array", ")", "value", ".", "map", "{", "|", "x", "|", "x", ".", "respond_to?", "(", ":to_hash", ")", "?", "call_method_with_optional_parameters", "(", "x", ",", ":to_hash", ",", ":nested", "=>", "true", ")", ":", "x", "}", "elsif", "value", ".", "respond_to?", "(", ":to_hash", ")", "call_method_with_optional_parameters", "(", "value", ",", ":to_hash", ",", ":nested", "=>", "true", ")", "elsif", "value", ".", "respond_to?", "(", ":as_json", ")", "value", ".", "as_json", "(", ":nested", "=>", "true", ")", "else", "value", "end", "end", "hash", "end" ]
ActiveSupport seemed to cause problems when just using as_json, so using to_hash
[ "ActiveSupport", "seemed", "to", "cause", "problems", "when", "just", "using", "as_json", "so", "using", "to_hash" ]
cadf132b865ff82f7b09fadfec1d294a714c6728
https://github.com/thriventures/storage_room_gem/blob/cadf132b865ff82f7b09fadfec1d294a714c6728/lib/storage_room/accessors.rb#L137-L154
9,857
thriventures/storage_room_gem
lib/storage_room/accessors.rb
StorageRoom.Accessors.call_method_with_optional_parameters
def call_method_with_optional_parameters(object, method_name, parameters) if object.respond_to?(method_name) if object.method(method_name).arity == -1 object.send(method_name, parameters) else object.send(method_name) end end end
ruby
def call_method_with_optional_parameters(object, method_name, parameters) if object.respond_to?(method_name) if object.method(method_name).arity == -1 object.send(method_name, parameters) else object.send(method_name) end end end
[ "def", "call_method_with_optional_parameters", "(", "object", ",", "method_name", ",", "parameters", ")", "if", "object", ".", "respond_to?", "(", "method_name", ")", "if", "object", ".", "method", "(", "method_name", ")", ".", "arity", "==", "-", "1", "object", ".", "send", "(", "method_name", ",", "parameters", ")", "else", "object", ".", "send", "(", "method_name", ")", "end", "end", "end" ]
Helper to not call to_hash with the wrong number of arguments
[ "Helper", "to", "not", "call", "to_hash", "with", "the", "wrong", "number", "of", "arguments" ]
cadf132b865ff82f7b09fadfec1d294a714c6728
https://github.com/thriventures/storage_room_gem/blob/cadf132b865ff82f7b09fadfec1d294a714c6728/lib/storage_room/accessors.rb#L190-L198
9,858
thriventures/storage_room_gem
lib/storage_room/accessors.rb
StorageRoom.Accessors.initialize_from_response_data
def initialize_from_response_data # :nodoc: run_callbacks :initialize_from_response_data do self.class.attribute_options_including_superclasses.each do |name, options| value = if options[:type] == :key self[name].blank? ? options[:default] : self[name] elsif options[:type] == :one hash = self[name.to_s] hash && hash['@type'] ? self.class.new_from_response_data(hash) : nil elsif options[:type] == :many response_data[name] && response_data[name].map{|hash| self.class.new_from_response_data(hash)} || [] else raise "Invalid type: #{options[:type]}" end send("#{name}=", value) end end end
ruby
def initialize_from_response_data # :nodoc: run_callbacks :initialize_from_response_data do self.class.attribute_options_including_superclasses.each do |name, options| value = if options[:type] == :key self[name].blank? ? options[:default] : self[name] elsif options[:type] == :one hash = self[name.to_s] hash && hash['@type'] ? self.class.new_from_response_data(hash) : nil elsif options[:type] == :many response_data[name] && response_data[name].map{|hash| self.class.new_from_response_data(hash)} || [] else raise "Invalid type: #{options[:type]}" end send("#{name}=", value) end end end
[ "def", "initialize_from_response_data", "# :nodoc:", "run_callbacks", ":initialize_from_response_data", "do", "self", ".", "class", ".", "attribute_options_including_superclasses", ".", "each", "do", "|", "name", ",", "options", "|", "value", "=", "if", "options", "[", ":type", "]", "==", ":key", "self", "[", "name", "]", ".", "blank?", "?", "options", "[", ":default", "]", ":", "self", "[", "name", "]", "elsif", "options", "[", ":type", "]", "==", ":one", "hash", "=", "self", "[", "name", ".", "to_s", "]", "hash", "&&", "hash", "[", "'@type'", "]", "?", "self", ".", "class", ".", "new_from_response_data", "(", "hash", ")", ":", "nil", "elsif", "options", "[", ":type", "]", "==", ":many", "response_data", "[", "name", "]", "&&", "response_data", "[", "name", "]", ".", "map", "{", "|", "hash", "|", "self", ".", "class", ".", "new_from_response_data", "(", "hash", ")", "}", "||", "[", "]", "else", "raise", "\"Invalid type: #{options[:type]}\"", "end", "send", "(", "\"#{name}=\"", ",", "value", ")", "end", "end", "end" ]
Iterate over the response data and initialize the attributes
[ "Iterate", "over", "the", "response", "data", "and", "initialize", "the", "attributes" ]
cadf132b865ff82f7b09fadfec1d294a714c6728
https://github.com/thriventures/storage_room_gem/blob/cadf132b865ff82f7b09fadfec1d294a714c6728/lib/storage_room/accessors.rb#L201-L218
9,859
ludocracy/Duxml
lib/duxml/meta/history.rb
Duxml.History.xml
def xml h = Element.new('history') events.each do |event| h << event.xml end h end
ruby
def xml h = Element.new('history') events.each do |event| h << event.xml end h end
[ "def", "xml", "h", "=", "Element", ".", "new", "(", "'history'", ")", "events", ".", "each", "do", "|", "event", "|", "h", "<<", "event", ".", "xml", "end", "h", "end" ]
used when creating a new metadata file for a static XML file @return [Doc] returns self as XML document
[ "used", "when", "creating", "a", "new", "metadata", "file", "for", "a", "static", "XML", "file" ]
b7d16c0bd27195825620091dfa60e21712221720
https://github.com/ludocracy/Duxml/blob/b7d16c0bd27195825620091dfa60e21712221720/lib/duxml/meta/history.rb#L44-L48
9,860
mkj-is/Truty
lib/truty/general.rb
Truty.General.general
def general(input, convert = [:all]) output = input output = ellipsis(output) if (convert.include?(:all) || convert.include?(:ellipsis)) output = multicharacters(output) if (convert.include? (:all) || convert.include?(:characters)) output = brackets_whitespace(output) if (convert.include?(:all) || convert.include?(:brackets)) output = emdash(output) if (convert.include?(:all) || convert.include?(:dashes)) output = endash(output) if (convert.include?(:all) || convert.include?(:dashes)) output = name_abbreviations(output) if (convert.include?(:all) || convert.include?(:abbreviations)) output = multiplication_sign(output) if (convert.include?(:all) || convert.include?(:multiplication)) output = space_between_numbers(output) if (convert.include?(:all) || convert.include?(:numbers)) output = units(output) if (convert.include?(:all) || convert.include?(:units)) output = widows(output) if (convert.include?(:all) || convert.include?(:widows)) output end
ruby
def general(input, convert = [:all]) output = input output = ellipsis(output) if (convert.include?(:all) || convert.include?(:ellipsis)) output = multicharacters(output) if (convert.include? (:all) || convert.include?(:characters)) output = brackets_whitespace(output) if (convert.include?(:all) || convert.include?(:brackets)) output = emdash(output) if (convert.include?(:all) || convert.include?(:dashes)) output = endash(output) if (convert.include?(:all) || convert.include?(:dashes)) output = name_abbreviations(output) if (convert.include?(:all) || convert.include?(:abbreviations)) output = multiplication_sign(output) if (convert.include?(:all) || convert.include?(:multiplication)) output = space_between_numbers(output) if (convert.include?(:all) || convert.include?(:numbers)) output = units(output) if (convert.include?(:all) || convert.include?(:units)) output = widows(output) if (convert.include?(:all) || convert.include?(:widows)) output end
[ "def", "general", "(", "input", ",", "convert", "=", "[", ":all", "]", ")", "output", "=", "input", "output", "=", "ellipsis", "(", "output", ")", "if", "(", "convert", ".", "include?", "(", ":all", ")", "||", "convert", ".", "include?", "(", ":ellipsis", ")", ")", "output", "=", "multicharacters", "(", "output", ")", "if", "(", "convert", ".", "include?", "(", ":all", ")", "||", "convert", ".", "include?", "(", ":characters", ")", ")", "output", "=", "brackets_whitespace", "(", "output", ")", "if", "(", "convert", ".", "include?", "(", ":all", ")", "||", "convert", ".", "include?", "(", ":brackets", ")", ")", "output", "=", "emdash", "(", "output", ")", "if", "(", "convert", ".", "include?", "(", ":all", ")", "||", "convert", ".", "include?", "(", ":dashes", ")", ")", "output", "=", "endash", "(", "output", ")", "if", "(", "convert", ".", "include?", "(", ":all", ")", "||", "convert", ".", "include?", "(", ":dashes", ")", ")", "output", "=", "name_abbreviations", "(", "output", ")", "if", "(", "convert", ".", "include?", "(", ":all", ")", "||", "convert", ".", "include?", "(", ":abbreviations", ")", ")", "output", "=", "multiplication_sign", "(", "output", ")", "if", "(", "convert", ".", "include?", "(", ":all", ")", "||", "convert", ".", "include?", "(", ":multiplication", ")", ")", "output", "=", "space_between_numbers", "(", "output", ")", "if", "(", "convert", ".", "include?", "(", ":all", ")", "||", "convert", ".", "include?", "(", ":numbers", ")", ")", "output", "=", "units", "(", "output", ")", "if", "(", "convert", ".", "include?", "(", ":all", ")", "||", "convert", ".", "include?", "(", ":units", ")", ")", "output", "=", "widows", "(", "output", ")", "if", "(", "convert", ".", "include?", "(", ":all", ")", "||", "convert", ".", "include?", "(", ":widows", ")", ")", "output", "end" ]
Improves basic non-language specific issues in typography. @param input [String] The paragraph which will be converted. @param convert [Array] Array of symbols with features that should be improved (possibilities: +all+, +hyphens+, +quotes+, +ellipsis+, +dashes+, +abbreviations+, +prepositions+, +numbers+, +dates+, +characters+, +brackets+, +multiplication+, +units+, +widows+) @return [String] Paragraph with improved typography.
[ "Improves", "basic", "non", "-", "language", "specific", "issues", "in", "typography", "." ]
315f49ad73cc2fa814a7793aa1b19657870ce98f
https://github.com/mkj-is/Truty/blob/315f49ad73cc2fa814a7793aa1b19657870ce98f/lib/truty/general.rb#L25-L38
9,861
mkj-is/Truty
lib/truty/general.rb
Truty.General.brackets_whitespace
def brackets_whitespace(input) output = input.gsub(/([\(\[\{])\s*/, '\1') output = output.gsub(/\s*([\]\)\}])/, '\1') output = output.gsub(/\s+([\(\[\{])\s*/, ' \1') output = output.gsub(/\s*([\]\)\}])\s+/, '\1 ') end
ruby
def brackets_whitespace(input) output = input.gsub(/([\(\[\{])\s*/, '\1') output = output.gsub(/\s*([\]\)\}])/, '\1') output = output.gsub(/\s+([\(\[\{])\s*/, ' \1') output = output.gsub(/\s*([\]\)\}])\s+/, '\1 ') end
[ "def", "brackets_whitespace", "(", "input", ")", "output", "=", "input", ".", "gsub", "(", "/", "\\(", "\\[", "\\{", "\\s", "/", ",", "'\\1'", ")", "output", "=", "output", ".", "gsub", "(", "/", "\\s", "\\]", "\\)", "\\}", "/", ",", "'\\1'", ")", "output", "=", "output", ".", "gsub", "(", "/", "\\s", "\\(", "\\[", "\\{", "\\s", "/", ",", "' \\1'", ")", "output", "=", "output", ".", "gsub", "(", "/", "\\s", "\\]", "\\)", "\\}", "\\s", "/", ",", "'\\1 '", ")", "end" ]
Fixes spaces around various brackets. @param input [String] The paragraph which will be converted. @return [String] Paragraph with correct spaces around brackets.
[ "Fixes", "spaces", "around", "various", "brackets", "." ]
315f49ad73cc2fa814a7793aa1b19657870ce98f
https://github.com/mkj-is/Truty/blob/315f49ad73cc2fa814a7793aa1b19657870ce98f/lib/truty/general.rb#L118-L123
9,862
xufeisofly/organismo
lib/organismo/element.rb
Organismo.Element.create
def create if text.match(/\_QUOTE/) require 'organismo/element/quote' Organismo::Element::Quote.new(text, location) elsif text.match(/\_SRC/) require 'organismo/element/code' Organismo::Element::Code.new(text, location) elsif text.match(/\_EXAMPLE/) require 'organismo/element/example' Organismo::Element::Example.new(text, location) elsif text.match(/\*/) require 'organismo/element/header' Organismo::Element::Header.new(text, location) elsif text.match(/\[\[\S*(\.png)|(\jpg)|(\.jpeg)\]\]/) require 'organismo/element/image' Organismo::Element::Image.new(text, location) elsif text.match(/\[\[\S*\]\]/) require 'organismo/element/link' Organismo::Element::Link.new(text, location) elsif text.match(/\-/) require 'organismo/element/plain_list' Organismo::Element::PlainList.new(text, location) else require 'organismo/element/text' Organismo::Element::Text.new(text, location) end end
ruby
def create if text.match(/\_QUOTE/) require 'organismo/element/quote' Organismo::Element::Quote.new(text, location) elsif text.match(/\_SRC/) require 'organismo/element/code' Organismo::Element::Code.new(text, location) elsif text.match(/\_EXAMPLE/) require 'organismo/element/example' Organismo::Element::Example.new(text, location) elsif text.match(/\*/) require 'organismo/element/header' Organismo::Element::Header.new(text, location) elsif text.match(/\[\[\S*(\.png)|(\jpg)|(\.jpeg)\]\]/) require 'organismo/element/image' Organismo::Element::Image.new(text, location) elsif text.match(/\[\[\S*\]\]/) require 'organismo/element/link' Organismo::Element::Link.new(text, location) elsif text.match(/\-/) require 'organismo/element/plain_list' Organismo::Element::PlainList.new(text, location) else require 'organismo/element/text' Organismo::Element::Text.new(text, location) end end
[ "def", "create", "if", "text", ".", "match", "(", "/", "\\_", "/", ")", "require", "'organismo/element/quote'", "Organismo", "::", "Element", "::", "Quote", ".", "new", "(", "text", ",", "location", ")", "elsif", "text", ".", "match", "(", "/", "\\_", "/", ")", "require", "'organismo/element/code'", "Organismo", "::", "Element", "::", "Code", ".", "new", "(", "text", ",", "location", ")", "elsif", "text", ".", "match", "(", "/", "\\_", "/", ")", "require", "'organismo/element/example'", "Organismo", "::", "Element", "::", "Example", ".", "new", "(", "text", ",", "location", ")", "elsif", "text", ".", "match", "(", "/", "\\*", "/", ")", "require", "'organismo/element/header'", "Organismo", "::", "Element", "::", "Header", ".", "new", "(", "text", ",", "location", ")", "elsif", "text", ".", "match", "(", "/", "\\[", "\\[", "\\S", "\\.", "\\j", "\\.", "\\]", "\\]", "/", ")", "require", "'organismo/element/image'", "Organismo", "::", "Element", "::", "Image", ".", "new", "(", "text", ",", "location", ")", "elsif", "text", ".", "match", "(", "/", "\\[", "\\[", "\\S", "\\]", "\\]", "/", ")", "require", "'organismo/element/link'", "Organismo", "::", "Element", "::", "Link", ".", "new", "(", "text", ",", "location", ")", "elsif", "text", ".", "match", "(", "/", "\\-", "/", ")", "require", "'organismo/element/plain_list'", "Organismo", "::", "Element", "::", "PlainList", ".", "new", "(", "text", ",", "location", ")", "else", "require", "'organismo/element/text'", "Organismo", "::", "Element", "::", "Text", ".", "new", "(", "text", ",", "location", ")", "end", "end" ]
require and initialize different instance depending on string regex
[ "require", "and", "initialize", "different", "instance", "depending", "on", "string", "regex" ]
cc133fc1c6206cb0efbff28daa7c9309481cd03e
https://github.com/xufeisofly/organismo/blob/cc133fc1c6206cb0efbff28daa7c9309481cd03e/lib/organismo/element.rb#L12-L38
9,863
octoai/gem-octocore-cassandra
lib/octocore-cassandra/email.rb
Octo.Email.send
def send(email, subject, opts = {}) if email.nil? or subject.nil? raise ArgumentError, 'Email Address or Subject is missing' else message = { from_name: Octo.get_config(:email_sender).fetch(:name), from_email: Octo.get_config(:email_sender).fetch(:email), subject: subject, text: opts.fetch('text', nil), html: opts.fetch('html', nil), to: [{ email: email, name: opts.fetch('name', nil) }] } # Pass the message to resque only when mandrill key is present _mandrill_config = ENV['MANDRILL_API_KEY'] || Octo.get_config(:mandrill_api_key) if _mandrill_config and !_mandrill_config.empty? enqueue_msg(message) end end end
ruby
def send(email, subject, opts = {}) if email.nil? or subject.nil? raise ArgumentError, 'Email Address or Subject is missing' else message = { from_name: Octo.get_config(:email_sender).fetch(:name), from_email: Octo.get_config(:email_sender).fetch(:email), subject: subject, text: opts.fetch('text', nil), html: opts.fetch('html', nil), to: [{ email: email, name: opts.fetch('name', nil) }] } # Pass the message to resque only when mandrill key is present _mandrill_config = ENV['MANDRILL_API_KEY'] || Octo.get_config(:mandrill_api_key) if _mandrill_config and !_mandrill_config.empty? enqueue_msg(message) end end end
[ "def", "send", "(", "email", ",", "subject", ",", "opts", "=", "{", "}", ")", "if", "email", ".", "nil?", "or", "subject", ".", "nil?", "raise", "ArgumentError", ",", "'Email Address or Subject is missing'", "else", "message", "=", "{", "from_name", ":", "Octo", ".", "get_config", "(", ":email_sender", ")", ".", "fetch", "(", ":name", ")", ",", "from_email", ":", "Octo", ".", "get_config", "(", ":email_sender", ")", ".", "fetch", "(", ":email", ")", ",", "subject", ":", "subject", ",", "text", ":", "opts", ".", "fetch", "(", "'text'", ",", "nil", ")", ",", "html", ":", "opts", ".", "fetch", "(", "'html'", ",", "nil", ")", ",", "to", ":", "[", "{", "email", ":", "email", ",", "name", ":", "opts", ".", "fetch", "(", "'name'", ",", "nil", ")", "}", "]", "}", "# Pass the message to resque only when mandrill key is present", "_mandrill_config", "=", "ENV", "[", "'MANDRILL_API_KEY'", "]", "||", "Octo", ".", "get_config", "(", ":mandrill_api_key", ")", "if", "_mandrill_config", "and", "!", "_mandrill_config", ".", "empty?", "enqueue_msg", "(", "message", ")", "end", "end", "end" ]
Send Emails using mandrill api @param [Text] email Email Address of the receiver @param [Text] subject Subject of Email @param [Hash] opt Hash contain other message details
[ "Send", "Emails", "using", "mandrill", "api" ]
c0977dce5ba0eb174ff810f161aba151069935df
https://github.com/octoai/gem-octocore-cassandra/blob/c0977dce5ba0eb174ff810f161aba151069935df/lib/octocore-cassandra/email.rb#L14-L38
9,864
andytinycat/debeasy
lib/debeasy/package.rb
Debeasy.Package.parse_control_file
def parse_control_file @control_file_contents.scan(/^([\w-]+?): (.*?)\n(?! )/m).each do |entry| field, value = entry @fields[field.gsub("-", "_").downcase] = value end @fields["installed_size"] = @fields["installed_size"].to_i * 1024 unless @fields["installed_size"].nil? end
ruby
def parse_control_file @control_file_contents.scan(/^([\w-]+?): (.*?)\n(?! )/m).each do |entry| field, value = entry @fields[field.gsub("-", "_").downcase] = value end @fields["installed_size"] = @fields["installed_size"].to_i * 1024 unless @fields["installed_size"].nil? end
[ "def", "parse_control_file", "@control_file_contents", ".", "scan", "(", "/", "\\w", "\\n", "/m", ")", ".", "each", "do", "|", "entry", "|", "field", ",", "value", "=", "entry", "@fields", "[", "field", ".", "gsub", "(", "\"-\"", ",", "\"_\"", ")", ".", "downcase", "]", "=", "value", "end", "@fields", "[", "\"installed_size\"", "]", "=", "@fields", "[", "\"installed_size\"", "]", ".", "to_i", "*", "1024", "unless", "@fields", "[", "\"installed_size\"", "]", ".", "nil?", "end" ]
Parse the available fields out of the Debian control file.
[ "Parse", "the", "available", "fields", "out", "of", "the", "Debian", "control", "file", "." ]
5f3a17a29eb47a12bb1e6d385d02e4426e379eb5
https://github.com/andytinycat/debeasy/blob/5f3a17a29eb47a12bb1e6d385d02e4426e379eb5/lib/debeasy/package.rb#L116-L122
9,865
RuthThompson/elastic_queue
lib/elastic_queue/query.rb
ElasticQueue.Query.method_missing
def method_missing(method, *args, &block) if @queue.respond_to?(method) proc = @queue.scopes[method] instance_exec *args, &proc end end
ruby
def method_missing(method, *args, &block) if @queue.respond_to?(method) proc = @queue.scopes[method] instance_exec *args, &proc end end
[ "def", "method_missing", "(", "method", ",", "*", "args", ",", "&", "block", ")", "if", "@queue", ".", "respond_to?", "(", "method", ")", "proc", "=", "@queue", ".", "scopes", "[", "method", "]", "instance_exec", "args", ",", "proc", "end", "end" ]
this allows you to chain scopes the 2+ scopes in the chain will be called on a query object and not on the base object
[ "this", "allows", "you", "to", "chain", "scopes", "the", "2", "+", "scopes", "in", "the", "chain", "will", "be", "called", "on", "a", "query", "object", "and", "not", "on", "the", "base", "object" ]
f91842c389a60145ff44ccd990e697a8094c7309
https://github.com/RuthThompson/elastic_queue/blob/f91842c389a60145ff44ccd990e697a8094c7309/lib/elastic_queue/query.rb#L84-L89
9,866
rike422/loose-leaf
app/channels/loose_leaf/collaboration_channel.rb
LooseLeaf.CollaborationChannel.document
def document(data) document = collaborative_model.find_by_collaborative_key(data['id']) @documents ||= [] @documents << document send_attribute_versions(document) stream_from "loose_leaf.documents.#{document.id}.operations" end
ruby
def document(data) document = collaborative_model.find_by_collaborative_key(data['id']) @documents ||= [] @documents << document send_attribute_versions(document) stream_from "loose_leaf.documents.#{document.id}.operations" end
[ "def", "document", "(", "data", ")", "document", "=", "collaborative_model", ".", "find_by_collaborative_key", "(", "data", "[", "'id'", "]", ")", "@documents", "||=", "[", "]", "@documents", "<<", "document", "send_attribute_versions", "(", "document", ")", "stream_from", "\"loose_leaf.documents.#{document.id}.operations\"", "end" ]
Subscribe to changes to a document
[ "Subscribe", "to", "changes", "to", "a", "document" ]
ea3cb93667f83e5f4abb3c7879fc0220157aeb81
https://github.com/rike422/loose-leaf/blob/ea3cb93667f83e5f4abb3c7879fc0220157aeb81/app/channels/loose_leaf/collaboration_channel.rb#L13-L22
9,867
rike422/loose-leaf
app/channels/loose_leaf/collaboration_channel.rb
LooseLeaf.CollaborationChannel.send_attribute_versions
def send_attribute_versions(document) collaborative_model.collaborative_attributes.each do |attribute_name| attribute = document.collaborative_attribute(attribute_name) transmit( document_id: document.id, action: 'attribute', attribute: attribute_name, version: attribute.version ) end end
ruby
def send_attribute_versions(document) collaborative_model.collaborative_attributes.each do |attribute_name| attribute = document.collaborative_attribute(attribute_name) transmit( document_id: document.id, action: 'attribute', attribute: attribute_name, version: attribute.version ) end end
[ "def", "send_attribute_versions", "(", "document", ")", "collaborative_model", ".", "collaborative_attributes", ".", "each", "do", "|", "attribute_name", "|", "attribute", "=", "document", ".", "collaborative_attribute", "(", "attribute_name", ")", "transmit", "(", "document_id", ":", "document", ".", "id", ",", "action", ":", "'attribute'", ",", "attribute", ":", "attribute_name", ",", "version", ":", "attribute", ".", "version", ")", "end", "end" ]
Send out initial versions
[ "Send", "out", "initial", "versions" ]
ea3cb93667f83e5f4abb3c7879fc0220157aeb81
https://github.com/rike422/loose-leaf/blob/ea3cb93667f83e5f4abb3c7879fc0220157aeb81/app/channels/loose_leaf/collaboration_channel.rb#L43-L54
9,868
maxjacobson/todo_lint
lib/todo_lint/cli.rb
TodoLint.Cli.load_files
def load_files(file_finder) if file_finder.options.fetch(:files).empty? file_finder.list(*options[:extensions]) else file_finder.options.fetch(:files) { [] } end end
ruby
def load_files(file_finder) if file_finder.options.fetch(:files).empty? file_finder.list(*options[:extensions]) else file_finder.options.fetch(:files) { [] } end end
[ "def", "load_files", "(", "file_finder", ")", "if", "file_finder", ".", "options", ".", "fetch", "(", ":files", ")", ".", "empty?", "file_finder", ".", "list", "(", "options", "[", ":extensions", "]", ")", "else", "file_finder", ".", "options", ".", "fetch", "(", ":files", ")", "{", "[", "]", "}", "end", "end" ]
Loads the files to be read @return [Array<String>] @example cli.load_files(file_finder) @api public
[ "Loads", "the", "files", "to", "be", "read" ]
0d1061383ea205ef4c74edc64568e308ac1af990
https://github.com/maxjacobson/todo_lint/blob/0d1061383ea205ef4c74edc64568e308ac1af990/lib/todo_lint/cli.rb#L39-L45
9,869
maxjacobson/todo_lint
lib/todo_lint/cli.rb
TodoLint.Cli.print_report
def print_report todos = [] finder = FileFinder.new(path, options) files = load_files(finder) files.each do |file| todos += Todo.within(File.open(file), :config => @options) end todos.sort.each.with_index do |todo, num| due_date = if todo.due_date tag_context = " via #{todo.tag}" if todo.tag? Rainbow(" (due #{todo.due_date.to_date}#{tag_context})") .public_send(todo.due_date.overdue? ? :red : :blue) else Rainbow(" (no due date)").red end puts "#{num + 1}. #{todo.task}#{due_date} " + Rainbow( "(#{todo.relative_path}:#{todo.line_number}:" \ "#{todo.character_number})" ).yellow end exit 0 end
ruby
def print_report todos = [] finder = FileFinder.new(path, options) files = load_files(finder) files.each do |file| todos += Todo.within(File.open(file), :config => @options) end todos.sort.each.with_index do |todo, num| due_date = if todo.due_date tag_context = " via #{todo.tag}" if todo.tag? Rainbow(" (due #{todo.due_date.to_date}#{tag_context})") .public_send(todo.due_date.overdue? ? :red : :blue) else Rainbow(" (no due date)").red end puts "#{num + 1}. #{todo.task}#{due_date} " + Rainbow( "(#{todo.relative_path}:#{todo.line_number}:" \ "#{todo.character_number})" ).yellow end exit 0 end
[ "def", "print_report", "todos", "=", "[", "]", "finder", "=", "FileFinder", ".", "new", "(", "path", ",", "options", ")", "files", "=", "load_files", "(", "finder", ")", "files", ".", "each", "do", "|", "file", "|", "todos", "+=", "Todo", ".", "within", "(", "File", ".", "open", "(", "file", ")", ",", ":config", "=>", "@options", ")", "end", "todos", ".", "sort", ".", "each", ".", "with_index", "do", "|", "todo", ",", "num", "|", "due_date", "=", "if", "todo", ".", "due_date", "tag_context", "=", "\" via #{todo.tag}\"", "if", "todo", ".", "tag?", "Rainbow", "(", "\" (due #{todo.due_date.to_date}#{tag_context})\"", ")", ".", "public_send", "(", "todo", ".", "due_date", ".", "overdue?", "?", ":red", ":", ":blue", ")", "else", "Rainbow", "(", "\" (no due date)\"", ")", ".", "red", "end", "puts", "\"#{num + 1}. #{todo.task}#{due_date} \"", "+", "Rainbow", "(", "\"(#{todo.relative_path}:#{todo.line_number}:\"", "\"#{todo.character_number})\"", ")", ".", "yellow", "end", "exit", "0", "end" ]
Print report of todos in codebase, then exit @return by exiting with 0 @api private
[ "Print", "report", "of", "todos", "in", "codebase", "then", "exit" ]
0d1061383ea205ef4c74edc64568e308ac1af990
https://github.com/maxjacobson/todo_lint/blob/0d1061383ea205ef4c74edc64568e308ac1af990/lib/todo_lint/cli.rb#L94-L117
9,870
aprescott/redhead
lib/redhead/header_set.rb
Redhead.HeaderSet.[]=
def []=(key, value) h = self[key] if h h.value = value else new_header = Redhead::Header.new(key, TO_RAW[key], value) self << new_header end end
ruby
def []=(key, value) h = self[key] if h h.value = value else new_header = Redhead::Header.new(key, TO_RAW[key], value) self << new_header end end
[ "def", "[]=", "(", "key", ",", "value", ")", "h", "=", "self", "[", "key", "]", "if", "h", "h", ".", "value", "=", "value", "else", "new_header", "=", "Redhead", "::", "Header", ".", "new", "(", "key", ",", "TO_RAW", "[", "key", "]", ",", "value", ")", "self", "<<", "new_header", "end", "end" ]
If there is a header in the set with a key matching _key_, then set its value to _value_. If there is no header matching _key_, create a new header with the given key and value.
[ "If", "there", "is", "a", "header", "in", "the", "set", "with", "a", "key", "matching", "_key_", "then", "set", "its", "value", "to", "_value_", ".", "If", "there", "is", "no", "header", "matching", "_key_", "create", "a", "new", "header", "with", "the", "given", "key", "and", "value", "." ]
4fe032029e6d3e5ebe88d61bbb0d5150fe204b3d
https://github.com/aprescott/redhead/blob/4fe032029e6d3e5ebe88d61bbb0d5150fe204b3d/lib/redhead/header_set.rb#L43-L51
9,871
aprescott/redhead
lib/redhead/header_set.rb
Redhead.HeaderSet.delete
def delete(key) header = self[key] @headers.reject! { |header| header.key == key } ? header : nil end
ruby
def delete(key) header = self[key] @headers.reject! { |header| header.key == key } ? header : nil end
[ "def", "delete", "(", "key", ")", "header", "=", "self", "[", "key", "]", "@headers", ".", "reject!", "{", "|", "header", "|", "header", ".", "key", "==", "key", "}", "?", "header", ":", "nil", "end" ]
Removes any headers with key names matching _key_ from the set.
[ "Removes", "any", "headers", "with", "key", "names", "matching", "_key_", "from", "the", "set", "." ]
4fe032029e6d3e5ebe88d61bbb0d5150fe204b3d
https://github.com/aprescott/redhead/blob/4fe032029e6d3e5ebe88d61bbb0d5150fe204b3d/lib/redhead/header_set.rb#L66-L69
9,872
erpe/acts_as_referred
lib/acts_as_referred/controller.rb
ActsAsReferred.Controller._supply_model_hook
def _supply_model_hook # 3.2.1 -> adwords auto-tagging - (show hint to manual tag adwords): # ?gclid=xxxx # 3.2.2 -> manual tagging # ?utm_source=google&utm_medium=cpc&utm_term=my_keyword&utm_campaign=my_summerdeal # 3.2.3 -> manual url-tagging specific for piwik # ?pk_campaign=my_summerdeal&pk_kwd=my_keyword # cookie / session persisted: # e.g.: "req=http://foo/baz?utm_campaign=plonk|ref=http://google.com/search|count=0" tmp = session[:__reqref] _struct = nil if tmp arr = tmp.split('|') _struct = OpenStruct.new( request_url: arr[0].split('=',2)[1], referrer_url: minlength_or_nil(arr[1].split('=',2)[1]), visit_count: arr[2].split('=',2)[1].to_i ) end ActiveRecord::Base.send( :define_method, '_get_reqref', proc{ _struct } ) end
ruby
def _supply_model_hook # 3.2.1 -> adwords auto-tagging - (show hint to manual tag adwords): # ?gclid=xxxx # 3.2.2 -> manual tagging # ?utm_source=google&utm_medium=cpc&utm_term=my_keyword&utm_campaign=my_summerdeal # 3.2.3 -> manual url-tagging specific for piwik # ?pk_campaign=my_summerdeal&pk_kwd=my_keyword # cookie / session persisted: # e.g.: "req=http://foo/baz?utm_campaign=plonk|ref=http://google.com/search|count=0" tmp = session[:__reqref] _struct = nil if tmp arr = tmp.split('|') _struct = OpenStruct.new( request_url: arr[0].split('=',2)[1], referrer_url: minlength_or_nil(arr[1].split('=',2)[1]), visit_count: arr[2].split('=',2)[1].to_i ) end ActiveRecord::Base.send( :define_method, '_get_reqref', proc{ _struct } ) end
[ "def", "_supply_model_hook", "# 3.2.1 -> adwords auto-tagging - (show hint to manual tag adwords):", "# ?gclid=xxxx ", "# 3.2.2 -> manual tagging ", "# ?utm_source=google&utm_medium=cpc&utm_term=my_keyword&utm_campaign=my_summerdeal ", "# 3.2.3 -> manual url-tagging specific for piwik ", "# ?pk_campaign=my_summerdeal&pk_kwd=my_keyword ", "# cookie / session persisted:", "# e.g.: \"req=http://foo/baz?utm_campaign=plonk|ref=http://google.com/search|count=0\"", "tmp", "=", "session", "[", ":__reqref", "]", "_struct", "=", "nil", "if", "tmp", "arr", "=", "tmp", ".", "split", "(", "'|'", ")", "_struct", "=", "OpenStruct", ".", "new", "(", "request_url", ":", "arr", "[", "0", "]", ".", "split", "(", "'='", ",", "2", ")", "[", "1", "]", ",", "referrer_url", ":", "minlength_or_nil", "(", "arr", "[", "1", "]", ".", "split", "(", "'='", ",", "2", ")", "[", "1", "]", ")", ",", "visit_count", ":", "arr", "[", "2", "]", ".", "split", "(", "'='", ",", "2", ")", "[", "1", "]", ".", "to_i", ")", "end", "ActiveRecord", "::", "Base", ".", "send", "(", ":define_method", ",", "'_get_reqref'", ",", "proc", "{", "_struct", "}", ")", "end" ]
The before_filter which processes necessary data for +acts_as_referred+ - models
[ "The", "before_filter", "which", "processes", "necessary", "data", "for", "+", "acts_as_referred", "+", "-", "models" ]
d1ffb3208e6e358c9888cec71c7bd76d30a0fdd3
https://github.com/erpe/acts_as_referred/blob/d1ffb3208e6e358c9888cec71c7bd76d30a0fdd3/lib/acts_as_referred/controller.rb#L16-L43
9,873
quixoten/queue_to_the_future
lib/queue_to_the_future/coordinator.rb
QueueToTheFuture.Coordinator.shutdown
def shutdown(force = false) @workforce.mu_synchronize do Thread.pass until @job_queue.empty? unless force while worker = @workforce.shift; worker.terminate; end end nil end
ruby
def shutdown(force = false) @workforce.mu_synchronize do Thread.pass until @job_queue.empty? unless force while worker = @workforce.shift; worker.terminate; end end nil end
[ "def", "shutdown", "(", "force", "=", "false", ")", "@workforce", ".", "mu_synchronize", "do", "Thread", ".", "pass", "until", "@job_queue", ".", "empty?", "unless", "force", "while", "worker", "=", "@workforce", ".", "shift", ";", "worker", ".", "terminate", ";", "end", "end", "nil", "end" ]
Prevents more workers from being created and waits for all jobs to finish. Once the jobs have completed the workers are terminated. To start up again just QueueToTheFuture::schedule more jobs once this method returns. @param [true, false] force If set to true, shutdown immediately and clear the queue without waiting for any jobs to complete.
[ "Prevents", "more", "workers", "from", "being", "created", "and", "waits", "for", "all", "jobs", "to", "finish", ".", "Once", "the", "jobs", "have", "completed", "the", "workers", "are", "terminated", "." ]
dd8260fa165ee42b95e6d76bc665fdf68339dfd6
https://github.com/quixoten/queue_to_the_future/blob/dd8260fa165ee42b95e6d76bc665fdf68339dfd6/lib/queue_to_the_future/coordinator.rb#L69-L76
9,874
lexruee/coach4rb
lib/coach4rb/coach.rb
Coach4rb.Coach.authenticate
def authenticate(username, password) begin options = {authorization: basic_auth_encryption(username, password)} url = url_for_path('/authenticateduser/') client.get(url, options) do |response| if response.code == 200 a_hash = parse response Resource::User.from_coach a_hash else false end end rescue raise 'Error: Could not authenticate user!' end end
ruby
def authenticate(username, password) begin options = {authorization: basic_auth_encryption(username, password)} url = url_for_path('/authenticateduser/') client.get(url, options) do |response| if response.code == 200 a_hash = parse response Resource::User.from_coach a_hash else false end end rescue raise 'Error: Could not authenticate user!' end end
[ "def", "authenticate", "(", "username", ",", "password", ")", "begin", "options", "=", "{", "authorization", ":", "basic_auth_encryption", "(", "username", ",", "password", ")", "}", "url", "=", "url_for_path", "(", "'/authenticateduser/'", ")", "client", ".", "get", "(", "url", ",", "options", ")", "do", "|", "response", "|", "if", "response", ".", "code", "==", "200", "a_hash", "=", "parse", "response", "Resource", "::", "User", ".", "from_coach", "a_hash", "else", "false", "end", "end", "rescue", "raise", "'Error: Could not authenticate user!'", "end", "end" ]
Creates a Coach client for the cyber coach webservcie. @param [Client] client @param [ResponseParser] response_parser @param [Boolean] debug @return [Coach] Authenticates a user against the Cyber Coach Webservice. @param username @param password @return [User] ====Example @example @coach.authenticate('arueedlinger', 'test')
[ "Creates", "a", "Coach", "client", "for", "the", "cyber", "coach", "webservcie", "." ]
59105bfe45a0717e655e0deff4d1540d511f6b02
https://github.com/lexruee/coach4rb/blob/59105bfe45a0717e655e0deff4d1540d511f6b02/lib/coach4rb/coach.rb#L30-L45
9,875
lexruee/coach4rb
lib/coach4rb/coach.rb
Coach4rb.Coach.user_exists?
def user_exists?(username) begin url = url_for_path(user_path(username)) client.get(url) { |response| response.code == 200 } rescue raise 'Error: Could not test user existence!' end end
ruby
def user_exists?(username) begin url = url_for_path(user_path(username)) client.get(url) { |response| response.code == 200 } rescue raise 'Error: Could not test user existence!' end end
[ "def", "user_exists?", "(", "username", ")", "begin", "url", "=", "url_for_path", "(", "user_path", "(", "username", ")", ")", "client", ".", "get", "(", "url", ")", "{", "|", "response", "|", "response", ".", "code", "==", "200", "}", "rescue", "raise", "'Error: Could not test user existence!'", "end", "end" ]
Tests if the user given its username exists.. @param username @return [Boolean] ====Examples @example @coach.user_exsists?('arueedlinger')
[ "Tests", "if", "the", "user", "given", "its", "username", "exists", ".." ]
59105bfe45a0717e655e0deff4d1540d511f6b02
https://github.com/lexruee/coach4rb/blob/59105bfe45a0717e655e0deff4d1540d511f6b02/lib/coach4rb/coach.rb#L74-L81
9,876
lexruee/coach4rb
lib/coach4rb/coach.rb
Coach4rb.Coach.create_user
def create_user(options={}, &block) builder = Builder::User.new(public_visible: Privacy::Public) block.call(builder) url = url_for_path(user_path(builder.username)) begin client.put(url, builder.to_xml, options) do |response| a_hash = parse response Resource::User.from_coach a_hash end rescue =>e raise e if debug false end end
ruby
def create_user(options={}, &block) builder = Builder::User.new(public_visible: Privacy::Public) block.call(builder) url = url_for_path(user_path(builder.username)) begin client.put(url, builder.to_xml, options) do |response| a_hash = parse response Resource::User.from_coach a_hash end rescue =>e raise e if debug false end end
[ "def", "create_user", "(", "options", "=", "{", "}", ",", "&", "block", ")", "builder", "=", "Builder", "::", "User", ".", "new", "(", "public_visible", ":", "Privacy", "::", "Public", ")", "block", ".", "call", "(", "builder", ")", "url", "=", "url_for_path", "(", "user_path", "(", "builder", ".", "username", ")", ")", "begin", "client", ".", "put", "(", "url", ",", "builder", ".", "to_xml", ",", "options", ")", "do", "|", "response", "|", "a_hash", "=", "parse", "response", "Resource", "::", "User", ".", "from_coach", "a_hash", "end", "rescue", "=>", "e", "raise", "e", "if", "debug", "false", "end", "end" ]
Creates a user with public visibility as default. @param [Hash] options @param [Block] block @return [User] ====Examples @example @coach.create_user do |user| user.real_name= 'the hoff' user.username= 'wantsomemoney' user.password= 'test' user.email= '[email protected]' user.public_visible= 2 end
[ "Creates", "a", "user", "with", "public", "visibility", "as", "default", "." ]
59105bfe45a0717e655e0deff4d1540d511f6b02
https://github.com/lexruee/coach4rb/blob/59105bfe45a0717e655e0deff4d1540d511f6b02/lib/coach4rb/coach.rb#L113-L127
9,877
lexruee/coach4rb
lib/coach4rb/coach.rb
Coach4rb.Coach.delete_user
def delete_user(user, options={}) raise 'Error: Param user is nil!' if user.nil? url = if user.is_a?(Resource::User) url_for_resource(user) elsif user.is_a?(String) url_for_path(user_path(user)) else raise 'Error: Invalid parameters!' end begin client.delete(url, options) do |response| response.code == 200 end rescue => e raise e if debug end end
ruby
def delete_user(user, options={}) raise 'Error: Param user is nil!' if user.nil? url = if user.is_a?(Resource::User) url_for_resource(user) elsif user.is_a?(String) url_for_path(user_path(user)) else raise 'Error: Invalid parameters!' end begin client.delete(url, options) do |response| response.code == 200 end rescue => e raise e if debug end end
[ "def", "delete_user", "(", "user", ",", "options", "=", "{", "}", ")", "raise", "'Error: Param user is nil!'", "if", "user", ".", "nil?", "url", "=", "if", "user", ".", "is_a?", "(", "Resource", "::", "User", ")", "url_for_resource", "(", "user", ")", "elsif", "user", ".", "is_a?", "(", "String", ")", "url_for_path", "(", "user_path", "(", "user", ")", ")", "else", "raise", "'Error: Invalid parameters!'", "end", "begin", "client", ".", "delete", "(", "url", ",", "options", ")", "do", "|", "response", "|", "response", ".", "code", "==", "200", "end", "rescue", "=>", "e", "raise", "e", "if", "debug", "end", "end" ]
Deletes a user. @param [User\String] user @param [Hash] options @return [Boolean] ====Examples @example @coach.delete_user(user) @example @coach.delete_user('arueedlinger')
[ "Deletes", "a", "user", "." ]
59105bfe45a0717e655e0deff4d1540d511f6b02
https://github.com/lexruee/coach4rb/blob/59105bfe45a0717e655e0deff4d1540d511f6b02/lib/coach4rb/coach.rb#L181-L198
9,878
lexruee/coach4rb
lib/coach4rb/coach.rb
Coach4rb.Coach.create_partnership
def create_partnership(first_user, second_user, options={}, &block) raise 'Error: Param first_user is nil!' if first_user.nil? raise 'Error: Param second_user is nil!' if second_user.nil? path = if first_user.is_a?(Resource::User) && second_user.is_a?(Resource::User) partnership_path(first_user.username, second_user.username) elsif first_user.is_a?(String) && second_user.is_a?(String) partnership_path(first_user, second_user) else raise 'Error: Invalid parameters!' end url = url_for_path(path) builder = Builder::Partnership.new(public_visible: Privacy::Public) block.call(builder) if block_given? begin client.put(url, builder.to_xml, options) do |response| a_hash = parse response Resource::Partnership.from_coach a_hash end rescue => e raise e if debug false end end
ruby
def create_partnership(first_user, second_user, options={}, &block) raise 'Error: Param first_user is nil!' if first_user.nil? raise 'Error: Param second_user is nil!' if second_user.nil? path = if first_user.is_a?(Resource::User) && second_user.is_a?(Resource::User) partnership_path(first_user.username, second_user.username) elsif first_user.is_a?(String) && second_user.is_a?(String) partnership_path(first_user, second_user) else raise 'Error: Invalid parameters!' end url = url_for_path(path) builder = Builder::Partnership.new(public_visible: Privacy::Public) block.call(builder) if block_given? begin client.put(url, builder.to_xml, options) do |response| a_hash = parse response Resource::Partnership.from_coach a_hash end rescue => e raise e if debug false end end
[ "def", "create_partnership", "(", "first_user", ",", "second_user", ",", "options", "=", "{", "}", ",", "&", "block", ")", "raise", "'Error: Param first_user is nil!'", "if", "first_user", ".", "nil?", "raise", "'Error: Param second_user is nil!'", "if", "second_user", ".", "nil?", "path", "=", "if", "first_user", ".", "is_a?", "(", "Resource", "::", "User", ")", "&&", "second_user", ".", "is_a?", "(", "Resource", "::", "User", ")", "partnership_path", "(", "first_user", ".", "username", ",", "second_user", ".", "username", ")", "elsif", "first_user", ".", "is_a?", "(", "String", ")", "&&", "second_user", ".", "is_a?", "(", "String", ")", "partnership_path", "(", "first_user", ",", "second_user", ")", "else", "raise", "'Error: Invalid parameters!'", "end", "url", "=", "url_for_path", "(", "path", ")", "builder", "=", "Builder", "::", "Partnership", ".", "new", "(", "public_visible", ":", "Privacy", "::", "Public", ")", "block", ".", "call", "(", "builder", ")", "if", "block_given?", "begin", "client", ".", "put", "(", "url", ",", "builder", ".", "to_xml", ",", "options", ")", "do", "|", "response", "|", "a_hash", "=", "parse", "response", "Resource", "::", "Partnership", ".", "from_coach", "a_hash", "end", "rescue", "=>", "e", "raise", "e", "if", "debug", "false", "end", "end" ]
Creates a partnership with public visibility as default. @param [User|String] first_user @param [User|String] second_user @param [Hash] options @return [Partnership] ====Examples @example @coach.create_partnership('arueedlinger','wanze2') @example @coach.create_partnership('arueedlinger','wanze2') do |p| p.public_visible = Coach4rb::Private end
[ "Creates", "a", "partnership", "with", "public", "visibility", "as", "default", "." ]
59105bfe45a0717e655e0deff4d1540d511f6b02
https://github.com/lexruee/coach4rb/blob/59105bfe45a0717e655e0deff4d1540d511f6b02/lib/coach4rb/coach.rb#L217-L240
9,879
lexruee/coach4rb
lib/coach4rb/coach.rb
Coach4rb.Coach.delete_partnership
def delete_partnership(partnership, options={}) raise 'Error: Param partnership is nil!' if partnership.nil? url = url_for_resource(partnership) begin client.delete(url, options) do |response| response.code == 200 end rescue => e raise e if debug false end end
ruby
def delete_partnership(partnership, options={}) raise 'Error: Param partnership is nil!' if partnership.nil? url = url_for_resource(partnership) begin client.delete(url, options) do |response| response.code == 200 end rescue => e raise e if debug false end end
[ "def", "delete_partnership", "(", "partnership", ",", "options", "=", "{", "}", ")", "raise", "'Error: Param partnership is nil!'", "if", "partnership", ".", "nil?", "url", "=", "url_for_resource", "(", "partnership", ")", "begin", "client", ".", "delete", "(", "url", ",", "options", ")", "do", "|", "response", "|", "response", ".", "code", "==", "200", "end", "rescue", "=>", "e", "raise", "e", "if", "debug", "false", "end", "end" ]
Deletes a partnership @param [Partnership] partnership @param [Hash] options @return [Boolean]
[ "Deletes", "a", "partnership" ]
59105bfe45a0717e655e0deff4d1540d511f6b02
https://github.com/lexruee/coach4rb/blob/59105bfe45a0717e655e0deff4d1540d511f6b02/lib/coach4rb/coach.rb#L249-L261
9,880
lexruee/coach4rb
lib/coach4rb/coach.rb
Coach4rb.Coach.breakup_between
def breakup_between(first_user, second_user, options={}) raise 'Error: Param first_user is nil!' if first_user.nil? raise 'Error: Param second_user is nil!' if second_user.nil? path = if first_user.is_a?(Resource::User) && second_user.is_a?(Resource::User) partnership_path(first_user.username, second_user.username) elsif first_user.is_a?(String) && second_user.is_a?(String) partnership_path(first_user, second_user) else raise 'Error: Invalid parameters!' end url = url_for_path(path) begin client.delete(url, options) do |response| response.code == 200 end rescue => e raise e if debug false end end
ruby
def breakup_between(first_user, second_user, options={}) raise 'Error: Param first_user is nil!' if first_user.nil? raise 'Error: Param second_user is nil!' if second_user.nil? path = if first_user.is_a?(Resource::User) && second_user.is_a?(Resource::User) partnership_path(first_user.username, second_user.username) elsif first_user.is_a?(String) && second_user.is_a?(String) partnership_path(first_user, second_user) else raise 'Error: Invalid parameters!' end url = url_for_path(path) begin client.delete(url, options) do |response| response.code == 200 end rescue => e raise e if debug false end end
[ "def", "breakup_between", "(", "first_user", ",", "second_user", ",", "options", "=", "{", "}", ")", "raise", "'Error: Param first_user is nil!'", "if", "first_user", ".", "nil?", "raise", "'Error: Param second_user is nil!'", "if", "second_user", ".", "nil?", "path", "=", "if", "first_user", ".", "is_a?", "(", "Resource", "::", "User", ")", "&&", "second_user", ".", "is_a?", "(", "Resource", "::", "User", ")", "partnership_path", "(", "first_user", ".", "username", ",", "second_user", ".", "username", ")", "elsif", "first_user", ".", "is_a?", "(", "String", ")", "&&", "second_user", ".", "is_a?", "(", "String", ")", "partnership_path", "(", "first_user", ",", "second_user", ")", "else", "raise", "'Error: Invalid parameters!'", "end", "url", "=", "url_for_path", "(", "path", ")", "begin", "client", ".", "delete", "(", "url", ",", "options", ")", "do", "|", "response", "|", "response", ".", "code", "==", "200", "end", "rescue", "=>", "e", "raise", "e", "if", "debug", "false", "end", "end" ]
Breaks up a partnership between two users. @param [User|String] first_user @param [User|String] second_user @param [Hash] options @return [Boolean]
[ "Breaks", "up", "a", "partnership", "between", "two", "users", "." ]
59105bfe45a0717e655e0deff4d1540d511f6b02
https://github.com/lexruee/coach4rb/blob/59105bfe45a0717e655e0deff4d1540d511f6b02/lib/coach4rb/coach.rb#L271-L291
9,881
lexruee/coach4rb
lib/coach4rb/coach.rb
Coach4rb.Coach.create_subscription
def create_subscription(user_partnership, sport, options={}, &block) raise 'Error: Param user_partnership is nil!' if user_partnership.nil? raise 'Error: Param sport is nil!' if sport.nil? url = if user_partnership.is_a?(Resource::User) url_for_path(subscription_user_path(user_partnership.username, sport)) elsif user_partnership.is_a?(Resource::Partnership) first_username = user_partnership.first_user.username second_username = user_partnership.second_user.username url_for_path(subscription_partnership_path(first_username, second_username, sport)) elsif user_partnership.is_a?(String) url_for_uri(user_partnership) else raise 'Error: Invalid parameter!' end builder = Builder::Subscription.new(public_visible: Privacy::Public) block.call(builder) if block_given? begin client.put(url, builder.to_xml, options) do |response| a_hash = parse response Resource::Subscription.from_coach a_hash end rescue => e raise e if debug false end end
ruby
def create_subscription(user_partnership, sport, options={}, &block) raise 'Error: Param user_partnership is nil!' if user_partnership.nil? raise 'Error: Param sport is nil!' if sport.nil? url = if user_partnership.is_a?(Resource::User) url_for_path(subscription_user_path(user_partnership.username, sport)) elsif user_partnership.is_a?(Resource::Partnership) first_username = user_partnership.first_user.username second_username = user_partnership.second_user.username url_for_path(subscription_partnership_path(first_username, second_username, sport)) elsif user_partnership.is_a?(String) url_for_uri(user_partnership) else raise 'Error: Invalid parameter!' end builder = Builder::Subscription.new(public_visible: Privacy::Public) block.call(builder) if block_given? begin client.put(url, builder.to_xml, options) do |response| a_hash = parse response Resource::Subscription.from_coach a_hash end rescue => e raise e if debug false end end
[ "def", "create_subscription", "(", "user_partnership", ",", "sport", ",", "options", "=", "{", "}", ",", "&", "block", ")", "raise", "'Error: Param user_partnership is nil!'", "if", "user_partnership", ".", "nil?", "raise", "'Error: Param sport is nil!'", "if", "sport", ".", "nil?", "url", "=", "if", "user_partnership", ".", "is_a?", "(", "Resource", "::", "User", ")", "url_for_path", "(", "subscription_user_path", "(", "user_partnership", ".", "username", ",", "sport", ")", ")", "elsif", "user_partnership", ".", "is_a?", "(", "Resource", "::", "Partnership", ")", "first_username", "=", "user_partnership", ".", "first_user", ".", "username", "second_username", "=", "user_partnership", ".", "second_user", ".", "username", "url_for_path", "(", "subscription_partnership_path", "(", "first_username", ",", "second_username", ",", "sport", ")", ")", "elsif", "user_partnership", ".", "is_a?", "(", "String", ")", "url_for_uri", "(", "user_partnership", ")", "else", "raise", "'Error: Invalid parameter!'", "end", "builder", "=", "Builder", "::", "Subscription", ".", "new", "(", "public_visible", ":", "Privacy", "::", "Public", ")", "block", ".", "call", "(", "builder", ")", "if", "block_given?", "begin", "client", ".", "put", "(", "url", ",", "builder", ".", "to_xml", ",", "options", ")", "do", "|", "response", "|", "a_hash", "=", "parse", "response", "Resource", "::", "Subscription", ".", "from_coach", "a_hash", "end", "rescue", "=>", "e", "raise", "e", "if", "debug", "false", "end", "end" ]
Creates a subscription with public visibility as default. @param [User|Partnership|String] user_partnership @param [String] sport @param [Hash] options @param [Block] block @return [Subscription] ====Examples @example @coach.create_subscription(user, :boxing) do |subscription| subscription.public_visible = Coach4rb::Privacy::Public end @example @coach.create_subscription(user, :boxing) @example partnership = @coach.partnership 'arueedlinger', 'asarteam5' @coach.subscribe(partnership, :running)
[ "Creates", "a", "subscription", "with", "public", "visibility", "as", "default", "." ]
59105bfe45a0717e655e0deff4d1540d511f6b02
https://github.com/lexruee/coach4rb/blob/59105bfe45a0717e655e0deff4d1540d511f6b02/lib/coach4rb/coach.rb#L315-L343
9,882
lexruee/coach4rb
lib/coach4rb/coach.rb
Coach4rb.Coach.create_entry
def create_entry(user_partnership, sport, options={}, &block) raise 'Error: Param user_partnership is nil!' if user_partnership.nil? raise 'Error: Param sport is nil!' if sport.nil? entry_type = sport.downcase.to_sym builder = Builder::Entry.builder(entry_type) url = if user_partnership.is_a?(Resource::Entity) url_for_resource(user_partnership) + sport.to_s elsif user_partnership.is_a?(String) url_for_uri(user_partnership) + sport.to_s else raise 'Error: Invalid parameter!' end block.call(builder) if block_given? begin client.post(url, builder.to_xml, options) do |response| if uri = response.headers[:location] entry_by_uri(uri, options) else false end end rescue => e raise e if debug false end end
ruby
def create_entry(user_partnership, sport, options={}, &block) raise 'Error: Param user_partnership is nil!' if user_partnership.nil? raise 'Error: Param sport is nil!' if sport.nil? entry_type = sport.downcase.to_sym builder = Builder::Entry.builder(entry_type) url = if user_partnership.is_a?(Resource::Entity) url_for_resource(user_partnership) + sport.to_s elsif user_partnership.is_a?(String) url_for_uri(user_partnership) + sport.to_s else raise 'Error: Invalid parameter!' end block.call(builder) if block_given? begin client.post(url, builder.to_xml, options) do |response| if uri = response.headers[:location] entry_by_uri(uri, options) else false end end rescue => e raise e if debug false end end
[ "def", "create_entry", "(", "user_partnership", ",", "sport", ",", "options", "=", "{", "}", ",", "&", "block", ")", "raise", "'Error: Param user_partnership is nil!'", "if", "user_partnership", ".", "nil?", "raise", "'Error: Param sport is nil!'", "if", "sport", ".", "nil?", "entry_type", "=", "sport", ".", "downcase", ".", "to_sym", "builder", "=", "Builder", "::", "Entry", ".", "builder", "(", "entry_type", ")", "url", "=", "if", "user_partnership", ".", "is_a?", "(", "Resource", "::", "Entity", ")", "url_for_resource", "(", "user_partnership", ")", "+", "sport", ".", "to_s", "elsif", "user_partnership", ".", "is_a?", "(", "String", ")", "url_for_uri", "(", "user_partnership", ")", "+", "sport", ".", "to_s", "else", "raise", "'Error: Invalid parameter!'", "end", "block", ".", "call", "(", "builder", ")", "if", "block_given?", "begin", "client", ".", "post", "(", "url", ",", "builder", ".", "to_xml", ",", "options", ")", "do", "|", "response", "|", "if", "uri", "=", "response", ".", "headers", "[", ":location", "]", "entry_by_uri", "(", "uri", ",", "options", ")", "else", "false", "end", "end", "rescue", "=>", "e", "raise", "e", "if", "debug", "false", "end", "end" ]
Creates an entry with public visibility as default. @param [User|Partnership|String] user_partnership @param [Hash] options @param [Block] block @return [Entry|Boolean] ====Examples @example entry = @coach.create_entry(@user, :running) do |e| e.comment = 'test' e.number_of_rounds = 10 e.public_visible = Coach4rb::Privacy::Public end @example entry = @coach.create_entry(@user, :soccer) do |e| e.comment = 'test' e.number_of_rounds = 10 end
[ "Creates", "an", "entry", "with", "public", "visibility", "as", "default", "." ]
59105bfe45a0717e655e0deff4d1540d511f6b02
https://github.com/lexruee/coach4rb/blob/59105bfe45a0717e655e0deff4d1540d511f6b02/lib/coach4rb/coach.rb#L432-L461
9,883
lexruee/coach4rb
lib/coach4rb/coach.rb
Coach4rb.Coach.update_entry
def update_entry(entry, options={}, &block) raise 'Error: Param entry is nil!' if entry.nil? url, entry_type = if entry.is_a?(Resource::Entry) [url_for_resource(entry), entry.type] else *, type, id = url_for_uri(entry).split('/') type = type.downcase.to_sym [url_for_uri(entry), type] end builder = Builder::Entry.builder(entry_type) block.call(builder) begin client.put(url, builder.to_xml, options) do |response| a_hash = parse(response) Resource::Entry.from_coach a_hash end rescue => e raise e if debug false end end
ruby
def update_entry(entry, options={}, &block) raise 'Error: Param entry is nil!' if entry.nil? url, entry_type = if entry.is_a?(Resource::Entry) [url_for_resource(entry), entry.type] else *, type, id = url_for_uri(entry).split('/') type = type.downcase.to_sym [url_for_uri(entry), type] end builder = Builder::Entry.builder(entry_type) block.call(builder) begin client.put(url, builder.to_xml, options) do |response| a_hash = parse(response) Resource::Entry.from_coach a_hash end rescue => e raise e if debug false end end
[ "def", "update_entry", "(", "entry", ",", "options", "=", "{", "}", ",", "&", "block", ")", "raise", "'Error: Param entry is nil!'", "if", "entry", ".", "nil?", "url", ",", "entry_type", "=", "if", "entry", ".", "is_a?", "(", "Resource", "::", "Entry", ")", "[", "url_for_resource", "(", "entry", ")", ",", "entry", ".", "type", "]", "else", "*", ",", "type", ",", "id", "=", "url_for_uri", "(", "entry", ")", ".", "split", "(", "'/'", ")", "type", "=", "type", ".", "downcase", ".", "to_sym", "[", "url_for_uri", "(", "entry", ")", ",", "type", "]", "end", "builder", "=", "Builder", "::", "Entry", ".", "builder", "(", "entry_type", ")", "block", ".", "call", "(", "builder", ")", "begin", "client", ".", "put", "(", "url", ",", "builder", ".", "to_xml", ",", "options", ")", "do", "|", "response", "|", "a_hash", "=", "parse", "(", "response", ")", "Resource", "::", "Entry", ".", "from_coach", "a_hash", "end", "rescue", "=>", "e", "raise", "e", "if", "debug", "false", "end", "end" ]
Updates an entry. @param [Entry|String] entry @param [Hash] options @param [Block] block @return [Entry|Boolean] ====Examples @example entry = @coach.entry_by_uri '/CyberCoachServer/resources/users/wantsomemoney/Running/1138/' updated_entry = @proxy.update_entry(entry) do |entry| entry.comment = 'Test!!' end @example uri = '/CyberCoachServer/resources/users/wantsomemoney/Running/1138/' res = @proxy.update_entry(uri) do |entry| entry.comment = 'Test!' end
[ "Updates", "an", "entry", "." ]
59105bfe45a0717e655e0deff4d1540d511f6b02
https://github.com/lexruee/coach4rb/blob/59105bfe45a0717e655e0deff4d1540d511f6b02/lib/coach4rb/coach.rb#L484-L506
9,884
lexruee/coach4rb
lib/coach4rb/coach.rb
Coach4rb.Coach.delete_entry
def delete_entry(entry, options={}) raise 'Error: Param entry is nil!' if entry.nil? url = if entry.is_a?(Resource::Entry) url_for_resource(entry) elsif entry.is_a?(String) url_for_uri(entry) else raise 'Error: Invalid parameter!' end begin client.delete(url, options) do |response| response.code == 200 end rescue => e raise e if debug false end end
ruby
def delete_entry(entry, options={}) raise 'Error: Param entry is nil!' if entry.nil? url = if entry.is_a?(Resource::Entry) url_for_resource(entry) elsif entry.is_a?(String) url_for_uri(entry) else raise 'Error: Invalid parameter!' end begin client.delete(url, options) do |response| response.code == 200 end rescue => e raise e if debug false end end
[ "def", "delete_entry", "(", "entry", ",", "options", "=", "{", "}", ")", "raise", "'Error: Param entry is nil!'", "if", "entry", ".", "nil?", "url", "=", "if", "entry", ".", "is_a?", "(", "Resource", "::", "Entry", ")", "url_for_resource", "(", "entry", ")", "elsif", "entry", ".", "is_a?", "(", "String", ")", "url_for_uri", "(", "entry", ")", "else", "raise", "'Error: Invalid parameter!'", "end", "begin", "client", ".", "delete", "(", "url", ",", "options", ")", "do", "|", "response", "|", "response", ".", "code", "==", "200", "end", "rescue", "=>", "e", "raise", "e", "if", "debug", "false", "end", "end" ]
Deletes an entry.. @param [Entry|String] entry @param [Hash] options @return [Boolean]
[ "Deletes", "an", "entry", ".." ]
59105bfe45a0717e655e0deff4d1540d511f6b02
https://github.com/lexruee/coach4rb/blob/59105bfe45a0717e655e0deff4d1540d511f6b02/lib/coach4rb/coach.rb#L515-L533
9,885
lexruee/coach4rb
lib/coach4rb/coach.rb
Coach4rb.Coach.user
def user(user, options={}) raise 'Error: Param user is nil!' if user.nil? url = if user.is_a?(Resource::User) url_for_resource(user) elsif user.is_a?(String) url_for_path(user_path(user)) else raise 'Error: Invalid parameter!' end url = append_query_params(url, options) client.get(url, options) do |response| a_hash = parse(response) Resource::User.from_coach a_hash end end
ruby
def user(user, options={}) raise 'Error: Param user is nil!' if user.nil? url = if user.is_a?(Resource::User) url_for_resource(user) elsif user.is_a?(String) url_for_path(user_path(user)) else raise 'Error: Invalid parameter!' end url = append_query_params(url, options) client.get(url, options) do |response| a_hash = parse(response) Resource::User.from_coach a_hash end end
[ "def", "user", "(", "user", ",", "options", "=", "{", "}", ")", "raise", "'Error: Param user is nil!'", "if", "user", ".", "nil?", "url", "=", "if", "user", ".", "is_a?", "(", "Resource", "::", "User", ")", "url_for_resource", "(", "user", ")", "elsif", "user", ".", "is_a?", "(", "String", ")", "url_for_path", "(", "user_path", "(", "user", ")", ")", "else", "raise", "'Error: Invalid parameter!'", "end", "url", "=", "append_query_params", "(", "url", ",", "options", ")", "client", ".", "get", "(", "url", ",", "options", ")", "do", "|", "response", "|", "a_hash", "=", "parse", "(", "response", ")", "Resource", "::", "User", ".", "from_coach", "a_hash", "end", "end" ]
Retrieves a user by its username. @param [String|User] username | user @param [Hash] options @return [User] ====Examples @example user = @coach.user a_user @example user = @coach.user 'arueedlinger' @example user = @coach.user 'arueedlinger', query: { start: 0, soze: 10 }
[ "Retrieves", "a", "user", "by", "its", "username", "." ]
59105bfe45a0717e655e0deff4d1540d511f6b02
https://github.com/lexruee/coach4rb/blob/59105bfe45a0717e655e0deff4d1540d511f6b02/lib/coach4rb/coach.rb#L550-L565
9,886
lexruee/coach4rb
lib/coach4rb/coach.rb
Coach4rb.Coach.user_by_uri
def user_by_uri(uri, options={}) raise 'Error: Param uri is nil!' if uri.nil? url = url_for_uri(uri) url = append_query_params(url, options) client.get(url, options) do |response| a_hash = parse(response) Resource::User.from_coach a_hash end end
ruby
def user_by_uri(uri, options={}) raise 'Error: Param uri is nil!' if uri.nil? url = url_for_uri(uri) url = append_query_params(url, options) client.get(url, options) do |response| a_hash = parse(response) Resource::User.from_coach a_hash end end
[ "def", "user_by_uri", "(", "uri", ",", "options", "=", "{", "}", ")", "raise", "'Error: Param uri is nil!'", "if", "uri", ".", "nil?", "url", "=", "url_for_uri", "(", "uri", ")", "url", "=", "append_query_params", "(", "url", ",", "options", ")", "client", ".", "get", "(", "url", ",", "options", ")", "do", "|", "response", "|", "a_hash", "=", "parse", "(", "response", ")", "Resource", "::", "User", ".", "from_coach", "a_hash", "end", "end" ]
Retrieves a user by its uri. @param [String] uri @param [Hash] options @return [User] ====Examples @example user = @coach.user_by_uri '/CyberCoachServer/resources/users/arueedlinger', query: { start: 0, soze: 10 } @example user = @coach.user_by_uri '/CyberCoachServer/resources/users/arueedlinger'
[ "Retrieves", "a", "user", "by", "its", "uri", "." ]
59105bfe45a0717e655e0deff4d1540d511f6b02
https://github.com/lexruee/coach4rb/blob/59105bfe45a0717e655e0deff4d1540d511f6b02/lib/coach4rb/coach.rb#L581-L590
9,887
lexruee/coach4rb
lib/coach4rb/coach.rb
Coach4rb.Coach.users
def users(options={query: {}}) url = url_for_path(user_path) url = append_query_params(url, options) client.get(url, options) do |response| a_hash = parse(response) Resource::Page.from_coach a_hash, Resource::User end end
ruby
def users(options={query: {}}) url = url_for_path(user_path) url = append_query_params(url, options) client.get(url, options) do |response| a_hash = parse(response) Resource::Page.from_coach a_hash, Resource::User end end
[ "def", "users", "(", "options", "=", "{", "query", ":", "{", "}", "}", ")", "url", "=", "url_for_path", "(", "user_path", ")", "url", "=", "append_query_params", "(", "url", ",", "options", ")", "client", ".", "get", "(", "url", ",", "options", ")", "do", "|", "response", "|", "a_hash", "=", "parse", "(", "response", ")", "Resource", "::", "Page", ".", "from_coach", "a_hash", ",", "Resource", "::", "User", "end", "end" ]
Retrieves users. @param [Hash] options @return [PageResource] ====Examples @example users = @coach.users @example users = @coach.users query: { start: 0, size: 10}
[ "Retrieves", "users", "." ]
59105bfe45a0717e655e0deff4d1540d511f6b02
https://github.com/lexruee/coach4rb/blob/59105bfe45a0717e655e0deff4d1540d511f6b02/lib/coach4rb/coach.rb#L604-L611
9,888
lexruee/coach4rb
lib/coach4rb/coach.rb
Coach4rb.Coach.partnership_by_uri
def partnership_by_uri(uri, options={}) raise 'Error: Param uri is nil!' if uri.nil? url = url_for_uri(uri) url = append_query_params(url, options) client.get(url, options) do |response| a_hash = parse(response) Resource::Partnership.from_coach a_hash end end
ruby
def partnership_by_uri(uri, options={}) raise 'Error: Param uri is nil!' if uri.nil? url = url_for_uri(uri) url = append_query_params(url, options) client.get(url, options) do |response| a_hash = parse(response) Resource::Partnership.from_coach a_hash end end
[ "def", "partnership_by_uri", "(", "uri", ",", "options", "=", "{", "}", ")", "raise", "'Error: Param uri is nil!'", "if", "uri", ".", "nil?", "url", "=", "url_for_uri", "(", "uri", ")", "url", "=", "append_query_params", "(", "url", ",", "options", ")", "client", ".", "get", "(", "url", ",", "options", ")", "do", "|", "response", "|", "a_hash", "=", "parse", "(", "response", ")", "Resource", "::", "Partnership", ".", "from_coach", "a_hash", "end", "end" ]
Retrieves a partnership by its uri. @param [String] uri @param [Hash] options @return [Partnership] ====Examples @example partnership = @coach.partnership_by_uri '/CyberCoachServer/resources/partnerships/arueedlinger;asarteam5/'
[ "Retrieves", "a", "partnership", "by", "its", "uri", "." ]
59105bfe45a0717e655e0deff4d1540d511f6b02
https://github.com/lexruee/coach4rb/blob/59105bfe45a0717e655e0deff4d1540d511f6b02/lib/coach4rb/coach.rb#L624-L633
9,889
lexruee/coach4rb
lib/coach4rb/coach.rb
Coach4rb.Coach.partnership
def partnership(first_username, second_username, options={}) raise 'Error: Param first_username is nil!' if first_username.nil? raise 'Error: Param second_username is nil!' if second_username.nil? url = url_for_path(partnership_path(first_username, second_username)) url = append_query_params(url, options) client.get(url, options) do |response| a_hash = parse(response) Resource::Partnership.from_coach a_hash end end
ruby
def partnership(first_username, second_username, options={}) raise 'Error: Param first_username is nil!' if first_username.nil? raise 'Error: Param second_username is nil!' if second_username.nil? url = url_for_path(partnership_path(first_username, second_username)) url = append_query_params(url, options) client.get(url, options) do |response| a_hash = parse(response) Resource::Partnership.from_coach a_hash end end
[ "def", "partnership", "(", "first_username", ",", "second_username", ",", "options", "=", "{", "}", ")", "raise", "'Error: Param first_username is nil!'", "if", "first_username", ".", "nil?", "raise", "'Error: Param second_username is nil!'", "if", "second_username", ".", "nil?", "url", "=", "url_for_path", "(", "partnership_path", "(", "first_username", ",", "second_username", ")", ")", "url", "=", "append_query_params", "(", "url", ",", "options", ")", "client", ".", "get", "(", "url", ",", "options", ")", "do", "|", "response", "|", "a_hash", "=", "parse", "(", "response", ")", "Resource", "::", "Partnership", ".", "from_coach", "a_hash", "end", "end" ]
Retrieves a partnership by the first username and second username. @param [String] first_username @param [String] second_username @param [Hash] options @return [Partnership] ====Examples @example partnership = @coach.partnership 'arueedlinger', 'asarteam5'
[ "Retrieves", "a", "partnership", "by", "the", "first", "username", "and", "second", "username", "." ]
59105bfe45a0717e655e0deff4d1540d511f6b02
https://github.com/lexruee/coach4rb/blob/59105bfe45a0717e655e0deff4d1540d511f6b02/lib/coach4rb/coach.rb#L647-L657
9,890
lexruee/coach4rb
lib/coach4rb/coach.rb
Coach4rb.Coach.partnerships
def partnerships(options={query: {}}) url = url_for_path(partnership_path) url = append_query_params(url, options) client.get(url, options) do |response| a_hash = parse(response) Resource::Page.from_coach a_hash, Resource::Partnership end end
ruby
def partnerships(options={query: {}}) url = url_for_path(partnership_path) url = append_query_params(url, options) client.get(url, options) do |response| a_hash = parse(response) Resource::Page.from_coach a_hash, Resource::Partnership end end
[ "def", "partnerships", "(", "options", "=", "{", "query", ":", "{", "}", "}", ")", "url", "=", "url_for_path", "(", "partnership_path", ")", "url", "=", "append_query_params", "(", "url", ",", "options", ")", "client", ".", "get", "(", "url", ",", "options", ")", "do", "|", "response", "|", "a_hash", "=", "parse", "(", "response", ")", "Resource", "::", "Page", ".", "from_coach", "a_hash", ",", "Resource", "::", "Partnership", "end", "end" ]
Retrieves partnerships. @param [Hash] options @return [PageResource] ====Examples @example partnerships = @coach.partnerships @example partnerships = @coach.partnerships query: { start: 0, size: 10}
[ "Retrieves", "partnerships", "." ]
59105bfe45a0717e655e0deff4d1540d511f6b02
https://github.com/lexruee/coach4rb/blob/59105bfe45a0717e655e0deff4d1540d511f6b02/lib/coach4rb/coach.rb#L671-L678
9,891
NUBIC/aker
lib/aker/form/middleware/logout_responder.rb
Aker::Form::Middleware.LogoutResponder.call
def call(env) if env['REQUEST_METHOD'] == 'GET' && env['PATH_INFO'] == logout_path(env) ::Rack::Response.new(login_html(env, :logged_out => true)) do |resp| resp['Content-Type'] = 'text/html' end.finish else @app.call(env) end end
ruby
def call(env) if env['REQUEST_METHOD'] == 'GET' && env['PATH_INFO'] == logout_path(env) ::Rack::Response.new(login_html(env, :logged_out => true)) do |resp| resp['Content-Type'] = 'text/html' end.finish else @app.call(env) end end
[ "def", "call", "(", "env", ")", "if", "env", "[", "'REQUEST_METHOD'", "]", "==", "'GET'", "&&", "env", "[", "'PATH_INFO'", "]", "==", "logout_path", "(", "env", ")", "::", "Rack", "::", "Response", ".", "new", "(", "login_html", "(", "env", ",", ":logged_out", "=>", "true", ")", ")", "do", "|", "resp", "|", "resp", "[", "'Content-Type'", "]", "=", "'text/html'", "end", ".", "finish", "else", "@app", ".", "call", "(", "env", ")", "end", "end" ]
When given `GET` to the configured logout path, builds a Rack response containing the login form with a "you have been logged out" notification. Otherwise, passes the response on. @return a finished Rack response
[ "When", "given", "GET", "to", "the", "configured", "logout", "path", "builds", "a", "Rack", "response", "containing", "the", "login", "form", "with", "a", "you", "have", "been", "logged", "out", "notification", ".", "Otherwise", "passes", "the", "response", "on", "." ]
ff43606a8812e38f96bbe71b46e7f631cbeacf1c
https://github.com/NUBIC/aker/blob/ff43606a8812e38f96bbe71b46e7f631cbeacf1c/lib/aker/form/middleware/logout_responder.rb#L18-L26
9,892
visagio/render_super
lib/render_super.rb
RenderSuper.InstanceMethods.render_with_super
def render_with_super(*args, &block) if args.first == :super last_view = view_stack.last || {:view => instance_variable_get(:@virtual_path).split('/').last} options = args[1] || {} options[:locals] ||= {} options[:locals].reverse_merge!(last_view[:locals] || {}) if last_view[:templates].nil? last_view[:templates] = lookup_context.find_all_templates(last_view[:view], last_view[:partial], options[:locals].keys) last_view[:templates].shift end options[:template] = last_view[:templates].shift view_stack << last_view result = render_without_super options view_stack.pop result else options = args.first if options.is_a?(Hash) current_view = {:view => options[:partial], :partial => true} if options[:partial] current_view = {:view => options[:template], :partial => false} if current_view.nil? && options[:template] current_view[:locals] = options[:locals] if !current_view.nil? && options[:locals] view_stack << current_view if current_view.present? end result = render_without_super(*args, &block) view_stack.pop if current_view.present? result end end
ruby
def render_with_super(*args, &block) if args.first == :super last_view = view_stack.last || {:view => instance_variable_get(:@virtual_path).split('/').last} options = args[1] || {} options[:locals] ||= {} options[:locals].reverse_merge!(last_view[:locals] || {}) if last_view[:templates].nil? last_view[:templates] = lookup_context.find_all_templates(last_view[:view], last_view[:partial], options[:locals].keys) last_view[:templates].shift end options[:template] = last_view[:templates].shift view_stack << last_view result = render_without_super options view_stack.pop result else options = args.first if options.is_a?(Hash) current_view = {:view => options[:partial], :partial => true} if options[:partial] current_view = {:view => options[:template], :partial => false} if current_view.nil? && options[:template] current_view[:locals] = options[:locals] if !current_view.nil? && options[:locals] view_stack << current_view if current_view.present? end result = render_without_super(*args, &block) view_stack.pop if current_view.present? result end end
[ "def", "render_with_super", "(", "*", "args", ",", "&", "block", ")", "if", "args", ".", "first", "==", ":super", "last_view", "=", "view_stack", ".", "last", "||", "{", ":view", "=>", "instance_variable_get", "(", ":@virtual_path", ")", ".", "split", "(", "'/'", ")", ".", "last", "}", "options", "=", "args", "[", "1", "]", "||", "{", "}", "options", "[", ":locals", "]", "||=", "{", "}", "options", "[", ":locals", "]", ".", "reverse_merge!", "(", "last_view", "[", ":locals", "]", "||", "{", "}", ")", "if", "last_view", "[", ":templates", "]", ".", "nil?", "last_view", "[", ":templates", "]", "=", "lookup_context", ".", "find_all_templates", "(", "last_view", "[", ":view", "]", ",", "last_view", "[", ":partial", "]", ",", "options", "[", ":locals", "]", ".", "keys", ")", "last_view", "[", ":templates", "]", ".", "shift", "end", "options", "[", ":template", "]", "=", "last_view", "[", ":templates", "]", ".", "shift", "view_stack", "<<", "last_view", "result", "=", "render_without_super", "options", "view_stack", ".", "pop", "result", "else", "options", "=", "args", ".", "first", "if", "options", ".", "is_a?", "(", "Hash", ")", "current_view", "=", "{", ":view", "=>", "options", "[", ":partial", "]", ",", ":partial", "=>", "true", "}", "if", "options", "[", ":partial", "]", "current_view", "=", "{", ":view", "=>", "options", "[", ":template", "]", ",", ":partial", "=>", "false", "}", "if", "current_view", ".", "nil?", "&&", "options", "[", ":template", "]", "current_view", "[", ":locals", "]", "=", "options", "[", ":locals", "]", "if", "!", "current_view", ".", "nil?", "&&", "options", "[", ":locals", "]", "view_stack", "<<", "current_view", "if", "current_view", ".", "present?", "end", "result", "=", "render_without_super", "(", "args", ",", "block", ")", "view_stack", ".", "pop", "if", "current_view", ".", "present?", "result", "end", "end" ]
Adds rendering option. ==render :super This renders the "super" template, i.e. the one hidden by the plugin
[ "Adds", "rendering", "option", "." ]
680fdfda19233ca81ed851ae83a9eda99030a9a1
https://github.com/visagio/render_super/blob/680fdfda19233ca81ed851ae83a9eda99030a9a1/lib/render_super.rb#L42-L69
9,893
simonswine/php_fpm_docker
lib/php_fpm_docker/pool.rb
PhpFpmDocker.Pool.bind_mounts
def bind_mounts ret_val = @launcher.bind_mounts ret_val << File.dirname(@config['listen']) ret_val += valid_web_paths ret_val.uniq end
ruby
def bind_mounts ret_val = @launcher.bind_mounts ret_val << File.dirname(@config['listen']) ret_val += valid_web_paths ret_val.uniq end
[ "def", "bind_mounts", "ret_val", "=", "@launcher", ".", "bind_mounts", "ret_val", "<<", "File", ".", "dirname", "(", "@config", "[", "'listen'", "]", ")", "ret_val", "+=", "valid_web_paths", "ret_val", ".", "uniq", "end" ]
Find out bind mount paths
[ "Find", "out", "bind", "mount", "paths" ]
2d7ab79fb6394a6a3f90457f58fb584cd916ffcd
https://github.com/simonswine/php_fpm_docker/blob/2d7ab79fb6394a6a3f90457f58fb584cd916ffcd/lib/php_fpm_docker/pool.rb#L60-L65
9,894
simonswine/php_fpm_docker
lib/php_fpm_docker/pool.rb
PhpFpmDocker.Pool.spawn_command
def spawn_command [ @launcher.spawn_cmd_path, '-s', @config['listen'], '-U', listen_uid.to_s, '-G', listen_gid.to_s, '-M', '0660', '-u', uid.to_s, '-g', gid.to_s, '-C', '4', '-n' ] end
ruby
def spawn_command [ @launcher.spawn_cmd_path, '-s', @config['listen'], '-U', listen_uid.to_s, '-G', listen_gid.to_s, '-M', '0660', '-u', uid.to_s, '-g', gid.to_s, '-C', '4', '-n' ] end
[ "def", "spawn_command", "[", "@launcher", ".", "spawn_cmd_path", ",", "'-s'", ",", "@config", "[", "'listen'", "]", ",", "'-U'", ",", "listen_uid", ".", "to_s", ",", "'-G'", ",", "listen_gid", ".", "to_s", ",", "'-M'", ",", "'0660'", ",", "'-u'", ",", "uid", ".", "to_s", ",", "'-g'", ",", "gid", ".", "to_s", ",", "'-C'", ",", "'4'", ",", "'-n'", "]", "end" ]
Build the spawn command
[ "Build", "the", "spawn", "command" ]
2d7ab79fb6394a6a3f90457f58fb584cd916ffcd
https://github.com/simonswine/php_fpm_docker/blob/2d7ab79fb6394a6a3f90457f58fb584cd916ffcd/lib/php_fpm_docker/pool.rb#L104-L116
9,895
dannguyen/active_scraper
app/models/active_scraper/cached_request.rb
ActiveScraper.CachedRequest.to_uri
def to_uri h = self.attributes.symbolize_keys.slice(:scheme, :host, :path) h[:query] = self.unobfuscated_query || self.query return Addressable::URI.new(h) end
ruby
def to_uri h = self.attributes.symbolize_keys.slice(:scheme, :host, :path) h[:query] = self.unobfuscated_query || self.query return Addressable::URI.new(h) end
[ "def", "to_uri", "h", "=", "self", ".", "attributes", ".", "symbolize_keys", ".", "slice", "(", ":scheme", ",", ":host", ",", ":path", ")", "h", "[", ":query", "]", "=", "self", ".", "unobfuscated_query", "||", "self", ".", "query", "return", "Addressable", "::", "URI", ".", "new", "(", "h", ")", "end" ]
during a fresh query, we need to actually use the unobfuscated_query
[ "during", "a", "fresh", "query", "we", "need", "to", "actually", "use", "the", "unobfuscated_query" ]
f6d24ea99d4851f7bae69a2080863b58bb6b7266
https://github.com/dannguyen/active_scraper/blob/f6d24ea99d4851f7bae69a2080863b58bb6b7266/app/models/active_scraper/cached_request.rb#L68-L73
9,896
zaypay/zaypay_gem
lib/zaypay/price_setting.rb
Zaypay.PriceSetting.locale_string_for_ip
def locale_string_for_ip(ip) get "/#{ip}/pay/#{price_setting_id}/locale_for_ip" do |data| parts = data[:locale].split('-') Zaypay::Util.stringify_locale_hash({:country => parts[1], :language => parts[0]}) end end
ruby
def locale_string_for_ip(ip) get "/#{ip}/pay/#{price_setting_id}/locale_for_ip" do |data| parts = data[:locale].split('-') Zaypay::Util.stringify_locale_hash({:country => parts[1], :language => parts[0]}) end end
[ "def", "locale_string_for_ip", "(", "ip", ")", "get", "\"/#{ip}/pay/#{price_setting_id}/locale_for_ip\"", "do", "|", "data", "|", "parts", "=", "data", "[", ":locale", "]", ".", "split", "(", "'-'", ")", "Zaypay", "::", "Util", ".", "stringify_locale_hash", "(", "{", ":country", "=>", "parts", "[", "1", "]", ",", ":language", "=>", "parts", "[", "0", "]", "}", ")", "end", "end" ]
Returns the default locale as a string for a given ip_address, with the first part representing the language, the second part the country This method comes in handy when you want to preselect the language and country when your customer creates a payment on your website. = Example: # We take an ip-address from Great Britain for example: ip = "212.58.226.75" @price_setting.locale_string_for_ip(ip) => 'en-GB' Also see {#locale_for_ip} @param [String] ip an ip-address (e.g. from your site's visitors) @return [String] a string that represents the default locale for the given IP, in a language-country format.
[ "Returns", "the", "default", "locale", "as", "a", "string", "for", "a", "given", "ip_address", "with", "the", "first", "part", "representing", "the", "language", "the", "second", "part", "the", "country" ]
8001736687c8c7e98c6cbe7078194529ff02f6fb
https://github.com/zaypay/zaypay_gem/blob/8001736687c8c7e98c6cbe7078194529ff02f6fb/lib/zaypay/price_setting.rb#L56-L61
9,897
zaypay/zaypay_gem
lib/zaypay/price_setting.rb
Zaypay.PriceSetting.country_has_been_configured_for_ip
def country_has_been_configured_for_ip(ip, options={}) # options can take a :amount key locale = locale_for_ip(ip) country = list_countries(options).select{ |c| c.has_value? locale[:country] }.first {:country => country, :locale => locale} if country end
ruby
def country_has_been_configured_for_ip(ip, options={}) # options can take a :amount key locale = locale_for_ip(ip) country = list_countries(options).select{ |c| c.has_value? locale[:country] }.first {:country => country, :locale => locale} if country end
[ "def", "country_has_been_configured_for_ip", "(", "ip", ",", "options", "=", "{", "}", ")", "# options can take a :amount key", "locale", "=", "locale_for_ip", "(", "ip", ")", "country", "=", "list_countries", "(", "options", ")", ".", "select", "{", "|", "c", "|", "c", ".", "has_value?", "locale", "[", ":country", "]", "}", ".", "first", "{", ":country", "=>", "country", ",", ":locale", "=>", "locale", "}", "if", "country", "end" ]
Returns a country as a Hash, if the country of the given IP has been configured for your Price Setting. If the country of the given IP has been configured for this Price Setting, it returns a hash with *:country* and *:locale* subhashes, else it returns *nil*. @param [String] ip an ip-address (e.g. from your site's visitors) @return [Hash] a hash containing *:country* and *:locale* subhashes
[ "Returns", "a", "country", "as", "a", "Hash", "if", "the", "country", "of", "the", "given", "IP", "has", "been", "configured", "for", "your", "Price", "Setting", "." ]
8001736687c8c7e98c6cbe7078194529ff02f6fb
https://github.com/zaypay/zaypay_gem/blob/8001736687c8c7e98c6cbe7078194529ff02f6fb/lib/zaypay/price_setting.rb#L89-L94
9,898
zaypay/zaypay_gem
lib/zaypay/price_setting.rb
Zaypay.PriceSetting.list_payment_methods
def list_payment_methods(options={}) raise Zaypay::Error.new(:locale_not_set, "locale was not set for your price setting") if @locale.nil? get "/#{options[:amount]}/#{@locale}/pay/#{price_setting_id}/payments/new" do |data| Zaypay::Util.arrayify_if_not_an_array(data[:payment_methods][:payment_method]) end end
ruby
def list_payment_methods(options={}) raise Zaypay::Error.new(:locale_not_set, "locale was not set for your price setting") if @locale.nil? get "/#{options[:amount]}/#{@locale}/pay/#{price_setting_id}/payments/new" do |data| Zaypay::Util.arrayify_if_not_an_array(data[:payment_methods][:payment_method]) end end
[ "def", "list_payment_methods", "(", "options", "=", "{", "}", ")", "raise", "Zaypay", "::", "Error", ".", "new", "(", ":locale_not_set", ",", "\"locale was not set for your price setting\"", ")", "if", "@locale", ".", "nil?", "get", "\"/#{options[:amount]}/#{@locale}/pay/#{price_setting_id}/payments/new\"", "do", "|", "data", "|", "Zaypay", "::", "Util", ".", "arrayify_if_not_an_array", "(", "data", "[", ":payment_methods", "]", "[", ":payment_method", "]", ")", "end", "end" ]
Returns an array of payment methods that are available to your Price Setting with a given locale @param [Hash] options an options-hash that can take an *:amount* option, in case you want to use dynamic amounts @return [Array] an array of payment methods, each represented by a hash. @raise [Zaypay::Error] in case you call this method before setting a locale
[ "Returns", "an", "array", "of", "payment", "methods", "that", "are", "available", "to", "your", "Price", "Setting", "with", "a", "given", "locale" ]
8001736687c8c7e98c6cbe7078194529ff02f6fb
https://github.com/zaypay/zaypay_gem/blob/8001736687c8c7e98c6cbe7078194529ff02f6fb/lib/zaypay/price_setting.rb#L132-L137
9,899
zaypay/zaypay_gem
lib/zaypay/price_setting.rb
Zaypay.PriceSetting.create_payment
def create_payment(options={}) raise Zaypay::Error.new(:locale_not_set, "locale was not set for your price setting") if @locale.nil? raise Zaypay::Error.new(:payment_method_id_not_set, "payment_method_id was not set for your price setting") if @payment_method_id.nil? query = {:payment_method_id => payment_method_id} query.merge!(options) amount = query.delete(:amount) post "/#{amount}/#{@locale}/pay/#{price_setting_id}/payments", query do |data| payment_hash data end end
ruby
def create_payment(options={}) raise Zaypay::Error.new(:locale_not_set, "locale was not set for your price setting") if @locale.nil? raise Zaypay::Error.new(:payment_method_id_not_set, "payment_method_id was not set for your price setting") if @payment_method_id.nil? query = {:payment_method_id => payment_method_id} query.merge!(options) amount = query.delete(:amount) post "/#{amount}/#{@locale}/pay/#{price_setting_id}/payments", query do |data| payment_hash data end end
[ "def", "create_payment", "(", "options", "=", "{", "}", ")", "raise", "Zaypay", "::", "Error", ".", "new", "(", ":locale_not_set", ",", "\"locale was not set for your price setting\"", ")", "if", "@locale", ".", "nil?", "raise", "Zaypay", "::", "Error", ".", "new", "(", ":payment_method_id_not_set", ",", "\"payment_method_id was not set for your price setting\"", ")", "if", "@payment_method_id", ".", "nil?", "query", "=", "{", ":payment_method_id", "=>", "payment_method_id", "}", "query", ".", "merge!", "(", "options", ")", "amount", "=", "query", ".", "delete", "(", ":amount", ")", "post", "\"/#{amount}/#{@locale}/pay/#{price_setting_id}/payments\"", ",", "query", "do", "|", "data", "|", "payment_hash", "data", "end", "end" ]
Creates a payment on the Zaypay platform. You can provide an options-hash, which will add additional data to your payment. The following keys have special functionalities: :amount # Enables dynamic pricing. It must be an integer representing the price in cents. :payalogue_id # Adds the URL of the payalogue specified to your payment as :payalogue_url. Any other keys will be added to a key named :your_variables, which can be used for your future reference. Please check the {file:/README.rdoc README} for the structure of the payment returned. = Example: @price_setting.create_payment(:payalogue_id => payalogue_id, :amount => optional_amount, :my_variable_1 => "value_1", :my_variable_2 => "value_2") @param [Hash] options an options-hash that can take an *:amount*, *:payalogue_id* as options, and any other keys can be used as your custom variables for your own reference @return [Hash] a hash containing data of the payment you just created @raise [Zaypay::Error] in case you call this method before setting a *locale* or a *payment_method_id*
[ "Creates", "a", "payment", "on", "the", "Zaypay", "platform", "." ]
8001736687c8c7e98c6cbe7078194529ff02f6fb
https://github.com/zaypay/zaypay_gem/blob/8001736687c8c7e98c6cbe7078194529ff02f6fb/lib/zaypay/price_setting.rb#L154-L163