repo
stringlengths
5
58
path
stringlengths
9
168
func_name
stringlengths
9
130
original_string
stringlengths
66
10.5k
language
stringclasses
1 value
code
stringlengths
66
10.5k
code_tokens
sequence
docstring
stringlengths
8
16k
docstring_tokens
sequence
sha
stringlengths
40
40
url
stringlengths
94
266
partition
stringclasses
1 value
lokalportal/chain_options
lib/chain_options/option.rb
ChainOptions.Option.new_value
def new_value(*args, &block) value = value_from_args(args, &block) value = if incremental incremental_value(value) else filter_value(transformed_value(value)) end if value_valid?(value) self.custom_value = value elsif invalid.to_s == 'default' && !incremental default_value else fail ArgumentError, "The value #{value.inspect} is not valid." end end
ruby
def new_value(*args, &block) value = value_from_args(args, &block) value = if incremental incremental_value(value) else filter_value(transformed_value(value)) end if value_valid?(value) self.custom_value = value elsif invalid.to_s == 'default' && !incremental default_value else fail ArgumentError, "The value #{value.inspect} is not valid." end end
[ "def", "new_value", "(", "*", "args", ",", "&", "block", ")", "value", "=", "value_from_args", "(", "args", ",", "&", "block", ")", "value", "=", "if", "incremental", "incremental_value", "(", "value", ")", "else", "filter_value", "(", "transformed_value", "(", "value", ")", ")", "end", "if", "value_valid?", "(", "value", ")", "self", ".", "custom_value", "=", "value", "elsif", "invalid", ".", "to_s", "==", "'default'", "&&", "!", "incremental", "default_value", "else", "fail", "ArgumentError", ",", "\"The value #{value.inspect} is not valid.\"", "end", "end" ]
Extracts options and sets all the parameters. Builds a new value for the option. It automatically applies transformations and filters and validates the resulting value, raising an exception if the value is not valid.
[ "Extracts", "options", "and", "sets", "all", "the", "parameters", "." ]
b42cd6c03aeca8938b274225ebaa38fe3803866a
https://github.com/lokalportal/chain_options/blob/b42cd6c03aeca8938b274225ebaa38fe3803866a/lib/chain_options/option.rb#L35-L51
train
lokalportal/chain_options
lib/chain_options/option.rb
ChainOptions.Option.to_h
def to_h PARAMETERS.each_with_object({}) do |param, hash| next if send(param).nil? hash[param] = send(param) end end
ruby
def to_h PARAMETERS.each_with_object({}) do |param, hash| next if send(param).nil? hash[param] = send(param) end end
[ "def", "to_h", "PARAMETERS", ".", "each_with_object", "(", "{", "}", ")", "do", "|", "param", ",", "hash", "|", "next", "if", "send", "(", "param", ")", ".", "nil?", "hash", "[", "param", "]", "=", "send", "(", "param", ")", "end", "end" ]
Looks through the parameters and returns the non-nil values as a hash
[ "Looks", "through", "the", "parameters", "and", "returns", "the", "non", "-", "nil", "values", "as", "a", "hash" ]
b42cd6c03aeca8938b274225ebaa38fe3803866a
https://github.com/lokalportal/chain_options/blob/b42cd6c03aeca8938b274225ebaa38fe3803866a/lib/chain_options/option.rb#L75-L81
train
lokalportal/chain_options
lib/chain_options/option.rb
ChainOptions.Option.value_from_args
def value_from_args(args, &block) return block if ChainOptions::Util.blank?(args) && block && allow_block flat_value(args) end
ruby
def value_from_args(args, &block) return block if ChainOptions::Util.blank?(args) && block && allow_block flat_value(args) end
[ "def", "value_from_args", "(", "args", ",", "&", "block", ")", "return", "block", "if", "ChainOptions", "::", "Util", ".", "blank?", "(", "args", ")", "&&", "block", "&&", "allow_block", "flat_value", "(", "args", ")", "end" ]
Returns the block if nothing else if given and blocks are allowed to be values.
[ "Returns", "the", "block", "if", "nothing", "else", "if", "given", "and", "blocks", "are", "allowed", "to", "be", "values", "." ]
b42cd6c03aeca8938b274225ebaa38fe3803866a
https://github.com/lokalportal/chain_options/blob/b42cd6c03aeca8938b274225ebaa38fe3803866a/lib/chain_options/option.rb#L102-L106
train
lokalportal/chain_options
lib/chain_options/option.rb
ChainOptions.Option.flat_value
def flat_value(args) return args.first if args.is_a?(Enumerable) && args.count == 1 args end
ruby
def flat_value(args) return args.first if args.is_a?(Enumerable) && args.count == 1 args end
[ "def", "flat_value", "(", "args", ")", "return", "args", ".", "first", "if", "args", ".", "is_a?", "(", "Enumerable", ")", "&&", "args", ".", "count", "==", "1", "args", "end" ]
Reverses the auto-cast to Array that is applied at `new_value`.
[ "Reverses", "the", "auto", "-", "cast", "to", "Array", "that", "is", "applied", "at", "new_value", "." ]
b42cd6c03aeca8938b274225ebaa38fe3803866a
https://github.com/lokalportal/chain_options/blob/b42cd6c03aeca8938b274225ebaa38fe3803866a/lib/chain_options/option.rb#L111-L115
train
lokalportal/chain_options
lib/chain_options/option.rb
ChainOptions.Option.transformed_value
def transformed_value(value) return value unless transform transformed = Array(value).map(&transform) value.is_a?(Enumerable) ? transformed : transformed.first end
ruby
def transformed_value(value) return value unless transform transformed = Array(value).map(&transform) value.is_a?(Enumerable) ? transformed : transformed.first end
[ "def", "transformed_value", "(", "value", ")", "return", "value", "unless", "transform", "transformed", "=", "Array", "(", "value", ")", ".", "map", "(", "&", "transform", ")", "value", ".", "is_a?", "(", "Enumerable", ")", "?", "transformed", ":", "transformed", ".", "first", "end" ]
Applies a transformation to the given value. @param [Object] value The new value to be transformed If a `transform` was set up for the given option, it is used as `to_proc` target when iterating over the value. The value is always treated as a collection during this phase.
[ "Applies", "a", "transformation", "to", "the", "given", "value", "." ]
b42cd6c03aeca8938b274225ebaa38fe3803866a
https://github.com/lokalportal/chain_options/blob/b42cd6c03aeca8938b274225ebaa38fe3803866a/lib/chain_options/option.rb#L160-L165
train
ChrisSandison/missing_text
lib/missing_text/writer.rb
MissingText.Writer.get_entry_for
def get_entry_for(entry, language) if entry.length > 1 entry_string = get_entry_for_rec(entry[1..-1], language, hashes[language][entry[0]]) else entry_string = hashes[language][entry[0]] end if entry_string.kind_of?(Array) entry_string = entry_string.map(&:inspect).join(', ') end entry_string end
ruby
def get_entry_for(entry, language) if entry.length > 1 entry_string = get_entry_for_rec(entry[1..-1], language, hashes[language][entry[0]]) else entry_string = hashes[language][entry[0]] end if entry_string.kind_of?(Array) entry_string = entry_string.map(&:inspect).join(', ') end entry_string end
[ "def", "get_entry_for", "(", "entry", ",", "language", ")", "if", "entry", ".", "length", ">", "1", "entry_string", "=", "get_entry_for_rec", "(", "entry", "[", "1", "..", "-", "1", "]", ",", "language", ",", "hashes", "[", "language", "]", "[", "entry", "[", "0", "]", "]", ")", "else", "entry_string", "=", "hashes", "[", "language", "]", "[", "entry", "[", "0", "]", "]", "end", "if", "entry_string", ".", "kind_of?", "(", "Array", ")", "entry_string", "=", "entry_string", ".", "map", "(", "&", ":inspect", ")", ".", "join", "(", "', '", ")", "end", "entry_string", "end" ]
Takes in a locale code and returns the string for that language
[ "Takes", "in", "a", "locale", "code", "and", "returns", "the", "string", "for", "that", "language" ]
dd33f0118f0a69798537e0280a6c62dc387f3e81
https://github.com/ChrisSandison/missing_text/blob/dd33f0118f0a69798537e0280a6c62dc387f3e81/lib/missing_text/writer.rb#L63-L74
train
cordawyn/redlander
lib/redlander/parsing.rb
Redlander.Parsing.from
def from(content, options = {}) format = options[:format].to_s mime_type = options[:mime_type] && options[:mime_type].to_s type_uri = options[:type_uri] && options[:type_uri].to_s base_uri = options[:base_uri] && options[:base_uri].to_s content = Uri.new(content) if content.is_a?(URI) # FIXME: to be fixed in librdf: # ntriples parser absolutely needs "\n" at the end of the input if format == "ntriples" && !content.is_a?(Uri) && !content.end_with?("\n") content << "\n" end rdf_parser = Redland.librdf_new_parser(Redlander.rdf_world, format, mime_type, type_uri) raise RedlandError, "Failed to create a new '#{format}' parser" if rdf_parser.null? begin if block_given? rdf_stream = if content.is_a?(Uri) Redland.librdf_parser_parse_as_stream(rdf_parser, content.rdf_uri, base_uri) else Redland.librdf_parser_parse_string_as_stream(rdf_parser, content, base_uri) end raise RedlandError, "Failed to create a new stream" if rdf_stream.null? begin while Redland.librdf_stream_end(rdf_stream).zero? statement = Statement.new(Redland.librdf_stream_get_object(rdf_stream)) statements.add(statement) if yield statement Redland.librdf_stream_next(rdf_stream) end ensure Redland.librdf_free_stream(rdf_stream) end else if content.is_a?(Uri) Redland.librdf_parser_parse_into_model(rdf_parser, content.rdf_uri, base_uri, @rdf_model).zero? else Redland.librdf_parser_parse_string_into_model(rdf_parser, content, base_uri, @rdf_model).zero? end end ensure Redland.librdf_free_parser(rdf_parser) end self end
ruby
def from(content, options = {}) format = options[:format].to_s mime_type = options[:mime_type] && options[:mime_type].to_s type_uri = options[:type_uri] && options[:type_uri].to_s base_uri = options[:base_uri] && options[:base_uri].to_s content = Uri.new(content) if content.is_a?(URI) # FIXME: to be fixed in librdf: # ntriples parser absolutely needs "\n" at the end of the input if format == "ntriples" && !content.is_a?(Uri) && !content.end_with?("\n") content << "\n" end rdf_parser = Redland.librdf_new_parser(Redlander.rdf_world, format, mime_type, type_uri) raise RedlandError, "Failed to create a new '#{format}' parser" if rdf_parser.null? begin if block_given? rdf_stream = if content.is_a?(Uri) Redland.librdf_parser_parse_as_stream(rdf_parser, content.rdf_uri, base_uri) else Redland.librdf_parser_parse_string_as_stream(rdf_parser, content, base_uri) end raise RedlandError, "Failed to create a new stream" if rdf_stream.null? begin while Redland.librdf_stream_end(rdf_stream).zero? statement = Statement.new(Redland.librdf_stream_get_object(rdf_stream)) statements.add(statement) if yield statement Redland.librdf_stream_next(rdf_stream) end ensure Redland.librdf_free_stream(rdf_stream) end else if content.is_a?(Uri) Redland.librdf_parser_parse_into_model(rdf_parser, content.rdf_uri, base_uri, @rdf_model).zero? else Redland.librdf_parser_parse_string_into_model(rdf_parser, content, base_uri, @rdf_model).zero? end end ensure Redland.librdf_free_parser(rdf_parser) end self end
[ "def", "from", "(", "content", ",", "options", "=", "{", "}", ")", "format", "=", "options", "[", ":format", "]", ".", "to_s", "mime_type", "=", "options", "[", ":mime_type", "]", "&&", "options", "[", ":mime_type", "]", ".", "to_s", "type_uri", "=", "options", "[", ":type_uri", "]", "&&", "options", "[", ":type_uri", "]", ".", "to_s", "base_uri", "=", "options", "[", ":base_uri", "]", "&&", "options", "[", ":base_uri", "]", ".", "to_s", "content", "=", "Uri", ".", "new", "(", "content", ")", "if", "content", ".", "is_a?", "(", "URI", ")", "if", "format", "==", "\"ntriples\"", "&&", "!", "content", ".", "is_a?", "(", "Uri", ")", "&&", "!", "content", ".", "end_with?", "(", "\"\\n\"", ")", "content", "<<", "\"\\n\"", "end", "rdf_parser", "=", "Redland", ".", "librdf_new_parser", "(", "Redlander", ".", "rdf_world", ",", "format", ",", "mime_type", ",", "type_uri", ")", "raise", "RedlandError", ",", "\"Failed to create a new '#{format}' parser\"", "if", "rdf_parser", ".", "null?", "begin", "if", "block_given?", "rdf_stream", "=", "if", "content", ".", "is_a?", "(", "Uri", ")", "Redland", ".", "librdf_parser_parse_as_stream", "(", "rdf_parser", ",", "content", ".", "rdf_uri", ",", "base_uri", ")", "else", "Redland", ".", "librdf_parser_parse_string_as_stream", "(", "rdf_parser", ",", "content", ",", "base_uri", ")", "end", "raise", "RedlandError", ",", "\"Failed to create a new stream\"", "if", "rdf_stream", ".", "null?", "begin", "while", "Redland", ".", "librdf_stream_end", "(", "rdf_stream", ")", ".", "zero?", "statement", "=", "Statement", ".", "new", "(", "Redland", ".", "librdf_stream_get_object", "(", "rdf_stream", ")", ")", "statements", ".", "add", "(", "statement", ")", "if", "yield", "statement", "Redland", ".", "librdf_stream_next", "(", "rdf_stream", ")", "end", "ensure", "Redland", ".", "librdf_free_stream", "(", "rdf_stream", ")", "end", "else", "if", "content", ".", "is_a?", "(", "Uri", ")", "Redland", ".", "librdf_parser_parse_into_model", "(", "rdf_parser", ",", "content", ".", "rdf_uri", ",", "base_uri", ",", "@rdf_model", ")", ".", "zero?", "else", "Redland", ".", "librdf_parser_parse_string_into_model", "(", "rdf_parser", ",", "content", ",", "base_uri", ",", "@rdf_model", ")", ".", "zero?", "end", "end", "ensure", "Redland", ".", "librdf_free_parser", "(", "rdf_parser", ")", "end", "self", "end" ]
Core parsing method for non-streams @note If a block is given, the extracted statements will be yielded into the block and inserted into the model depending on the output of the block (if true, the statement will be added, if false, the statement will not be added). @param [String, URI] content - Can be a String, causing the statements to be extracted directly from it, or - URI causing the content to be first pulled from the specified URI (or a local file, if URI schema == "file:") @param [Hash] options @option options [String] :format name of the parser to use, @option options [String] :mime_type MIME type of the syntax, if applicable, @option options [String, URI] :type_uri URI of syntax, if applicable, @option options [String, URI] :base_uri base URI, to be applied to the nodes with relative URIs. @yieldparam [Statement] @raise [RedlandError] if it fails to create a parser or stream @return [Model]
[ "Core", "parsing", "method", "for", "non", "-", "streams" ]
a5c84e15a7602c674606e531bda6a616b1237c44
https://github.com/cordawyn/redlander/blob/a5c84e15a7602c674606e531bda6a616b1237c44/lib/redlander/parsing.rb#L30-L76
train
mobyinc/Cathode
lib/cathode/index_request.rb
Cathode.IndexRequest.model
def model if @resource_tree.size > 1 parent_model_id = params["#{@resource_tree.first.name.to_s.singularize}_id"] model = @resource_tree.first.model.find(parent_model_id) @resource_tree.drop(1).each do |resource| model = model.send resource.name end model else super.all end end
ruby
def model if @resource_tree.size > 1 parent_model_id = params["#{@resource_tree.first.name.to_s.singularize}_id"] model = @resource_tree.first.model.find(parent_model_id) @resource_tree.drop(1).each do |resource| model = model.send resource.name end model else super.all end end
[ "def", "model", "if", "@resource_tree", ".", "size", ">", "1", "parent_model_id", "=", "params", "[", "\"#{@resource_tree.first.name.to_s.singularize}_id\"", "]", "model", "=", "@resource_tree", ".", "first", ".", "model", ".", "find", "(", "parent_model_id", ")", "@resource_tree", ".", "drop", "(", "1", ")", ".", "each", "do", "|", "resource", "|", "model", "=", "model", ".", "send", "resource", ".", "name", "end", "model", "else", "super", ".", "all", "end", "end" ]
Determine the model to use depending on the request. If a sub-resource was requested, use the parent model to get the association. Otherwise, use all the resource's model's records.
[ "Determine", "the", "model", "to", "use", "depending", "on", "the", "request", ".", "If", "a", "sub", "-", "resource", "was", "requested", "use", "the", "parent", "model", "to", "get", "the", "association", ".", "Otherwise", "use", "all", "the", "resource", "s", "model", "s", "records", "." ]
e17be4fb62ad61417e2a3a0a77406459015468a1
https://github.com/mobyinc/Cathode/blob/e17be4fb62ad61417e2a3a0a77406459015468a1/lib/cathode/index_request.rb#L7-L18
train
mobyinc/Cathode
lib/cathode/index_request.rb
Cathode.IndexRequest.default_action_block
def default_action_block proc do all_records = model if allowed?(:paging) && params[:page] page = params[:page] per_page = params[:per_page] || 10 lower_bound = (per_page - 1) * page upper_bound = lower_bound + per_page - 1 body all_records[lower_bound..upper_bound] else body all_records end end end
ruby
def default_action_block proc do all_records = model if allowed?(:paging) && params[:page] page = params[:page] per_page = params[:per_page] || 10 lower_bound = (per_page - 1) * page upper_bound = lower_bound + per_page - 1 body all_records[lower_bound..upper_bound] else body all_records end end end
[ "def", "default_action_block", "proc", "do", "all_records", "=", "model", "if", "allowed?", "(", ":paging", ")", "&&", "params", "[", ":page", "]", "page", "=", "params", "[", ":page", "]", "per_page", "=", "params", "[", ":per_page", "]", "||", "10", "lower_bound", "=", "(", "per_page", "-", "1", ")", "*", "page", "upper_bound", "=", "lower_bound", "+", "per_page", "-", "1", "body", "all_records", "[", "lower_bound", "..", "upper_bound", "]", "else", "body", "all_records", "end", "end", "end" ]
Determine the default action to use depending on the request. If the `page` param was passed and the action allows paging, page the results. Otherwise, set the request body to all records.
[ "Determine", "the", "default", "action", "to", "use", "depending", "on", "the", "request", ".", "If", "the", "page", "param", "was", "passed", "and", "the", "action", "allows", "paging", "page", "the", "results", ".", "Otherwise", "set", "the", "request", "body", "to", "all", "records", "." ]
e17be4fb62ad61417e2a3a0a77406459015468a1
https://github.com/mobyinc/Cathode/blob/e17be4fb62ad61417e2a3a0a77406459015468a1/lib/cathode/index_request.rb#L23-L38
train
jamiely/simulator
lib/simulator/equation.rb
Simulator.Equation.evaluate_in
def evaluate_in(context, periods = []) sandbox = Sandbox.new context, periods sandbox.instance_eval &@equation_block end
ruby
def evaluate_in(context, periods = []) sandbox = Sandbox.new context, periods sandbox.instance_eval &@equation_block end
[ "def", "evaluate_in", "(", "context", ",", "periods", "=", "[", "]", ")", "sandbox", "=", "Sandbox", ".", "new", "context", ",", "periods", "sandbox", ".", "instance_eval", "&", "@equation_block", "end" ]
evaluate the equation in the passed context
[ "evaluate", "the", "equation", "in", "the", "passed", "context" ]
21395b72241d8f3ca93f90eecb5e1ad2870e9f69
https://github.com/jamiely/simulator/blob/21395b72241d8f3ca93f90eecb5e1ad2870e9f69/lib/simulator/equation.rb#L11-L14
train
jmettraux/rufus-jig
lib/rufus/jig/couch.rb
Rufus::Jig.Couch.all
def all(opts={}) opts = opts.dup # don't touch the original path = adjust('_all_docs') opts[:include_docs] = true if opts[:include_docs].nil? adjust_params(opts) keys = opts.delete(:keys) return [] if keys && keys.empty? res = if keys opts[:cache] = :with_body if opts[:cache].nil? @http.post(path, { 'keys' => keys }, opts) else @http.get(path, opts) end rows = res['rows'] docs = if opts[:params][:include_docs] rows.map { |row| row['doc'] } else rows.map { |row| { '_id' => row['id'], '_rev' => row['value']['rev'] } } end if opts[:include_design_docs] == false docs = docs.reject { |doc| DESIGN_PATH_REGEX.match(doc['_id']) } end docs end
ruby
def all(opts={}) opts = opts.dup # don't touch the original path = adjust('_all_docs') opts[:include_docs] = true if opts[:include_docs].nil? adjust_params(opts) keys = opts.delete(:keys) return [] if keys && keys.empty? res = if keys opts[:cache] = :with_body if opts[:cache].nil? @http.post(path, { 'keys' => keys }, opts) else @http.get(path, opts) end rows = res['rows'] docs = if opts[:params][:include_docs] rows.map { |row| row['doc'] } else rows.map { |row| { '_id' => row['id'], '_rev' => row['value']['rev'] } } end if opts[:include_design_docs] == false docs = docs.reject { |doc| DESIGN_PATH_REGEX.match(doc['_id']) } end docs end
[ "def", "all", "(", "opts", "=", "{", "}", ")", "opts", "=", "opts", ".", "dup", "path", "=", "adjust", "(", "'_all_docs'", ")", "opts", "[", ":include_docs", "]", "=", "true", "if", "opts", "[", ":include_docs", "]", ".", "nil?", "adjust_params", "(", "opts", ")", "keys", "=", "opts", ".", "delete", "(", ":keys", ")", "return", "[", "]", "if", "keys", "&&", "keys", ".", "empty?", "res", "=", "if", "keys", "opts", "[", ":cache", "]", "=", ":with_body", "if", "opts", "[", ":cache", "]", ".", "nil?", "@http", ".", "post", "(", "path", ",", "{", "'keys'", "=>", "keys", "}", ",", "opts", ")", "else", "@http", ".", "get", "(", "path", ",", "opts", ")", "end", "rows", "=", "res", "[", "'rows'", "]", "docs", "=", "if", "opts", "[", ":params", "]", "[", ":include_docs", "]", "rows", ".", "map", "{", "|", "row", "|", "row", "[", "'doc'", "]", "}", "else", "rows", ".", "map", "{", "|", "row", "|", "{", "'_id'", "=>", "row", "[", "'id'", "]", ",", "'_rev'", "=>", "row", "[", "'value'", "]", "[", "'rev'", "]", "}", "}", "end", "if", "opts", "[", ":include_design_docs", "]", "==", "false", "docs", "=", "docs", ".", "reject", "{", "|", "doc", "|", "DESIGN_PATH_REGEX", ".", "match", "(", "doc", "[", "'_id'", "]", ")", "}", "end", "docs", "end" ]
Returns all the docs in the current database. c = Rufus::Jig::Couch.new('http://127.0.0.1:5984, 'my_db') docs = c.all docs = c.all(:include_docs => false) docs = c.all(:include_design_docs => false) docs = c.all(:skip => 10, :limit => 10) It understands (passes) all the options for CouchDB view API : http://wiki.apache.org/couchdb/HTTP_view_API#Querying_Options
[ "Returns", "all", "the", "docs", "in", "the", "current", "database", "." ]
3df3661a71823b2f0f08ec605abeaa33e3a0ad38
https://github.com/jmettraux/rufus-jig/blob/3df3661a71823b2f0f08ec605abeaa33e3a0ad38/lib/rufus/jig/couch.rb#L113-L148
train
jmettraux/rufus-jig
lib/rufus/jig/couch.rb
Rufus::Jig.Couch.attach
def attach(doc_id, doc_rev, attachment_name, data, opts=nil) if opts.nil? opts = data data = attachment_name attachment_name = doc_rev doc_rev = doc_id['_rev'] doc_id = doc_id['_id'] end attachment_name = attachment_name.gsub(/\//, '%2F') ct = opts[:content_type] raise(ArgumentError.new( ":content_type option must be specified" )) unless ct opts[:cache] = false path = adjust("#{doc_id}/#{attachment_name}?rev=#{doc_rev}") if @http.variant == :patron # patron, as of 0.4.5 (~> 0.4.10), has difficulties when PUTting # attachements # this is a fallback to net/http require 'net/http' http = Net::HTTP.new(@http.host, @http.port) req = Net::HTTP::Put.new(path) req['User-Agent'] = "rufus-jig #{Rufus::Jig::VERSION} (patron 0.4.x fallback to net/http)" req['Content-Type'] = opts[:content_type] req['Accept'] = 'application/json' req.body = data res = Rufus::Jig::HttpResponse.new(http.start { |h| h.request(req) }) return @http.send(:respond, :put, path, nil, opts, nil, res) end @http.put(path, data, opts) end
ruby
def attach(doc_id, doc_rev, attachment_name, data, opts=nil) if opts.nil? opts = data data = attachment_name attachment_name = doc_rev doc_rev = doc_id['_rev'] doc_id = doc_id['_id'] end attachment_name = attachment_name.gsub(/\//, '%2F') ct = opts[:content_type] raise(ArgumentError.new( ":content_type option must be specified" )) unless ct opts[:cache] = false path = adjust("#{doc_id}/#{attachment_name}?rev=#{doc_rev}") if @http.variant == :patron # patron, as of 0.4.5 (~> 0.4.10), has difficulties when PUTting # attachements # this is a fallback to net/http require 'net/http' http = Net::HTTP.new(@http.host, @http.port) req = Net::HTTP::Put.new(path) req['User-Agent'] = "rufus-jig #{Rufus::Jig::VERSION} (patron 0.4.x fallback to net/http)" req['Content-Type'] = opts[:content_type] req['Accept'] = 'application/json' req.body = data res = Rufus::Jig::HttpResponse.new(http.start { |h| h.request(req) }) return @http.send(:respond, :put, path, nil, opts, nil, res) end @http.put(path, data, opts) end
[ "def", "attach", "(", "doc_id", ",", "doc_rev", ",", "attachment_name", ",", "data", ",", "opts", "=", "nil", ")", "if", "opts", ".", "nil?", "opts", "=", "data", "data", "=", "attachment_name", "attachment_name", "=", "doc_rev", "doc_rev", "=", "doc_id", "[", "'_rev'", "]", "doc_id", "=", "doc_id", "[", "'_id'", "]", "end", "attachment_name", "=", "attachment_name", ".", "gsub", "(", "/", "\\/", "/", ",", "'%2F'", ")", "ct", "=", "opts", "[", ":content_type", "]", "raise", "(", "ArgumentError", ".", "new", "(", "\":content_type option must be specified\"", ")", ")", "unless", "ct", "opts", "[", ":cache", "]", "=", "false", "path", "=", "adjust", "(", "\"#{doc_id}/#{attachment_name}?rev=#{doc_rev}\"", ")", "if", "@http", ".", "variant", "==", ":patron", "require", "'net/http'", "http", "=", "Net", "::", "HTTP", ".", "new", "(", "@http", ".", "host", ",", "@http", ".", "port", ")", "req", "=", "Net", "::", "HTTP", "::", "Put", ".", "new", "(", "path", ")", "req", "[", "'User-Agent'", "]", "=", "\"rufus-jig #{Rufus::Jig::VERSION} (patron 0.4.x fallback to net/http)\"", "req", "[", "'Content-Type'", "]", "=", "opts", "[", ":content_type", "]", "req", "[", "'Accept'", "]", "=", "'application/json'", "req", ".", "body", "=", "data", "res", "=", "Rufus", "::", "Jig", "::", "HttpResponse", ".", "new", "(", "http", ".", "start", "{", "|", "h", "|", "h", ".", "request", "(", "req", ")", "}", ")", "return", "@http", ".", "send", "(", ":respond", ",", ":put", ",", "path", ",", "nil", ",", "opts", ",", "nil", ",", "res", ")", "end", "@http", ".", "put", "(", "path", ",", "data", ",", "opts", ")", "end" ]
Attaches a file to a couch document. couch.attach( doc['_id'], doc['_rev'], 'my_picture', data, :content_type => 'image/jpeg') or couch.attach( doc, 'my_picture', data, :content_type => 'image/jpeg')
[ "Attaches", "a", "file", "to", "a", "couch", "document", "." ]
3df3661a71823b2f0f08ec605abeaa33e3a0ad38
https://github.com/jmettraux/rufus-jig/blob/3df3661a71823b2f0f08ec605abeaa33e3a0ad38/lib/rufus/jig/couch.rb#L215-L262
train
jmettraux/rufus-jig
lib/rufus/jig/couch.rb
Rufus::Jig.Couch.detach
def detach(doc_id, doc_rev, attachment_name=nil) if attachment_name.nil? attachment_name = doc_rev doc_rev = doc_id['_rev'] doc_id = doc_id['_id'] end attachment_name = attachment_name.gsub(/\//, '%2F') path = adjust("#{doc_id}/#{attachment_name}?rev=#{doc_rev}") @http.delete(path) end
ruby
def detach(doc_id, doc_rev, attachment_name=nil) if attachment_name.nil? attachment_name = doc_rev doc_rev = doc_id['_rev'] doc_id = doc_id['_id'] end attachment_name = attachment_name.gsub(/\//, '%2F') path = adjust("#{doc_id}/#{attachment_name}?rev=#{doc_rev}") @http.delete(path) end
[ "def", "detach", "(", "doc_id", ",", "doc_rev", ",", "attachment_name", "=", "nil", ")", "if", "attachment_name", ".", "nil?", "attachment_name", "=", "doc_rev", "doc_rev", "=", "doc_id", "[", "'_rev'", "]", "doc_id", "=", "doc_id", "[", "'_id'", "]", "end", "attachment_name", "=", "attachment_name", ".", "gsub", "(", "/", "\\/", "/", ",", "'%2F'", ")", "path", "=", "adjust", "(", "\"#{doc_id}/#{attachment_name}?rev=#{doc_rev}\"", ")", "@http", ".", "delete", "(", "path", ")", "end" ]
Detaches a file from a couch document. couch.detach(doc['_id'], doc['_rev'], 'my_picture') or couch.detach(doc, 'my_picture')
[ "Detaches", "a", "file", "from", "a", "couch", "document", "." ]
3df3661a71823b2f0f08ec605abeaa33e3a0ad38
https://github.com/jmettraux/rufus-jig/blob/3df3661a71823b2f0f08ec605abeaa33e3a0ad38/lib/rufus/jig/couch.rb#L272-L285
train
jmettraux/rufus-jig
lib/rufus/jig/couch.rb
Rufus::Jig.Couch.on_change
def on_change(opts={}, &block) query = { 'feed' => 'continuous', 'heartbeat' => opts[:heartbeat] || 20_000 } #'since' => 0 } # that's already the default query['include_docs'] = true if block.arity > 2 query = query.map { |k, v| "#{k}=#{v}" }.join('&') socket = TCPSocket.open(@http.host, @http.port) auth = @http.options[:basic_auth] if auth auth = Base64.encode64(auth.join(':')).strip auth = "Authorization: Basic #{auth}\r\n" else auth = '' end socket.print("GET /#{path}/_changes?#{query} HTTP/1.1\r\n") socket.print("User-Agent: rufus-jig #{Rufus::Jig::VERSION}\r\n") #socket.print("Accept: application/json;charset=UTF-8\r\n") socket.print(auth) socket.print("\r\n") # consider reply answer = socket.gets.strip status = answer.match(/^HTTP\/.+ (\d{3}) /)[1].to_i raise Rufus::Jig::HttpError.new(status, answer) if status != 200 # discard headers loop do data = socket.gets break if data.nil? || data == "\r\n" end # the on_change loop loop do data = socket.gets break if data.nil? data = (Rufus::Json.decode(data) rescue nil) next unless data.is_a?(Hash) args = [ data['id'], (data['deleted'] == true) ] args << data['doc'] if block.arity > 2 block.call(*args) end on_change(opts, &block) if opts[:reconnect] end
ruby
def on_change(opts={}, &block) query = { 'feed' => 'continuous', 'heartbeat' => opts[:heartbeat] || 20_000 } #'since' => 0 } # that's already the default query['include_docs'] = true if block.arity > 2 query = query.map { |k, v| "#{k}=#{v}" }.join('&') socket = TCPSocket.open(@http.host, @http.port) auth = @http.options[:basic_auth] if auth auth = Base64.encode64(auth.join(':')).strip auth = "Authorization: Basic #{auth}\r\n" else auth = '' end socket.print("GET /#{path}/_changes?#{query} HTTP/1.1\r\n") socket.print("User-Agent: rufus-jig #{Rufus::Jig::VERSION}\r\n") #socket.print("Accept: application/json;charset=UTF-8\r\n") socket.print(auth) socket.print("\r\n") # consider reply answer = socket.gets.strip status = answer.match(/^HTTP\/.+ (\d{3}) /)[1].to_i raise Rufus::Jig::HttpError.new(status, answer) if status != 200 # discard headers loop do data = socket.gets break if data.nil? || data == "\r\n" end # the on_change loop loop do data = socket.gets break if data.nil? data = (Rufus::Json.decode(data) rescue nil) next unless data.is_a?(Hash) args = [ data['id'], (data['deleted'] == true) ] args << data['doc'] if block.arity > 2 block.call(*args) end on_change(opts, &block) if opts[:reconnect] end
[ "def", "on_change", "(", "opts", "=", "{", "}", ",", "&", "block", ")", "query", "=", "{", "'feed'", "=>", "'continuous'", ",", "'heartbeat'", "=>", "opts", "[", ":heartbeat", "]", "||", "20_000", "}", "query", "[", "'include_docs'", "]", "=", "true", "if", "block", ".", "arity", ">", "2", "query", "=", "query", ".", "map", "{", "|", "k", ",", "v", "|", "\"#{k}=#{v}\"", "}", ".", "join", "(", "'&'", ")", "socket", "=", "TCPSocket", ".", "open", "(", "@http", ".", "host", ",", "@http", ".", "port", ")", "auth", "=", "@http", ".", "options", "[", ":basic_auth", "]", "if", "auth", "auth", "=", "Base64", ".", "encode64", "(", "auth", ".", "join", "(", "':'", ")", ")", ".", "strip", "auth", "=", "\"Authorization: Basic #{auth}\\r\\n\"", "else", "auth", "=", "''", "end", "socket", ".", "print", "(", "\"GET /#{path}/_changes?#{query} HTTP/1.1\\r\\n\"", ")", "socket", ".", "print", "(", "\"User-Agent: rufus-jig #{Rufus::Jig::VERSION}\\r\\n\"", ")", "socket", ".", "print", "(", "auth", ")", "socket", ".", "print", "(", "\"\\r\\n\"", ")", "answer", "=", "socket", ".", "gets", ".", "strip", "status", "=", "answer", ".", "match", "(", "/", "\\/", "\\d", "/", ")", "[", "1", "]", ".", "to_i", "raise", "Rufus", "::", "Jig", "::", "HttpError", ".", "new", "(", "status", ",", "answer", ")", "if", "status", "!=", "200", "loop", "do", "data", "=", "socket", ".", "gets", "break", "if", "data", ".", "nil?", "||", "data", "==", "\"\\r\\n\"", "end", "loop", "do", "data", "=", "socket", ".", "gets", "break", "if", "data", ".", "nil?", "data", "=", "(", "Rufus", "::", "Json", ".", "decode", "(", "data", ")", "rescue", "nil", ")", "next", "unless", "data", ".", "is_a?", "(", "Hash", ")", "args", "=", "[", "data", "[", "'id'", "]", ",", "(", "data", "[", "'deleted'", "]", "==", "true", ")", "]", "args", "<<", "data", "[", "'doc'", "]", "if", "block", ".", "arity", ">", "2", "block", ".", "call", "(", "*", "args", ")", "end", "on_change", "(", "opts", ",", "&", "block", ")", "if", "opts", "[", ":reconnect", "]", "end" ]
Watches the database for changes. db.on_change do |doc_id, deleted| puts "doc #{doc_id} has been #{deleted ? 'deleted' : 'changed'}" end db.on_change do |doc_id, deleted, doc| puts "doc #{doc_id} has been #{deleted ? 'deleted' : 'changed'}" p doc end This is a blocking method. One might want to wrap it inside of a Thread. Note : doc inclusion (third parameter to the block) only works with CouchDB >= 0.11.
[ "Watches", "the", "database", "for", "changes", "." ]
3df3661a71823b2f0f08ec605abeaa33e3a0ad38
https://github.com/jmettraux/rufus-jig/blob/3df3661a71823b2f0f08ec605abeaa33e3a0ad38/lib/rufus/jig/couch.rb#L303-L356
train
jmettraux/rufus-jig
lib/rufus/jig/couch.rb
Rufus::Jig.Couch.nuke_design_documents
def nuke_design_documents docs = get('_all_docs')['rows'] views = docs.select { |d| d['id'] && DESIGN_PATH_REGEX.match(d['id']) } views.each { |v| delete(v['id'], v['value']['rev']) } end
ruby
def nuke_design_documents docs = get('_all_docs')['rows'] views = docs.select { |d| d['id'] && DESIGN_PATH_REGEX.match(d['id']) } views.each { |v| delete(v['id'], v['value']['rev']) } end
[ "def", "nuke_design_documents", "docs", "=", "get", "(", "'_all_docs'", ")", "[", "'rows'", "]", "views", "=", "docs", ".", "select", "{", "|", "d", "|", "d", "[", "'id'", "]", "&&", "DESIGN_PATH_REGEX", ".", "match", "(", "d", "[", "'id'", "]", ")", "}", "views", ".", "each", "{", "|", "v", "|", "delete", "(", "v", "[", "'id'", "]", ",", "v", "[", "'value'", "]", "[", "'rev'", "]", ")", "}", "end" ]
A development method. Removes all the design documents in this couch database. Used in tests setup or teardown, when views are subject to frequent changes (rufus-doric and co).
[ "A", "development", "method", ".", "Removes", "all", "the", "design", "documents", "in", "this", "couch", "database", "." ]
3df3661a71823b2f0f08ec605abeaa33e3a0ad38
https://github.com/jmettraux/rufus-jig/blob/3df3661a71823b2f0f08ec605abeaa33e3a0ad38/lib/rufus/jig/couch.rb#L366-L373
train
jmettraux/rufus-jig
lib/rufus/jig/couch.rb
Rufus::Jig.Couch.query
def query(path, opts={}) opts = opts.dup # don't touch the original raw = opts.delete(:raw) path = if DESIGN_PATH_REGEX.match(path) path else doc_id, view = path.split(':') path = "_design/#{doc_id}/_view/#{view}" end path = adjust(path) adjust_params(opts) keys = opts.delete(:keys) res = if keys opts[:cache] = :with_body if opts[:cache].nil? @http.post(path, { 'keys' => keys }, opts) else @http.get(path, opts) end return nil if res == true # POST and the view doesn't exist return res if raw res.nil? ? res : res['rows'] end
ruby
def query(path, opts={}) opts = opts.dup # don't touch the original raw = opts.delete(:raw) path = if DESIGN_PATH_REGEX.match(path) path else doc_id, view = path.split(':') path = "_design/#{doc_id}/_view/#{view}" end path = adjust(path) adjust_params(opts) keys = opts.delete(:keys) res = if keys opts[:cache] = :with_body if opts[:cache].nil? @http.post(path, { 'keys' => keys }, opts) else @http.get(path, opts) end return nil if res == true # POST and the view doesn't exist return res if raw res.nil? ? res : res['rows'] end
[ "def", "query", "(", "path", ",", "opts", "=", "{", "}", ")", "opts", "=", "opts", ".", "dup", "raw", "=", "opts", ".", "delete", "(", ":raw", ")", "path", "=", "if", "DESIGN_PATH_REGEX", ".", "match", "(", "path", ")", "path", "else", "doc_id", ",", "view", "=", "path", ".", "split", "(", "':'", ")", "path", "=", "\"_design/#{doc_id}/_view/#{view}\"", "end", "path", "=", "adjust", "(", "path", ")", "adjust_params", "(", "opts", ")", "keys", "=", "opts", ".", "delete", "(", ":keys", ")", "res", "=", "if", "keys", "opts", "[", ":cache", "]", "=", ":with_body", "if", "opts", "[", ":cache", "]", ".", "nil?", "@http", ".", "post", "(", "path", ",", "{", "'keys'", "=>", "keys", "}", ",", "opts", ")", "else", "@http", ".", "get", "(", "path", ",", "opts", ")", "end", "return", "nil", "if", "res", "==", "true", "return", "res", "if", "raw", "res", ".", "nil?", "?", "res", ":", "res", "[", "'rows'", "]", "end" ]
Queries a view. res = couch.query('_design/my_test/_view/my_view') # [ {"id"=>"c3", "key"=>"capuccino", "value"=>nil}, # {"id"=>"c0", "key"=>"espresso", "value"=>nil}, # {"id"=>"c2", "key"=>"macchiato", "value"=>nil}, # {"id"=>"c4", "key"=>"macchiato", "value"=>nil}, # {"id"=>"c1", "key"=>"ristretto", "value"=>nil} ] # or simply : res = couch.query('my_test:my_view') Accepts the usual couch parameters : limit, skip, descending, keys, startkey, endkey, ...
[ "Queries", "a", "view", "." ]
3df3661a71823b2f0f08ec605abeaa33e3a0ad38
https://github.com/jmettraux/rufus-jig/blob/3df3661a71823b2f0f08ec605abeaa33e3a0ad38/lib/rufus/jig/couch.rb#L392-L425
train
jmettraux/rufus-jig
lib/rufus/jig/couch.rb
Rufus::Jig.Couch.query_for_docs
def query_for_docs(path, opts={}) res = query(path, opts.merge(:include_docs => true)) if res.nil? nil elsif opts[:raw] res else res.collect { |row| row['doc'] }.uniq end end
ruby
def query_for_docs(path, opts={}) res = query(path, opts.merge(:include_docs => true)) if res.nil? nil elsif opts[:raw] res else res.collect { |row| row['doc'] }.uniq end end
[ "def", "query_for_docs", "(", "path", ",", "opts", "=", "{", "}", ")", "res", "=", "query", "(", "path", ",", "opts", ".", "merge", "(", ":include_docs", "=>", "true", ")", ")", "if", "res", ".", "nil?", "nil", "elsif", "opts", "[", ":raw", "]", "res", "else", "res", ".", "collect", "{", "|", "row", "|", "row", "[", "'doc'", "]", "}", ".", "uniq", "end", "end" ]
A shortcut for query(path, :include_docs => true).collect { |row| row['doc'] }
[ "A", "shortcut", "for" ]
3df3661a71823b2f0f08ec605abeaa33e3a0ad38
https://github.com/jmettraux/rufus-jig/blob/3df3661a71823b2f0f08ec605abeaa33e3a0ad38/lib/rufus/jig/couch.rb#L431-L442
train
jstanley0/mvclient
lib/mvclient/client.rb
Motivosity.Client.send_appreciation!
def send_appreciation!(user_id, opts = {}) params = { "toUserID" => user_id } params["companyValueID"] = opts[:company_value_id] if opts[:company_value_id] params["amount"] = opts[:amount] if opts[:amount] params["note"] = opts[:note] if opts[:note] params["privateAppreciation"] = opts[:private] || false put "/api/v1/user/#{user_id}/appreciation", {}, params end
ruby
def send_appreciation!(user_id, opts = {}) params = { "toUserID" => user_id } params["companyValueID"] = opts[:company_value_id] if opts[:company_value_id] params["amount"] = opts[:amount] if opts[:amount] params["note"] = opts[:note] if opts[:note] params["privateAppreciation"] = opts[:private] || false put "/api/v1/user/#{user_id}/appreciation", {}, params end
[ "def", "send_appreciation!", "(", "user_id", ",", "opts", "=", "{", "}", ")", "params", "=", "{", "\"toUserID\"", "=>", "user_id", "}", "params", "[", "\"companyValueID\"", "]", "=", "opts", "[", ":company_value_id", "]", "if", "opts", "[", ":company_value_id", "]", "params", "[", "\"amount\"", "]", "=", "opts", "[", ":amount", "]", "if", "opts", "[", ":amount", "]", "params", "[", "\"note\"", "]", "=", "opts", "[", ":note", "]", "if", "opts", "[", ":note", "]", "params", "[", "\"privateAppreciation\"", "]", "=", "opts", "[", ":private", "]", "||", "false", "put", "\"/api/v1/user/#{user_id}/appreciation\"", ",", "{", "}", ",", "params", "end" ]
sends appreciation to another User raises BalanceError if insufficient funds exist
[ "sends", "appreciation", "to", "another", "User", "raises", "BalanceError", "if", "insufficient", "funds", "exist" ]
22de66a942515f7ea8ac4dd8de71412ad2b1ad29
https://github.com/jstanley0/mvclient/blob/22de66a942515f7ea8ac4dd8de71412ad2b1ad29/lib/mvclient/client.rb#L51-L58
train
redding/ns-options
lib/ns-options/namespace_data.rb
NsOptions.NamespaceData.define
def define(&block) if block && block.arity > 0 block.call @ns elsif block @ns.instance_eval(&block) end @ns end
ruby
def define(&block) if block && block.arity > 0 block.call @ns elsif block @ns.instance_eval(&block) end @ns end
[ "def", "define", "(", "&", "block", ")", "if", "block", "&&", "block", ".", "arity", ">", "0", "block", ".", "call", "@ns", "elsif", "block", "@ns", ".", "instance_eval", "(", "&", "block", ")", "end", "@ns", "end" ]
define the parent ns using the given block
[ "define", "the", "parent", "ns", "using", "the", "given", "block" ]
63618a18e7a1d270dffc5a3cfea70ef45569e061
https://github.com/redding/ns-options/blob/63618a18e7a1d270dffc5a3cfea70ef45569e061/lib/ns-options/namespace_data.rb#L82-L89
train
rixth/tay
lib/tay/packager.rb
Tay.Packager.extension_id
def extension_id raise Tay::PrivateKeyNotFound.new unless private_key_exists? public_key = OpenSSL::PKey::RSA.new(File.read(full_key_path)).public_key.to_der hash = Digest::SHA256.hexdigest(public_key)[0...32] hash.unpack('C*').map{ |c| c < 97 ? c + 49 : c + 10 }.pack('C*') end
ruby
def extension_id raise Tay::PrivateKeyNotFound.new unless private_key_exists? public_key = OpenSSL::PKey::RSA.new(File.read(full_key_path)).public_key.to_der hash = Digest::SHA256.hexdigest(public_key)[0...32] hash.unpack('C*').map{ |c| c < 97 ? c + 49 : c + 10 }.pack('C*') end
[ "def", "extension_id", "raise", "Tay", "::", "PrivateKeyNotFound", ".", "new", "unless", "private_key_exists?", "public_key", "=", "OpenSSL", "::", "PKey", "::", "RSA", ".", "new", "(", "File", ".", "read", "(", "full_key_path", ")", ")", ".", "public_key", ".", "to_der", "hash", "=", "Digest", "::", "SHA256", ".", "hexdigest", "(", "public_key", ")", "[", "0", "...", "32", "]", "hash", ".", "unpack", "(", "'C*'", ")", ".", "map", "{", "|", "c", "|", "c", "<", "97", "?", "c", "+", "49", ":", "c", "+", "10", "}", ".", "pack", "(", "'C*'", ")", "end" ]
Calculate the extension's ID from the key Core concepts from supercollider.dk
[ "Calculate", "the", "extension", "s", "ID", "from", "the", "key", "Core", "concepts", "from", "supercollider", ".", "dk" ]
60a5d64aa54e7ef13d10d9c8fb7825e2febea8e5
https://github.com/rixth/tay/blob/60a5d64aa54e7ef13d10d9c8fb7825e2febea8e5/lib/tay/packager.rb#L47-L53
train
rixth/tay
lib/tay/packager.rb
Tay.Packager.write_new_key
def write_new_key File.open(full_key_path, 'w') do |f| f.write OpenSSL::PKey::RSA.generate(1024).export() end end
ruby
def write_new_key File.open(full_key_path, 'w') do |f| f.write OpenSSL::PKey::RSA.generate(1024).export() end end
[ "def", "write_new_key", "File", ".", "open", "(", "full_key_path", ",", "'w'", ")", "do", "|", "f", "|", "f", ".", "write", "OpenSSL", "::", "PKey", "::", "RSA", ".", "generate", "(", "1024", ")", ".", "export", "(", ")", "end", "end" ]
Generate a key with OpenSSL and write it to the key path
[ "Generate", "a", "key", "with", "OpenSSL", "and", "write", "it", "to", "the", "key", "path" ]
60a5d64aa54e7ef13d10d9c8fb7825e2febea8e5
https://github.com/rixth/tay/blob/60a5d64aa54e7ef13d10d9c8fb7825e2febea8e5/lib/tay/packager.rb#L69-L73
train
mccraigmccraig/rsxml
lib/rsxml/xml.rb
Rsxml.Xml.traverse
def traverse(element, visitor, context = Visitor::Context.new) ns_bindings = namespace_bindings_from_defs(element.namespace_definitions) context.ns_stack.push(ns_bindings) eelement, eattrs = explode_element(element) begin visitor.element(context, eelement, eattrs, ns_bindings) do element.children.each do |child| if child.element? traverse(child, visitor, context) elsif child.text? visitor.text(context, child.content) else Rsxml.log{|logger| logger.warn("unknown Nokogiri Node type: #{child.inspect}")} end end end ensure context.ns_stack.pop end visitor end
ruby
def traverse(element, visitor, context = Visitor::Context.new) ns_bindings = namespace_bindings_from_defs(element.namespace_definitions) context.ns_stack.push(ns_bindings) eelement, eattrs = explode_element(element) begin visitor.element(context, eelement, eattrs, ns_bindings) do element.children.each do |child| if child.element? traverse(child, visitor, context) elsif child.text? visitor.text(context, child.content) else Rsxml.log{|logger| logger.warn("unknown Nokogiri Node type: #{child.inspect}")} end end end ensure context.ns_stack.pop end visitor end
[ "def", "traverse", "(", "element", ",", "visitor", ",", "context", "=", "Visitor", "::", "Context", ".", "new", ")", "ns_bindings", "=", "namespace_bindings_from_defs", "(", "element", ".", "namespace_definitions", ")", "context", ".", "ns_stack", ".", "push", "(", "ns_bindings", ")", "eelement", ",", "eattrs", "=", "explode_element", "(", "element", ")", "begin", "visitor", ".", "element", "(", "context", ",", "eelement", ",", "eattrs", ",", "ns_bindings", ")", "do", "element", ".", "children", ".", "each", "do", "|", "child", "|", "if", "child", ".", "element?", "traverse", "(", "child", ",", "visitor", ",", "context", ")", "elsif", "child", ".", "text?", "visitor", ".", "text", "(", "context", ",", "child", ".", "content", ")", "else", "Rsxml", ".", "log", "{", "|", "logger", "|", "logger", ".", "warn", "(", "\"unknown Nokogiri Node type: #{child.inspect}\"", ")", "}", "end", "end", "end", "ensure", "context", ".", "ns_stack", ".", "pop", "end", "visitor", "end" ]
pre-order traversal of the Nokogiri Nodes, calling methods on the visitor with each Node
[ "pre", "-", "order", "traversal", "of", "the", "Nokogiri", "Nodes", "calling", "methods", "on", "the", "visitor", "with", "each", "Node" ]
3699c186f01be476a5942d64cd5c39f4d6bbe175
https://github.com/mccraigmccraig/rsxml/blob/3699c186f01be476a5942d64cd5c39f4d6bbe175/lib/rsxml/xml.rb#L63-L86
train
fenton-project/fenton_shell
lib/fenton_shell/config_file.rb
FentonShell.ConfigFile.config_file_create
def config_file_create(global_options, options) config_directory_create(global_options) file = "#{global_options[:directory]}/config" options.store(:fenton_server_url, global_options[:fenton_server_url]) content = config_generation(options) File.write(file, content) [true, 'ConfigFile': ['created!']] end
ruby
def config_file_create(global_options, options) config_directory_create(global_options) file = "#{global_options[:directory]}/config" options.store(:fenton_server_url, global_options[:fenton_server_url]) content = config_generation(options) File.write(file, content) [true, 'ConfigFile': ['created!']] end
[ "def", "config_file_create", "(", "global_options", ",", "options", ")", "config_directory_create", "(", "global_options", ")", "file", "=", "\"#{global_options[:directory]}/config\"", "options", ".", "store", "(", ":fenton_server_url", ",", "global_options", "[", ":fenton_server_url", "]", ")", "content", "=", "config_generation", "(", "options", ")", "File", ".", "write", "(", "file", ",", "content", ")", "[", "true", ",", "'ConfigFile'", ":", "[", "'created!'", "]", "]", "end" ]
Creates the configuration file @param options [Hash] fields from fenton command line @return [Object] true or false @return [String] message on success or failure
[ "Creates", "the", "configuration", "file" ]
6e1d76186fa7ee7a3be141afad9361e3a3e0ec91
https://github.com/fenton-project/fenton_shell/blob/6e1d76186fa7ee7a3be141afad9361e3a3e0ec91/lib/fenton_shell/config_file.rb#L69-L78
train
fenton-project/fenton_shell
lib/fenton_shell/config_file.rb
FentonShell.ConfigFile.config_generation
def config_generation(options) config_contents = {} config_options = options.keys.map(&:to_sym).sort.uniq config_options.delete(:password) config_options.each do |config_option| config_contents.store(config_option.to_sym, options[config_option]) end config_contents.store(:default_organization, options[:username]) config_contents.to_yaml end
ruby
def config_generation(options) config_contents = {} config_options = options.keys.map(&:to_sym).sort.uniq config_options.delete(:password) config_options.each do |config_option| config_contents.store(config_option.to_sym, options[config_option]) end config_contents.store(:default_organization, options[:username]) config_contents.to_yaml end
[ "def", "config_generation", "(", "options", ")", "config_contents", "=", "{", "}", "config_options", "=", "options", ".", "keys", ".", "map", "(", "&", ":to_sym", ")", ".", "sort", ".", "uniq", "config_options", ".", "delete", "(", ":password", ")", "config_options", ".", "each", "do", "|", "config_option", "|", "config_contents", ".", "store", "(", "config_option", ".", "to_sym", ",", "options", "[", "config_option", "]", ")", "end", "config_contents", ".", "store", "(", ":default_organization", ",", "options", "[", ":username", "]", ")", "config_contents", ".", "to_yaml", "end" ]
Generates the configuration file content @param options [Hash] fields from fenton command line @return [String] true or false
[ "Generates", "the", "configuration", "file", "content" ]
6e1d76186fa7ee7a3be141afad9361e3a3e0ec91
https://github.com/fenton-project/fenton_shell/blob/6e1d76186fa7ee7a3be141afad9361e3a3e0ec91/lib/fenton_shell/config_file.rb#L84-L96
train
GoConflux/conify
lib/conify/helpers.rb
Conify.Helpers.format_with_bang
def format_with_bang(message) return message if !message.is_a?(String) return '' if message.to_s.strip == '' " ! " + message.encode('utf-8', 'binary', invalid: :replace, undef: :replace).split("\n").join("\n ! ") end
ruby
def format_with_bang(message) return message if !message.is_a?(String) return '' if message.to_s.strip == '' " ! " + message.encode('utf-8', 'binary', invalid: :replace, undef: :replace).split("\n").join("\n ! ") end
[ "def", "format_with_bang", "(", "message", ")", "return", "message", "if", "!", "message", ".", "is_a?", "(", "String", ")", "return", "''", "if", "message", ".", "to_s", ".", "strip", "==", "''", "\" ! \"", "+", "message", ".", "encode", "(", "'utf-8'", ",", "'binary'", ",", "invalid", ":", ":replace", ",", "undef", ":", ":replace", ")", ".", "split", "(", "\"\\n\"", ")", ".", "join", "(", "\"\\n ! \"", ")", "end" ]
Add a bang to an error message
[ "Add", "a", "bang", "to", "an", "error", "message" ]
2232fa8a3b144566f4558ab888988559d4dff6bd
https://github.com/GoConflux/conify/blob/2232fa8a3b144566f4558ab888988559d4dff6bd/lib/conify/helpers.rb#L11-L15
train
GoConflux/conify
lib/conify/helpers.rb
Conify.Helpers.to_table
def to_table(data, headers) column_lengths = [] gutter = 2 table = '' # Figure out column widths based on longest string in each column (including the header string) headers.each { |header| width = data.map { |_| _[header] }.max_by(&:length).length width = header.length if width < header.length column_lengths << width } # format the length of a table cell string to make it as wide as the column (by adding extra spaces) format_row_entry = lambda { |entry, i| entry + (' ' * (column_lengths[i] - entry.length + gutter)) } # Add headers headers.each_with_index { |header, i| table += format_row_entry.call(header, i) } table += "\n" # Add line breaks under headers column_lengths.each { |length| table += (('-' * length) + (' ' * gutter)) } table += "\n" # Add rows data.each { |row| headers.each_with_index { |header, i| table += format_row_entry.call(row[header], i) } table += "\n" } table end
ruby
def to_table(data, headers) column_lengths = [] gutter = 2 table = '' # Figure out column widths based on longest string in each column (including the header string) headers.each { |header| width = data.map { |_| _[header] }.max_by(&:length).length width = header.length if width < header.length column_lengths << width } # format the length of a table cell string to make it as wide as the column (by adding extra spaces) format_row_entry = lambda { |entry, i| entry + (' ' * (column_lengths[i] - entry.length + gutter)) } # Add headers headers.each_with_index { |header, i| table += format_row_entry.call(header, i) } table += "\n" # Add line breaks under headers column_lengths.each { |length| table += (('-' * length) + (' ' * gutter)) } table += "\n" # Add rows data.each { |row| headers.each_with_index { |header, i| table += format_row_entry.call(row[header], i) } table += "\n" } table end
[ "def", "to_table", "(", "data", ",", "headers", ")", "column_lengths", "=", "[", "]", "gutter", "=", "2", "table", "=", "''", "headers", ".", "each", "{", "|", "header", "|", "width", "=", "data", ".", "map", "{", "|", "_", "|", "_", "[", "header", "]", "}", ".", "max_by", "(", "&", ":length", ")", ".", "length", "width", "=", "header", ".", "length", "if", "width", "<", "header", ".", "length", "column_lengths", "<<", "width", "}", "format_row_entry", "=", "lambda", "{", "|", "entry", ",", "i", "|", "entry", "+", "(", "' '", "*", "(", "column_lengths", "[", "i", "]", "-", "entry", ".", "length", "+", "gutter", ")", ")", "}", "headers", ".", "each_with_index", "{", "|", "header", ",", "i", "|", "table", "+=", "format_row_entry", ".", "call", "(", "header", ",", "i", ")", "}", "table", "+=", "\"\\n\"", "column_lengths", ".", "each", "{", "|", "length", "|", "table", "+=", "(", "(", "'-'", "*", "length", ")", "+", "(", "' '", "*", "gutter", ")", ")", "}", "table", "+=", "\"\\n\"", "data", ".", "each", "{", "|", "row", "|", "headers", ".", "each_with_index", "{", "|", "header", ",", "i", "|", "table", "+=", "format_row_entry", ".", "call", "(", "row", "[", "header", "]", ",", "i", ")", "}", "table", "+=", "\"\\n\"", "}", "table", "end" ]
format some data into a table to then be displayed to the user
[ "format", "some", "data", "into", "a", "table", "to", "then", "be", "displayed", "to", "the", "user" ]
2232fa8a3b144566f4558ab888988559d4dff6bd
https://github.com/GoConflux/conify/blob/2232fa8a3b144566f4558ab888988559d4dff6bd/lib/conify/helpers.rb#L28-L71
train
xiuxian123/loyals
projects/loyal_warden/lib/warden/proxy.rb
Warden.Proxy.clear_strategies_cache!
def clear_strategies_cache!(*args) scope, opts = _retrieve_scope_and_opts(args) @winning_strategies.delete(scope) @strategies[scope].each do |k, v| v.clear! if args.empty? || args.include?(k) end end
ruby
def clear_strategies_cache!(*args) scope, opts = _retrieve_scope_and_opts(args) @winning_strategies.delete(scope) @strategies[scope].each do |k, v| v.clear! if args.empty? || args.include?(k) end end
[ "def", "clear_strategies_cache!", "(", "*", "args", ")", "scope", ",", "opts", "=", "_retrieve_scope_and_opts", "(", "args", ")", "@winning_strategies", ".", "delete", "(", "scope", ")", "@strategies", "[", "scope", "]", ".", "each", "do", "|", "k", ",", "v", "|", "v", ".", "clear!", "if", "args", ".", "empty?", "||", "args", ".", "include?", "(", "k", ")", "end", "end" ]
Clear the cache of performed strategies so far. Warden runs each strategy just once during the request lifecycle. You can clear the strategies cache if you want to allow a strategy to be run more than once. This method has the same API as authenticate, allowing you to clear specific strategies for given scope: Parameters: args - a list of symbols (labels) that name the strategies to attempt opts - an options hash that contains the :scope of the user to check Example: # Clear all strategies for the configured default_scope env['warden'].clear_strategies_cache! # Clear all strategies for the :admin scope env['warden'].clear_strategies_cache!(:scope => :admin) # Clear password strategy for the :admin scope env['warden'].clear_strategies_cache!(:password, :scope => :admin) :api: public
[ "Clear", "the", "cache", "of", "performed", "strategies", "so", "far", ".", "Warden", "runs", "each", "strategy", "just", "once", "during", "the", "request", "lifecycle", ".", "You", "can", "clear", "the", "strategies", "cache", "if", "you", "want", "to", "allow", "a", "strategy", "to", "be", "run", "more", "than", "once", "." ]
41f586ca1551f64e5375ad32a406d5fca0afae43
https://github.com/xiuxian123/loyals/blob/41f586ca1551f64e5375ad32a406d5fca0afae43/projects/loyal_warden/lib/warden/proxy.rb#L71-L78
train
xiuxian123/loyals
projects/loyal_warden/lib/warden/proxy.rb
Warden.Proxy.set_user
def set_user(user, opts = {}) scope = (opts[:scope] ||= @config.default_scope) # Get the default options from the master configuration for the given scope opts = (@config[:scope_defaults][scope] || {}).merge(opts) opts[:event] ||= :set_user @users[scope] = user if opts[:store] != false && opts[:event] != :fetch options = env[ENV_SESSION_OPTIONS] options[:renew] = true if options session_serializer.store(user, scope) end run_callbacks = opts.fetch(:run_callbacks, true) manager._run_callbacks(:after_set_user, user, self, opts) if run_callbacks @users[scope] end
ruby
def set_user(user, opts = {}) scope = (opts[:scope] ||= @config.default_scope) # Get the default options from the master configuration for the given scope opts = (@config[:scope_defaults][scope] || {}).merge(opts) opts[:event] ||= :set_user @users[scope] = user if opts[:store] != false && opts[:event] != :fetch options = env[ENV_SESSION_OPTIONS] options[:renew] = true if options session_serializer.store(user, scope) end run_callbacks = opts.fetch(:run_callbacks, true) manager._run_callbacks(:after_set_user, user, self, opts) if run_callbacks @users[scope] end
[ "def", "set_user", "(", "user", ",", "opts", "=", "{", "}", ")", "scope", "=", "(", "opts", "[", ":scope", "]", "||=", "@config", ".", "default_scope", ")", "opts", "=", "(", "@config", "[", ":scope_defaults", "]", "[", "scope", "]", "||", "{", "}", ")", ".", "merge", "(", "opts", ")", "opts", "[", ":event", "]", "||=", ":set_user", "@users", "[", "scope", "]", "=", "user", "if", "opts", "[", ":store", "]", "!=", "false", "&&", "opts", "[", ":event", "]", "!=", ":fetch", "options", "=", "env", "[", "ENV_SESSION_OPTIONS", "]", "options", "[", ":renew", "]", "=", "true", "if", "options", "session_serializer", ".", "store", "(", "user", ",", "scope", ")", "end", "run_callbacks", "=", "opts", ".", "fetch", "(", ":run_callbacks", ",", "true", ")", "manager", ".", "_run_callbacks", "(", ":after_set_user", ",", "user", ",", "self", ",", "opts", ")", "if", "run_callbacks", "@users", "[", "scope", "]", "end" ]
Manually set the user into the session and auth proxy Parameters: user - An object that has been setup to serialize into and out of the session. opts - An options hash. Use the :scope option to set the scope of the user, set the :store option to false to skip serializing into the session, set the :run_callbacks to false to skip running the callbacks (the default is true). :api: public
[ "Manually", "set", "the", "user", "into", "the", "session", "and", "auth", "proxy" ]
41f586ca1551f64e5375ad32a406d5fca0afae43
https://github.com/xiuxian123/loyals/blob/41f586ca1551f64e5375ad32a406d5fca0afae43/projects/loyal_warden/lib/warden/proxy.rb#L164-L182
train
tongueroo/lono
lib/lono/core.rb
Lono.Core.env_from_profile
def env_from_profile(aws_profile) data = YAML.load_file("#{Lono.root}/config/settings.yml") env = data.find do |_env, setting| setting ||= {} profiles = setting['aws_profiles'] profiles && profiles.include?(aws_profile) end env.first if env end
ruby
def env_from_profile(aws_profile) data = YAML.load_file("#{Lono.root}/config/settings.yml") env = data.find do |_env, setting| setting ||= {} profiles = setting['aws_profiles'] profiles && profiles.include?(aws_profile) end env.first if env end
[ "def", "env_from_profile", "(", "aws_profile", ")", "data", "=", "YAML", ".", "load_file", "(", "\"#{Lono.root}/config/settings.yml\"", ")", "env", "=", "data", ".", "find", "do", "|", "_env", ",", "setting", "|", "setting", "||=", "{", "}", "profiles", "=", "setting", "[", "'aws_profiles'", "]", "profiles", "&&", "profiles", ".", "include?", "(", "aws_profile", ")", "end", "env", ".", "first", "if", "env", "end" ]
Do not use the Setting class to load the profile because it can cause an infinite loop then if we decide to use Lono.env from within settings class.
[ "Do", "not", "use", "the", "Setting", "class", "to", "load", "the", "profile", "because", "it", "can", "cause", "an", "infinite", "loop", "then", "if", "we", "decide", "to", "use", "Lono", ".", "env", "from", "within", "settings", "class", "." ]
0135ec4cdb641970cd0bf7a5947b09d3153f739a
https://github.com/tongueroo/lono/blob/0135ec4cdb641970cd0bf7a5947b09d3153f739a/lib/lono/core.rb#L46-L54
train
szhu/hashcontrol
lib/hash_control/validator.rb
HashControl.Validator.require
def require(*keys) permitted_keys.merge keys required_keys = keys.to_set unless (missing_keys = required_keys - hash_keys).empty? error "required #{terms} #{missing_keys.to_a} missing" + postscript end self end
ruby
def require(*keys) permitted_keys.merge keys required_keys = keys.to_set unless (missing_keys = required_keys - hash_keys).empty? error "required #{terms} #{missing_keys.to_a} missing" + postscript end self end
[ "def", "require", "(", "*", "keys", ")", "permitted_keys", ".", "merge", "keys", "required_keys", "=", "keys", ".", "to_set", "unless", "(", "missing_keys", "=", "required_keys", "-", "hash_keys", ")", ".", "empty?", "error", "\"required #{terms} #{missing_keys.to_a} missing\"", "+", "postscript", "end", "self", "end" ]
Specifies keys that must exist
[ "Specifies", "keys", "that", "must", "exist" ]
e416c0af53f1ce582ef2d3cd074b9aeefc1fab4f
https://github.com/szhu/hashcontrol/blob/e416c0af53f1ce582ef2d3cd074b9aeefc1fab4f/lib/hash_control/validator.rb#L20-L27
train
cordawyn/redlander
lib/redlander/node.rb
Redlander.Node.datatype
def datatype if instance_variable_defined?(:@datatype) @datatype else @datatype = if literal? rdf_uri = Redland.librdf_node_get_literal_value_datatype_uri(rdf_node) rdf_uri.null? ? XmlSchema.datatype_of("") : URI.parse(Redland.librdf_uri_to_string(rdf_uri)) else nil end end end
ruby
def datatype if instance_variable_defined?(:@datatype) @datatype else @datatype = if literal? rdf_uri = Redland.librdf_node_get_literal_value_datatype_uri(rdf_node) rdf_uri.null? ? XmlSchema.datatype_of("") : URI.parse(Redland.librdf_uri_to_string(rdf_uri)) else nil end end end
[ "def", "datatype", "if", "instance_variable_defined?", "(", ":@datatype", ")", "@datatype", "else", "@datatype", "=", "if", "literal?", "rdf_uri", "=", "Redland", ".", "librdf_node_get_literal_value_datatype_uri", "(", "rdf_node", ")", "rdf_uri", ".", "null?", "?", "XmlSchema", ".", "datatype_of", "(", "\"\"", ")", ":", "URI", ".", "parse", "(", "Redland", ".", "librdf_uri_to_string", "(", "rdf_uri", ")", ")", "else", "nil", "end", "end", "end" ]
Datatype URI for the literal node, or nil
[ "Datatype", "URI", "for", "the", "literal", "node", "or", "nil" ]
a5c84e15a7602c674606e531bda6a616b1237c44
https://github.com/cordawyn/redlander/blob/a5c84e15a7602c674606e531bda6a616b1237c44/lib/redlander/node.rb#L40-L51
train
cordawyn/redlander
lib/redlander/node.rb
Redlander.Node.value
def value if resource? uri elsif blank? Redland.librdf_node_get_blank_identifier(rdf_node).force_encoding("UTF-8") else v = Redland.librdf_node_get_literal_value(rdf_node).force_encoding("UTF-8") v << "@#{lang}" if lang XmlSchema.instantiate(v, datatype) end end
ruby
def value if resource? uri elsif blank? Redland.librdf_node_get_blank_identifier(rdf_node).force_encoding("UTF-8") else v = Redland.librdf_node_get_literal_value(rdf_node).force_encoding("UTF-8") v << "@#{lang}" if lang XmlSchema.instantiate(v, datatype) end end
[ "def", "value", "if", "resource?", "uri", "elsif", "blank?", "Redland", ".", "librdf_node_get_blank_identifier", "(", "rdf_node", ")", ".", "force_encoding", "(", "\"UTF-8\"", ")", "else", "v", "=", "Redland", ".", "librdf_node_get_literal_value", "(", "rdf_node", ")", ".", "force_encoding", "(", "\"UTF-8\"", ")", "v", "<<", "\"@#{lang}\"", "if", "lang", "XmlSchema", ".", "instantiate", "(", "v", ",", "datatype", ")", "end", "end" ]
Value of the literal node as a Ruby object instance. Returns an instance of URI for resource nodes, "blank identifier" for blank nodes. @return [URI, Any]
[ "Value", "of", "the", "literal", "node", "as", "a", "Ruby", "object", "instance", "." ]
a5c84e15a7602c674606e531bda6a616b1237c44
https://github.com/cordawyn/redlander/blob/a5c84e15a7602c674606e531bda6a616b1237c44/lib/redlander/node.rb#L134-L144
train
jdickey/repository-base
lib/repository/base.rb
Repository.Base.delete
def delete(identifier) RecordDeleter.new(identifier: identifier, dao: dao, factory: factory) .delete end
ruby
def delete(identifier) RecordDeleter.new(identifier: identifier, dao: dao, factory: factory) .delete end
[ "def", "delete", "(", "identifier", ")", "RecordDeleter", ".", "new", "(", "identifier", ":", "identifier", ",", "dao", ":", "dao", ",", "factory", ":", "factory", ")", ".", "delete", "end" ]
Remove a record from the underlying DAO whose slug matches the passed-in identifier. @param identifier [String] [Slug](http://en.wikipedia.org/wiki/Semantic_URL#Slug) for record to be deleted. @return [Repository::Support::StoreResult] An object containing information about the success or failure of an action. @since 0.0.5
[ "Remove", "a", "record", "from", "the", "underlying", "DAO", "whose", "slug", "matches", "the", "passed", "-", "in", "identifier", "." ]
b0f14156c1345d9ae878868cb6500f721653b4dc
https://github.com/jdickey/repository-base/blob/b0f14156c1345d9ae878868cb6500f721653b4dc/lib/repository/base.rb#L64-L67
train
rspeicher/will_paginate_renderers
lib/will_paginate_renderers/gmail.rb
WillPaginateRenderers.Gmail.window
def window base = @collection.offset high = base + @collection.per_page high = @collection.total_entries if high > @collection.total_entries # TODO: What's the best way to allow customization of this text, particularly "of"? tag(:span, " #{base + 1} - #{high} of #{@collection.total_entries} ", :class => WillPaginateRenderers.pagination_options[:gmail_window_class]) end
ruby
def window base = @collection.offset high = base + @collection.per_page high = @collection.total_entries if high > @collection.total_entries # TODO: What's the best way to allow customization of this text, particularly "of"? tag(:span, " #{base + 1} - #{high} of #{@collection.total_entries} ", :class => WillPaginateRenderers.pagination_options[:gmail_window_class]) end
[ "def", "window", "base", "=", "@collection", ".", "offset", "high", "=", "base", "+", "@collection", ".", "per_page", "high", "=", "@collection", ".", "total_entries", "if", "high", ">", "@collection", ".", "total_entries", "tag", "(", ":span", ",", "\" #{base + 1} - #{high} of #{@collection.total_entries} \"", ",", ":class", "=>", "WillPaginateRenderers", ".", "pagination_options", "[", ":gmail_window_class", "]", ")", "end" ]
Renders the "x - y of z" text
[ "Renders", "the", "x", "-", "y", "of", "z", "text" ]
30f1b1b8aaab70237858b93d9aa74464e4e42fb3
https://github.com/rspeicher/will_paginate_renderers/blob/30f1b1b8aaab70237858b93d9aa74464e4e42fb3/lib/will_paginate_renderers/gmail.rb#L74-L82
train
maxehmookau/echonest-ruby-api
lib/echonest-ruby-api/artist.rb
Echonest.Artist.news
def news(options = { results: 1 }) response = get_response(results: options[:results], name: @name) response[:news].collect do |b| Blog.new(name: b[:name], site: b[:site], url: b[:url]) end end
ruby
def news(options = { results: 1 }) response = get_response(results: options[:results], name: @name) response[:news].collect do |b| Blog.new(name: b[:name], site: b[:site], url: b[:url]) end end
[ "def", "news", "(", "options", "=", "{", "results", ":", "1", "}", ")", "response", "=", "get_response", "(", "results", ":", "options", "[", ":results", "]", ",", "name", ":", "@name", ")", "response", "[", ":news", "]", ".", "collect", "do", "|", "b", "|", "Blog", ".", "new", "(", "name", ":", "b", "[", ":name", "]", ",", "site", ":", "b", "[", ":site", "]", ",", "url", ":", "b", "[", ":url", "]", ")", "end", "end" ]
This appears to be from more "reputable" sources?
[ "This", "appears", "to", "be", "from", "more", "reputable", "sources?" ]
5d90cb6adec03d139f264665206ad507b6cc0a00
https://github.com/maxehmookau/echonest-ruby-api/blob/5d90cb6adec03d139f264665206ad507b6cc0a00/lib/echonest-ruby-api/artist.rb#L40-L46
train
sugaryourcoffee/syclink
lib/syclink/website.rb
SycLink.Website.list_links
def list_links(args = {}) if args.empty? links else links.select { |link| link.match? args } end end
ruby
def list_links(args = {}) if args.empty? links else links.select { |link| link.match? args } end end
[ "def", "list_links", "(", "args", "=", "{", "}", ")", "if", "args", ".", "empty?", "links", "else", "links", ".", "select", "{", "|", "link", "|", "link", ".", "match?", "args", "}", "end", "end" ]
List links that match the attributes
[ "List", "links", "that", "match", "the", "attributes" ]
941ee2045c946daa1e0db394eb643aa82c1254cc
https://github.com/sugaryourcoffee/syclink/blob/941ee2045c946daa1e0db394eb643aa82c1254cc/lib/syclink/website.rb#L38-L44
train
sugaryourcoffee/syclink
lib/syclink/website.rb
SycLink.Website.merge_links_on
def merge_links_on(attribute, concat_string = ',') links_group_by(attribute) .select { |key, link_list| links.size > 1 } .map do |key, link_list| merge_attributes = Link::ATTRS - [attribute] link_list.first .update(Hash[extract_columns(link_list, merge_attributes) .map { |c| c.uniq.join(concat_string) } .collect { |v| [merge_attributes.shift, v] }]) link_list.shift link_list.each { |link| links.delete(link) } end end
ruby
def merge_links_on(attribute, concat_string = ',') links_group_by(attribute) .select { |key, link_list| links.size > 1 } .map do |key, link_list| merge_attributes = Link::ATTRS - [attribute] link_list.first .update(Hash[extract_columns(link_list, merge_attributes) .map { |c| c.uniq.join(concat_string) } .collect { |v| [merge_attributes.shift, v] }]) link_list.shift link_list.each { |link| links.delete(link) } end end
[ "def", "merge_links_on", "(", "attribute", ",", "concat_string", "=", "','", ")", "links_group_by", "(", "attribute", ")", ".", "select", "{", "|", "key", ",", "link_list", "|", "links", ".", "size", ">", "1", "}", ".", "map", "do", "|", "key", ",", "link_list", "|", "merge_attributes", "=", "Link", "::", "ATTRS", "-", "[", "attribute", "]", "link_list", ".", "first", ".", "update", "(", "Hash", "[", "extract_columns", "(", "link_list", ",", "merge_attributes", ")", ".", "map", "{", "|", "c", "|", "c", ".", "uniq", ".", "join", "(", "concat_string", ")", "}", ".", "collect", "{", "|", "v", "|", "[", "merge_attributes", ".", "shift", ",", "v", "]", "}", "]", ")", "link_list", ".", "shift", "link_list", ".", "each", "{", "|", "link", "|", "links", ".", "delete", "(", "link", ")", "}", "end", "end" ]
Merge links based on the provided attribue to one link by combining the values. The first link will be updated and the obsolete links are deleted and will be returned
[ "Merge", "links", "based", "on", "the", "provided", "attribue", "to", "one", "link", "by", "combining", "the", "values", ".", "The", "first", "link", "will", "be", "updated", "and", "the", "obsolete", "links", "are", "deleted", "and", "will", "be", "returned" ]
941ee2045c946daa1e0db394eb643aa82c1254cc
https://github.com/sugaryourcoffee/syclink/blob/941ee2045c946daa1e0db394eb643aa82c1254cc/lib/syclink/website.rb#L60-L72
train
sugaryourcoffee/syclink
lib/syclink/website.rb
SycLink.Website.links_group_by
def links_group_by(attribute, linkz = links) linkz.map { |link| { key: link.send(attribute), link: link } } .group_by { |entry| entry[:key] } .each { |key, link| link.map! { |l| l[:link] }} end
ruby
def links_group_by(attribute, linkz = links) linkz.map { |link| { key: link.send(attribute), link: link } } .group_by { |entry| entry[:key] } .each { |key, link| link.map! { |l| l[:link] }} end
[ "def", "links_group_by", "(", "attribute", ",", "linkz", "=", "links", ")", "linkz", ".", "map", "{", "|", "link", "|", "{", "key", ":", "link", ".", "send", "(", "attribute", ")", ",", "link", ":", "link", "}", "}", ".", "group_by", "{", "|", "entry", "|", "entry", "[", ":key", "]", "}", ".", "each", "{", "|", "key", ",", "link", "|", "link", ".", "map!", "{", "|", "l", "|", "l", "[", ":link", "]", "}", "}", "end" ]
Groups the links on the provided attribute. If no links array is provided the links from self are used
[ "Groups", "the", "links", "on", "the", "provided", "attribute", ".", "If", "no", "links", "array", "is", "provided", "the", "links", "from", "self", "are", "used" ]
941ee2045c946daa1e0db394eb643aa82c1254cc
https://github.com/sugaryourcoffee/syclink/blob/941ee2045c946daa1e0db394eb643aa82c1254cc/lib/syclink/website.rb#L76-L80
train
sugaryourcoffee/syclink
lib/syclink/website.rb
SycLink.Website.links_duplicate_on
def links_duplicate_on(attribute, separator) links.map do |link| link.send(attribute).split(separator).collect do |value| link.dup.update(Hash[attribute, value]) end end.flatten end
ruby
def links_duplicate_on(attribute, separator) links.map do |link| link.send(attribute).split(separator).collect do |value| link.dup.update(Hash[attribute, value]) end end.flatten end
[ "def", "links_duplicate_on", "(", "attribute", ",", "separator", ")", "links", ".", "map", "do", "|", "link", "|", "link", ".", "send", "(", "attribute", ")", ".", "split", "(", "separator", ")", ".", "collect", "do", "|", "value", "|", "link", ".", "dup", ".", "update", "(", "Hash", "[", "attribute", ",", "value", "]", ")", "end", "end", ".", "flatten", "end" ]
Create multiple Links based on the attribute provided. The specified spearator will splitt the attribute value in distinct values and for each different value a Link will be created
[ "Create", "multiple", "Links", "based", "on", "the", "attribute", "provided", ".", "The", "specified", "spearator", "will", "splitt", "the", "attribute", "value", "in", "distinct", "values", "and", "for", "each", "different", "value", "a", "Link", "will", "be", "created" ]
941ee2045c946daa1e0db394eb643aa82c1254cc
https://github.com/sugaryourcoffee/syclink/blob/941ee2045c946daa1e0db394eb643aa82c1254cc/lib/syclink/website.rb#L92-L98
train
sugaryourcoffee/syclink
lib/syclink/website.rb
SycLink.Website.link_attribute_list
def link_attribute_list(attribute, separator = nil) links.map {|link| link.send(attribute).split(separator)}.flatten.uniq.sort end
ruby
def link_attribute_list(attribute, separator = nil) links.map {|link| link.send(attribute).split(separator)}.flatten.uniq.sort end
[ "def", "link_attribute_list", "(", "attribute", ",", "separator", "=", "nil", ")", "links", ".", "map", "{", "|", "link", "|", "link", ".", "send", "(", "attribute", ")", ".", "split", "(", "separator", ")", "}", ".", "flatten", ".", "uniq", ".", "sort", "end" ]
List all attributes of the links
[ "List", "all", "attributes", "of", "the", "links" ]
941ee2045c946daa1e0db394eb643aa82c1254cc
https://github.com/sugaryourcoffee/syclink/blob/941ee2045c946daa1e0db394eb643aa82c1254cc/lib/syclink/website.rb#L106-L108
train
Deradon/Rdcpu16
lib/dcpu16/cpu.rb
DCPU16.CPU.run
def run @started_at = Time.now max_cycles = 1 while true do if @cycle < max_cycles step else diff = Time.now - @started_at max_cycles = (diff * @clock_cycle) end end end
ruby
def run @started_at = Time.now max_cycles = 1 while true do if @cycle < max_cycles step else diff = Time.now - @started_at max_cycles = (diff * @clock_cycle) end end end
[ "def", "run", "@started_at", "=", "Time", ".", "now", "max_cycles", "=", "1", "while", "true", "do", "if", "@cycle", "<", "max_cycles", "step", "else", "diff", "=", "Time", ".", "now", "-", "@started_at", "max_cycles", "=", "(", "diff", "*", "@clock_cycle", ")", "end", "end", "end" ]
Run in endless loop
[ "Run", "in", "endless", "loop" ]
a4460927aa64c2a514c57993e8ea13f5b48377e9
https://github.com/Deradon/Rdcpu16/blob/a4460927aa64c2a514c57993e8ea13f5b48377e9/lib/dcpu16/cpu.rb#L51-L63
train
dannyxu2015/imwukong
lib/imwukong/api.rb
Imwukong.Base.wk_api_info
def wk_api_info(api_method='') api_method ||= '' fail 'Invalid wukong api' unless api_method == '' || api_method =~ WK_API_FORMAT if api_method.size > 0 m = api_method.to_s.match(/^wk_([a-zA-Z0-9]+)_(.+)/) method_group = m[1].singularize method_name = m[2] end apis = api_method.size > 0 ? API_LIST.select { |a| a[:method_group]==method_group && method_name==a[:method_name] } : API_LIST fail 'api not found' unless apis.present? apis.map do |api| method_group = api[:method_pluralize] ? api[:method_group].pluralize : api[:method_group] method_name = "wk_#{method_group}_#{api[:method_name]}" "#{method_name}, #{api_url(api)}, #{api[:args].inspect} " end end
ruby
def wk_api_info(api_method='') api_method ||= '' fail 'Invalid wukong api' unless api_method == '' || api_method =~ WK_API_FORMAT if api_method.size > 0 m = api_method.to_s.match(/^wk_([a-zA-Z0-9]+)_(.+)/) method_group = m[1].singularize method_name = m[2] end apis = api_method.size > 0 ? API_LIST.select { |a| a[:method_group]==method_group && method_name==a[:method_name] } : API_LIST fail 'api not found' unless apis.present? apis.map do |api| method_group = api[:method_pluralize] ? api[:method_group].pluralize : api[:method_group] method_name = "wk_#{method_group}_#{api[:method_name]}" "#{method_name}, #{api_url(api)}, #{api[:args].inspect} " end end
[ "def", "wk_api_info", "(", "api_method", "=", "''", ")", "api_method", "||=", "''", "fail", "'Invalid wukong api'", "unless", "api_method", "==", "''", "||", "api_method", "=~", "WK_API_FORMAT", "if", "api_method", ".", "size", ">", "0", "m", "=", "api_method", ".", "to_s", ".", "match", "(", "/", "/", ")", "method_group", "=", "m", "[", "1", "]", ".", "singularize", "method_name", "=", "m", "[", "2", "]", "end", "apis", "=", "api_method", ".", "size", ">", "0", "?", "API_LIST", ".", "select", "{", "|", "a", "|", "a", "[", ":method_group", "]", "==", "method_group", "&&", "method_name", "==", "a", "[", ":method_name", "]", "}", ":", "API_LIST", "fail", "'api not found'", "unless", "apis", ".", "present?", "apis", ".", "map", "do", "|", "api", "|", "method_group", "=", "api", "[", ":method_pluralize", "]", "?", "api", "[", ":method_group", "]", ".", "pluralize", ":", "api", "[", ":method_group", "]", "method_name", "=", "\"wk_#{method_group}_#{api[:method_name]}\"", "\"#{method_name}, #{api_url(api)}, #{api[:args].inspect} \"", "end", "end" ]
api detail info, include request url & arguments @param api_method, string, default output information of all api @return an array of match api info string, format: api_name, REQUEST url, arguments symbol array
[ "api", "detail", "info", "include", "request", "url", "&", "arguments" ]
80c7712cef13e7ee6bd84e604371d47acda89927
https://github.com/dannyxu2015/imwukong/blob/80c7712cef13e7ee6bd84e604371d47acda89927/lib/imwukong/api.rb#L484-L499
train
astjohn/cornerstone
app/models/cornerstone/post.rb
Cornerstone.Post.update_counter_cache
def update_counter_cache self.discussion.reply_count = Post.where(:discussion_id => self.discussion.id) .count - 1 self.discussion.save end
ruby
def update_counter_cache self.discussion.reply_count = Post.where(:discussion_id => self.discussion.id) .count - 1 self.discussion.save end
[ "def", "update_counter_cache", "self", ".", "discussion", ".", "reply_count", "=", "Post", ".", "where", "(", ":discussion_id", "=>", "self", ".", "discussion", ".", "id", ")", ".", "count", "-", "1", "self", ".", "discussion", ".", "save", "end" ]
Custom counter cache. Does not include the first post of a discussion.
[ "Custom", "counter", "cache", ".", "Does", "not", "include", "the", "first", "post", "of", "a", "discussion", "." ]
d7af7c06288477c961f3e328b8640df4be337301
https://github.com/astjohn/cornerstone/blob/d7af7c06288477c961f3e328b8640df4be337301/app/models/cornerstone/post.rb#L74-L78
train
astjohn/cornerstone
app/models/cornerstone/post.rb
Cornerstone.Post.anonymous_or_user_attr
def anonymous_or_user_attr(attr) unless self.user_id.nil? mthd = "user_#{attr.to_s}" # TODO: rails caching is messing this relationship up. # will .user work even if model name is something else. e.g. AdminUser ?? self.user.send(attr) else case attr when :cornerstone_name self.send(:name) when :cornerstone_email self.send(:email) end end end
ruby
def anonymous_or_user_attr(attr) unless self.user_id.nil? mthd = "user_#{attr.to_s}" # TODO: rails caching is messing this relationship up. # will .user work even if model name is something else. e.g. AdminUser ?? self.user.send(attr) else case attr when :cornerstone_name self.send(:name) when :cornerstone_email self.send(:email) end end end
[ "def", "anonymous_or_user_attr", "(", "attr", ")", "unless", "self", ".", "user_id", ".", "nil?", "mthd", "=", "\"user_#{attr.to_s}\"", "self", ".", "user", ".", "send", "(", "attr", ")", "else", "case", "attr", "when", ":cornerstone_name", "self", ".", "send", "(", ":name", ")", "when", ":cornerstone_email", "self", ".", "send", "(", ":email", ")", "end", "end", "end" ]
Returns the requested attribute of the user if it exists, or post's attribute
[ "Returns", "the", "requested", "attribute", "of", "the", "user", "if", "it", "exists", "or", "post", "s", "attribute" ]
d7af7c06288477c961f3e328b8640df4be337301
https://github.com/astjohn/cornerstone/blob/d7af7c06288477c961f3e328b8640df4be337301/app/models/cornerstone/post.rb#L81-L95
train
SpeciesFileGroup/taxonifi
lib/taxonifi/export/format/obo_nomenclature.rb
Taxonifi::Export.OboNomenclature.export
def export() super f = new_output_file('obo_nomenclature.obo') # header f.puts 'format-version: 1.2' f.puts "date: #{@time}" f.puts 'saved-by: someone' f.puts 'auto-generated-by: Taxonifi' f.puts 'synonymtypedef: COMMONNAME "common name"' f.puts 'synonymtypedef: MISSPELLING "misspelling" EXACT' f.puts 'synonymtypedef: TAXONNAMEUSAGE "name with (author year)" NARROW' f.puts "default-namespace: #{@namespace}" f.puts "ontology: FIX-ME-taxonifi-ontology\n\n" # terms @name_collection.collection.each do |n| f.puts '[Term]' f.puts "id: #{id_string(n)}" f.puts "name: #{n.name}" f.puts "is_a: #{id_string(n.parent)} ! #{n.parent.name}" if n.parent f.puts "property_value: has_rank #{rank_string(n)}" f.puts end # typedefs f.puts "[Typedef]" f.puts "id: has_rank" f.puts "name: has taxonomic rank" f.puts "is_metadata_tag: true" true end
ruby
def export() super f = new_output_file('obo_nomenclature.obo') # header f.puts 'format-version: 1.2' f.puts "date: #{@time}" f.puts 'saved-by: someone' f.puts 'auto-generated-by: Taxonifi' f.puts 'synonymtypedef: COMMONNAME "common name"' f.puts 'synonymtypedef: MISSPELLING "misspelling" EXACT' f.puts 'synonymtypedef: TAXONNAMEUSAGE "name with (author year)" NARROW' f.puts "default-namespace: #{@namespace}" f.puts "ontology: FIX-ME-taxonifi-ontology\n\n" # terms @name_collection.collection.each do |n| f.puts '[Term]' f.puts "id: #{id_string(n)}" f.puts "name: #{n.name}" f.puts "is_a: #{id_string(n.parent)} ! #{n.parent.name}" if n.parent f.puts "property_value: has_rank #{rank_string(n)}" f.puts end # typedefs f.puts "[Typedef]" f.puts "id: has_rank" f.puts "name: has taxonomic rank" f.puts "is_metadata_tag: true" true end
[ "def", "export", "(", ")", "super", "f", "=", "new_output_file", "(", "'obo_nomenclature.obo'", ")", "f", ".", "puts", "'format-version: 1.2'", "f", ".", "puts", "\"date: #{@time}\"", "f", ".", "puts", "'saved-by: someone'", "f", ".", "puts", "'auto-generated-by: Taxonifi'", "f", ".", "puts", "'synonymtypedef: COMMONNAME \"common name\"'", "f", ".", "puts", "'synonymtypedef: MISSPELLING \"misspelling\" EXACT'", "f", ".", "puts", "'synonymtypedef: TAXONNAMEUSAGE \"name with (author year)\" NARROW'", "f", ".", "puts", "\"default-namespace: #{@namespace}\"", "f", ".", "puts", "\"ontology: FIX-ME-taxonifi-ontology\\n\\n\"", "@name_collection", ".", "collection", ".", "each", "do", "|", "n", "|", "f", ".", "puts", "'[Term]'", "f", ".", "puts", "\"id: #{id_string(n)}\"", "f", ".", "puts", "\"name: #{n.name}\"", "f", ".", "puts", "\"is_a: #{id_string(n.parent)} ! #{n.parent.name}\"", "if", "n", ".", "parent", "f", ".", "puts", "\"property_value: has_rank #{rank_string(n)}\"", "f", ".", "puts", "end", "f", ".", "puts", "\"[Typedef]\"", "f", ".", "puts", "\"id: has_rank\"", "f", ".", "puts", "\"name: has taxonomic rank\"", "f", ".", "puts", "\"is_metadata_tag: true\"", "true", "end" ]
Writes the file.
[ "Writes", "the", "file", "." ]
100dc94e7ffd378f6a81381c13768e35b2b65bf2
https://github.com/SpeciesFileGroup/taxonifi/blob/100dc94e7ffd378f6a81381c13768e35b2b65bf2/lib/taxonifi/export/format/obo_nomenclature.rb#L28-L60
train
culturecode/templatr
app/models/templatr/field.rb
Templatr.Field.has_unique_name
def has_unique_name invalid = false if template invalid ||= template.common_fields.any? {|field| field.name.downcase == self.name.downcase && field != self } invalid ||= template.default_fields.any? {|field| field.name.downcase == self.name.downcase && field != self } else scope = self.class.common.where("LOWER(name) = LOWER(?)", self.name) scope = scope.where("id != ?", self.id) if persisted? invalid ||= scope.exists? end errors.add(:name, "has already been taken") if invalid end
ruby
def has_unique_name invalid = false if template invalid ||= template.common_fields.any? {|field| field.name.downcase == self.name.downcase && field != self } invalid ||= template.default_fields.any? {|field| field.name.downcase == self.name.downcase && field != self } else scope = self.class.common.where("LOWER(name) = LOWER(?)", self.name) scope = scope.where("id != ?", self.id) if persisted? invalid ||= scope.exists? end errors.add(:name, "has already been taken") if invalid end
[ "def", "has_unique_name", "invalid", "=", "false", "if", "template", "invalid", "||=", "template", ".", "common_fields", ".", "any?", "{", "|", "field", "|", "field", ".", "name", ".", "downcase", "==", "self", ".", "name", ".", "downcase", "&&", "field", "!=", "self", "}", "invalid", "||=", "template", ".", "default_fields", ".", "any?", "{", "|", "field", "|", "field", ".", "name", ".", "downcase", "==", "self", ".", "name", ".", "downcase", "&&", "field", "!=", "self", "}", "else", "scope", "=", "self", ".", "class", ".", "common", ".", "where", "(", "\"LOWER(name) = LOWER(?)\"", ",", "self", ".", "name", ")", "scope", "=", "scope", ".", "where", "(", "\"id != ?\"", ",", "self", ".", "id", ")", "if", "persisted?", "invalid", "||=", "scope", ".", "exists?", "end", "errors", ".", "add", "(", ":name", ",", "\"has already been taken\"", ")", "if", "invalid", "end" ]
Checks the current template and the common fields for any field with the same name
[ "Checks", "the", "current", "template", "and", "the", "common", "fields", "for", "any", "field", "with", "the", "same", "name" ]
0bffb930736b4339fb8a9e8adc080404dc6860d8
https://github.com/culturecode/templatr/blob/0bffb930736b4339fb8a9e8adc080404dc6860d8/app/models/templatr/field.rb#L157-L169
train
culturecode/templatr
app/models/templatr/field.rb
Templatr.Field.disambiguate_fields
def disambiguate_fields if name_changed? # New, Updated fields = self.class.specific.where("LOWER(name) = LOWER(?)", self.name) fields.update_all(:disambiguate => fields.many?) end if name_was # Updated, Destroyed fields = self.class.specific.where("LOWER(name) = LOWER(?)", self.name_was) fields.update_all(:disambiguate => fields.many?) end end
ruby
def disambiguate_fields if name_changed? # New, Updated fields = self.class.specific.where("LOWER(name) = LOWER(?)", self.name) fields.update_all(:disambiguate => fields.many?) end if name_was # Updated, Destroyed fields = self.class.specific.where("LOWER(name) = LOWER(?)", self.name_was) fields.update_all(:disambiguate => fields.many?) end end
[ "def", "disambiguate_fields", "if", "name_changed?", "fields", "=", "self", ".", "class", ".", "specific", ".", "where", "(", "\"LOWER(name) = LOWER(?)\"", ",", "self", ".", "name", ")", "fields", ".", "update_all", "(", ":disambiguate", "=>", "fields", ".", "many?", ")", "end", "if", "name_was", "fields", "=", "self", ".", "class", ".", "specific", ".", "where", "(", "\"LOWER(name) = LOWER(?)\"", ",", "self", ".", "name_was", ")", "fields", ".", "update_all", "(", ":disambiguate", "=>", "fields", ".", "many?", ")", "end", "end" ]
Finds all fields with the same name and ensures they know there is another field with the same name thus allowing us to have them a prefix that lets us identify them in a query string
[ "Finds", "all", "fields", "with", "the", "same", "name", "and", "ensures", "they", "know", "there", "is", "another", "field", "with", "the", "same", "name", "thus", "allowing", "us", "to", "have", "them", "a", "prefix", "that", "lets", "us", "identify", "them", "in", "a", "query", "string" ]
0bffb930736b4339fb8a9e8adc080404dc6860d8
https://github.com/culturecode/templatr/blob/0bffb930736b4339fb8a9e8adc080404dc6860d8/app/models/templatr/field.rb#L192-L202
train
mochnatiy/flexible_accessibility
lib/flexible_accessibility/route_provider.rb
FlexibleAccessibility.RouteProvider.app_routes_as_hash
def app_routes_as_hash Rails.application.routes.routes.each do |route| controller = route.defaults[:controller] next if controller.nil? key = controller.split('/').map(&:camelize).join('::') routes[key] ||= [] routes[key] << route.defaults[:action] end end
ruby
def app_routes_as_hash Rails.application.routes.routes.each do |route| controller = route.defaults[:controller] next if controller.nil? key = controller.split('/').map(&:camelize).join('::') routes[key] ||= [] routes[key] << route.defaults[:action] end end
[ "def", "app_routes_as_hash", "Rails", ".", "application", ".", "routes", ".", "routes", ".", "each", "do", "|", "route", "|", "controller", "=", "route", ".", "defaults", "[", ":controller", "]", "next", "if", "controller", ".", "nil?", "key", "=", "controller", ".", "split", "(", "'/'", ")", ".", "map", "(", "&", ":camelize", ")", ".", "join", "(", "'::'", ")", "routes", "[", "key", "]", "||=", "[", "]", "routes", "[", "key", "]", "<<", "route", ".", "defaults", "[", ":action", "]", "end", "end" ]
Routes from routes.rb
[ "Routes", "from", "routes", ".", "rb" ]
ffd7f76e0765aa28909625b3bfa282264b8a5195
https://github.com/mochnatiy/flexible_accessibility/blob/ffd7f76e0765aa28909625b3bfa282264b8a5195/lib/flexible_accessibility/route_provider.rb#L96-L106
train
andymarthin/bca_statement
lib/bca_statement/client.rb
BcaStatement.Client.get_statement
def get_statement(start_date = '2016-08-29', end_date = '2016-09-01') return nil unless @access_token @timestamp = Time.now.iso8601(3) @start_date = start_date.to_s @end_date = end_date.to_s @path = "/banking/v3/corporates/" @relative_url = "#{@path}#{@corporate_id}/accounts/#{@account_number}/statements?EndDate=#{@end_date}&StartDate=#{@start_date}" begin response = RestClient.get("#{@base_url}#{@relative_url}", "Content-Type": 'application/json', "Authorization": "Bearer #{@access_token}", "Origin": @domain, "X-BCA-Key": @api_key, "X-BCA-Timestamp": @timestamp, "X-BCA-Signature": signature) elements = JSON.parse response.body statements = [] elements['Data'].each do |element| year = Date.parse(@start_date).strftime('%m').to_i.eql?(12) ? Date.parse(@start_date).strftime('%Y') : Date.parse(@end_date).strftime('%Y') date = element['TransactionDate'].eql?("PEND") ? element['TransactionDate'] : "#{element['TransactionDate']}/#{year}" attribute = { date: date, brance_code: element['BranchCode'], type: element['TransactionType'], amount: element['TransactionAmount'].to_f, name: element['TransactionName'], trailer: element['Trailer'] } statements << BcaStatement::Entities::Statement.new(attribute) end statements rescue RestClient::ExceptionWithResponse => err return nil end end
ruby
def get_statement(start_date = '2016-08-29', end_date = '2016-09-01') return nil unless @access_token @timestamp = Time.now.iso8601(3) @start_date = start_date.to_s @end_date = end_date.to_s @path = "/banking/v3/corporates/" @relative_url = "#{@path}#{@corporate_id}/accounts/#{@account_number}/statements?EndDate=#{@end_date}&StartDate=#{@start_date}" begin response = RestClient.get("#{@base_url}#{@relative_url}", "Content-Type": 'application/json', "Authorization": "Bearer #{@access_token}", "Origin": @domain, "X-BCA-Key": @api_key, "X-BCA-Timestamp": @timestamp, "X-BCA-Signature": signature) elements = JSON.parse response.body statements = [] elements['Data'].each do |element| year = Date.parse(@start_date).strftime('%m').to_i.eql?(12) ? Date.parse(@start_date).strftime('%Y') : Date.parse(@end_date).strftime('%Y') date = element['TransactionDate'].eql?("PEND") ? element['TransactionDate'] : "#{element['TransactionDate']}/#{year}" attribute = { date: date, brance_code: element['BranchCode'], type: element['TransactionType'], amount: element['TransactionAmount'].to_f, name: element['TransactionName'], trailer: element['Trailer'] } statements << BcaStatement::Entities::Statement.new(attribute) end statements rescue RestClient::ExceptionWithResponse => err return nil end end
[ "def", "get_statement", "(", "start_date", "=", "'2016-08-29'", ",", "end_date", "=", "'2016-09-01'", ")", "return", "nil", "unless", "@access_token", "@timestamp", "=", "Time", ".", "now", ".", "iso8601", "(", "3", ")", "@start_date", "=", "start_date", ".", "to_s", "@end_date", "=", "end_date", ".", "to_s", "@path", "=", "\"/banking/v3/corporates/\"", "@relative_url", "=", "\"#{@path}#{@corporate_id}/accounts/#{@account_number}/statements?EndDate=#{@end_date}&StartDate=#{@start_date}\"", "begin", "response", "=", "RestClient", ".", "get", "(", "\"#{@base_url}#{@relative_url}\"", ",", "\"Content-Type\"", ":", "'application/json'", ",", "\"Authorization\"", ":", "\"Bearer #{@access_token}\"", ",", "\"Origin\"", ":", "@domain", ",", "\"X-BCA-Key\"", ":", "@api_key", ",", "\"X-BCA-Timestamp\"", ":", "@timestamp", ",", "\"X-BCA-Signature\"", ":", "signature", ")", "elements", "=", "JSON", ".", "parse", "response", ".", "body", "statements", "=", "[", "]", "elements", "[", "'Data'", "]", ".", "each", "do", "|", "element", "|", "year", "=", "Date", ".", "parse", "(", "@start_date", ")", ".", "strftime", "(", "'%m'", ")", ".", "to_i", ".", "eql?", "(", "12", ")", "?", "Date", ".", "parse", "(", "@start_date", ")", ".", "strftime", "(", "'%Y'", ")", ":", "Date", ".", "parse", "(", "@end_date", ")", ".", "strftime", "(", "'%Y'", ")", "date", "=", "element", "[", "'TransactionDate'", "]", ".", "eql?", "(", "\"PEND\"", ")", "?", "element", "[", "'TransactionDate'", "]", ":", "\"#{element['TransactionDate']}/#{year}\"", "attribute", "=", "{", "date", ":", "date", ",", "brance_code", ":", "element", "[", "'BranchCode'", "]", ",", "type", ":", "element", "[", "'TransactionType'", "]", ",", "amount", ":", "element", "[", "'TransactionAmount'", "]", ".", "to_f", ",", "name", ":", "element", "[", "'TransactionName'", "]", ",", "trailer", ":", "element", "[", "'Trailer'", "]", "}", "statements", "<<", "BcaStatement", "::", "Entities", "::", "Statement", ".", "new", "(", "attribute", ")", "end", "statements", "rescue", "RestClient", "::", "ExceptionWithResponse", "=>", "err", "return", "nil", "end", "end" ]
Get your BCA Bisnis account statement for a period up to 31 days.
[ "Get", "your", "BCA", "Bisnis", "account", "statement", "for", "a", "period", "up", "to", "31", "days", "." ]
d095a1623077d89202296271904bc68e5bfb960c
https://github.com/andymarthin/bca_statement/blob/d095a1623077d89202296271904bc68e5bfb960c/lib/bca_statement/client.rb#L24-L60
train
andymarthin/bca_statement
lib/bca_statement/client.rb
BcaStatement.Client.balance
def balance return nil unless @access_token begin @timestamp = Time.now.iso8601(3) @relative_url = "/banking/v3/corporates/#{@corporate_id}/accounts/#{@account_number}" response = RestClient.get("#{@base_url}#{@relative_url}", "Content-Type": 'application/json', "Authorization": "Bearer #{@access_token}", "Origin": @domain, "X-BCA-Key": @api_key, "X-BCA-Timestamp": @timestamp, "X-BCA-Signature": signature) data = JSON.parse response.body if account_detail_success = data['AccountDetailDataSuccess'] detail = account_detail_success.first attribute = { account_number: detail['AccountNumber'], currency: detail['Currency'], balance: detail['Balance'].to_f, available_balance: detail['AvailableBalance'].to_f, float_amount: detail['FloatAmount'].to_f, hold_amount: detail['HoldAmount'].to_f, plafon: detail['Plafon'].to_f } BcaStatement::Entities::Balance.new(attribute) else return nil end rescue RestClient::ExceptionWithResponse => err return nil end end
ruby
def balance return nil unless @access_token begin @timestamp = Time.now.iso8601(3) @relative_url = "/banking/v3/corporates/#{@corporate_id}/accounts/#{@account_number}" response = RestClient.get("#{@base_url}#{@relative_url}", "Content-Type": 'application/json', "Authorization": "Bearer #{@access_token}", "Origin": @domain, "X-BCA-Key": @api_key, "X-BCA-Timestamp": @timestamp, "X-BCA-Signature": signature) data = JSON.parse response.body if account_detail_success = data['AccountDetailDataSuccess'] detail = account_detail_success.first attribute = { account_number: detail['AccountNumber'], currency: detail['Currency'], balance: detail['Balance'].to_f, available_balance: detail['AvailableBalance'].to_f, float_amount: detail['FloatAmount'].to_f, hold_amount: detail['HoldAmount'].to_f, plafon: detail['Plafon'].to_f } BcaStatement::Entities::Balance.new(attribute) else return nil end rescue RestClient::ExceptionWithResponse => err return nil end end
[ "def", "balance", "return", "nil", "unless", "@access_token", "begin", "@timestamp", "=", "Time", ".", "now", ".", "iso8601", "(", "3", ")", "@relative_url", "=", "\"/banking/v3/corporates/#{@corporate_id}/accounts/#{@account_number}\"", "response", "=", "RestClient", ".", "get", "(", "\"#{@base_url}#{@relative_url}\"", ",", "\"Content-Type\"", ":", "'application/json'", ",", "\"Authorization\"", ":", "\"Bearer #{@access_token}\"", ",", "\"Origin\"", ":", "@domain", ",", "\"X-BCA-Key\"", ":", "@api_key", ",", "\"X-BCA-Timestamp\"", ":", "@timestamp", ",", "\"X-BCA-Signature\"", ":", "signature", ")", "data", "=", "JSON", ".", "parse", "response", ".", "body", "if", "account_detail_success", "=", "data", "[", "'AccountDetailDataSuccess'", "]", "detail", "=", "account_detail_success", ".", "first", "attribute", "=", "{", "account_number", ":", "detail", "[", "'AccountNumber'", "]", ",", "currency", ":", "detail", "[", "'Currency'", "]", ",", "balance", ":", "detail", "[", "'Balance'", "]", ".", "to_f", ",", "available_balance", ":", "detail", "[", "'AvailableBalance'", "]", ".", "to_f", ",", "float_amount", ":", "detail", "[", "'FloatAmount'", "]", ".", "to_f", ",", "hold_amount", ":", "detail", "[", "'HoldAmount'", "]", ".", "to_f", ",", "plafon", ":", "detail", "[", "'Plafon'", "]", ".", "to_f", "}", "BcaStatement", "::", "Entities", "::", "Balance", ".", "new", "(", "attribute", ")", "else", "return", "nil", "end", "rescue", "RestClient", "::", "ExceptionWithResponse", "=>", "err", "return", "nil", "end", "end" ]
Get your BCA Bisnis account balance information
[ "Get", "your", "BCA", "Bisnis", "account", "balance", "information" ]
d095a1623077d89202296271904bc68e5bfb960c
https://github.com/andymarthin/bca_statement/blob/d095a1623077d89202296271904bc68e5bfb960c/lib/bca_statement/client.rb#L63-L97
train
tsenying/simple_geocoder
lib/simple_geocoder/geocoder.rb
SimpleGeocoder.Geocoder.geocode!
def geocode!(address, options = {}) response = call_geocoder_service(address, options) if response.is_a?(Net::HTTPOK) return JSON.parse response.body else raise ResponseError.new response end end
ruby
def geocode!(address, options = {}) response = call_geocoder_service(address, options) if response.is_a?(Net::HTTPOK) return JSON.parse response.body else raise ResponseError.new response end end
[ "def", "geocode!", "(", "address", ",", "options", "=", "{", "}", ")", "response", "=", "call_geocoder_service", "(", "address", ",", "options", ")", "if", "response", ".", "is_a?", "(", "Net", "::", "HTTPOK", ")", "return", "JSON", ".", "parse", "response", ".", "body", "else", "raise", "ResponseError", ".", "new", "response", "end", "end" ]
raise ResponseError exception on error
[ "raise", "ResponseError", "exception", "on", "error" ]
8958504584dc02c048f56295f1c4f19e52a2be6a
https://github.com/tsenying/simple_geocoder/blob/8958504584dc02c048f56295f1c4f19e52a2be6a/lib/simple_geocoder/geocoder.rb#L26-L33
train
tsenying/simple_geocoder
lib/simple_geocoder/geocoder.rb
SimpleGeocoder.Geocoder.find_location
def find_location(address) result = geocode(address) if result['status'] == 'OK' return result['results'][0]['geometry']['location'] else latlon_regexp = /(-?([1-8]?[0-9]\.{1}\d{1,6}|90\.{1}0{1,6})),(-?((([1]?[0-7][0-9]|[1-9]?[0-9])\.{1}\d{1,6})|[1]?[1-8][0]\.{1}0{1,6}))/ if address =~ latlon_regexp location = $&.split(',').map {|e| e.to_f} return { "lat" => location[0], "lng" => location[1] } else return nil end end end
ruby
def find_location(address) result = geocode(address) if result['status'] == 'OK' return result['results'][0]['geometry']['location'] else latlon_regexp = /(-?([1-8]?[0-9]\.{1}\d{1,6}|90\.{1}0{1,6})),(-?((([1]?[0-7][0-9]|[1-9]?[0-9])\.{1}\d{1,6})|[1]?[1-8][0]\.{1}0{1,6}))/ if address =~ latlon_regexp location = $&.split(',').map {|e| e.to_f} return { "lat" => location[0], "lng" => location[1] } else return nil end end end
[ "def", "find_location", "(", "address", ")", "result", "=", "geocode", "(", "address", ")", "if", "result", "[", "'status'", "]", "==", "'OK'", "return", "result", "[", "'results'", "]", "[", "0", "]", "[", "'geometry'", "]", "[", "'location'", "]", "else", "latlon_regexp", "=", "/", "\\.", "\\d", "\\.", "\\.", "\\d", "\\.", "/", "if", "address", "=~", "latlon_regexp", "location", "=", "$&", ".", "split", "(", "','", ")", ".", "map", "{", "|", "e", "|", "e", ".", "to_f", "}", "return", "{", "\"lat\"", "=>", "location", "[", "0", "]", ",", "\"lng\"", "=>", "location", "[", "1", "]", "}", "else", "return", "nil", "end", "end", "end" ]
if geocoding fails, then look for lat,lng string in address
[ "if", "geocoding", "fails", "then", "look", "for", "lat", "lng", "string", "in", "address" ]
8958504584dc02c048f56295f1c4f19e52a2be6a
https://github.com/tsenying/simple_geocoder/blob/8958504584dc02c048f56295f1c4f19e52a2be6a/lib/simple_geocoder/geocoder.rb#L36-L49
train
jeremyruppel/psql
lib/psql/database.rb
PSQL.Database.object
def object( object_name ) object = objects.find do |obj| obj[ 'name' ] == object_name end if !object raise "Database #{name} does not have an object named '#{object_name}'." end klass = PSQL.const_get object[ 'type' ].capitalize klass.new object[ 'name' ], name end
ruby
def object( object_name ) object = objects.find do |obj| obj[ 'name' ] == object_name end if !object raise "Database #{name} does not have an object named '#{object_name}'." end klass = PSQL.const_get object[ 'type' ].capitalize klass.new object[ 'name' ], name end
[ "def", "object", "(", "object_name", ")", "object", "=", "objects", ".", "find", "do", "|", "obj", "|", "obj", "[", "'name'", "]", "==", "object_name", "end", "if", "!", "object", "raise", "\"Database #{name} does not have an object named '#{object_name}'.\"", "end", "klass", "=", "PSQL", ".", "const_get", "object", "[", "'type'", "]", ".", "capitalize", "klass", ".", "new", "object", "[", "'name'", "]", ",", "name", "end" ]
Finds a database object by name. Objects are tables, views, or sequences.
[ "Finds", "a", "database", "object", "by", "name", ".", "Objects", "are", "tables", "views", "or", "sequences", "." ]
feb0a6cc5ca8b18c60412bc6b2a1ff4239fc42b9
https://github.com/jeremyruppel/psql/blob/feb0a6cc5ca8b18c60412bc6b2a1ff4239fc42b9/lib/psql/database.rb#L19-L30
train
npepinpe/redstruct
lib/redstruct/factory.rb
Redstruct.Factory.delete
def delete(options = {}) return each({ match: '*', count: 500, max_iterations: 1_000_000, batch_size: 500 }.merge(options)) do |keys| @connection.del(*keys) end end
ruby
def delete(options = {}) return each({ match: '*', count: 500, max_iterations: 1_000_000, batch_size: 500 }.merge(options)) do |keys| @connection.del(*keys) end end
[ "def", "delete", "(", "options", "=", "{", "}", ")", "return", "each", "(", "{", "match", ":", "'*'", ",", "count", ":", "500", ",", "max_iterations", ":", "1_000_000", ",", "batch_size", ":", "500", "}", ".", "merge", "(", "options", ")", ")", "do", "|", "keys", "|", "@connection", ".", "del", "(", "*", "keys", ")", "end", "end" ]
Deletes all keys created by the factory. By defaults will iterate at most of 500 million keys @param [Hash] options accepts the options as given in each @see Redstruct::Factory#each
[ "Deletes", "all", "keys", "created", "by", "the", "factory", ".", "By", "defaults", "will", "iterate", "at", "most", "of", "500", "million", "keys" ]
c97b45e7227f8ed9029f0effff352fc4d82dc3cb
https://github.com/npepinpe/redstruct/blob/c97b45e7227f8ed9029f0effff352fc4d82dc3cb/lib/redstruct/factory.rb#L60-L64
train
npepinpe/redstruct
lib/redstruct/factory.rb
Redstruct.Factory.script
def script(script, **options) return Redstruct::Script.new(script: script, connection: @connection, **options) end
ruby
def script(script, **options) return Redstruct::Script.new(script: script, connection: @connection, **options) end
[ "def", "script", "(", "script", ",", "**", "options", ")", "return", "Redstruct", "::", "Script", ".", "new", "(", "script", ":", "script", ",", "connection", ":", "@connection", ",", "**", "options", ")", "end" ]
Creates using this factory's connection @see Redstruct::Script#new @return [Redstruct::Script] script sharing the factory connection
[ "Creates", "using", "this", "factory", "s", "connection" ]
c97b45e7227f8ed9029f0effff352fc4d82dc3cb
https://github.com/npepinpe/redstruct/blob/c97b45e7227f8ed9029f0effff352fc4d82dc3cb/lib/redstruct/factory.rb#L79-L81
train
evg2108/rails-carrierwave-focuspoint
lib/rails-carrierwave-focuspoint/uploader_additions.rb
FocuspointRails.UploaderAdditions.crop_with_focuspoint
def crop_with_focuspoint(width = nil, height = nil) if self.respond_to? "resize_to_limit" begin x = model.focus_x || 0 y = -(model.focus_y || 0) manipulate! do |img| orig_w = img['width'] orig_h = img['height'] ratio = width.to_f / height orig_ratio = orig_w.to_f / orig_h x_offset = 0 y_offset = 0 w = orig_w h = orig_h if ratio < orig_ratio w = orig_h * ratio half_w = w / 2.0 half_orig_w = orig_w / 2.0 x_offset = x * half_orig_w x_offset = (x <=> 0.0) * (half_orig_w - half_w) if x != 0 && x_offset.abs > half_orig_w - half_w elsif ratio > orig_ratio h = orig_w / ratio half_h = h / 2.0 half_orig_h = orig_h / 2.0 y_offset = y * half_orig_h y_offset = (y <=> 0.0) * (half_orig_h - half_h) if y != 0 && y_offset.abs > half_orig_h - half_h end img.combine_options do |op| op.crop "#{w.to_i}x#{h.to_i}#{'%+d' % x_offset.round}#{'%+d' % y_offset.round}" op.gravity 'Center' end img.resize("#{width}x#{height}") img end rescue Exception => e raise "Failed to crop - #{e.message}" end else raise "Failed to crop #{attachment}. Add mini_magick." end end
ruby
def crop_with_focuspoint(width = nil, height = nil) if self.respond_to? "resize_to_limit" begin x = model.focus_x || 0 y = -(model.focus_y || 0) manipulate! do |img| orig_w = img['width'] orig_h = img['height'] ratio = width.to_f / height orig_ratio = orig_w.to_f / orig_h x_offset = 0 y_offset = 0 w = orig_w h = orig_h if ratio < orig_ratio w = orig_h * ratio half_w = w / 2.0 half_orig_w = orig_w / 2.0 x_offset = x * half_orig_w x_offset = (x <=> 0.0) * (half_orig_w - half_w) if x != 0 && x_offset.abs > half_orig_w - half_w elsif ratio > orig_ratio h = orig_w / ratio half_h = h / 2.0 half_orig_h = orig_h / 2.0 y_offset = y * half_orig_h y_offset = (y <=> 0.0) * (half_orig_h - half_h) if y != 0 && y_offset.abs > half_orig_h - half_h end img.combine_options do |op| op.crop "#{w.to_i}x#{h.to_i}#{'%+d' % x_offset.round}#{'%+d' % y_offset.round}" op.gravity 'Center' end img.resize("#{width}x#{height}") img end rescue Exception => e raise "Failed to crop - #{e.message}" end else raise "Failed to crop #{attachment}. Add mini_magick." end end
[ "def", "crop_with_focuspoint", "(", "width", "=", "nil", ",", "height", "=", "nil", ")", "if", "self", ".", "respond_to?", "\"resize_to_limit\"", "begin", "x", "=", "model", ".", "focus_x", "||", "0", "y", "=", "-", "(", "model", ".", "focus_y", "||", "0", ")", "manipulate!", "do", "|", "img", "|", "orig_w", "=", "img", "[", "'width'", "]", "orig_h", "=", "img", "[", "'height'", "]", "ratio", "=", "width", ".", "to_f", "/", "height", "orig_ratio", "=", "orig_w", ".", "to_f", "/", "orig_h", "x_offset", "=", "0", "y_offset", "=", "0", "w", "=", "orig_w", "h", "=", "orig_h", "if", "ratio", "<", "orig_ratio", "w", "=", "orig_h", "*", "ratio", "half_w", "=", "w", "/", "2.0", "half_orig_w", "=", "orig_w", "/", "2.0", "x_offset", "=", "x", "*", "half_orig_w", "x_offset", "=", "(", "x", "<=>", "0.0", ")", "*", "(", "half_orig_w", "-", "half_w", ")", "if", "x", "!=", "0", "&&", "x_offset", ".", "abs", ">", "half_orig_w", "-", "half_w", "elsif", "ratio", ">", "orig_ratio", "h", "=", "orig_w", "/", "ratio", "half_h", "=", "h", "/", "2.0", "half_orig_h", "=", "orig_h", "/", "2.0", "y_offset", "=", "y", "*", "half_orig_h", "y_offset", "=", "(", "y", "<=>", "0.0", ")", "*", "(", "half_orig_h", "-", "half_h", ")", "if", "y", "!=", "0", "&&", "y_offset", ".", "abs", ">", "half_orig_h", "-", "half_h", "end", "img", ".", "combine_options", "do", "|", "op", "|", "op", ".", "crop", "\"#{w.to_i}x#{h.to_i}#{'%+d' % x_offset.round}#{'%+d' % y_offset.round}\"", "op", ".", "gravity", "'Center'", "end", "img", ".", "resize", "(", "\"#{width}x#{height}\"", ")", "img", "end", "rescue", "Exception", "=>", "e", "raise", "\"Failed to crop - #{e.message}\"", "end", "else", "raise", "\"Failed to crop #{attachment}. Add mini_magick.\"", "end", "end" ]
Performs cropping with focuspoint
[ "Performs", "cropping", "with", "focuspoint" ]
75bf387ac6c1a8f2e4c3fcfdf65d6666ea93edd7
https://github.com/evg2108/rails-carrierwave-focuspoint/blob/75bf387ac6c1a8f2e4c3fcfdf65d6666ea93edd7/lib/rails-carrierwave-focuspoint/uploader_additions.rb#L4-L56
train
markus/breeze
lib/breeze/veur.rb
Breeze.Veur.report
def report(title, columns, rows) table = capture_table([columns] + rows) title = "=== #{title} " title << "=" * [(table.split($/).max{|a,b| a.size <=> b.size }.size - title.size), 3].max puts title puts table end
ruby
def report(title, columns, rows) table = capture_table([columns] + rows) title = "=== #{title} " title << "=" * [(table.split($/).max{|a,b| a.size <=> b.size }.size - title.size), 3].max puts title puts table end
[ "def", "report", "(", "title", ",", "columns", ",", "rows", ")", "table", "=", "capture_table", "(", "[", "columns", "]", "+", "rows", ")", "title", "=", "\"=== #{title} \"", "title", "<<", "\"=\"", "*", "[", "(", "table", ".", "split", "(", "$/", ")", ".", "max", "{", "|", "a", ",", "b", "|", "a", ".", "size", "<=>", "b", ".", "size", "}", ".", "size", "-", "title", ".", "size", ")", ",", "3", "]", ".", "max", "puts", "title", "puts", "table", "end" ]
Print a table with a title and a top border of matching width.
[ "Print", "a", "table", "with", "a", "title", "and", "a", "top", "border", "of", "matching", "width", "." ]
a633783946ed4270354fa1491a9beda4f2bac1f6
https://github.com/markus/breeze/blob/a633783946ed4270354fa1491a9beda4f2bac1f6/lib/breeze/veur.rb#L59-L65
train
markus/breeze
lib/breeze/veur.rb
Breeze.Veur.capture_table
def capture_table(table) return 'none' if table.size == 1 # the first row is for column titles $stdout = StringIO.new # start capturing the output print_table(table.map{ |row| row.map(&:to_s) }) output = $stdout $stdout = STDOUT # restore normal output return output.string end
ruby
def capture_table(table) return 'none' if table.size == 1 # the first row is for column titles $stdout = StringIO.new # start capturing the output print_table(table.map{ |row| row.map(&:to_s) }) output = $stdout $stdout = STDOUT # restore normal output return output.string end
[ "def", "capture_table", "(", "table", ")", "return", "'none'", "if", "table", ".", "size", "==", "1", "$stdout", "=", "StringIO", ".", "new", "print_table", "(", "table", ".", "map", "{", "|", "row", "|", "row", ".", "map", "(", "&", ":to_s", ")", "}", ")", "output", "=", "$stdout", "$stdout", "=", "STDOUT", "return", "output", ".", "string", "end" ]
capture table in order to determine its width
[ "capture", "table", "in", "order", "to", "determine", "its", "width" ]
a633783946ed4270354fa1491a9beda4f2bac1f6
https://github.com/markus/breeze/blob/a633783946ed4270354fa1491a9beda4f2bac1f6/lib/breeze/veur.rb#L68-L75
train
bcobb/and_feathers
lib/and_feathers/archive.rb
AndFeathers.Archive.to_io
def to_io(package_type, traversal = :each) package_type.open do |package| package.add_directory(@initial_version) send(traversal) do |child| case child when File package.add_file(child) when Directory package.add_directory(child) end end end end
ruby
def to_io(package_type, traversal = :each) package_type.open do |package| package.add_directory(@initial_version) send(traversal) do |child| case child when File package.add_file(child) when Directory package.add_directory(child) end end end end
[ "def", "to_io", "(", "package_type", ",", "traversal", "=", ":each", ")", "package_type", ".", "open", "do", "|", "package", "|", "package", ".", "add_directory", "(", "@initial_version", ")", "send", "(", "traversal", ")", "do", "|", "child", "|", "case", "child", "when", "File", "package", ".", "add_file", "(", "child", ")", "when", "Directory", "package", ".", "add_directory", "(", "child", ")", "end", "end", "end", "end" ]
Returns this +Archive+ as a package of the given +package_type+ @example require 'and_feathers/gzipped_tarball' format = AndFeathers::GzippedTarball AndFeathers::Archive.new('test', 16877).to_io(format) @see https://github.com/bcobb/and_feathers-gzipped_tarball @see https://github.com/bcobb/and_feathers-zip @param package_type [.open,#add_file,#add_directory] @return [StringIO]
[ "Returns", "this", "+", "Archive", "+", "as", "a", "package", "of", "the", "given", "+", "package_type", "+" ]
f35b156f8ae6930851712bbaf502f97b3aa9a1b1
https://github.com/bcobb/and_feathers/blob/f35b156f8ae6930851712bbaf502f97b3aa9a1b1/lib/and_feathers/archive.rb#L84-L97
train
mkj-is/Truty
lib/truty/conversion.rb
Truty.Conversion.czech_html
def czech_html(input) coder = HTMLEntities.new encoded = coder.encode(input, :named, :decimal) czech_diacritics.each { |k, v| encoded.gsub!(k, v) } encoded end
ruby
def czech_html(input) coder = HTMLEntities.new encoded = coder.encode(input, :named, :decimal) czech_diacritics.each { |k, v| encoded.gsub!(k, v) } encoded end
[ "def", "czech_html", "(", "input", ")", "coder", "=", "HTMLEntities", ".", "new", "encoded", "=", "coder", ".", "encode", "(", "input", ",", ":named", ",", ":decimal", ")", "czech_diacritics", ".", "each", "{", "|", "k", ",", "v", "|", "encoded", ".", "gsub!", "(", "k", ",", "v", ")", "}", "encoded", "end" ]
Escapes string to readable Czech HTML entities. @param input [String] Text input. @return [String] Text with HTML entities.
[ "Escapes", "string", "to", "readable", "Czech", "HTML", "entities", "." ]
315f49ad73cc2fa814a7793aa1b19657870ce98f
https://github.com/mkj-is/Truty/blob/315f49ad73cc2fa814a7793aa1b19657870ce98f/lib/truty/conversion.rb#L59-L64
train
malev/freeling-client
lib/freeling_client/client.rb
FreelingClient.Client.call
def call(text) output = [] file = Tempfile.new('foo', encoding: 'utf-8') begin file.write(text) file.close stdin, stdout, stderr = Open3.popen3(command(file.path)) Timeout::timeout(@timeout) { until (line = stdout.gets).nil? output << line.chomp end message = stderr.readlines unless message.empty? raise ExtractionError, message.join("\n") end } rescue Timeout::Error raise ExtractionError, "Timeout" ensure file.close file.unlink end output end
ruby
def call(text) output = [] file = Tempfile.new('foo', encoding: 'utf-8') begin file.write(text) file.close stdin, stdout, stderr = Open3.popen3(command(file.path)) Timeout::timeout(@timeout) { until (line = stdout.gets).nil? output << line.chomp end message = stderr.readlines unless message.empty? raise ExtractionError, message.join("\n") end } rescue Timeout::Error raise ExtractionError, "Timeout" ensure file.close file.unlink end output end
[ "def", "call", "(", "text", ")", "output", "=", "[", "]", "file", "=", "Tempfile", ".", "new", "(", "'foo'", ",", "encoding", ":", "'utf-8'", ")", "begin", "file", ".", "write", "(", "text", ")", "file", ".", "close", "stdin", ",", "stdout", ",", "stderr", "=", "Open3", ".", "popen3", "(", "command", "(", "file", ".", "path", ")", ")", "Timeout", "::", "timeout", "(", "@timeout", ")", "{", "until", "(", "line", "=", "stdout", ".", "gets", ")", ".", "nil?", "output", "<<", "line", ".", "chomp", "end", "message", "=", "stderr", ".", "readlines", "unless", "message", ".", "empty?", "raise", "ExtractionError", ",", "message", ".", "join", "(", "\"\\n\"", ")", "end", "}", "rescue", "Timeout", "::", "Error", "raise", "ExtractionError", ",", "\"Timeout\"", "ensure", "file", ".", "close", "file", ".", "unlink", "end", "output", "end" ]
Initializes the client Example: >> client = FreelingClient::Client.new Arguments: server: (String) port: (String) timeout: (Integer) Calls the server with a given text Example: >> client = FreelingClient::Client.new >> client.call("Este texto está en español.") Arguments: text: (String)
[ "Initializes", "the", "client" ]
1ca32aa9edf8fbc60a48cf23bf298db38b84fc8c
https://github.com/malev/freeling-client/blob/1ca32aa9edf8fbc60a48cf23bf298db38b84fc8c/lib/freeling_client/client.rb#L35-L61
train
mobyinc/Cathode
lib/cathode/version.rb
Cathode.Version.action?
def action?(resource, action) resource = resource.to_sym action = action.to_sym return false unless resource?(resource) _resources.find(resource).actions.names.include? action end
ruby
def action?(resource, action) resource = resource.to_sym action = action.to_sym return false unless resource?(resource) _resources.find(resource).actions.names.include? action end
[ "def", "action?", "(", "resource", ",", "action", ")", "resource", "=", "resource", ".", "to_sym", "action", "=", "action", ".", "to_sym", "return", "false", "unless", "resource?", "(", "resource", ")", "_resources", ".", "find", "(", "resource", ")", ".", "actions", ".", "names", ".", "include?", "action", "end" ]
Whether an action is defined on a resource on the version. @param resource [Symbol] The resource's name @param action [Symbol] The action's name @return [Boolean]
[ "Whether", "an", "action", "is", "defined", "on", "a", "resource", "on", "the", "version", "." ]
e17be4fb62ad61417e2a3a0a77406459015468a1
https://github.com/mobyinc/Cathode/blob/e17be4fb62ad61417e2a3a0a77406459015468a1/lib/cathode/version.rb#L96-L103
train
billdueber/ruby-marc-marc4j
lib/marc/marc4j.rb
MARC.MARC4J.marc4j_to_rubymarc
def marc4j_to_rubymarc(marc4j) rmarc = MARC::Record.new rmarc.leader = marc4j.getLeader.marshal marc4j.getControlFields.each do |marc4j_control| rmarc.append( MARC::ControlField.new(marc4j_control.getTag(), marc4j_control.getData ) ) end marc4j.getDataFields.each do |marc4j_data| rdata = MARC::DataField.new( marc4j_data.getTag, marc4j_data.getIndicator1.chr, marc4j_data.getIndicator2.chr ) marc4j_data.getSubfields.each do |subfield| # We assume Marc21, skip corrupted data # if subfield.getCode is more than 255, subsequent .chr # would raise. if subfield.getCode > 255 if @logger @logger.warn("Marc4JReader: Corrupted MARC data, record id #{marc4j.getControlNumber}, field #{marc4j_data.tag}, corrupt subfield code byte #{subfield.getCode}. Skipping subfield, but continuing with record.") end next end rsubfield = MARC::Subfield.new(subfield.getCode.chr, subfield.getData) rdata.append rsubfield end rmarc.append rdata end return rmarc end
ruby
def marc4j_to_rubymarc(marc4j) rmarc = MARC::Record.new rmarc.leader = marc4j.getLeader.marshal marc4j.getControlFields.each do |marc4j_control| rmarc.append( MARC::ControlField.new(marc4j_control.getTag(), marc4j_control.getData ) ) end marc4j.getDataFields.each do |marc4j_data| rdata = MARC::DataField.new( marc4j_data.getTag, marc4j_data.getIndicator1.chr, marc4j_data.getIndicator2.chr ) marc4j_data.getSubfields.each do |subfield| # We assume Marc21, skip corrupted data # if subfield.getCode is more than 255, subsequent .chr # would raise. if subfield.getCode > 255 if @logger @logger.warn("Marc4JReader: Corrupted MARC data, record id #{marc4j.getControlNumber}, field #{marc4j_data.tag}, corrupt subfield code byte #{subfield.getCode}. Skipping subfield, but continuing with record.") end next end rsubfield = MARC::Subfield.new(subfield.getCode.chr, subfield.getData) rdata.append rsubfield end rmarc.append rdata end return rmarc end
[ "def", "marc4j_to_rubymarc", "(", "marc4j", ")", "rmarc", "=", "MARC", "::", "Record", ".", "new", "rmarc", ".", "leader", "=", "marc4j", ".", "getLeader", ".", "marshal", "marc4j", ".", "getControlFields", ".", "each", "do", "|", "marc4j_control", "|", "rmarc", ".", "append", "(", "MARC", "::", "ControlField", ".", "new", "(", "marc4j_control", ".", "getTag", "(", ")", ",", "marc4j_control", ".", "getData", ")", ")", "end", "marc4j", ".", "getDataFields", ".", "each", "do", "|", "marc4j_data", "|", "rdata", "=", "MARC", "::", "DataField", ".", "new", "(", "marc4j_data", ".", "getTag", ",", "marc4j_data", ".", "getIndicator1", ".", "chr", ",", "marc4j_data", ".", "getIndicator2", ".", "chr", ")", "marc4j_data", ".", "getSubfields", ".", "each", "do", "|", "subfield", "|", "if", "subfield", ".", "getCode", ">", "255", "if", "@logger", "@logger", ".", "warn", "(", "\"Marc4JReader: Corrupted MARC data, record id #{marc4j.getControlNumber}, field #{marc4j_data.tag}, corrupt subfield code byte #{subfield.getCode}. Skipping subfield, but continuing with record.\"", ")", "end", "next", "end", "rsubfield", "=", "MARC", "::", "Subfield", ".", "new", "(", "subfield", ".", "getCode", ".", "chr", ",", "subfield", ".", "getData", ")", "rdata", ".", "append", "rsubfield", "end", "rmarc", ".", "append", "rdata", "end", "return", "rmarc", "end" ]
Get a new coverter Given a marc4j record, return a rubymarc record
[ "Get", "a", "new", "coverter", "Given", "a", "marc4j", "record", "return", "a", "rubymarc", "record" ]
b6eaf1a2de8b82b53424d409fc1fbf4191a4fd9c
https://github.com/billdueber/ruby-marc-marc4j/blob/b6eaf1a2de8b82b53424d409fc1fbf4191a4fd9c/lib/marc/marc4j.rb#L20-L51
train
billdueber/ruby-marc-marc4j
lib/marc/marc4j.rb
MARC.MARC4J.rubymarc_to_marc4j
def rubymarc_to_marc4j(rmarc) marc4j = @factory.newRecord(rmarc.leader) rmarc.each do |f| if f.is_a? MARC::ControlField new_field = @factory.newControlField(f.tag, f.value) else new_field = @factory.new_data_field(f.tag, f.indicator1.ord, f.indicator2.ord) f.each do |sf| new_field.add_subfield(@factory.new_subfield(sf.code.ord, sf.value)) end end marc4j.add_variable_field(new_field) end return marc4j end
ruby
def rubymarc_to_marc4j(rmarc) marc4j = @factory.newRecord(rmarc.leader) rmarc.each do |f| if f.is_a? MARC::ControlField new_field = @factory.newControlField(f.tag, f.value) else new_field = @factory.new_data_field(f.tag, f.indicator1.ord, f.indicator2.ord) f.each do |sf| new_field.add_subfield(@factory.new_subfield(sf.code.ord, sf.value)) end end marc4j.add_variable_field(new_field) end return marc4j end
[ "def", "rubymarc_to_marc4j", "(", "rmarc", ")", "marc4j", "=", "@factory", ".", "newRecord", "(", "rmarc", ".", "leader", ")", "rmarc", ".", "each", "do", "|", "f", "|", "if", "f", ".", "is_a?", "MARC", "::", "ControlField", "new_field", "=", "@factory", ".", "newControlField", "(", "f", ".", "tag", ",", "f", ".", "value", ")", "else", "new_field", "=", "@factory", ".", "new_data_field", "(", "f", ".", "tag", ",", "f", ".", "indicator1", ".", "ord", ",", "f", ".", "indicator2", ".", "ord", ")", "f", ".", "each", "do", "|", "sf", "|", "new_field", ".", "add_subfield", "(", "@factory", ".", "new_subfield", "(", "sf", ".", "code", ".", "ord", ",", "sf", ".", "value", ")", ")", "end", "end", "marc4j", ".", "add_variable_field", "(", "new_field", ")", "end", "return", "marc4j", "end" ]
Given a rubymarc record, return a marc4j record
[ "Given", "a", "rubymarc", "record", "return", "a", "marc4j", "record" ]
b6eaf1a2de8b82b53424d409fc1fbf4191a4fd9c
https://github.com/billdueber/ruby-marc-marc4j/blob/b6eaf1a2de8b82b53424d409fc1fbf4191a4fd9c/lib/marc/marc4j.rb#L55-L69
train
billdueber/ruby-marc-marc4j
lib/marc/marc4j.rb
MARC.MARC4J.require_marc4j_jar
def require_marc4j_jar(jardir) unless defined? JRUBY_VERSION raise LoadError.new, "MARC::MARC4J requires the use of JRuby", nil end if jardir Dir.glob("#{jardir}/*.jar") do |x| require x end else Dir.glob(File.join(DEFAULT_JAR_RELATIVE_DIR, "*.jar")) do |x| require x end end end
ruby
def require_marc4j_jar(jardir) unless defined? JRUBY_VERSION raise LoadError.new, "MARC::MARC4J requires the use of JRuby", nil end if jardir Dir.glob("#{jardir}/*.jar") do |x| require x end else Dir.glob(File.join(DEFAULT_JAR_RELATIVE_DIR, "*.jar")) do |x| require x end end end
[ "def", "require_marc4j_jar", "(", "jardir", ")", "unless", "defined?", "JRUBY_VERSION", "raise", "LoadError", ".", "new", ",", "\"MARC::MARC4J requires the use of JRuby\"", ",", "nil", "end", "if", "jardir", "Dir", ".", "glob", "(", "\"#{jardir}/*.jar\"", ")", "do", "|", "x", "|", "require", "x", "end", "else", "Dir", ".", "glob", "(", "File", ".", "join", "(", "DEFAULT_JAR_RELATIVE_DIR", ",", "\"*.jar\"", ")", ")", "do", "|", "x", "|", "require", "x", "end", "end", "end" ]
Try to get the specified jarfile, or the bundled one if nothing is specified
[ "Try", "to", "get", "the", "specified", "jarfile", "or", "the", "bundled", "one", "if", "nothing", "is", "specified" ]
b6eaf1a2de8b82b53424d409fc1fbf4191a4fd9c
https://github.com/billdueber/ruby-marc-marc4j/blob/b6eaf1a2de8b82b53424d409fc1fbf4191a4fd9c/lib/marc/marc4j.rb#L81-L94
train
keita/temppath
lib/temppath.rb
Temppath.Generator.mkdir
def mkdir(option={}) mode = option[:mode] || 0700 path = create(option) path.mkdir(mode) return path end
ruby
def mkdir(option={}) mode = option[:mode] || 0700 path = create(option) path.mkdir(mode) return path end
[ "def", "mkdir", "(", "option", "=", "{", "}", ")", "mode", "=", "option", "[", ":mode", "]", "||", "0700", "path", "=", "create", "(", "option", ")", "path", ".", "mkdir", "(", "mode", ")", "return", "path", "end" ]
Create a temporary directory. @param option [Hash] @option option [Integer] :mode mode for the directory permission @option option [String] :basename prefix of directory name @option option [Pathname] :basedir pathname of base directory
[ "Create", "a", "temporary", "directory", "." ]
27d24d23c1f076733e9dc5cbc2f7a7826963a97c
https://github.com/keita/temppath/blob/27d24d23c1f076733e9dc5cbc2f7a7826963a97c/lib/temppath.rb#L169-L174
train
keita/temppath
lib/temppath.rb
Temppath.Generator.touch
def touch(option={}) mode = option[:mode] || 0600 path = create(option) path.open("w", mode) return path end
ruby
def touch(option={}) mode = option[:mode] || 0600 path = create(option) path.open("w", mode) return path end
[ "def", "touch", "(", "option", "=", "{", "}", ")", "mode", "=", "option", "[", ":mode", "]", "||", "0600", "path", "=", "create", "(", "option", ")", "path", ".", "open", "(", "\"w\"", ",", "mode", ")", "return", "path", "end" ]
Create a empty file. @param option [Hash] @option option [Integer] :mode mode for the file permission @option option [String] :basename prefix of filename @option option [Pathname] :basedir pathname of base directory
[ "Create", "a", "empty", "file", "." ]
27d24d23c1f076733e9dc5cbc2f7a7826963a97c
https://github.com/keita/temppath/blob/27d24d23c1f076733e9dc5cbc2f7a7826963a97c/lib/temppath.rb#L185-L190
train
ramz15/voter_love
lib/voter_love/voter.rb
VoterLove.Voter.up_vote
def up_vote(votable) is_votable?(votable) vote = get_vote(votable) if vote if vote.up_vote raise Exceptions::AlreadyVotedError.new(true) else vote.up_vote = true votable.down_votes -= 1 self.down_votes -= 1 if has_attribute?(:down_votes) end else vote = Vote.create(:votable => votable, :voter => self, :up_vote => true) end votable.up_votes += 1 self.up_votes += 1 if has_attribute?(:up_votes) Vote.transaction do save votable.save vote.save end true end
ruby
def up_vote(votable) is_votable?(votable) vote = get_vote(votable) if vote if vote.up_vote raise Exceptions::AlreadyVotedError.new(true) else vote.up_vote = true votable.down_votes -= 1 self.down_votes -= 1 if has_attribute?(:down_votes) end else vote = Vote.create(:votable => votable, :voter => self, :up_vote => true) end votable.up_votes += 1 self.up_votes += 1 if has_attribute?(:up_votes) Vote.transaction do save votable.save vote.save end true end
[ "def", "up_vote", "(", "votable", ")", "is_votable?", "(", "votable", ")", "vote", "=", "get_vote", "(", "votable", ")", "if", "vote", "if", "vote", ".", "up_vote", "raise", "Exceptions", "::", "AlreadyVotedError", ".", "new", "(", "true", ")", "else", "vote", ".", "up_vote", "=", "true", "votable", ".", "down_votes", "-=", "1", "self", ".", "down_votes", "-=", "1", "if", "has_attribute?", "(", ":down_votes", ")", "end", "else", "vote", "=", "Vote", ".", "create", "(", ":votable", "=>", "votable", ",", ":voter", "=>", "self", ",", ":up_vote", "=>", "true", ")", "end", "votable", ".", "up_votes", "+=", "1", "self", ".", "up_votes", "+=", "1", "if", "has_attribute?", "(", ":up_votes", ")", "Vote", ".", "transaction", "do", "save", "votable", ".", "save", "vote", ".", "save", "end", "true", "end" ]
Up vote any "votable" object. Raises an AlreadyVotedError if the voter already voted on the object.
[ "Up", "vote", "any", "votable", "object", ".", "Raises", "an", "AlreadyVotedError", "if", "the", "voter", "already", "voted", "on", "the", "object", "." ]
99e97562e31c1bd0498c7f7a9b8a209af14a22f5
https://github.com/ramz15/voter_love/blob/99e97562e31c1bd0498c7f7a9b8a209af14a22f5/lib/voter_love/voter.rb#L17-L44
train
ramz15/voter_love
lib/voter_love/voter.rb
VoterLove.Voter.up_vote!
def up_vote!(votable) begin up_vote(votable) success = true rescue Exceptions::AlreadyVotedError success = false end success end
ruby
def up_vote!(votable) begin up_vote(votable) success = true rescue Exceptions::AlreadyVotedError success = false end success end
[ "def", "up_vote!", "(", "votable", ")", "begin", "up_vote", "(", "votable", ")", "success", "=", "true", "rescue", "Exceptions", "::", "AlreadyVotedError", "success", "=", "false", "end", "success", "end" ]
Up vote any "votable" object without raising an error. Vote is ignored.
[ "Up", "vote", "any", "votable", "object", "without", "raising", "an", "error", ".", "Vote", "is", "ignored", "." ]
99e97562e31c1bd0498c7f7a9b8a209af14a22f5
https://github.com/ramz15/voter_love/blob/99e97562e31c1bd0498c7f7a9b8a209af14a22f5/lib/voter_love/voter.rb#L47-L55
train
ramz15/voter_love
lib/voter_love/voter.rb
VoterLove.Voter.down_vote!
def down_vote!(votable) begin down_vote(votable) success = true rescue Exceptions::AlreadyVotedError success = false end success end
ruby
def down_vote!(votable) begin down_vote(votable) success = true rescue Exceptions::AlreadyVotedError success = false end success end
[ "def", "down_vote!", "(", "votable", ")", "begin", "down_vote", "(", "votable", ")", "success", "=", "true", "rescue", "Exceptions", "::", "AlreadyVotedError", "success", "=", "false", "end", "success", "end" ]
Down vote a "votable" object without raising an error. Vote is ignored.
[ "Down", "vote", "a", "votable", "object", "without", "raising", "an", "error", ".", "Vote", "is", "ignored", "." ]
99e97562e31c1bd0498c7f7a9b8a209af14a22f5
https://github.com/ramz15/voter_love/blob/99e97562e31c1bd0498c7f7a9b8a209af14a22f5/lib/voter_love/voter.rb#L89-L97
train
ramz15/voter_love
lib/voter_love/voter.rb
VoterLove.Voter.up_voted?
def up_voted?(votable) is_votable?(votable) vote = get_vote(votable) return false if vote.nil? return true if vote.has_attribute?(:up_vote) && vote.up_vote false end
ruby
def up_voted?(votable) is_votable?(votable) vote = get_vote(votable) return false if vote.nil? return true if vote.has_attribute?(:up_vote) && vote.up_vote false end
[ "def", "up_voted?", "(", "votable", ")", "is_votable?", "(", "votable", ")", "vote", "=", "get_vote", "(", "votable", ")", "return", "false", "if", "vote", ".", "nil?", "return", "true", "if", "vote", ".", "has_attribute?", "(", ":up_vote", ")", "&&", "vote", ".", "up_vote", "false", "end" ]
Returns true if the voter up voted the "votable".
[ "Returns", "true", "if", "the", "voter", "up", "voted", "the", "votable", "." ]
99e97562e31c1bd0498c7f7a9b8a209af14a22f5
https://github.com/ramz15/voter_love/blob/99e97562e31c1bd0498c7f7a9b8a209af14a22f5/lib/voter_love/voter.rb#L107-L113
train
jimjh/genie-parser
lib/spirit/manifest.rb
Spirit.Manifest.check_types
def check_types(key='root', expected=TYPES, actual=self, opts={}) bad_type(key, expected, actual, opts) unless actual.is_a? expected.class case actual when Hash then actual.each { |k, v| check_types(k, expected[k], v) } when Enumerable then actual.each { |v| check_types(key, expected.first, v, enum: true) } end end
ruby
def check_types(key='root', expected=TYPES, actual=self, opts={}) bad_type(key, expected, actual, opts) unless actual.is_a? expected.class case actual when Hash then actual.each { |k, v| check_types(k, expected[k], v) } when Enumerable then actual.each { |v| check_types(key, expected.first, v, enum: true) } end end
[ "def", "check_types", "(", "key", "=", "'root'", ",", "expected", "=", "TYPES", ",", "actual", "=", "self", ",", "opts", "=", "{", "}", ")", "bad_type", "(", "key", ",", "expected", ",", "actual", ",", "opts", ")", "unless", "actual", ".", "is_a?", "expected", ".", "class", "case", "actual", "when", "Hash", "then", "actual", ".", "each", "{", "|", "k", ",", "v", "|", "check_types", "(", "k", ",", "expected", "[", "k", "]", ",", "v", ")", "}", "when", "Enumerable", "then", "actual", ".", "each", "{", "|", "v", "|", "check_types", "(", "key", ",", "expected", ".", "first", ",", "v", ",", "enum", ":", "true", ")", "}", "end", "end" ]
Checks that the given hash has the valid types for each value, if they exist. @raise [ManifestError] if a bad type is encountered.
[ "Checks", "that", "the", "given", "hash", "has", "the", "valid", "types", "for", "each", "value", "if", "they", "exist", "." ]
d627c1c1cc07c0ea082a2599ee45cd7e7ba9c932
https://github.com/jimjh/genie-parser/blob/d627c1c1cc07c0ea082a2599ee45cd7e7ba9c932/lib/spirit/manifest.rb#L54-L60
train
lkdjiin/cellula
lib/cellula/rules/wolfram_code_rule.rb
Cellula.WolframCodeRule.next_generation_cell
def next_generation_cell(left, middle, right) case [left, middle, right] when [1,1,1] then @binary_string[0].to_i when [1,1,0] then @binary_string[1].to_i when [1,0,1] then @binary_string[2].to_i when [1,0,0] then @binary_string[3].to_i when [0,1,1] then @binary_string[4].to_i when [0,1,0] then @binary_string[5].to_i when [0,0,1] then @binary_string[6].to_i when [0,0,0] then @binary_string[7].to_i end end
ruby
def next_generation_cell(left, middle, right) case [left, middle, right] when [1,1,1] then @binary_string[0].to_i when [1,1,0] then @binary_string[1].to_i when [1,0,1] then @binary_string[2].to_i when [1,0,0] then @binary_string[3].to_i when [0,1,1] then @binary_string[4].to_i when [0,1,0] then @binary_string[5].to_i when [0,0,1] then @binary_string[6].to_i when [0,0,0] then @binary_string[7].to_i end end
[ "def", "next_generation_cell", "(", "left", ",", "middle", ",", "right", ")", "case", "[", "left", ",", "middle", ",", "right", "]", "when", "[", "1", ",", "1", ",", "1", "]", "then", "@binary_string", "[", "0", "]", ".", "to_i", "when", "[", "1", ",", "1", ",", "0", "]", "then", "@binary_string", "[", "1", "]", ".", "to_i", "when", "[", "1", ",", "0", ",", "1", "]", "then", "@binary_string", "[", "2", "]", ".", "to_i", "when", "[", "1", ",", "0", ",", "0", "]", "then", "@binary_string", "[", "3", "]", ".", "to_i", "when", "[", "0", ",", "1", ",", "1", "]", "then", "@binary_string", "[", "4", "]", ".", "to_i", "when", "[", "0", ",", "1", ",", "0", "]", "then", "@binary_string", "[", "5", "]", ".", "to_i", "when", "[", "0", ",", "0", ",", "1", "]", "then", "@binary_string", "[", "6", "]", ".", "to_i", "when", "[", "0", ",", "0", ",", "0", "]", "then", "@binary_string", "[", "7", "]", ".", "to_i", "end", "end" ]
Returns 0 or 1.
[ "Returns", "0", "or", "1", "." ]
32ad29d9daaeeddc36432eaf350818f2461f9434
https://github.com/lkdjiin/cellula/blob/32ad29d9daaeeddc36432eaf350818f2461f9434/lib/cellula/rules/wolfram_code_rule.rb#L102-L113
train
filipjakubowski/jira_issues
lib/jira_issues/jira_issue_mapper.rb
JiraIssues.JiraIssueMapper.call
def call(issue) status = decode_status(issue) { key: issue.key, type: issue.issuetype.name, priority: issue.priority.name, status: status, #description: i.description, summary: issue.summary, created_date: issue.created, closed_date: issue.resolutiondate } end
ruby
def call(issue) status = decode_status(issue) { key: issue.key, type: issue.issuetype.name, priority: issue.priority.name, status: status, #description: i.description, summary: issue.summary, created_date: issue.created, closed_date: issue.resolutiondate } end
[ "def", "call", "(", "issue", ")", "status", "=", "decode_status", "(", "issue", ")", "{", "key", ":", "issue", ".", "key", ",", "type", ":", "issue", ".", "issuetype", ".", "name", ",", "priority", ":", "issue", ".", "priority", ".", "name", ",", "status", ":", "status", ",", "summary", ":", "issue", ".", "summary", ",", "created_date", ":", "issue", ".", "created", ",", "closed_date", ":", "issue", ".", "resolutiondate", "}", "end" ]
WIP ATM mapper serialises issue to JSON We might consider using objects
[ "WIP", "ATM", "mapper", "serialises", "issue", "to", "JSON", "We", "might", "consider", "using", "objects" ]
6545c1c2b3a72226ad309386d74ca86d35ff8bb1
https://github.com/filipjakubowski/jira_issues/blob/6545c1c2b3a72226ad309386d74ca86d35ff8bb1/lib/jira_issues/jira_issue_mapper.rb#L7-L19
train
bcobb/and_feathers
lib/and_feathers/directory.rb
AndFeathers.Directory.path
def path if @parent ::File.join(@parent.path, name) else if name != '.' ::File.join('.', name) else name end end end
ruby
def path if @parent ::File.join(@parent.path, name) else if name != '.' ::File.join('.', name) else name end end end
[ "def", "path", "if", "@parent", "::", "File", ".", "join", "(", "@parent", ".", "path", ",", "name", ")", "else", "if", "name", "!=", "'.'", "::", "File", ".", "join", "(", "'.'", ",", "name", ")", "else", "name", "end", "end", "end" ]
This +Directory+'s path @return [String]
[ "This", "+", "Directory", "+", "s", "path" ]
f35b156f8ae6930851712bbaf502f97b3aa9a1b1
https://github.com/bcobb/and_feathers/blob/f35b156f8ae6930851712bbaf502f97b3aa9a1b1/lib/and_feathers/directory.rb#L66-L76
train
bcobb/and_feathers
lib/and_feathers/directory.rb
AndFeathers.Directory.|
def |(other) if !other.is_a?(Directory) raise ArgumentError, "#{other} is not a Directory" end dup.tap do |directory| other.files.each do |file| directory.add_file(file.dup) end other.directories.each do |new_directory| existing_directory = @directories[new_directory.name] if existing_directory.nil? directory.add_directory(new_directory.dup) else directory.add_directory(new_directory | existing_directory) end end end end
ruby
def |(other) if !other.is_a?(Directory) raise ArgumentError, "#{other} is not a Directory" end dup.tap do |directory| other.files.each do |file| directory.add_file(file.dup) end other.directories.each do |new_directory| existing_directory = @directories[new_directory.name] if existing_directory.nil? directory.add_directory(new_directory.dup) else directory.add_directory(new_directory | existing_directory) end end end end
[ "def", "|", "(", "other", ")", "if", "!", "other", ".", "is_a?", "(", "Directory", ")", "raise", "ArgumentError", ",", "\"#{other} is not a Directory\"", "end", "dup", ".", "tap", "do", "|", "directory", "|", "other", ".", "files", ".", "each", "do", "|", "file", "|", "directory", ".", "add_file", "(", "file", ".", "dup", ")", "end", "other", ".", "directories", ".", "each", "do", "|", "new_directory", "|", "existing_directory", "=", "@directories", "[", "new_directory", ".", "name", "]", "if", "existing_directory", ".", "nil?", "directory", ".", "add_directory", "(", "new_directory", ".", "dup", ")", "else", "directory", ".", "add_directory", "(", "new_directory", "|", "existing_directory", ")", "end", "end", "end", "end" ]
Computes the union of this +Directory+ with another +Directory+. If the two directories have a file path in common, the file in the +other+ +Directory+ takes precedence. If the two directories have a sub-directory path in common, the union's sub-directory path will be the union of those two sub-directories. @raise [ArgumentError] if the +other+ parameter is not a +Directory+ @param other [Directory] @return [Directory]
[ "Computes", "the", "union", "of", "this", "+", "Directory", "+", "with", "another", "+", "Directory", "+", ".", "If", "the", "two", "directories", "have", "a", "file", "path", "in", "common", "the", "file", "in", "the", "+", "other", "+", "+", "Directory", "+", "takes", "precedence", ".", "If", "the", "two", "directories", "have", "a", "sub", "-", "directory", "path", "in", "common", "the", "union", "s", "sub", "-", "directory", "path", "will", "be", "the", "union", "of", "those", "two", "sub", "-", "directories", "." ]
f35b156f8ae6930851712bbaf502f97b3aa9a1b1
https://github.com/bcobb/and_feathers/blob/f35b156f8ae6930851712bbaf502f97b3aa9a1b1/lib/and_feathers/directory.rb#L100-L120
train
bcobb/and_feathers
lib/and_feathers/directory.rb
AndFeathers.Directory.each
def each(&block) files.each(&block) directories.each do |subdirectory| block.call(subdirectory) subdirectory.each(&block) end end
ruby
def each(&block) files.each(&block) directories.each do |subdirectory| block.call(subdirectory) subdirectory.each(&block) end end
[ "def", "each", "(", "&", "block", ")", "files", ".", "each", "(", "&", "block", ")", "directories", ".", "each", "do", "|", "subdirectory", "|", "block", ".", "call", "(", "subdirectory", ")", "subdirectory", ".", "each", "(", "&", "block", ")", "end", "end" ]
Iterates through this +Directory+'s children depth-first @yieldparam child [File, Directory]
[ "Iterates", "through", "this", "+", "Directory", "+", "s", "children", "depth", "-", "first" ]
f35b156f8ae6930851712bbaf502f97b3aa9a1b1
https://github.com/bcobb/and_feathers/blob/f35b156f8ae6930851712bbaf502f97b3aa9a1b1/lib/and_feathers/directory.rb#L145-L153
train
seamusabshere/characterizable
lib/characterizable/better_hash.rb
Characterizable.BetterHash.slice
def slice(*keep) inject(Characterizable::BetterHash.new) do |memo, ary| if keep.include?(ary[0]) memo[ary[0]] = ary[1] end memo end end
ruby
def slice(*keep) inject(Characterizable::BetterHash.new) do |memo, ary| if keep.include?(ary[0]) memo[ary[0]] = ary[1] end memo end end
[ "def", "slice", "(", "*", "keep", ")", "inject", "(", "Characterizable", "::", "BetterHash", ".", "new", ")", "do", "|", "memo", ",", "ary", "|", "if", "keep", ".", "include?", "(", "ary", "[", "0", "]", ")", "memo", "[", "ary", "[", "0", "]", "]", "=", "ary", "[", "1", "]", "end", "memo", "end", "end" ]
I need this because otherwise it will try to do self.class.new on subclasses which would get "0 for 1" arguments error with Snapshot, among other things
[ "I", "need", "this", "because", "otherwise", "it", "will", "try", "to", "do", "self", ".", "class", ".", "new", "on", "subclasses", "which", "would", "get", "0", "for", "1", "arguments", "error", "with", "Snapshot", "among", "other", "things" ]
2b0f67b2137eb9b02c7ee36e3295f94c1eb90c18
https://github.com/seamusabshere/characterizable/blob/2b0f67b2137eb9b02c7ee36e3295f94c1eb90c18/lib/characterizable/better_hash.rb#L29-L36
train
quixoten/queue_to_the_future
lib/queue_to_the_future/job.rb
QueueToTheFuture.Job.method_missing
def method_missing(*args, &block) Thread.pass until defined?(@result) case @result when Exception def self.method_missing(*args, &block); raise @result; end else def self.method_missing(*args, &block); @result.send(*args, &block); end end self.method_missing(*args, &block) end
ruby
def method_missing(*args, &block) Thread.pass until defined?(@result) case @result when Exception def self.method_missing(*args, &block); raise @result; end else def self.method_missing(*args, &block); @result.send(*args, &block); end end self.method_missing(*args, &block) end
[ "def", "method_missing", "(", "*", "args", ",", "&", "block", ")", "Thread", ".", "pass", "until", "defined?", "(", "@result", ")", "case", "@result", "when", "Exception", "def", "self", ".", "method_missing", "(", "*", "args", ",", "&", "block", ")", ";", "raise", "@result", ";", "end", "else", "def", "self", ".", "method_missing", "(", "*", "args", ",", "&", "block", ")", ";", "@result", ".", "send", "(", "*", "args", ",", "&", "block", ")", ";", "end", "end", "self", ".", "method_missing", "(", "*", "args", ",", "&", "block", ")", "end" ]
Allows the job to behave as the return value of the block. Accessing any method on the job will cause code to block until the job is completed.
[ "Allows", "the", "job", "to", "behave", "as", "the", "return", "value", "of", "the", "block", "." ]
dd8260fa165ee42b95e6d76bc665fdf68339dfd6
https://github.com/quixoten/queue_to_the_future/blob/dd8260fa165ee42b95e6d76bc665fdf68339dfd6/lib/queue_to_the_future/job.rb#L34-L45
train
pluginaweek/enumerate_by
lib/enumerate_by.rb
EnumerateBy.MacroMethods.enumerate_by
def enumerate_by(attribute = :name, options = {}) options.reverse_merge!(:cache => true) options.assert_valid_keys(:cache) extend EnumerateBy::ClassMethods extend EnumerateBy::Bootstrapped include EnumerateBy::InstanceMethods # The attribute representing a record's enumerator cattr_accessor :enumerator_attribute self.enumerator_attribute = attribute # Whether to perform caching of enumerators within finder queries cattr_accessor :perform_enumerator_caching self.perform_enumerator_caching = options[:cache] # The cache store to use for queries (default is a memory store) cattr_accessor :enumerator_cache_store self.enumerator_cache_store = ActiveSupport::Cache::MemoryStore.new validates_presence_of attribute validates_uniqueness_of attribute end
ruby
def enumerate_by(attribute = :name, options = {}) options.reverse_merge!(:cache => true) options.assert_valid_keys(:cache) extend EnumerateBy::ClassMethods extend EnumerateBy::Bootstrapped include EnumerateBy::InstanceMethods # The attribute representing a record's enumerator cattr_accessor :enumerator_attribute self.enumerator_attribute = attribute # Whether to perform caching of enumerators within finder queries cattr_accessor :perform_enumerator_caching self.perform_enumerator_caching = options[:cache] # The cache store to use for queries (default is a memory store) cattr_accessor :enumerator_cache_store self.enumerator_cache_store = ActiveSupport::Cache::MemoryStore.new validates_presence_of attribute validates_uniqueness_of attribute end
[ "def", "enumerate_by", "(", "attribute", "=", ":name", ",", "options", "=", "{", "}", ")", "options", ".", "reverse_merge!", "(", ":cache", "=>", "true", ")", "options", ".", "assert_valid_keys", "(", ":cache", ")", "extend", "EnumerateBy", "::", "ClassMethods", "extend", "EnumerateBy", "::", "Bootstrapped", "include", "EnumerateBy", "::", "InstanceMethods", "cattr_accessor", ":enumerator_attribute", "self", ".", "enumerator_attribute", "=", "attribute", "cattr_accessor", ":perform_enumerator_caching", "self", ".", "perform_enumerator_caching", "=", "options", "[", ":cache", "]", "cattr_accessor", ":enumerator_cache_store", "self", ".", "enumerator_cache_store", "=", "ActiveSupport", "::", "Cache", "::", "MemoryStore", ".", "new", "validates_presence_of", "attribute", "validates_uniqueness_of", "attribute", "end" ]
Indicates that this class is an enumeration. The default attribute used to enumerate the class is +name+. You can override this by specifying a custom attribute that will be used to *uniquely* reference a record. *Note* that a presence and uniqueness validation is automatically defined for the given attribute since all records must have this value in order to be properly enumerated. Configuration options: * <tt>:cache</tt> - Whether to cache all finder queries for this enumeration. Default is true. == Defining enumerators The enumerators of the class uniquely identify each record in the table. The enumerator value is based on the attribute described above. In scenarios where the records are managed in code (like colors, countries, states, etc.), records can be automatically synchronized via #bootstrap. == Accessing records The actual records for an enumeration can be accessed via shortcut helpers like so: Color['red'] # => #<Color id: 1, name: "red"> Color['green'] # => #<Color id: 2, name: "green"> When caching is enabled, these lookup queries are cached so that there is no performance hit. == Associations When using enumerations together with +belongs_to+ associations, the enumerator value can be used as a shortcut for assigning the association. In addition, the enumerator value is automatically used during serialization (xml and json) of the associated record instead of the foreign key for the association. For more information about how to use enumerations with associations, see EnumerateBy::Extensions::Associations and EnumerateBy::Extensions::Serializer. === Finders In order to be consistent by always using enumerators to reference records, a set of finder extensions are added to allow searching for records like so: class Car < ActiveRecord::Base belongs_to :color end Car.find_by_color('red') Car.all(:conditions => {:color => 'red'}) For more information about finders, see EnumerateBy::Extensions::BaseConditions.
[ "Indicates", "that", "this", "class", "is", "an", "enumeration", "." ]
6a7c1ce54602a352b3286dee633c3dc7f687ea97
https://github.com/pluginaweek/enumerate_by/blob/6a7c1ce54602a352b3286dee633c3dc7f687ea97/lib/enumerate_by.rb#L87-L109
train
pluginaweek/enumerate_by
lib/enumerate_by.rb
EnumerateBy.ClassMethods.typecast_enumerator
def typecast_enumerator(enumerator) if enumerator.is_a?(Array) enumerator.flatten! enumerator.map! {|value| typecast_enumerator(value)} enumerator else enumerator.is_a?(Symbol) ? enumerator.to_s : enumerator end end
ruby
def typecast_enumerator(enumerator) if enumerator.is_a?(Array) enumerator.flatten! enumerator.map! {|value| typecast_enumerator(value)} enumerator else enumerator.is_a?(Symbol) ? enumerator.to_s : enumerator end end
[ "def", "typecast_enumerator", "(", "enumerator", ")", "if", "enumerator", ".", "is_a?", "(", "Array", ")", "enumerator", ".", "flatten!", "enumerator", ".", "map!", "{", "|", "value", "|", "typecast_enumerator", "(", "value", ")", "}", "enumerator", "else", "enumerator", ".", "is_a?", "(", "Symbol", ")", "?", "enumerator", ".", "to_s", ":", "enumerator", "end", "end" ]
Typecasts the given enumerator to its actual value stored in the database. This will only convert symbols to strings. All other values will remain in the same type.
[ "Typecasts", "the", "given", "enumerator", "to", "its", "actual", "value", "stored", "in", "the", "database", ".", "This", "will", "only", "convert", "symbols", "to", "strings", ".", "All", "other", "values", "will", "remain", "in", "the", "same", "type", "." ]
6a7c1ce54602a352b3286dee633c3dc7f687ea97
https://github.com/pluginaweek/enumerate_by/blob/6a7c1ce54602a352b3286dee633c3dc7f687ea97/lib/enumerate_by.rb#L207-L215
train
humpyard/humpyard
app/models/humpyard/page.rb
Humpyard.Page.root_elements
def root_elements(yield_name = 'main') # my own elements ret = elements.where('container_id IS NULL and page_yield_name = ?', yield_name.to_s).order('position ASC') # sibling shared elements unless siblings.empty? ret += Humpyard::Element.where('container_id IS NULL and page_id in (?) and page_yield_name = ? and shared_state = ?', siblings, yield_name.to_s, Humpyard::Element::SHARED_STATES[:shared_on_siblings]).order('position ASC') end # ancestors shared elements unless ancestor_pages.empty? ret += Humpyard::Element.where('container_id IS NULL and page_id in (?) and page_yield_name = ? and shared_state = ?', ancestor_pages, yield_name.to_s, Humpyard::Element::SHARED_STATES[:shared_on_children]).order('position ASC') end ret end
ruby
def root_elements(yield_name = 'main') # my own elements ret = elements.where('container_id IS NULL and page_yield_name = ?', yield_name.to_s).order('position ASC') # sibling shared elements unless siblings.empty? ret += Humpyard::Element.where('container_id IS NULL and page_id in (?) and page_yield_name = ? and shared_state = ?', siblings, yield_name.to_s, Humpyard::Element::SHARED_STATES[:shared_on_siblings]).order('position ASC') end # ancestors shared elements unless ancestor_pages.empty? ret += Humpyard::Element.where('container_id IS NULL and page_id in (?) and page_yield_name = ? and shared_state = ?', ancestor_pages, yield_name.to_s, Humpyard::Element::SHARED_STATES[:shared_on_children]).order('position ASC') end ret end
[ "def", "root_elements", "(", "yield_name", "=", "'main'", ")", "ret", "=", "elements", ".", "where", "(", "'container_id IS NULL and page_yield_name = ?'", ",", "yield_name", ".", "to_s", ")", ".", "order", "(", "'position ASC'", ")", "unless", "siblings", ".", "empty?", "ret", "+=", "Humpyard", "::", "Element", ".", "where", "(", "'container_id IS NULL and page_id in (?) and page_yield_name = ? and shared_state = ?'", ",", "siblings", ",", "yield_name", ".", "to_s", ",", "Humpyard", "::", "Element", "::", "SHARED_STATES", "[", ":shared_on_siblings", "]", ")", ".", "order", "(", "'position ASC'", ")", "end", "unless", "ancestor_pages", ".", "empty?", "ret", "+=", "Humpyard", "::", "Element", ".", "where", "(", "'container_id IS NULL and page_id in (?) and page_yield_name = ? and shared_state = ?'", ",", "ancestor_pages", ",", "yield_name", ".", "to_s", ",", "Humpyard", "::", "Element", "::", "SHARED_STATES", "[", ":shared_on_children", "]", ")", ".", "order", "(", "'position ASC'", ")", "end", "ret", "end" ]
Return the elements on a yield container. Includes shared elemenents from siblings or parents
[ "Return", "the", "elements", "on", "a", "yield", "container", ".", "Includes", "shared", "elemenents", "from", "siblings", "or", "parents" ]
f344ab851f1dfd824c1e4cb4b92f7c62ac0acefd
https://github.com/humpyard/humpyard/blob/f344ab851f1dfd824c1e4cb4b92f7c62ac0acefd/app/models/humpyard/page.rb#L43-L55
train
humpyard/humpyard
app/models/humpyard/page.rb
Humpyard.Page.child_pages
def child_pages options={} if content_data.is_humpyard_dynamic_page? content_data.child_pages else if options[:single_root] and is_root_page? Page.where(["parent_id = ? or parent_id IS NULL and NOT id = ?", id, id]) else children end end end
ruby
def child_pages options={} if content_data.is_humpyard_dynamic_page? content_data.child_pages else if options[:single_root] and is_root_page? Page.where(["parent_id = ? or parent_id IS NULL and NOT id = ?", id, id]) else children end end end
[ "def", "child_pages", "options", "=", "{", "}", "if", "content_data", ".", "is_humpyard_dynamic_page?", "content_data", ".", "child_pages", "else", "if", "options", "[", ":single_root", "]", "and", "is_root_page?", "Page", ".", "where", "(", "[", "\"parent_id = ? or parent_id IS NULL and NOT id = ?\"", ",", "id", ",", "id", "]", ")", "else", "children", "end", "end", "end" ]
Find the child pages
[ "Find", "the", "child", "pages" ]
f344ab851f1dfd824c1e4cb4b92f7c62ac0acefd
https://github.com/humpyard/humpyard/blob/f344ab851f1dfd824c1e4cb4b92f7c62ac0acefd/app/models/humpyard/page.rb#L101-L111
train
humpyard/humpyard
app/models/humpyard/page.rb
Humpyard.Page.last_modified
def last_modified options = {} changed_at = [Time.zone.at(::File.new("#{Rails.root}").mtime), created_at, updated_at, modified_at] if(options[:include_pages]) changed_at << Humpyard::Page.select('updated_at').order('updated_at DESC').first.updated_at end (changed_at - [nil]).max.utc end
ruby
def last_modified options = {} changed_at = [Time.zone.at(::File.new("#{Rails.root}").mtime), created_at, updated_at, modified_at] if(options[:include_pages]) changed_at << Humpyard::Page.select('updated_at').order('updated_at DESC').first.updated_at end (changed_at - [nil]).max.utc end
[ "def", "last_modified", "options", "=", "{", "}", "changed_at", "=", "[", "Time", ".", "zone", ".", "at", "(", "::", "File", ".", "new", "(", "\"#{Rails.root}\"", ")", ".", "mtime", ")", ",", "created_at", ",", "updated_at", ",", "modified_at", "]", "if", "(", "options", "[", ":include_pages", "]", ")", "changed_at", "<<", "Humpyard", "::", "Page", ".", "select", "(", "'updated_at'", ")", ".", "order", "(", "'updated_at DESC'", ")", ".", "first", ".", "updated_at", "end", "(", "changed_at", "-", "[", "nil", "]", ")", ".", "max", ".", "utc", "end" ]
Return the logical modification time for the page, suitable for http caching, generational cache keys, etc.
[ "Return", "the", "logical", "modification", "time", "for", "the", "page", "suitable", "for", "http", "caching", "generational", "cache", "keys", "etc", "." ]
f344ab851f1dfd824c1e4cb4b92f7c62ac0acefd
https://github.com/humpyard/humpyard/blob/f344ab851f1dfd824c1e4cb4b92f7c62ac0acefd/app/models/humpyard/page.rb#L143-L151
train
dleavitt/dragonfly-dropbox_data_store
lib/dragonfly/dropbox_data_store.rb
Dragonfly.DropboxDataStore.url_for
def url_for(path, opts = {}) path = absolute(path) (opts[:expires] ? storage.media(path) : storage.shares(path))['url'] end
ruby
def url_for(path, opts = {}) path = absolute(path) (opts[:expires] ? storage.media(path) : storage.shares(path))['url'] end
[ "def", "url_for", "(", "path", ",", "opts", "=", "{", "}", ")", "path", "=", "absolute", "(", "path", ")", "(", "opts", "[", ":expires", "]", "?", "storage", ".", "media", "(", "path", ")", ":", "storage", ".", "shares", "(", "path", ")", ")", "[", "'url'", "]", "end" ]
Only option is "expires" and it's a boolean
[ "Only", "option", "is", "expires", "and", "it", "s", "a", "boolean" ]
30fe8c7edd32e7b21d62bcb20af31097aa382e29
https://github.com/dleavitt/dragonfly-dropbox_data_store/blob/30fe8c7edd32e7b21d62bcb20af31097aa382e29/lib/dragonfly/dropbox_data_store.rb#L55-L58
train
mrlhumphreys/board_game_grid
lib/board_game_grid/square.rb
BoardGameGrid.Square.attribute_match?
def attribute_match?(attribute, value) hash_obj_matcher = lambda do |obj, k, v| value = obj.send(k) if !value.nil? && v.is_a?(Hash) v.all? { |k2,v2| hash_obj_matcher.call(value, k2, v2) } else value == v end end hash_obj_matcher.call(self, attribute, value) end
ruby
def attribute_match?(attribute, value) hash_obj_matcher = lambda do |obj, k, v| value = obj.send(k) if !value.nil? && v.is_a?(Hash) v.all? { |k2,v2| hash_obj_matcher.call(value, k2, v2) } else value == v end end hash_obj_matcher.call(self, attribute, value) end
[ "def", "attribute_match?", "(", "attribute", ",", "value", ")", "hash_obj_matcher", "=", "lambda", "do", "|", "obj", ",", "k", ",", "v", "|", "value", "=", "obj", ".", "send", "(", "k", ")", "if", "!", "value", ".", "nil?", "&&", "v", ".", "is_a?", "(", "Hash", ")", "v", ".", "all?", "{", "|", "k2", ",", "v2", "|", "hash_obj_matcher", ".", "call", "(", "value", ",", "k2", ",", "v2", ")", "}", "else", "value", "==", "v", "end", "end", "hash_obj_matcher", ".", "call", "(", "self", ",", "attribute", ",", "value", ")", "end" ]
checks if the square matches the attributes passed. @param [Symbol] attribute the square's attribute. @param [Object,Hash] value a value to match on. Can be a hash of attribute/value pairs for deep matching ==== Example: # Check if square has a piece owned by player 1 square.attribute_match?(:piece, player_number: 1)
[ "checks", "if", "the", "square", "matches", "the", "attributes", "passed", "." ]
df07a84c7f7db076d055c6063f1e418f0c8ed288
https://github.com/mrlhumphreys/board_game_grid/blob/df07a84c7f7db076d055c6063f1e418f0c8ed288/lib/board_game_grid/square.rb#L62-L73
train
ryym/dio
lib/dio/module_base.rb
Dio.ModuleBase.included
def included(base) my_injector = injector injector_holder = Module.new do define_method :__dio_injector__ do my_injector end end base.extend(ClassMethods, injector_holder) base.include(InstanceMethods) end
ruby
def included(base) my_injector = injector injector_holder = Module.new do define_method :__dio_injector__ do my_injector end end base.extend(ClassMethods, injector_holder) base.include(InstanceMethods) end
[ "def", "included", "(", "base", ")", "my_injector", "=", "injector", "injector_holder", "=", "Module", ".", "new", "do", "define_method", ":__dio_injector__", "do", "my_injector", "end", "end", "base", ".", "extend", "(", "ClassMethods", ",", "injector_holder", ")", "base", ".", "include", "(", "InstanceMethods", ")", "end" ]
Add some methods to a class which includes Dio module.
[ "Add", "some", "methods", "to", "a", "class", "which", "includes", "Dio", "module", "." ]
4547c3e75d43be7bd73335576e5e5dc3a8fa7efd
https://github.com/ryym/dio/blob/4547c3e75d43be7bd73335576e5e5dc3a8fa7efd/lib/dio/module_base.rb#L68-L77
train
smsified/smsified-ruby
lib/smsified/oneapi.rb
Smsified.OneAPI.send_sms
def send_sms(options) raise ArgumentError, 'an options Hash is required' if !options.instance_of?(Hash) raise ArgumentError, ':sender_address is required' if options[:sender_address].nil? && @sender_address.nil? raise ArgumentError, ':address is required' if options[:address].nil? raise ArgumentError, ':message is required' if options[:message].nil? options[:sender_address] = options[:sender_address] || @sender_address query_options = options.clone query_options.delete(:sender_address) query_options = camelcase_keys(query_options) Response.new self.class.post("/smsmessaging/outbound/#{options[:sender_address]}/requests", :body => build_query_string(query_options), :basic_auth => @auth, :headers => SMSIFIED_HTTP_HEADERS) end
ruby
def send_sms(options) raise ArgumentError, 'an options Hash is required' if !options.instance_of?(Hash) raise ArgumentError, ':sender_address is required' if options[:sender_address].nil? && @sender_address.nil? raise ArgumentError, ':address is required' if options[:address].nil? raise ArgumentError, ':message is required' if options[:message].nil? options[:sender_address] = options[:sender_address] || @sender_address query_options = options.clone query_options.delete(:sender_address) query_options = camelcase_keys(query_options) Response.new self.class.post("/smsmessaging/outbound/#{options[:sender_address]}/requests", :body => build_query_string(query_options), :basic_auth => @auth, :headers => SMSIFIED_HTTP_HEADERS) end
[ "def", "send_sms", "(", "options", ")", "raise", "ArgumentError", ",", "'an options Hash is required'", "if", "!", "options", ".", "instance_of?", "(", "Hash", ")", "raise", "ArgumentError", ",", "':sender_address is required'", "if", "options", "[", ":sender_address", "]", ".", "nil?", "&&", "@sender_address", ".", "nil?", "raise", "ArgumentError", ",", "':address is required'", "if", "options", "[", ":address", "]", ".", "nil?", "raise", "ArgumentError", ",", "':message is required'", "if", "options", "[", ":message", "]", ".", "nil?", "options", "[", ":sender_address", "]", "=", "options", "[", ":sender_address", "]", "||", "@sender_address", "query_options", "=", "options", ".", "clone", "query_options", ".", "delete", "(", ":sender_address", ")", "query_options", "=", "camelcase_keys", "(", "query_options", ")", "Response", ".", "new", "self", ".", "class", ".", "post", "(", "\"/smsmessaging/outbound/#{options[:sender_address]}/requests\"", ",", ":body", "=>", "build_query_string", "(", "query_options", ")", ",", ":basic_auth", "=>", "@auth", ",", ":headers", "=>", "SMSIFIED_HTTP_HEADERS", ")", "end" ]
Intantiate a new class to work with OneAPI @param [required, Hash] params to create the user @option params [required, String] :username username to authenticate with @option params [required, String] :password to authenticate with @option params [optional, String] :base_uri of an alternative location of SMSified @option params [optional, String] :destination_address to use with subscriptions @option params [optional, String] :sender_address to use with subscriptions @option params [optional, Boolean] :debug to turn on the HTTparty debugging to stdout @raise [ArgumentError] if :username is not passed as an option @raise [ArgumentError] if :password is not passed as an option @example one_api = OneAPI.new :username => 'user', :password => '123' Send an SMS to one or more addresses @param [required, Hash] params to send an sms @option params [required, String] :address to send the SMS to @option params [required, String] :message to send with the SMS @option params [optional, String] :sender_address to use with subscriptions, required if not provided on initialization of OneAPI @option params [optional, String] :notify_url to send callbacks to @return [Object] A Response Object with http and data instance methods @raise [ArgumentError] if :sender_address is not passed as an option when not passed on object creation @raise [ArgumentError] if :address is not provided as an option @raise [ArgumentError] if :message is not provided as an option @example one_api.send_sms :address => '14155551212', :message => 'Hi there!', :sender_address => '13035551212' one_api.send_sms :address => ['14155551212', '13035551212'], :message => 'Hi there!', :sender_address => '13035551212'
[ "Intantiate", "a", "new", "class", "to", "work", "with", "OneAPI" ]
1c7a0f445ffe7fe0fb035a1faf44ac55687a4488
https://github.com/smsified/smsified-ruby/blob/1c7a0f445ffe7fe0fb035a1faf44ac55687a4488/lib/smsified/oneapi.rb#L56-L71
train
smsified/smsified-ruby
lib/smsified/oneapi.rb
Smsified.OneAPI.method_missing
def method_missing(method, *args) if method.to_s.match /subscription/ if args.size == 2 @subscriptions.send method, args[0], args[1] else @subscriptions.send method, args[0] end else if method == :delivery_status || method == :retrieve_sms || method == :search_sms @reporting.send method, args[0] else raise RuntimeError, 'Unknown method' end end end
ruby
def method_missing(method, *args) if method.to_s.match /subscription/ if args.size == 2 @subscriptions.send method, args[0], args[1] else @subscriptions.send method, args[0] end else if method == :delivery_status || method == :retrieve_sms || method == :search_sms @reporting.send method, args[0] else raise RuntimeError, 'Unknown method' end end end
[ "def", "method_missing", "(", "method", ",", "*", "args", ")", "if", "method", ".", "to_s", ".", "match", "/", "/", "if", "args", ".", "size", "==", "2", "@subscriptions", ".", "send", "method", ",", "args", "[", "0", "]", ",", "args", "[", "1", "]", "else", "@subscriptions", ".", "send", "method", ",", "args", "[", "0", "]", "end", "else", "if", "method", "==", ":delivery_status", "||", "method", "==", ":retrieve_sms", "||", "method", "==", ":search_sms", "@reporting", ".", "send", "method", ",", "args", "[", "0", "]", "else", "raise", "RuntimeError", ",", "'Unknown method'", "end", "end", "end" ]
Dispatches method calls to other objects for subscriptions and reporting
[ "Dispatches", "method", "calls", "to", "other", "objects", "for", "subscriptions", "and", "reporting" ]
1c7a0f445ffe7fe0fb035a1faf44ac55687a4488
https://github.com/smsified/smsified-ruby/blob/1c7a0f445ffe7fe0fb035a1faf44ac55687a4488/lib/smsified/oneapi.rb#L75-L89
train
NUBIC/aker
lib/aker/authorities/automatic_access.rb
Aker::Authorities.AutomaticAccess.amplify!
def amplify!(user) user.portals << @portal unless user.portals.include?(@portal) user.default_portal = @portal unless user.default_portal user end
ruby
def amplify!(user) user.portals << @portal unless user.portals.include?(@portal) user.default_portal = @portal unless user.default_portal user end
[ "def", "amplify!", "(", "user", ")", "user", ".", "portals", "<<", "@portal", "unless", "user", ".", "portals", ".", "include?", "(", "@portal", ")", "user", ".", "default_portal", "=", "@portal", "unless", "user", ".", "default_portal", "user", "end" ]
Adds the configured portal to the user if necessary. @return [Aker::User]
[ "Adds", "the", "configured", "portal", "to", "the", "user", "if", "necessary", "." ]
ff43606a8812e38f96bbe71b46e7f631cbeacf1c
https://github.com/NUBIC/aker/blob/ff43606a8812e38f96bbe71b46e7f631cbeacf1c/lib/aker/authorities/automatic_access.rb#L30-L34
train
akwiatkowski/simple_metar_parser
lib/simple_metar_parser/metar.rb
SimpleMetarParser.Metar.decode
def decode self.raw_splits.each do |split| self.modules.each do |m| m.decode_split(split) end end end
ruby
def decode self.raw_splits.each do |split| self.modules.each do |m| m.decode_split(split) end end end
[ "def", "decode", "self", ".", "raw_splits", ".", "each", "do", "|", "split", "|", "self", ".", "modules", ".", "each", "do", "|", "m", "|", "m", ".", "decode_split", "(", "split", ")", "end", "end", "end" ]
Decode all string fragments
[ "Decode", "all", "string", "fragments" ]
ff8ea6162c7be6137c8e56b768784e58d7c8ad01
https://github.com/akwiatkowski/simple_metar_parser/blob/ff8ea6162c7be6137c8e56b768784e58d7c8ad01/lib/simple_metar_parser/metar.rb#L81-L87
train
blambeau/domain
lib/domain/factory.rb
Domain.Factory.sbyc
def sbyc(super_domain = Object, &pred) Class.new(super_domain){ extend SByC.new(super_domain, pred) } end
ruby
def sbyc(super_domain = Object, &pred) Class.new(super_domain){ extend SByC.new(super_domain, pred) } end
[ "def", "sbyc", "(", "super_domain", "=", "Object", ",", "&", "pred", ")", "Class", ".", "new", "(", "super_domain", ")", "{", "extend", "SByC", ".", "new", "(", "super_domain", ",", "pred", ")", "}", "end" ]
Creates a domain through specialization by constraint @param [Class] super_domain the super_domain of the factored domain @param [Proc] pred the domain predicate @return [Class] the created domain as a ruby Class @api public
[ "Creates", "a", "domain", "through", "specialization", "by", "constraint" ]
3fd010cbf2e156013e0ea9afa608ba9b44e7bc75
https://github.com/blambeau/domain/blob/3fd010cbf2e156013e0ea9afa608ba9b44e7bc75/lib/domain/factory.rb#L19-L21
train
chocolateboy/wireless
lib/wireless/synchronized_store.rb
Wireless.SynchronizedStore.get_or_create
def get_or_create(key) @lock.synchronize do if @store.include?(key) @store[key] elsif block_given? @store[key] = yield else # XXX don't expose the receiver as this class is an internal # implementation detail raise Wireless::KeyError.new( "#{@type} not found: #{key}", key: key ) end end end
ruby
def get_or_create(key) @lock.synchronize do if @store.include?(key) @store[key] elsif block_given? @store[key] = yield else # XXX don't expose the receiver as this class is an internal # implementation detail raise Wireless::KeyError.new( "#{@type} not found: #{key}", key: key ) end end end
[ "def", "get_or_create", "(", "key", ")", "@lock", ".", "synchronize", "do", "if", "@store", ".", "include?", "(", "key", ")", "@store", "[", "key", "]", "elsif", "block_given?", "@store", "[", "key", "]", "=", "yield", "else", "raise", "Wireless", "::", "KeyError", ".", "new", "(", "\"#{@type} not found: #{key}\"", ",", "key", ":", "key", ")", "end", "end", "end" ]
Retrieve a value from the store. If it doesn't exist and a block is supplied, create and return it; otherwise, raise a KeyError. A synchronized version of: store[key] ||= value
[ "Retrieve", "a", "value", "from", "the", "store", ".", "If", "it", "doesn", "t", "exist", "and", "a", "block", "is", "supplied", "create", "and", "return", "it", ";", "otherwise", "raise", "a", "KeyError", "." ]
d764691d39d64557693ac500e2b763ed4c5bf24d
https://github.com/chocolateboy/wireless/blob/d764691d39d64557693ac500e2b763ed4c5bf24d/lib/wireless/synchronized_store.rb#L51-L66
train
danielweinmann/unlock_gateway
lib/unlock_gateway/controller.rb
UnlockGateway.Controller.transition_state
def transition_state(state) authorize @contribution @initiative = @contribution.initiative @user = @contribution.user state = state.to_sym transition = @contribution.transition_by_state(state) initial_state = @contribution.state_name resource_name = @contribution.class.model_name.human if @contribution.send("can_#{transition}?") begin if @contribution.state_on_gateway != state if @contribution.update_state_on_gateway!(state) @contribution.send("#{transition}!") else flash[:alert] = t('flash.actions.update.alert', resource_name: resource_name) end else @contribution.send("#{transition}!") end rescue flash[:alert] = t('flash.actions.update.alert', resource_name: resource_name) end else flash[:alert] = t('flash.actions.update.alert', resource_name: resource_name) end if flash[:alert].present? render 'initiatives/contributions/show' else if initial_state == :pending flash[:notice] = t('flash.actions.create.notice', resource_name: resource_name) else flash[:notice] = t('flash.actions.update.notice', resource_name: resource_name) end redirect_to initiative_contribution_path(@contribution.initiative.id, @contribution) end end
ruby
def transition_state(state) authorize @contribution @initiative = @contribution.initiative @user = @contribution.user state = state.to_sym transition = @contribution.transition_by_state(state) initial_state = @contribution.state_name resource_name = @contribution.class.model_name.human if @contribution.send("can_#{transition}?") begin if @contribution.state_on_gateway != state if @contribution.update_state_on_gateway!(state) @contribution.send("#{transition}!") else flash[:alert] = t('flash.actions.update.alert', resource_name: resource_name) end else @contribution.send("#{transition}!") end rescue flash[:alert] = t('flash.actions.update.alert', resource_name: resource_name) end else flash[:alert] = t('flash.actions.update.alert', resource_name: resource_name) end if flash[:alert].present? render 'initiatives/contributions/show' else if initial_state == :pending flash[:notice] = t('flash.actions.create.notice', resource_name: resource_name) else flash[:notice] = t('flash.actions.update.notice', resource_name: resource_name) end redirect_to initiative_contribution_path(@contribution.initiative.id, @contribution) end end
[ "def", "transition_state", "(", "state", ")", "authorize", "@contribution", "@initiative", "=", "@contribution", ".", "initiative", "@user", "=", "@contribution", ".", "user", "state", "=", "state", ".", "to_sym", "transition", "=", "@contribution", ".", "transition_by_state", "(", "state", ")", "initial_state", "=", "@contribution", ".", "state_name", "resource_name", "=", "@contribution", ".", "class", ".", "model_name", ".", "human", "if", "@contribution", ".", "send", "(", "\"can_#{transition}?\"", ")", "begin", "if", "@contribution", ".", "state_on_gateway", "!=", "state", "if", "@contribution", ".", "update_state_on_gateway!", "(", "state", ")", "@contribution", ".", "send", "(", "\"#{transition}!\"", ")", "else", "flash", "[", ":alert", "]", "=", "t", "(", "'flash.actions.update.alert'", ",", "resource_name", ":", "resource_name", ")", "end", "else", "@contribution", ".", "send", "(", "\"#{transition}!\"", ")", "end", "rescue", "flash", "[", ":alert", "]", "=", "t", "(", "'flash.actions.update.alert'", ",", "resource_name", ":", "resource_name", ")", "end", "else", "flash", "[", ":alert", "]", "=", "t", "(", "'flash.actions.update.alert'", ",", "resource_name", ":", "resource_name", ")", "end", "if", "flash", "[", ":alert", "]", ".", "present?", "render", "'initiatives/contributions/show'", "else", "if", "initial_state", "==", ":pending", "flash", "[", ":notice", "]", "=", "t", "(", "'flash.actions.create.notice'", ",", "resource_name", ":", "resource_name", ")", "else", "flash", "[", ":notice", "]", "=", "t", "(", "'flash.actions.update.notice'", ",", "resource_name", ":", "resource_name", ")", "end", "redirect_to", "initiative_contribution_path", "(", "@contribution", ".", "initiative", ".", "id", ",", "@contribution", ")", "end", "end" ]
This method authorizes @contribution, checks if the contribution can be transitioned to the desired state, calls Contribution#update_state_on_gateway!, transition the contribution's state, and return the proper JSON for Unlock's AJAX calls
[ "This", "method", "authorizes" ]
50fe59d4d97874ce7372cb2830a87af5424ebdd3
https://github.com/danielweinmann/unlock_gateway/blob/50fe59d4d97874ce7372cb2830a87af5424ebdd3/lib/unlock_gateway/controller.rb#L67-L102
train
petebrowne/machined
lib/machined/cli.rb
Machined.CLI.rack_options
def rack_options # :nodoc: symbolized_options(:port, :host, :server, :daemonize, :pid).tap do |rack_options| rack_options[:environment] = environment rack_options[:Port] = rack_options.delete :port rack_options[:Host] = rack_options.delete :host rack_options[:app] = machined end end
ruby
def rack_options # :nodoc: symbolized_options(:port, :host, :server, :daemonize, :pid).tap do |rack_options| rack_options[:environment] = environment rack_options[:Port] = rack_options.delete :port rack_options[:Host] = rack_options.delete :host rack_options[:app] = machined end end
[ "def", "rack_options", "symbolized_options", "(", ":port", ",", ":host", ",", ":server", ",", ":daemonize", ",", ":pid", ")", ".", "tap", "do", "|", "rack_options", "|", "rack_options", "[", ":environment", "]", "=", "environment", "rack_options", "[", ":Port", "]", "=", "rack_options", ".", "delete", ":port", "rack_options", "[", ":Host", "]", "=", "rack_options", ".", "delete", ":host", "rack_options", "[", ":app", "]", "=", "machined", "end", "end" ]
Returns the options needed for setting up the Rack server.
[ "Returns", "the", "options", "needed", "for", "setting", "up", "the", "Rack", "server", "." ]
4f3921bc5098104096474300e933f009f1b4f7dd
https://github.com/petebrowne/machined/blob/4f3921bc5098104096474300e933f009f1b4f7dd/lib/machined/cli.rb#L87-L94
train
petebrowne/machined
lib/machined/cli.rb
Machined.CLI.symbolized_options
def symbolized_options(*keys) # :nodoc: @symbolized_options ||= begin opts = {}.merge(options) opts.merge! saved_options if saved_options? opts.symbolize_keys end @symbolized_options.slice(*keys) end
ruby
def symbolized_options(*keys) # :nodoc: @symbolized_options ||= begin opts = {}.merge(options) opts.merge! saved_options if saved_options? opts.symbolize_keys end @symbolized_options.slice(*keys) end
[ "def", "symbolized_options", "(", "*", "keys", ")", "@symbolized_options", "||=", "begin", "opts", "=", "{", "}", ".", "merge", "(", "options", ")", "opts", ".", "merge!", "saved_options", "if", "saved_options?", "opts", ".", "symbolize_keys", "end", "@symbolized_options", ".", "slice", "(", "*", "keys", ")", "end" ]
Returns a mutable options hash with symbolized keys. Optionally, returns only the keys given.
[ "Returns", "a", "mutable", "options", "hash", "with", "symbolized", "keys", ".", "Optionally", "returns", "only", "the", "keys", "given", "." ]
4f3921bc5098104096474300e933f009f1b4f7dd
https://github.com/petebrowne/machined/blob/4f3921bc5098104096474300e933f009f1b4f7dd/lib/machined/cli.rb#L98-L105
train
Deradon/Rails-LookUpTable
lib/look_up_table/base.rb
LookUpTable.ClassMethods.look_up_table
def look_up_table(lut_key, options = {}, &block) options = { :batch_size => 10000, :prefix => "#{self.name}/", :read_on_init => false, :use_cache => true, :sql_mode => true, :where => nil }.merge(options) self.lut_set_proc(lut_key, block) self.lut_set_options(lut_key, options) self.lut(lut_key) if options[:read_on_init] end
ruby
def look_up_table(lut_key, options = {}, &block) options = { :batch_size => 10000, :prefix => "#{self.name}/", :read_on_init => false, :use_cache => true, :sql_mode => true, :where => nil }.merge(options) self.lut_set_proc(lut_key, block) self.lut_set_options(lut_key, options) self.lut(lut_key) if options[:read_on_init] end
[ "def", "look_up_table", "(", "lut_key", ",", "options", "=", "{", "}", ",", "&", "block", ")", "options", "=", "{", ":batch_size", "=>", "10000", ",", ":prefix", "=>", "\"#{self.name}/\"", ",", ":read_on_init", "=>", "false", ",", ":use_cache", "=>", "true", ",", ":sql_mode", "=>", "true", ",", ":where", "=>", "nil", "}", ".", "merge", "(", "options", ")", "self", ".", "lut_set_proc", "(", "lut_key", ",", "block", ")", "self", ".", "lut_set_options", "(", "lut_key", ",", "options", ")", "self", ".", "lut", "(", "lut_key", ")", "if", "options", "[", ":read_on_init", "]", "end" ]
== Defining LookUpTables # Sample class: Foobar(id: integer, foo: string, bar: integer) === Simplest way to define a LookUpTable: look_up_table :id look_up_table :foo look_up_table :bar === Add some options to your LookUpTable: look_up_table :foo, :batch_size => 5000, :where => "id > 10000" === Pass a block to define the LUT manually look_up_table :foo do |lut, foobar| lut[foobar.foo] = foobar.id end === Turn off AutoFinder and completly define the whole LUT yourself: look_up_table :foo, :sql_mode => false do |lut| Foobar.where("id > 10000").each do |foobar| lut[foobar.foo] = foobar.id end end
[ "==", "Defining", "LookUpTables" ]
da873f48b039ef01ed3d3820d3a59d8886281be1
https://github.com/Deradon/Rails-LookUpTable/blob/da873f48b039ef01ed3d3820d3a59d8886281be1/lib/look_up_table/base.rb#L38-L52
train
Deradon/Rails-LookUpTable
lib/look_up_table/base.rb
LookUpTable.ClassMethods.lut
def lut(lut_key = nil, lut_item_key = nil) @lut ||= {} if lut_key.nil? hash = {} self.lut_keys.each { |key| hash[key] = self.lut(key) } # CHECK: use .inject? return hash end @lut[lut_key.intern] ||= lut_read(lut_key) || {} if lut_key.respond_to?(:intern) self.lut_deep_hash_call(:lut, @lut, lut_key, lut_item_key) end
ruby
def lut(lut_key = nil, lut_item_key = nil) @lut ||= {} if lut_key.nil? hash = {} self.lut_keys.each { |key| hash[key] = self.lut(key) } # CHECK: use .inject? return hash end @lut[lut_key.intern] ||= lut_read(lut_key) || {} if lut_key.respond_to?(:intern) self.lut_deep_hash_call(:lut, @lut, lut_key, lut_item_key) end
[ "def", "lut", "(", "lut_key", "=", "nil", ",", "lut_item_key", "=", "nil", ")", "@lut", "||=", "{", "}", "if", "lut_key", ".", "nil?", "hash", "=", "{", "}", "self", ".", "lut_keys", ".", "each", "{", "|", "key", "|", "hash", "[", "key", "]", "=", "self", ".", "lut", "(", "key", ")", "}", "return", "hash", "end", "@lut", "[", "lut_key", ".", "intern", "]", "||=", "lut_read", "(", "lut_key", ")", "||", "{", "}", "if", "lut_key", ".", "respond_to?", "(", ":intern", ")", "self", ".", "lut_deep_hash_call", "(", ":lut", ",", "@lut", ",", "lut_key", ",", "lut_item_key", ")", "end" ]
== Calling LookUpTables === Call without any params * Returns: All LUTs defined within Foobar Foobar.lut => { :foo => { :a => 1 }, :bar => { :b => 2 }, :foobar => { :c => 3, :d => 4, :e => 5 } } === Call with :lut_key: * Returns: Hash representing LUT defined by :lut_key Foobar.lut :foo => { :a => 1 } === Call with array of :lut_keys * Returns: Hash representing LUT defined with :lut_key in given Array Foobar.lut [:foo, :bar] => { :foo => { :a => 1 }, :bar => { :b => 2 } } === Call with Call with :lut_key and :lut_item_key * Returns: Value in LUT defined by :lut_key and :lut_item_key Foobar.lut :foo, "foobar" => 1 # So we've got a Foobar with :foo => "foobar", its ID is '1' === Call with Call with :lut_key and :lut_item_key as Array * Returns: Hash representing LUT defined by :lut_key with :lut_item_keys in Array Foobar.lut :foobar, ["foo", "bar", "oof"] => { "foo" => 3, "bar" => 4, "oof" => nil } # So we got Foobars with ID '3' and '4' # and no Foobar defined by :foobar => :oof === Call with :lut_key as a Hash * Returns: Hash representing LUTs given by keys of passed Hash. - If given value of Hash-Item is nil, will get whole LUT. - If given value is String or Symbol, will get value of LUT. - If given value is Array, will get values of entries. * Example: Foobar.lut { :foo => :a, :bar => nil, :foobar => [:c, :d] } => { :foo => 1, :bar => { :b => 2 }, :foobar => { :c => 3, :d => 4 } }
[ "==", "Calling", "LookUpTables" ]
da873f48b039ef01ed3d3820d3a59d8886281be1
https://github.com/Deradon/Rails-LookUpTable/blob/da873f48b039ef01ed3d3820d3a59d8886281be1/lib/look_up_table/base.rb#L112-L124
train
Deradon/Rails-LookUpTable
lib/look_up_table/base.rb
LookUpTable.ClassMethods.lut_reload
def lut_reload(lut_key = nil) if lut_key lut_reset(lut_key) lut(lut_key) else lut_keys.each { |k| lut_reload(k) } end lut_keys end
ruby
def lut_reload(lut_key = nil) if lut_key lut_reset(lut_key) lut(lut_key) else lut_keys.each { |k| lut_reload(k) } end lut_keys end
[ "def", "lut_reload", "(", "lut_key", "=", "nil", ")", "if", "lut_key", "lut_reset", "(", "lut_key", ")", "lut", "(", "lut_key", ")", "else", "lut_keys", ".", "each", "{", "|", "k", "|", "lut_reload", "(", "k", ")", "}", "end", "lut_keys", "end" ]
Reading LUT and writing cache again
[ "Reading", "LUT", "and", "writing", "cache", "again" ]
da873f48b039ef01ed3d3820d3a59d8886281be1
https://github.com/Deradon/Rails-LookUpTable/blob/da873f48b039ef01ed3d3820d3a59d8886281be1/lib/look_up_table/base.rb#L141-L150
train
Deradon/Rails-LookUpTable
lib/look_up_table/base.rb
LookUpTable.ClassMethods.lut_read
def lut_read(name) return nil unless options = lut_options(name)# HACK if options[:use_cache] lut_read_from_cache(name) else lut_read_without_cache(name) end end
ruby
def lut_read(name) return nil unless options = lut_options(name)# HACK if options[:use_cache] lut_read_from_cache(name) else lut_read_without_cache(name) end end
[ "def", "lut_read", "(", "name", ")", "return", "nil", "unless", "options", "=", "lut_options", "(", "name", ")", "if", "options", "[", ":use_cache", "]", "lut_read_from_cache", "(", "name", ")", "else", "lut_read_without_cache", "(", "name", ")", "end", "end" ]
Reads a single lut
[ "Reads", "a", "single", "lut" ]
da873f48b039ef01ed3d3820d3a59d8886281be1
https://github.com/Deradon/Rails-LookUpTable/blob/da873f48b039ef01ed3d3820d3a59d8886281be1/lib/look_up_table/base.rb#L210-L218
train