repo
stringlengths 5
58
| path
stringlengths 9
168
| func_name
stringlengths 9
130
| original_string
stringlengths 66
10.5k
| language
stringclasses 1
value | code
stringlengths 66
10.5k
| code_tokens
list | docstring
stringlengths 8
16k
| docstring_tokens
list | sha
stringlengths 40
40
| url
stringlengths 94
266
| partition
stringclasses 1
value |
---|---|---|---|---|---|---|---|---|---|---|---|
chicks/sugarcrm | lib/sugarcrm/associations/association.rb | SugarCRM.Association.define_methods | def define_methods
methods = []
pretty_name = @relationship[:target][:name]
methods << define_method(@link_field)
methods << define_alias(pretty_name, @link_field) if pretty_name != @link_field
methods
end | ruby | def define_methods
methods = []
pretty_name = @relationship[:target][:name]
methods << define_method(@link_field)
methods << define_alias(pretty_name, @link_field) if pretty_name != @link_field
methods
end | [
"def",
"define_methods",
"methods",
"=",
"[",
"]",
"pretty_name",
"=",
"@relationship",
"[",
":target",
"]",
"[",
":name",
"]",
"methods",
"<<",
"define_method",
"(",
"@link_field",
")",
"methods",
"<<",
"define_alias",
"(",
"pretty_name",
",",
"@link_field",
")",
"if",
"pretty_name",
"!=",
"@link_field",
"methods",
"end"
]
| Defines methods for accessing the association target on the owner class.
If the link_field name includes the owner class name, it is stripped before
creating the method. If this occurs, we also create an alias to the stripped
method using the full link_field name. | [
"Defines",
"methods",
"for",
"accessing",
"the",
"association",
"target",
"on",
"the",
"owner",
"class",
".",
"If",
"the",
"link_field",
"name",
"includes",
"the",
"owner",
"class",
"name",
"it",
"is",
"stripped",
"before",
"creating",
"the",
"method",
".",
"If",
"this",
"occurs",
"we",
"also",
"create",
"an",
"alias",
"to",
"the",
"stripped",
"method",
"using",
"the",
"full",
"link_field",
"name",
"."
]
| 360060139b13788a7ec462c6ecd08d3dbda9849a | https://github.com/chicks/sugarcrm/blob/360060139b13788a7ec462c6ecd08d3dbda9849a/lib/sugarcrm/associations/association.rb#L89-L95 | train |
chicks/sugarcrm | lib/sugarcrm/associations/association.rb | SugarCRM.Association.define_method | def define_method(link_field)
raise ArgumentError, "argument cannot be nil" if link_field.nil?
if (@owner.respond_to? link_field.to_sym) && @owner.debug
warn "Warning: Overriding method: #{@owner.class}##{link_field}"
end
@owner.class.module_eval %Q?
def #{link_field}
query_association :#{link_field}
end
?
link_field
end | ruby | def define_method(link_field)
raise ArgumentError, "argument cannot be nil" if link_field.nil?
if (@owner.respond_to? link_field.to_sym) && @owner.debug
warn "Warning: Overriding method: #{@owner.class}##{link_field}"
end
@owner.class.module_eval %Q?
def #{link_field}
query_association :#{link_field}
end
?
link_field
end | [
"def",
"define_method",
"(",
"link_field",
")",
"raise",
"ArgumentError",
",",
"\"argument cannot be nil\"",
"if",
"link_field",
".",
"nil?",
"if",
"(",
"@owner",
".",
"respond_to?",
"link_field",
".",
"to_sym",
")",
"&&",
"@owner",
".",
"debug",
"warn",
"\"Warning: Overriding method: #{@owner.class}##{link_field}\"",
"end",
"@owner",
".",
"class",
".",
"module_eval",
"%Q? def #{link_field} query_association :#{link_field} end ?",
"link_field",
"end"
]
| Generates the association proxy method for related module | [
"Generates",
"the",
"association",
"proxy",
"method",
"for",
"related",
"module"
]
| 360060139b13788a7ec462c6ecd08d3dbda9849a | https://github.com/chicks/sugarcrm/blob/360060139b13788a7ec462c6ecd08d3dbda9849a/lib/sugarcrm/associations/association.rb#L98-L109 | train |
chicks/sugarcrm | lib/sugarcrm/associations/association.rb | SugarCRM.Association.cardinality_for | def cardinality_for(*args)
args.inject([]) {|results,arg|
result = :many
result = :one if arg.singularize == arg
results << result
}
end | ruby | def cardinality_for(*args)
args.inject([]) {|results,arg|
result = :many
result = :one if arg.singularize == arg
results << result
}
end | [
"def",
"cardinality_for",
"(",
"*",
"args",
")",
"args",
".",
"inject",
"(",
"[",
"]",
")",
"{",
"|",
"results",
",",
"arg",
"|",
"result",
"=",
":many",
"result",
"=",
":one",
"if",
"arg",
".",
"singularize",
"==",
"arg",
"results",
"<<",
"result",
"}",
"end"
]
| Determines if the provided string is plural or singular
Plurality == Cardinality | [
"Determines",
"if",
"the",
"provided",
"string",
"is",
"plural",
"or",
"singular",
"Plurality",
"==",
"Cardinality"
]
| 360060139b13788a7ec462c6ecd08d3dbda9849a | https://github.com/chicks/sugarcrm/blob/360060139b13788a7ec462c6ecd08d3dbda9849a/lib/sugarcrm/associations/association.rb#L140-L146 | train |
chicks/sugarcrm | lib/sugarcrm/connection/request.rb | SugarCRM.Request.convert_reserved_characters | def convert_reserved_characters(string)
string.gsub!(/"/, '\"')
string.gsub!(/'/, '\'')
string.gsub!(/&/, '\&')
string.gsub!(/</, '\<')
string.gsub!(/</, '\>')
string
end | ruby | def convert_reserved_characters(string)
string.gsub!(/"/, '\"')
string.gsub!(/'/, '\'')
string.gsub!(/&/, '\&')
string.gsub!(/</, '\<')
string.gsub!(/</, '\>')
string
end | [
"def",
"convert_reserved_characters",
"(",
"string",
")",
"string",
".",
"gsub!",
"(",
"/",
"/",
",",
"'\\\"'",
")",
"string",
".",
"gsub!",
"(",
"/",
"/",
",",
"'\\''",
")",
"string",
".",
"gsub!",
"(",
"/",
"/",
",",
"'\\&'",
")",
"string",
".",
"gsub!",
"(",
"/",
"/",
",",
"'\\<'",
")",
"string",
".",
"gsub!",
"(",
"/",
"/",
",",
"'\\>'",
")",
"string",
"end"
]
| A tiny helper for converting reserved characters for html encoding | [
"A",
"tiny",
"helper",
"for",
"converting",
"reserved",
"characters",
"for",
"html",
"encoding"
]
| 360060139b13788a7ec462c6ecd08d3dbda9849a | https://github.com/chicks/sugarcrm/blob/360060139b13788a7ec462c6ecd08d3dbda9849a/lib/sugarcrm/connection/request.rb#L49-L56 | train |
chicks/sugarcrm | lib/sugarcrm/module.rb | SugarCRM.Module.fields | def fields
return @fields if fields_registered?
all_fields = @session.connection.get_fields(@name)
@fields = all_fields["module_fields"].with_indifferent_access
@link_fields= all_fields["link_fields"]
handle_empty_arrays
@fields_registered = true
@fields
end | ruby | def fields
return @fields if fields_registered?
all_fields = @session.connection.get_fields(@name)
@fields = all_fields["module_fields"].with_indifferent_access
@link_fields= all_fields["link_fields"]
handle_empty_arrays
@fields_registered = true
@fields
end | [
"def",
"fields",
"return",
"@fields",
"if",
"fields_registered?",
"all_fields",
"=",
"@session",
".",
"connection",
".",
"get_fields",
"(",
"@name",
")",
"@fields",
"=",
"all_fields",
"[",
"\"module_fields\"",
"]",
".",
"with_indifferent_access",
"@link_fields",
"=",
"all_fields",
"[",
"\"link_fields\"",
"]",
"handle_empty_arrays",
"@fields_registered",
"=",
"true",
"@fields",
"end"
]
| Returns the fields associated with the module | [
"Returns",
"the",
"fields",
"associated",
"with",
"the",
"module"
]
| 360060139b13788a7ec462c6ecd08d3dbda9849a | https://github.com/chicks/sugarcrm/blob/360060139b13788a7ec462c6ecd08d3dbda9849a/lib/sugarcrm/module.rb#L38-L46 | train |
chicks/sugarcrm | lib/sugarcrm/module.rb | SugarCRM.Module.required_fields | def required_fields
required_fields = []
ignore_fields = [:id, :date_entered, :date_modified]
self.fields.each_value do |field|
next if ignore_fields.include? field["name"].to_sym
required_fields << field["name"].to_sym if field["required"] == 1
end
required_fields
end | ruby | def required_fields
required_fields = []
ignore_fields = [:id, :date_entered, :date_modified]
self.fields.each_value do |field|
next if ignore_fields.include? field["name"].to_sym
required_fields << field["name"].to_sym if field["required"] == 1
end
required_fields
end | [
"def",
"required_fields",
"required_fields",
"=",
"[",
"]",
"ignore_fields",
"=",
"[",
":id",
",",
":date_entered",
",",
":date_modified",
"]",
"self",
".",
"fields",
".",
"each_value",
"do",
"|",
"field",
"|",
"next",
"if",
"ignore_fields",
".",
"include?",
"field",
"[",
"\"name\"",
"]",
".",
"to_sym",
"required_fields",
"<<",
"field",
"[",
"\"name\"",
"]",
".",
"to_sym",
"if",
"field",
"[",
"\"required\"",
"]",
"==",
"1",
"end",
"required_fields",
"end"
]
| Returns the required fields | [
"Returns",
"the",
"required",
"fields"
]
| 360060139b13788a7ec462c6ecd08d3dbda9849a | https://github.com/chicks/sugarcrm/blob/360060139b13788a7ec462c6ecd08d3dbda9849a/lib/sugarcrm/module.rb#L55-L63 | train |
chicks/sugarcrm | lib/sugarcrm/module.rb | SugarCRM.Module.deregister | def deregister
return true unless registered?
klass = self.klass
@session.namespace_const.instance_eval{ remove_const klass }
true
end | ruby | def deregister
return true unless registered?
klass = self.klass
@session.namespace_const.instance_eval{ remove_const klass }
true
end | [
"def",
"deregister",
"return",
"true",
"unless",
"registered?",
"klass",
"=",
"self",
".",
"klass",
"@session",
".",
"namespace_const",
".",
"instance_eval",
"{",
"remove_const",
"klass",
"}",
"true",
"end"
]
| Deregisters the module | [
"Deregisters",
"the",
"module"
]
| 360060139b13788a7ec462c6ecd08d3dbda9849a | https://github.com/chicks/sugarcrm/blob/360060139b13788a7ec462c6ecd08d3dbda9849a/lib/sugarcrm/module.rb#L99-L104 | train |
chicks/sugarcrm | lib/sugarcrm/attributes/attribute_serializers.rb | SugarCRM.AttributeSerializers.serialize_attribute | def serialize_attribute(name,value)
attr_value = value
attr_type = attr_type_for(name)
case attr_type
when :bool
attr_value = 0
attr_value = 1 if value
when :datetime, :datetimecombo
begin
attr_value = value.strftime("%Y-%m-%d %H:%M:%S")
rescue
attr_value = value
end
when :int
attr_value = value.to_s
end
{:name => name, :value => attr_value}
end | ruby | def serialize_attribute(name,value)
attr_value = value
attr_type = attr_type_for(name)
case attr_type
when :bool
attr_value = 0
attr_value = 1 if value
when :datetime, :datetimecombo
begin
attr_value = value.strftime("%Y-%m-%d %H:%M:%S")
rescue
attr_value = value
end
when :int
attr_value = value.to_s
end
{:name => name, :value => attr_value}
end | [
"def",
"serialize_attribute",
"(",
"name",
",",
"value",
")",
"attr_value",
"=",
"value",
"attr_type",
"=",
"attr_type_for",
"(",
"name",
")",
"case",
"attr_type",
"when",
":bool",
"attr_value",
"=",
"0",
"attr_value",
"=",
"1",
"if",
"value",
"when",
":datetime",
",",
":datetimecombo",
"begin",
"attr_value",
"=",
"value",
".",
"strftime",
"(",
"\"%Y-%m-%d %H:%M:%S\"",
")",
"rescue",
"attr_value",
"=",
"value",
"end",
"when",
":int",
"attr_value",
"=",
"value",
".",
"to_s",
"end",
"{",
":name",
"=>",
"name",
",",
":value",
"=>",
"attr_value",
"}",
"end"
]
| Un-typecasts the attribute - false becomes "0", 5234 becomes "5234", etc. | [
"Un",
"-",
"typecasts",
"the",
"attribute",
"-",
"false",
"becomes",
"0",
"5234",
"becomes",
"5234",
"etc",
"."
]
| 360060139b13788a7ec462c6ecd08d3dbda9849a | https://github.com/chicks/sugarcrm/blob/360060139b13788a7ec462c6ecd08d3dbda9849a/lib/sugarcrm/attributes/attribute_serializers.rb#L37-L54 | train |
chicks/sugarcrm | lib/sugarcrm/base.rb | SugarCRM.Base.save | def save(opts={})
options = { :validate => true }.merge(opts)
return false if !(new_record? || changed?)
if options[:validate]
return false if !valid?
end
begin
save!(options)
rescue
return false
end
true
end | ruby | def save(opts={})
options = { :validate => true }.merge(opts)
return false if !(new_record? || changed?)
if options[:validate]
return false if !valid?
end
begin
save!(options)
rescue
return false
end
true
end | [
"def",
"save",
"(",
"opts",
"=",
"{",
"}",
")",
"options",
"=",
"{",
":validate",
"=>",
"true",
"}",
".",
"merge",
"(",
"opts",
")",
"return",
"false",
"if",
"!",
"(",
"new_record?",
"||",
"changed?",
")",
"if",
"options",
"[",
":validate",
"]",
"return",
"false",
"if",
"!",
"valid?",
"end",
"begin",
"save!",
"(",
"options",
")",
"rescue",
"return",
"false",
"end",
"true",
"end"
]
| Saves the current object, checks that required fields are present.
returns true or false | [
"Saves",
"the",
"current",
"object",
"checks",
"that",
"required",
"fields",
"are",
"present",
".",
"returns",
"true",
"or",
"false"
]
| 360060139b13788a7ec462c6ecd08d3dbda9849a | https://github.com/chicks/sugarcrm/blob/360060139b13788a7ec462c6ecd08d3dbda9849a/lib/sugarcrm/base.rb#L190-L202 | train |
chicks/sugarcrm | lib/sugarcrm/attributes/attribute_validations.rb | SugarCRM.AttributeValidations.valid? | def valid?
@errors = (defined?(HashWithIndifferentAccess) ? HashWithIndifferentAccess : ActiveSupport::HashWithIndifferentAccess).new
self.class._module.required_fields.each do |attribute|
valid_attribute?(attribute)
end
# for rails compatibility
def @errors.full_messages
# After removing attributes without errors, flatten the error hash, repeating the name of the attribute before each message:
# e.g. {'name' => ['cannot be blank', 'is too long'], 'website' => ['is not valid']}
# will become 'name cannot be blank, name is too long, website is not valid
self.inject([]){|memo, obj| memo.concat(obj[1].inject([]){|m, o| m << "#{obj[0].to_s.humanize} #{o}" })}
end
# Rails needs each attribute to be present in the error hash (if the attribute has no error, it has [] as a value)
# Redefine the [] method for the errors hash to return [] instead of nil is the hash doesn't contain the key
class << @errors
alias :old_key_lookup :[]
def [](key)
old_key_lookup(key) || Array.new
end
end
@errors.size == 0
end | ruby | def valid?
@errors = (defined?(HashWithIndifferentAccess) ? HashWithIndifferentAccess : ActiveSupport::HashWithIndifferentAccess).new
self.class._module.required_fields.each do |attribute|
valid_attribute?(attribute)
end
# for rails compatibility
def @errors.full_messages
# After removing attributes without errors, flatten the error hash, repeating the name of the attribute before each message:
# e.g. {'name' => ['cannot be blank', 'is too long'], 'website' => ['is not valid']}
# will become 'name cannot be blank, name is too long, website is not valid
self.inject([]){|memo, obj| memo.concat(obj[1].inject([]){|m, o| m << "#{obj[0].to_s.humanize} #{o}" })}
end
# Rails needs each attribute to be present in the error hash (if the attribute has no error, it has [] as a value)
# Redefine the [] method for the errors hash to return [] instead of nil is the hash doesn't contain the key
class << @errors
alias :old_key_lookup :[]
def [](key)
old_key_lookup(key) || Array.new
end
end
@errors.size == 0
end | [
"def",
"valid?",
"@errors",
"=",
"(",
"defined?",
"(",
"HashWithIndifferentAccess",
")",
"?",
"HashWithIndifferentAccess",
":",
"ActiveSupport",
"::",
"HashWithIndifferentAccess",
")",
".",
"new",
"self",
".",
"class",
".",
"_module",
".",
"required_fields",
".",
"each",
"do",
"|",
"attribute",
"|",
"valid_attribute?",
"(",
"attribute",
")",
"end",
"def",
"@errors",
".",
"full_messages",
"self",
".",
"inject",
"(",
"[",
"]",
")",
"{",
"|",
"memo",
",",
"obj",
"|",
"memo",
".",
"concat",
"(",
"obj",
"[",
"1",
"]",
".",
"inject",
"(",
"[",
"]",
")",
"{",
"|",
"m",
",",
"o",
"|",
"m",
"<<",
"\"#{obj[0].to_s.humanize} #{o}\"",
"}",
")",
"}",
"end",
"class",
"<<",
"@errors",
"alias",
":old_key_lookup",
":[]",
"def",
"[]",
"(",
"key",
")",
"old_key_lookup",
"(",
"key",
")",
"||",
"Array",
".",
"new",
"end",
"end",
"@errors",
".",
"size",
"==",
"0",
"end"
]
| Checks to see if we have all the neccessary attributes | [
"Checks",
"to",
"see",
"if",
"we",
"have",
"all",
"the",
"neccessary",
"attributes"
]
| 360060139b13788a7ec462c6ecd08d3dbda9849a | https://github.com/chicks/sugarcrm/blob/360060139b13788a7ec462c6ecd08d3dbda9849a/lib/sugarcrm/attributes/attribute_validations.rb#L3-L28 | train |
chicks/sugarcrm | lib/sugarcrm/attributes/attribute_validations.rb | SugarCRM.AttributeValidations.validate_class_for | def validate_class_for(attribute, class_array)
return true if class_array.include? @attributes[attribute].class
add_error(attribute, "must be a #{class_array.join(" or ")} object (not #{@attributes[attribute].class})")
false
end | ruby | def validate_class_for(attribute, class_array)
return true if class_array.include? @attributes[attribute].class
add_error(attribute, "must be a #{class_array.join(" or ")} object (not #{@attributes[attribute].class})")
false
end | [
"def",
"validate_class_for",
"(",
"attribute",
",",
"class_array",
")",
"return",
"true",
"if",
"class_array",
".",
"include?",
"@attributes",
"[",
"attribute",
"]",
".",
"class",
"add_error",
"(",
"attribute",
",",
"\"must be a #{class_array.join(\" or \")} object (not #{@attributes[attribute].class})\"",
")",
"false",
"end"
]
| Compares the class of the attribute with the class or classes provided in the class array
returns true if they match, otherwise adds an entry to the @errors collection, and returns false | [
"Compares",
"the",
"class",
"of",
"the",
"attribute",
"with",
"the",
"class",
"or",
"classes",
"provided",
"in",
"the",
"class",
"array",
"returns",
"true",
"if",
"they",
"match",
"otherwise",
"adds",
"an",
"entry",
"to",
"the"
]
| 360060139b13788a7ec462c6ecd08d3dbda9849a | https://github.com/chicks/sugarcrm/blob/360060139b13788a7ec462c6ecd08d3dbda9849a/lib/sugarcrm/attributes/attribute_validations.rb#L50-L54 | train |
chicks/sugarcrm | lib/sugarcrm/attributes/attribute_validations.rb | SugarCRM.AttributeValidations.add_error | def add_error(attribute, message)
@errors[attribute] ||= []
@errors[attribute] = @errors[attribute] << message unless @errors[attribute].include? message
@errors
end | ruby | def add_error(attribute, message)
@errors[attribute] ||= []
@errors[attribute] = @errors[attribute] << message unless @errors[attribute].include? message
@errors
end | [
"def",
"add_error",
"(",
"attribute",
",",
"message",
")",
"@errors",
"[",
"attribute",
"]",
"||=",
"[",
"]",
"@errors",
"[",
"attribute",
"]",
"=",
"@errors",
"[",
"attribute",
"]",
"<<",
"message",
"unless",
"@errors",
"[",
"attribute",
"]",
".",
"include?",
"message",
"@errors",
"end"
]
| Add an error to the hash | [
"Add",
"an",
"error",
"to",
"the",
"hash"
]
| 360060139b13788a7ec462c6ecd08d3dbda9849a | https://github.com/chicks/sugarcrm/blob/360060139b13788a7ec462c6ecd08d3dbda9849a/lib/sugarcrm/attributes/attribute_validations.rb#L57-L61 | train |
chicks/sugarcrm | lib/sugarcrm/connection/response.rb | SugarCRM.Response.to_obj | def to_obj
# If this is not a "entry_list" response, just return
return @response unless @response && @response["entry_list"]
objects = []
@response["entry_list"].each do |object|
attributes = []
_module = resolve_module(object)
attributes = flatten_name_value_list(object)
namespace = @session.namespace_const
if namespace.const_get(_module)
if attributes.length == 0
raise AttributeParsingError, "response contains objects without attributes!"
end
objects << namespace.const_get(_module).new(attributes)
else
raise InvalidModule, "#{_module} does not exist, or is not accessible"
end
end
# If we only have one result, just return the object
if objects.length == 1 && !@options[:always_return_array]
return objects[0]
else
return objects
end
end | ruby | def to_obj
# If this is not a "entry_list" response, just return
return @response unless @response && @response["entry_list"]
objects = []
@response["entry_list"].each do |object|
attributes = []
_module = resolve_module(object)
attributes = flatten_name_value_list(object)
namespace = @session.namespace_const
if namespace.const_get(_module)
if attributes.length == 0
raise AttributeParsingError, "response contains objects without attributes!"
end
objects << namespace.const_get(_module).new(attributes)
else
raise InvalidModule, "#{_module} does not exist, or is not accessible"
end
end
# If we only have one result, just return the object
if objects.length == 1 && !@options[:always_return_array]
return objects[0]
else
return objects
end
end | [
"def",
"to_obj",
"return",
"@response",
"unless",
"@response",
"&&",
"@response",
"[",
"\"entry_list\"",
"]",
"objects",
"=",
"[",
"]",
"@response",
"[",
"\"entry_list\"",
"]",
".",
"each",
"do",
"|",
"object",
"|",
"attributes",
"=",
"[",
"]",
"_module",
"=",
"resolve_module",
"(",
"object",
")",
"attributes",
"=",
"flatten_name_value_list",
"(",
"object",
")",
"namespace",
"=",
"@session",
".",
"namespace_const",
"if",
"namespace",
".",
"const_get",
"(",
"_module",
")",
"if",
"attributes",
".",
"length",
"==",
"0",
"raise",
"AttributeParsingError",
",",
"\"response contains objects without attributes!\"",
"end",
"objects",
"<<",
"namespace",
".",
"const_get",
"(",
"_module",
")",
".",
"new",
"(",
"attributes",
")",
"else",
"raise",
"InvalidModule",
",",
"\"#{_module} does not exist, or is not accessible\"",
"end",
"end",
"if",
"objects",
".",
"length",
"==",
"1",
"&&",
"!",
"@options",
"[",
":always_return_array",
"]",
"return",
"objects",
"[",
"0",
"]",
"else",
"return",
"objects",
"end",
"end"
]
| Tries to instantiate and return an object with the values
populated from the response | [
"Tries",
"to",
"instantiate",
"and",
"return",
"an",
"object",
"with",
"the",
"values",
"populated",
"from",
"the",
"response"
]
| 360060139b13788a7ec462c6ecd08d3dbda9849a | https://github.com/chicks/sugarcrm/blob/360060139b13788a7ec462c6ecd08d3dbda9849a/lib/sugarcrm/connection/response.rb#L37-L62 | train |
chicks/sugarcrm | lib/sugarcrm/attributes/attribute_typecast.rb | SugarCRM.AttributeTypeCast.attr_type_for | def attr_type_for(attribute)
fields = self.class._module.fields
field = fields[attribute]
raise UninitializedModule, "#{self.class.session.namespace_const}Module #{self.class._module.name} was not initialized properly (fields.length == 0)" if fields.length == 0
raise InvalidAttribute, "#{self.class}._module.fields does not contain an entry for #{attribute} (of type: #{attribute.class})\nValid fields: #{self.class._module.fields.keys.sort.join(", ")}" if field.nil?
raise InvalidAttributeType, "#{self.class}._module.fields[#{attribute}] does not have a key for \'type\'" if field["type"].nil?
field["type"].to_sym
end | ruby | def attr_type_for(attribute)
fields = self.class._module.fields
field = fields[attribute]
raise UninitializedModule, "#{self.class.session.namespace_const}Module #{self.class._module.name} was not initialized properly (fields.length == 0)" if fields.length == 0
raise InvalidAttribute, "#{self.class}._module.fields does not contain an entry for #{attribute} (of type: #{attribute.class})\nValid fields: #{self.class._module.fields.keys.sort.join(", ")}" if field.nil?
raise InvalidAttributeType, "#{self.class}._module.fields[#{attribute}] does not have a key for \'type\'" if field["type"].nil?
field["type"].to_sym
end | [
"def",
"attr_type_for",
"(",
"attribute",
")",
"fields",
"=",
"self",
".",
"class",
".",
"_module",
".",
"fields",
"field",
"=",
"fields",
"[",
"attribute",
"]",
"raise",
"UninitializedModule",
",",
"\"#{self.class.session.namespace_const}Module #{self.class._module.name} was not initialized properly (fields.length == 0)\"",
"if",
"fields",
".",
"length",
"==",
"0",
"raise",
"InvalidAttribute",
",",
"\"#{self.class}._module.fields does not contain an entry for #{attribute} (of type: #{attribute.class})\\nValid fields: #{self.class._module.fields.keys.sort.join(\", \")}\"",
"if",
"field",
".",
"nil?",
"raise",
"InvalidAttributeType",
",",
"\"#{self.class}._module.fields[#{attribute}] does not have a key for \\'type\\'\"",
"if",
"field",
"[",
"\"type\"",
"]",
".",
"nil?",
"field",
"[",
"\"type\"",
"]",
".",
"to_sym",
"end"
]
| Returns the attribute type for a given attribute | [
"Returns",
"the",
"attribute",
"type",
"for",
"a",
"given",
"attribute"
]
| 360060139b13788a7ec462c6ecd08d3dbda9849a | https://github.com/chicks/sugarcrm/blob/360060139b13788a7ec462c6ecd08d3dbda9849a/lib/sugarcrm/attributes/attribute_typecast.rb#L6-L13 | train |
chicks/sugarcrm | lib/sugarcrm/attributes/attribute_typecast.rb | SugarCRM.AttributeTypeCast.typecast_attributes | def typecast_attributes
@attributes.each_pair do |name,value|
# skip primary key columns
# ajay Singh --> skip the loop if attribute is null (!name.present?)
next if (name == "id") or (!name.present?)
attr_type = attr_type_for(name)
# empty attributes should stay empty (e.g. an empty int field shouldn't be typecast as 0)
if [:datetime, :datetimecombo, :int].include? attr_type && (value.nil? || value == '')
@attributes[name] = nil
next
end
case attr_type
when :bool
@attributes[name] = (value == "1")
when :datetime, :datetimecombo
begin
@attributes[name] = DateTime.parse(value)
rescue
@attributes[name] = value
end
when :int
@attributes[name] = value.to_i
end
end
@attributes
end | ruby | def typecast_attributes
@attributes.each_pair do |name,value|
# skip primary key columns
# ajay Singh --> skip the loop if attribute is null (!name.present?)
next if (name == "id") or (!name.present?)
attr_type = attr_type_for(name)
# empty attributes should stay empty (e.g. an empty int field shouldn't be typecast as 0)
if [:datetime, :datetimecombo, :int].include? attr_type && (value.nil? || value == '')
@attributes[name] = nil
next
end
case attr_type
when :bool
@attributes[name] = (value == "1")
when :datetime, :datetimecombo
begin
@attributes[name] = DateTime.parse(value)
rescue
@attributes[name] = value
end
when :int
@attributes[name] = value.to_i
end
end
@attributes
end | [
"def",
"typecast_attributes",
"@attributes",
".",
"each_pair",
"do",
"|",
"name",
",",
"value",
"|",
"next",
"if",
"(",
"name",
"==",
"\"id\"",
")",
"or",
"(",
"!",
"name",
".",
"present?",
")",
"attr_type",
"=",
"attr_type_for",
"(",
"name",
")",
"if",
"[",
":datetime",
",",
":datetimecombo",
",",
":int",
"]",
".",
"include?",
"attr_type",
"&&",
"(",
"value",
".",
"nil?",
"||",
"value",
"==",
"''",
")",
"@attributes",
"[",
"name",
"]",
"=",
"nil",
"next",
"end",
"case",
"attr_type",
"when",
":bool",
"@attributes",
"[",
"name",
"]",
"=",
"(",
"value",
"==",
"\"1\"",
")",
"when",
":datetime",
",",
":datetimecombo",
"begin",
"@attributes",
"[",
"name",
"]",
"=",
"DateTime",
".",
"parse",
"(",
"value",
")",
"rescue",
"@attributes",
"[",
"name",
"]",
"=",
"value",
"end",
"when",
":int",
"@attributes",
"[",
"name",
"]",
"=",
"value",
".",
"to_i",
"end",
"end",
"@attributes",
"end"
]
| Attempts to typecast each attribute based on the module field type | [
"Attempts",
"to",
"typecast",
"each",
"attribute",
"based",
"on",
"the",
"module",
"field",
"type"
]
| 360060139b13788a7ec462c6ecd08d3dbda9849a | https://github.com/chicks/sugarcrm/blob/360060139b13788a7ec462c6ecd08d3dbda9849a/lib/sugarcrm/attributes/attribute_typecast.rb#L16-L43 | train |
kikonen/capybara-ng | lib/angular/setup.rb | Angular.Setup.make_nodes | def make_nodes(ids, opt)
result = []
ids.each do |id|
id = id.tr('"', '')
selector = "//*[@capybara-ng-match='#{id}']"
nodes = page.driver.find_xpath(selector)
raise NotFound.new("Failed to match found id to node") if nodes.empty?
result.concat(nodes)
end
page.evaluate_script("clearCapybaraNgMatches('#{opt[:root_selector]}')");
result
end | ruby | def make_nodes(ids, opt)
result = []
ids.each do |id|
id = id.tr('"', '')
selector = "//*[@capybara-ng-match='#{id}']"
nodes = page.driver.find_xpath(selector)
raise NotFound.new("Failed to match found id to node") if nodes.empty?
result.concat(nodes)
end
page.evaluate_script("clearCapybaraNgMatches('#{opt[:root_selector]}')");
result
end | [
"def",
"make_nodes",
"(",
"ids",
",",
"opt",
")",
"result",
"=",
"[",
"]",
"ids",
".",
"each",
"do",
"|",
"id",
"|",
"id",
"=",
"id",
".",
"tr",
"(",
"'\"'",
",",
"''",
")",
"selector",
"=",
"\"//*[@capybara-ng-match='#{id}']\"",
"nodes",
"=",
"page",
".",
"driver",
".",
"find_xpath",
"(",
"selector",
")",
"raise",
"NotFound",
".",
"new",
"(",
"\"Failed to match found id to node\"",
")",
"if",
"nodes",
".",
"empty?",
"result",
".",
"concat",
"(",
"nodes",
")",
"end",
"page",
".",
"evaluate_script",
"(",
"\"clearCapybaraNgMatches('#{opt[:root_selector]}')\"",
")",
";",
"result",
"end"
]
| Find nodes matching 'capybara-ng-match' attributes using ids
@return nodes matching ids | [
"Find",
"nodes",
"matching",
"capybara",
"-",
"ng",
"-",
"match",
"attributes",
"using",
"ids"
]
| a24bc9570629fe2bb441763803dd8aa0d046d46d | https://github.com/kikonen/capybara-ng/blob/a24bc9570629fe2bb441763803dd8aa0d046d46d/lib/angular/setup.rb#L40-L52 | train |
kikonen/capybara-ng | lib/angular/dsl.rb | Angular.DSL.ng_root_selector | def ng_root_selector(root_selector = nil)
opt = ng.page.ng_session_options
if root_selector
opt[:root_selector] = root_selector
end
opt[:root_selector] || ::Angular.root_selector
end | ruby | def ng_root_selector(root_selector = nil)
opt = ng.page.ng_session_options
if root_selector
opt[:root_selector] = root_selector
end
opt[:root_selector] || ::Angular.root_selector
end | [
"def",
"ng_root_selector",
"(",
"root_selector",
"=",
"nil",
")",
"opt",
"=",
"ng",
".",
"page",
".",
"ng_session_options",
"if",
"root_selector",
"opt",
"[",
":root_selector",
"]",
"=",
"root_selector",
"end",
"opt",
"[",
":root_selector",
"]",
"||",
"::",
"Angular",
".",
"root_selector",
"end"
]
| Get or set selector to find ng-app for current capybara test session
TIP: try using '[ng-app]', which will find ng-app as attribute anywhere.
@param root_selector if nil then return current value without change
@return test specific selector to find ng-app,
by default global ::Angular.root_selector is used. | [
"Get",
"or",
"set",
"selector",
"to",
"find",
"ng",
"-",
"app",
"for",
"current",
"capybara",
"test",
"session"
]
| a24bc9570629fe2bb441763803dd8aa0d046d46d | https://github.com/kikonen/capybara-ng/blob/a24bc9570629fe2bb441763803dd8aa0d046d46d/lib/angular/dsl.rb#L21-L27 | train |
kikonen/capybara-ng | lib/angular/dsl.rb | Angular.DSL.ng_binding | def ng_binding(binding, opt = {})
opt[:root_selector] ||= ng_root_selector
row = ng.row(opt)
ng_bindings(binding, opt)[row]
end | ruby | def ng_binding(binding, opt = {})
opt[:root_selector] ||= ng_root_selector
row = ng.row(opt)
ng_bindings(binding, opt)[row]
end | [
"def",
"ng_binding",
"(",
"binding",
",",
"opt",
"=",
"{",
"}",
")",
"opt",
"[",
":root_selector",
"]",
"||=",
"ng_root_selector",
"row",
"=",
"ng",
".",
"row",
"(",
"opt",
")",
"ng_bindings",
"(",
"binding",
",",
"opt",
")",
"[",
"row",
"]",
"end"
]
| Node for nth binding match
@param opt
- :row
- :exact
- :root_selector
- :wait
@return nth node | [
"Node",
"for",
"nth",
"binding",
"match"
]
| a24bc9570629fe2bb441763803dd8aa0d046d46d | https://github.com/kikonen/capybara-ng/blob/a24bc9570629fe2bb441763803dd8aa0d046d46d/lib/angular/dsl.rb#L114-L118 | train |
kikonen/capybara-ng | lib/angular/dsl.rb | Angular.DSL.ng_bindings | def ng_bindings(binding, opt = {})
opt[:root_selector] ||= ng_root_selector
ng.get_nodes_2 :findBindingsIds, [binding, opt[:exact] == true], opt
end | ruby | def ng_bindings(binding, opt = {})
opt[:root_selector] ||= ng_root_selector
ng.get_nodes_2 :findBindingsIds, [binding, opt[:exact] == true], opt
end | [
"def",
"ng_bindings",
"(",
"binding",
",",
"opt",
"=",
"{",
"}",
")",
"opt",
"[",
":root_selector",
"]",
"||=",
"ng_root_selector",
"ng",
".",
"get_nodes_2",
":findBindingsIds",
",",
"[",
"binding",
",",
"opt",
"[",
":exact",
"]",
"==",
"true",
"]",
",",
"opt",
"end"
]
| All nodes matching binding
@param opt
- :exact
- :root_selector
- :wait
@return [node, ...] | [
"All",
"nodes",
"matching",
"binding"
]
| a24bc9570629fe2bb441763803dd8aa0d046d46d | https://github.com/kikonen/capybara-ng/blob/a24bc9570629fe2bb441763803dd8aa0d046d46d/lib/angular/dsl.rb#L129-L132 | train |
kikonen/capybara-ng | lib/angular/dsl.rb | Angular.DSL.ng_model | def ng_model(model, opt = {})
opt[:root_selector] ||= ng_root_selector
row = ng.row(opt)
ng_models(model, opt)[row]
end | ruby | def ng_model(model, opt = {})
opt[:root_selector] ||= ng_root_selector
row = ng.row(opt)
ng_models(model, opt)[row]
end | [
"def",
"ng_model",
"(",
"model",
",",
"opt",
"=",
"{",
"}",
")",
"opt",
"[",
":root_selector",
"]",
"||=",
"ng_root_selector",
"row",
"=",
"ng",
".",
"row",
"(",
"opt",
")",
"ng_models",
"(",
"model",
",",
"opt",
")",
"[",
"row",
"]",
"end"
]
| Node for nth model match
@param opt
- :row
- :root_selector
- :wait
@return nth node | [
"Node",
"for",
"nth",
"model",
"match"
]
| a24bc9570629fe2bb441763803dd8aa0d046d46d | https://github.com/kikonen/capybara-ng/blob/a24bc9570629fe2bb441763803dd8aa0d046d46d/lib/angular/dsl.rb#L169-L173 | train |
kikonen/capybara-ng | lib/angular/dsl.rb | Angular.DSL.has_ng_options? | def has_ng_options?(options, opt = {})
opt[:root_selector] ||= ng_root_selector
ng_options(options, opt)
true
rescue NotFound
false
end | ruby | def has_ng_options?(options, opt = {})
opt[:root_selector] ||= ng_root_selector
ng_options(options, opt)
true
rescue NotFound
false
end | [
"def",
"has_ng_options?",
"(",
"options",
",",
"opt",
"=",
"{",
"}",
")",
"opt",
"[",
":root_selector",
"]",
"||=",
"ng_root_selector",
"ng_options",
"(",
"options",
",",
"opt",
")",
"true",
"rescue",
"NotFound",
"false",
"end"
]
| Does option exist
@param opt
- :root_selector
- :wait
@return true | false | [
"Does",
"option",
"exist"
]
| a24bc9570629fe2bb441763803dd8aa0d046d46d | https://github.com/kikonen/capybara-ng/blob/a24bc9570629fe2bb441763803dd8aa0d046d46d/lib/angular/dsl.rb#L196-L202 | train |
kikonen/capybara-ng | lib/angular/dsl.rb | Angular.DSL.ng_option | def ng_option(options, opt = {})
opt[:root_selector] ||= ng_root_selector
row = ng.row(opt)
ng_options(options, opt)[row]
end | ruby | def ng_option(options, opt = {})
opt[:root_selector] ||= ng_root_selector
row = ng.row(opt)
ng_options(options, opt)[row]
end | [
"def",
"ng_option",
"(",
"options",
",",
"opt",
"=",
"{",
"}",
")",
"opt",
"[",
":root_selector",
"]",
"||=",
"ng_root_selector",
"row",
"=",
"ng",
".",
"row",
"(",
"opt",
")",
"ng_options",
"(",
"options",
",",
"opt",
")",
"[",
"row",
"]",
"end"
]
| Node for nth option
@param opt
- :row
- :root_selector
- :wait
@return nth node | [
"Node",
"for",
"nth",
"option"
]
| a24bc9570629fe2bb441763803dd8aa0d046d46d | https://github.com/kikonen/capybara-ng/blob/a24bc9570629fe2bb441763803dd8aa0d046d46d/lib/angular/dsl.rb#L225-L229 | train |
kikonen/capybara-ng | lib/angular/dsl.rb | Angular.DSL.ng_repeater_row | def ng_repeater_row(repeater, opt = {})
opt[:root_selector] ||= ng_root_selector
row = ng.row(opt)
data = ng.get_nodes_2(:findRepeaterRowsIds, [repeater, row], opt)
data.first
end | ruby | def ng_repeater_row(repeater, opt = {})
opt[:root_selector] ||= ng_root_selector
row = ng.row(opt)
data = ng.get_nodes_2(:findRepeaterRowsIds, [repeater, row], opt)
data.first
end | [
"def",
"ng_repeater_row",
"(",
"repeater",
",",
"opt",
"=",
"{",
"}",
")",
"opt",
"[",
":root_selector",
"]",
"||=",
"ng_root_selector",
"row",
"=",
"ng",
".",
"row",
"(",
"opt",
")",
"data",
"=",
"ng",
".",
"get_nodes_2",
"(",
":findRepeaterRowsIds",
",",
"[",
"repeater",
",",
"row",
"]",
",",
"opt",
")",
"data",
".",
"first",
"end"
]
| Node for nth repeater row
@param opt
- :row
- :root_selector
- :wait
@return nth node | [
"Node",
"for",
"nth",
"repeater",
"row"
]
| a24bc9570629fe2bb441763803dd8aa0d046d46d | https://github.com/kikonen/capybara-ng/blob/a24bc9570629fe2bb441763803dd8aa0d046d46d/lib/angular/dsl.rb#L280-L285 | train |
kikonen/capybara-ng | lib/angular/dsl.rb | Angular.DSL.ng_repeater_column | def ng_repeater_column(repeater, binding, opt = {})
opt[:root_selector] ||= ng_root_selector
row = ng.row(opt)
ng_repeater_columns(repeater, binding, opt)[row]
end | ruby | def ng_repeater_column(repeater, binding, opt = {})
opt[:root_selector] ||= ng_root_selector
row = ng.row(opt)
ng_repeater_columns(repeater, binding, opt)[row]
end | [
"def",
"ng_repeater_column",
"(",
"repeater",
",",
"binding",
",",
"opt",
"=",
"{",
"}",
")",
"opt",
"[",
":root_selector",
"]",
"||=",
"ng_root_selector",
"row",
"=",
"ng",
".",
"row",
"(",
"opt",
")",
"ng_repeater_columns",
"(",
"repeater",
",",
"binding",
",",
"opt",
")",
"[",
"row",
"]",
"end"
]
| Node for column binding value in row
@param opt
- :row
- :root_selector
- :wait
@return nth node | [
"Node",
"for",
"column",
"binding",
"value",
"in",
"row"
]
| a24bc9570629fe2bb441763803dd8aa0d046d46d | https://github.com/kikonen/capybara-ng/blob/a24bc9570629fe2bb441763803dd8aa0d046d46d/lib/angular/dsl.rb#L309-L313 | train |
kikonen/capybara-ng | lib/angular/dsl.rb | Angular.DSL.ng_repeater_columns | def ng_repeater_columns(repeater, binding, opt = {})
opt[:root_selector] ||= ng_root_selector
ng.get_nodes_2 :findRepeaterColumnIds, [repeater, binding], opt
end | ruby | def ng_repeater_columns(repeater, binding, opt = {})
opt[:root_selector] ||= ng_root_selector
ng.get_nodes_2 :findRepeaterColumnIds, [repeater, binding], opt
end | [
"def",
"ng_repeater_columns",
"(",
"repeater",
",",
"binding",
",",
"opt",
"=",
"{",
"}",
")",
"opt",
"[",
":root_selector",
"]",
"||=",
"ng_root_selector",
"ng",
".",
"get_nodes_2",
":findRepeaterColumnIds",
",",
"[",
"repeater",
",",
"binding",
"]",
",",
"opt",
"end"
]
| Node for column binding value in all rows
@param opt
- :root_selector
- :wait
@return [node, ...] | [
"Node",
"for",
"column",
"binding",
"value",
"in",
"all",
"rows"
]
| a24bc9570629fe2bb441763803dd8aa0d046d46d | https://github.com/kikonen/capybara-ng/blob/a24bc9570629fe2bb441763803dd8aa0d046d46d/lib/angular/dsl.rb#L323-L326 | train |
willglynn/ruby-zbar | lib/zbar/image.rb | ZBar.Image.set_data | def set_data(format, data, width=nil, height=nil)
ZBar.zbar_image_set_format(@img, format)
# Note the @buffer jog: it's to keep Ruby GC from losing the last
# reference to the old @buffer before calling image_set_data.
new_buffer = FFI::MemoryPointer.from_string(data)
ZBar.zbar_image_set_data(@img, new_buffer, data.size, nil)
@buffer = new_buffer
if width && height
ZBar.zbar_image_set_size(@img, width.to_i, height.to_i)
end
end | ruby | def set_data(format, data, width=nil, height=nil)
ZBar.zbar_image_set_format(@img, format)
# Note the @buffer jog: it's to keep Ruby GC from losing the last
# reference to the old @buffer before calling image_set_data.
new_buffer = FFI::MemoryPointer.from_string(data)
ZBar.zbar_image_set_data(@img, new_buffer, data.size, nil)
@buffer = new_buffer
if width && height
ZBar.zbar_image_set_size(@img, width.to_i, height.to_i)
end
end | [
"def",
"set_data",
"(",
"format",
",",
"data",
",",
"width",
"=",
"nil",
",",
"height",
"=",
"nil",
")",
"ZBar",
".",
"zbar_image_set_format",
"(",
"@img",
",",
"format",
")",
"new_buffer",
"=",
"FFI",
"::",
"MemoryPointer",
".",
"from_string",
"(",
"data",
")",
"ZBar",
".",
"zbar_image_set_data",
"(",
"@img",
",",
"new_buffer",
",",
"data",
".",
"size",
",",
"nil",
")",
"@buffer",
"=",
"new_buffer",
"if",
"width",
"&&",
"height",
"ZBar",
".",
"zbar_image_set_size",
"(",
"@img",
",",
"width",
".",
"to_i",
",",
"height",
".",
"to_i",
")",
"end",
"end"
]
| Load arbitrary data from a string into the Image object.
Format must be a ZBar::Format constant. See the ZBar documentation
for what formats are supported, and how the data should be formatted.
Most everyone should use one of the <tt>Image.from_*</tt> methods instead. | [
"Load",
"arbitrary",
"data",
"from",
"a",
"string",
"into",
"the",
"Image",
"object",
"."
]
| 014ce55d4f4a41597bf20f5b1c529c53ecfbfd05 | https://github.com/willglynn/ruby-zbar/blob/014ce55d4f4a41597bf20f5b1c529c53ecfbfd05/lib/zbar/image.rb#L75-L87 | train |
willglynn/ruby-zbar | lib/zbar/image.rb | ZBar.Image.convert | def convert(format)
ptr = ZBar.zbar_image_convert(@img, format)
if ptr.null?
raise ArgumentError, "conversion failed"
else
Image.new(ptr)
end
end | ruby | def convert(format)
ptr = ZBar.zbar_image_convert(@img, format)
if ptr.null?
raise ArgumentError, "conversion failed"
else
Image.new(ptr)
end
end | [
"def",
"convert",
"(",
"format",
")",
"ptr",
"=",
"ZBar",
".",
"zbar_image_convert",
"(",
"@img",
",",
"format",
")",
"if",
"ptr",
".",
"null?",
"raise",
"ArgumentError",
",",
"\"conversion failed\"",
"else",
"Image",
".",
"new",
"(",
"ptr",
")",
"end",
"end"
]
| Ask ZBar to convert this image to a new format, returning a new Image.
Not all conversions are possible: for example, if ZBar was built without
JPEG support, it cannot convert JPEGs into anything else. | [
"Ask",
"ZBar",
"to",
"convert",
"this",
"image",
"to",
"a",
"new",
"format",
"returning",
"a",
"new",
"Image",
"."
]
| 014ce55d4f4a41597bf20f5b1c529c53ecfbfd05 | https://github.com/willglynn/ruby-zbar/blob/014ce55d4f4a41597bf20f5b1c529c53ecfbfd05/lib/zbar/image.rb#L93-L100 | train |
lassebunk/metamagic | lib/metamagic/renderer.rb | Metamagic.Renderer.transform_hash | def transform_hash(hash, path = "")
hash.each_with_object({}) do |(k, v), ret|
key = path + k.to_s
if v.is_a?(Hash)
ret.merge! transform_hash(v, "#{key}:")
else
ret[key] = v
end
end
end | ruby | def transform_hash(hash, path = "")
hash.each_with_object({}) do |(k, v), ret|
key = path + k.to_s
if v.is_a?(Hash)
ret.merge! transform_hash(v, "#{key}:")
else
ret[key] = v
end
end
end | [
"def",
"transform_hash",
"(",
"hash",
",",
"path",
"=",
"\"\"",
")",
"hash",
".",
"each_with_object",
"(",
"{",
"}",
")",
"do",
"|",
"(",
"k",
",",
"v",
")",
",",
"ret",
"|",
"key",
"=",
"path",
"+",
"k",
".",
"to_s",
"if",
"v",
".",
"is_a?",
"(",
"Hash",
")",
"ret",
".",
"merge!",
"transform_hash",
"(",
"v",
",",
"\"#{key}:\"",
")",
"else",
"ret",
"[",
"key",
"]",
"=",
"v",
"end",
"end",
"end"
]
| Transforms a nested hash into meta property keys. | [
"Transforms",
"a",
"nested",
"hash",
"into",
"meta",
"property",
"keys",
"."
]
| daf259d49795485f5c6b27a00586e0217b8f0ce4 | https://github.com/lassebunk/metamagic/blob/daf259d49795485f5c6b27a00586e0217b8f0ce4/lib/metamagic/renderer.rb#L112-L122 | train |
blockchain/api-v1-client-ruby | lib/blockchain/wallet.rb | Blockchain.Wallet.parse_json | def parse_json(response)
json_response = JSON.parse(response)
error = json_response['error']
if !error.nil? then raise APIException.new(error) end
return json_response
end | ruby | def parse_json(response)
json_response = JSON.parse(response)
error = json_response['error']
if !error.nil? then raise APIException.new(error) end
return json_response
end | [
"def",
"parse_json",
"(",
"response",
")",
"json_response",
"=",
"JSON",
".",
"parse",
"(",
"response",
")",
"error",
"=",
"json_response",
"[",
"'error'",
"]",
"if",
"!",
"error",
".",
"nil?",
"then",
"raise",
"APIException",
".",
"new",
"(",
"error",
")",
"end",
"return",
"json_response",
"end"
]
| convenience method that parses a response into json AND makes sure there are no errors | [
"convenience",
"method",
"that",
"parses",
"a",
"response",
"into",
"json",
"AND",
"makes",
"sure",
"there",
"are",
"no",
"errors"
]
| 85423b2e20bbe6928019f6441968eacdf7ca7f81 | https://github.com/blockchain/api-v1-client-ruby/blob/85423b2e20bbe6928019f6441968eacdf7ca7f81/lib/blockchain/wallet.rb#L123-L128 | train |
ruby-numo/numo-gnuplot | lib/numo/gnuplot.rb | Numo.Gnuplot.stats | def stats(filename,*args)
fn = OptArg.quote(filename)
opt = OptArg.parse(*args)
puts send_cmd "stats #{fn} #{opt}"
end | ruby | def stats(filename,*args)
fn = OptArg.quote(filename)
opt = OptArg.parse(*args)
puts send_cmd "stats #{fn} #{opt}"
end | [
"def",
"stats",
"(",
"filename",
",",
"*",
"args",
")",
"fn",
"=",
"OptArg",
".",
"quote",
"(",
"filename",
")",
"opt",
"=",
"OptArg",
".",
"parse",
"(",
"*",
"args",
")",
"puts",
"send_cmd",
"\"stats #{fn} #{opt}\"",
"end"
]
| This command prepares a statistical summary of the data in one or
two columns of a file. | [
"This",
"command",
"prepares",
"a",
"statistical",
"summary",
"of",
"the",
"data",
"in",
"one",
"or",
"two",
"columns",
"of",
"a",
"file",
"."
]
| 1f555ab430a1be9944002108895fabdd26942ead | https://github.com/ruby-numo/numo-gnuplot/blob/1f555ab430a1be9944002108895fabdd26942ead/lib/numo/gnuplot.rb#L135-L139 | train |
29decibel/html2markdown | lib/html2markdown/converter.rb | HTML2Markdown.Converter.parse_element | def parse_element(ele)
if ele.is_a? Nokogiri::XML::Text
return "#{ele.text}\n"
else
if (children = ele.children).count > 0
return wrap_node(ele,children.map {|ele| parse_element(ele)}.join )
else
return wrap_node(ele,ele.text)
end
end
end | ruby | def parse_element(ele)
if ele.is_a? Nokogiri::XML::Text
return "#{ele.text}\n"
else
if (children = ele.children).count > 0
return wrap_node(ele,children.map {|ele| parse_element(ele)}.join )
else
return wrap_node(ele,ele.text)
end
end
end | [
"def",
"parse_element",
"(",
"ele",
")",
"if",
"ele",
".",
"is_a?",
"Nokogiri",
"::",
"XML",
"::",
"Text",
"return",
"\"#{ele.text}\\n\"",
"else",
"if",
"(",
"children",
"=",
"ele",
".",
"children",
")",
".",
"count",
">",
"0",
"return",
"wrap_node",
"(",
"ele",
",",
"children",
".",
"map",
"{",
"|",
"ele",
"|",
"parse_element",
"(",
"ele",
")",
"}",
".",
"join",
")",
"else",
"return",
"wrap_node",
"(",
"ele",
",",
"ele",
".",
"text",
")",
"end",
"end",
"end"
]
| a normal element
maybe text
maybe node | [
"a",
"normal",
"element",
"maybe",
"text",
"maybe",
"node"
]
| 26c6a539a2e0540b349bd21c006d285196d5e54f | https://github.com/29decibel/html2markdown/blob/26c6a539a2e0540b349bd21c006d285196d5e54f/lib/html2markdown/converter.rb#L16-L26 | train |
29decibel/html2markdown | lib/html2markdown/converter.rb | HTML2Markdown.Converter.wrap_node | def wrap_node(node,contents=nil)
result = ''
contents.strip! unless contents==nil
# check if there is a custom parse exist
if respond_to? "parse_#{node.name}"
return self.send("parse_#{node.name}",node,contents)
end
# skip hidden node
return '' if node['style'] and node['style'] =~ /display:\s*none/
# default parse
case node.name.downcase
when 'i'
when 'script'
when 'style'
when 'li'
result << "* #{contents}\n"
when 'blockquote'
contents.split('\n').each do |part|
result << ">#{contents}\n"
end
when 'p'
result << "\n#{contents}\n"
when 'strong'
result << "**#{contents}**\n"
when 'h1'
result << "# #{contents}\n"
when 'h2'
result << "## #{contents}\n"
when 'h3'
result << "### #{contents}\n"
when 'h4'
result << "#### #{contents}\n"
when 'h5'
result << "##### #{contents}\n"
when 'h6'
result << "###### #{contents}\n"
when 'hr'
result << "****\n"
when 'br'
result << "\n"
when 'img'
result << "![#{node['alt']}](#{node['src']})"
when 'a'
result << "[#{contents}](#{node['href']})"
else
result << contents unless contents == nil
end
result
end | ruby | def wrap_node(node,contents=nil)
result = ''
contents.strip! unless contents==nil
# check if there is a custom parse exist
if respond_to? "parse_#{node.name}"
return self.send("parse_#{node.name}",node,contents)
end
# skip hidden node
return '' if node['style'] and node['style'] =~ /display:\s*none/
# default parse
case node.name.downcase
when 'i'
when 'script'
when 'style'
when 'li'
result << "* #{contents}\n"
when 'blockquote'
contents.split('\n').each do |part|
result << ">#{contents}\n"
end
when 'p'
result << "\n#{contents}\n"
when 'strong'
result << "**#{contents}**\n"
when 'h1'
result << "# #{contents}\n"
when 'h2'
result << "## #{contents}\n"
when 'h3'
result << "### #{contents}\n"
when 'h4'
result << "#### #{contents}\n"
when 'h5'
result << "##### #{contents}\n"
when 'h6'
result << "###### #{contents}\n"
when 'hr'
result << "****\n"
when 'br'
result << "\n"
when 'img'
result << "![#{node['alt']}](#{node['src']})"
when 'a'
result << "[#{contents}](#{node['href']})"
else
result << contents unless contents == nil
end
result
end | [
"def",
"wrap_node",
"(",
"node",
",",
"contents",
"=",
"nil",
")",
"result",
"=",
"''",
"contents",
".",
"strip!",
"unless",
"contents",
"==",
"nil",
"if",
"respond_to?",
"\"parse_#{node.name}\"",
"return",
"self",
".",
"send",
"(",
"\"parse_#{node.name}\"",
",",
"node",
",",
"contents",
")",
"end",
"return",
"''",
"if",
"node",
"[",
"'style'",
"]",
"and",
"node",
"[",
"'style'",
"]",
"=~",
"/",
"\\s",
"/",
"case",
"node",
".",
"name",
".",
"downcase",
"when",
"'i'",
"when",
"'script'",
"when",
"'style'",
"when",
"'li'",
"result",
"<<",
"\"* #{contents}\\n\"",
"when",
"'blockquote'",
"contents",
".",
"split",
"(",
"'\\n'",
")",
".",
"each",
"do",
"|",
"part",
"|",
"result",
"<<",
"\">#{contents}\\n\"",
"end",
"when",
"'p'",
"result",
"<<",
"\"\\n#{contents}\\n\"",
"when",
"'strong'",
"result",
"<<",
"\"**#{contents}**\\n\"",
"when",
"'h1'",
"result",
"<<",
"\"# #{contents}\\n\"",
"when",
"'h2'",
"result",
"<<",
"\"## #{contents}\\n\"",
"when",
"'h3'",
"result",
"<<",
"\"### #{contents}\\n\"",
"when",
"'h4'",
"result",
"<<",
"\"#### #{contents}\\n\"",
"when",
"'h5'",
"result",
"<<",
"\"##### #{contents}\\n\"",
"when",
"'h6'",
"result",
"<<",
"\"###### #{contents}\\n\"",
"when",
"'hr'",
"result",
"<<",
"\"****\\n\"",
"when",
"'br'",
"result",
"<<",
"\"\\n\"",
"when",
"'img'",
"result",
"<<",
"\"![#{node['alt']}](#{node['src']})\"",
"when",
"'a'",
"result",
"<<",
"\"[#{contents}](#{node['href']})\"",
"else",
"result",
"<<",
"contents",
"unless",
"contents",
"==",
"nil",
"end",
"result",
"end"
]
| wrap node with markdown | [
"wrap",
"node",
"with",
"markdown"
]
| 26c6a539a2e0540b349bd21c006d285196d5e54f | https://github.com/29decibel/html2markdown/blob/26c6a539a2e0540b349bd21c006d285196d5e54f/lib/html2markdown/converter.rb#L29-L77 | train |
29decibel/html2markdown | lib/html2markdown/converter.rb | HTML2Markdown.Converter.method_missing | def method_missing(name,*args,&block)
self.class.send :define_method,"parse_#{name}" do |node,contents|
block.call node,contents
end
end | ruby | def method_missing(name,*args,&block)
self.class.send :define_method,"parse_#{name}" do |node,contents|
block.call node,contents
end
end | [
"def",
"method_missing",
"(",
"name",
",",
"*",
"args",
",",
"&",
"block",
")",
"self",
".",
"class",
".",
"send",
":define_method",
",",
"\"parse_#{name}\"",
"do",
"|",
"node",
",",
"contents",
"|",
"block",
".",
"call",
"node",
",",
"contents",
"end",
"end"
]
| define custom node processor | [
"define",
"custom",
"node",
"processor"
]
| 26c6a539a2e0540b349bd21c006d285196d5e54f | https://github.com/29decibel/html2markdown/blob/26c6a539a2e0540b349bd21c006d285196d5e54f/lib/html2markdown/converter.rb#L80-L84 | train |
jirutka/asciidoctor-rouge | lib/asciidoctor/rouge/callouts_substitutor.rb | Asciidoctor::Rouge.CalloutsSubstitutor.convert_line | def convert_line(line_num)
return '' unless @callouts.key? line_num
@callouts[line_num]
.map { |num| convert_callout(num) }
.join(' ')
end | ruby | def convert_line(line_num)
return '' unless @callouts.key? line_num
@callouts[line_num]
.map { |num| convert_callout(num) }
.join(' ')
end | [
"def",
"convert_line",
"(",
"line_num",
")",
"return",
"''",
"unless",
"@callouts",
".",
"key?",
"line_num",
"@callouts",
"[",
"line_num",
"]",
".",
"map",
"{",
"|",
"num",
"|",
"convert_callout",
"(",
"num",
")",
"}",
".",
"join",
"(",
"' '",
")",
"end"
]
| Converts the extracted callout markers for the specified line.
@param line_num [Integer] the line number (1-based).
@return [String] converted callout markers for the _line_num_,
or an empty string if there are no callouts for that line. | [
"Converts",
"the",
"extracted",
"callout",
"markers",
"for",
"the",
"specified",
"line",
"."
]
| f01387cb4278c26ede3c81c2b3aa9bca9e950fd9 | https://github.com/jirutka/asciidoctor-rouge/blob/f01387cb4278c26ede3c81c2b3aa9bca9e950fd9/lib/asciidoctor/rouge/callouts_substitutor.rb#L51-L57 | train |
jirutka/asciidoctor-rouge | lib/asciidoctor/rouge/html_formatter.rb | Asciidoctor::Rouge.HtmlFormatter.stream_lines | def stream_lines(tokens, line_num)
yield line_start(line_num)
tokens.each do |token, value|
yield @inner.span(token, value)
end
yield line_end(line_num)
end | ruby | def stream_lines(tokens, line_num)
yield line_start(line_num)
tokens.each do |token, value|
yield @inner.span(token, value)
end
yield line_end(line_num)
end | [
"def",
"stream_lines",
"(",
"tokens",
",",
"line_num",
")",
"yield",
"line_start",
"(",
"line_num",
")",
"tokens",
".",
"each",
"do",
"|",
"token",
",",
"value",
"|",
"yield",
"@inner",
".",
"span",
"(",
"token",
",",
"value",
")",
"end",
"yield",
"line_end",
"(",
"line_num",
")",
"end"
]
| Formats tokens on the specified line into HTML.
@param tokens [Array<Rouge::Token>] tokens on the line.
@param line_nums [Integer] the line number (1-based).
@yield [String] gives formatted content. | [
"Formats",
"tokens",
"on",
"the",
"specified",
"line",
"into",
"HTML",
"."
]
| f01387cb4278c26ede3c81c2b3aa9bca9e950fd9 | https://github.com/jirutka/asciidoctor-rouge/blob/f01387cb4278c26ede3c81c2b3aa9bca9e950fd9/lib/asciidoctor/rouge/html_formatter.rb#L71-L79 | train |
aptinio/text-table | lib/text-table/table.rb | Text.Table.to_s | def to_s
rendered_rows = [separator] + text_table_rows.map(&:to_s) + [separator]
rendered_rows.unshift [separator, text_table_head.to_s] if head
rendered_rows << [text_table_foot.to_s, separator] if foot
rendered_rows.join
end | ruby | def to_s
rendered_rows = [separator] + text_table_rows.map(&:to_s) + [separator]
rendered_rows.unshift [separator, text_table_head.to_s] if head
rendered_rows << [text_table_foot.to_s, separator] if foot
rendered_rows.join
end | [
"def",
"to_s",
"rendered_rows",
"=",
"[",
"separator",
"]",
"+",
"text_table_rows",
".",
"map",
"(",
"&",
":to_s",
")",
"+",
"[",
"separator",
"]",
"rendered_rows",
".",
"unshift",
"[",
"separator",
",",
"text_table_head",
".",
"to_s",
"]",
"if",
"head",
"rendered_rows",
"<<",
"[",
"text_table_foot",
".",
"to_s",
",",
"separator",
"]",
"if",
"foot",
"rendered_rows",
".",
"join",
"end"
]
| Renders a pretty plain-text table. | [
"Renders",
"a",
"pretty",
"plain",
"-",
"text",
"table",
"."
]
| 42b0f78f8771d4649a7d7b959bce221656eeac58 | https://github.com/aptinio/text-table/blob/42b0f78f8771d4649a7d7b959bce221656eeac58/lib/text-table/table.rb#L168-L173 | train |
aptinio/text-table | lib/text-table/table.rb | Text.Table.align_column | def align_column(column_number, alignment)
set_alignment = Proc.new do |row, column_number_block, alignment_block|
cell = row.find do |cell_row|
row[0...row.index(cell_row)].map {|c| c.is_a?(Hash) ? c[:colspan] || 1 : 1}.inject(0, &:+) == column_number_block - 1
end
row[row.index(cell)] = hashify(cell, {:align => alignment_block}) if cell and not(cell.is_a?(Hash) && cell[:colspan].to_i > 0)
end
rows.each do |row|
next if row == :separator
set_alignment.call(row, column_number, alignment)
end
set_alignment.call(foot, column_number, alignment) if foot
return self
end | ruby | def align_column(column_number, alignment)
set_alignment = Proc.new do |row, column_number_block, alignment_block|
cell = row.find do |cell_row|
row[0...row.index(cell_row)].map {|c| c.is_a?(Hash) ? c[:colspan] || 1 : 1}.inject(0, &:+) == column_number_block - 1
end
row[row.index(cell)] = hashify(cell, {:align => alignment_block}) if cell and not(cell.is_a?(Hash) && cell[:colspan].to_i > 0)
end
rows.each do |row|
next if row == :separator
set_alignment.call(row, column_number, alignment)
end
set_alignment.call(foot, column_number, alignment) if foot
return self
end | [
"def",
"align_column",
"(",
"column_number",
",",
"alignment",
")",
"set_alignment",
"=",
"Proc",
".",
"new",
"do",
"|",
"row",
",",
"column_number_block",
",",
"alignment_block",
"|",
"cell",
"=",
"row",
".",
"find",
"do",
"|",
"cell_row",
"|",
"row",
"[",
"0",
"...",
"row",
".",
"index",
"(",
"cell_row",
")",
"]",
".",
"map",
"{",
"|",
"c",
"|",
"c",
".",
"is_a?",
"(",
"Hash",
")",
"?",
"c",
"[",
":colspan",
"]",
"||",
"1",
":",
"1",
"}",
".",
"inject",
"(",
"0",
",",
"&",
":+",
")",
"==",
"column_number_block",
"-",
"1",
"end",
"row",
"[",
"row",
".",
"index",
"(",
"cell",
")",
"]",
"=",
"hashify",
"(",
"cell",
",",
"{",
":align",
"=>",
"alignment_block",
"}",
")",
"if",
"cell",
"and",
"not",
"(",
"cell",
".",
"is_a?",
"(",
"Hash",
")",
"&&",
"cell",
"[",
":colspan",
"]",
".",
"to_i",
">",
"0",
")",
"end",
"rows",
".",
"each",
"do",
"|",
"row",
"|",
"next",
"if",
"row",
"==",
":separator",
"set_alignment",
".",
"call",
"(",
"row",
",",
"column_number",
",",
"alignment",
")",
"end",
"set_alignment",
".",
"call",
"(",
"foot",
",",
"column_number",
",",
"alignment",
")",
"if",
"foot",
"return",
"self",
"end"
]
| Aligns the cells and the footer of a column.
table = Text::Table.new :rows => [%w(a bb), %w(aa bbb), %w(aaa b)]
puts table
# +-----+-----+
# | a | bb |
# | aa | bbb |
# | aaa | b |
# +-----+-----+
table.align_column 2, :right
# +-----+-----+
# | a | bb |
# | aa | bbb |
# | aaa | b |
# +-----+-----+
Note that headers, spanned cells and cells with explicit alignments are not affected by <tt>align_column</tt>. | [
"Aligns",
"the",
"cells",
"and",
"the",
"footer",
"of",
"a",
"column",
"."
]
| 42b0f78f8771d4649a7d7b959bce221656eeac58 | https://github.com/aptinio/text-table/blob/42b0f78f8771d4649a7d7b959bce221656eeac58/lib/text-table/table.rb#L196-L209 | train |
jirutka/asciidoctor-rouge | lib/asciidoctor/rouge/passthroughs_substitutor.rb | Asciidoctor::Rouge.PassthroughsSubstitutor.restore | def restore(text)
return text if @node.passthroughs.empty?
# Fix passthrough placeholders that got caught up in syntax highlighting.
text = text.gsub(PASS_SLOT_RX, "#{PASS_START_MARK}\\1#{PASS_END_MARK}")
# Restore converted passthroughs.
@node.restore_passthroughs(text)
end | ruby | def restore(text)
return text if @node.passthroughs.empty?
# Fix passthrough placeholders that got caught up in syntax highlighting.
text = text.gsub(PASS_SLOT_RX, "#{PASS_START_MARK}\\1#{PASS_END_MARK}")
# Restore converted passthroughs.
@node.restore_passthroughs(text)
end | [
"def",
"restore",
"(",
"text",
")",
"return",
"text",
"if",
"@node",
".",
"passthroughs",
".",
"empty?",
"text",
"=",
"text",
".",
"gsub",
"(",
"PASS_SLOT_RX",
",",
"\"#{PASS_START_MARK}\\\\1#{PASS_END_MARK}\"",
")",
"@node",
".",
"restore_passthroughs",
"(",
"text",
")",
"end"
]
| Restores the extracted passthroughs by reinserting them into the
placeholder positions.
@param text [String] the text into which to restore the passthroughs.
@return [String] a copy of the *text* with restored passthroughs. | [
"Restores",
"the",
"extracted",
"passthroughs",
"by",
"reinserting",
"them",
"into",
"the",
"placeholder",
"positions",
"."
]
| f01387cb4278c26ede3c81c2b3aa9bca9e950fd9 | https://github.com/jirutka/asciidoctor-rouge/blob/f01387cb4278c26ede3c81c2b3aa9bca9e950fd9/lib/asciidoctor/rouge/passthroughs_substitutor.rb#L36-L44 | train |
voormedia/crafty | lib/crafty/tools.rb | Crafty.Tools.element! | def element!(name, content = nil, attributes = nil)
build! do
if content or block_given?
@_crafted << "<#{name}#{Tools.format_attributes(attributes)}>"
if block_given?
value = yield
content = value if !@_appended or value.kind_of? String
end
content = content.to_s
@_crafted << Tools.escape(content) if content != ""
@_crafted << "</#{name}>"
else
@_crafted << "<#{name}#{Tools.format_attributes(attributes)}/>"
end
end
end | ruby | def element!(name, content = nil, attributes = nil)
build! do
if content or block_given?
@_crafted << "<#{name}#{Tools.format_attributes(attributes)}>"
if block_given?
value = yield
content = value if !@_appended or value.kind_of? String
end
content = content.to_s
@_crafted << Tools.escape(content) if content != ""
@_crafted << "</#{name}>"
else
@_crafted << "<#{name}#{Tools.format_attributes(attributes)}/>"
end
end
end | [
"def",
"element!",
"(",
"name",
",",
"content",
"=",
"nil",
",",
"attributes",
"=",
"nil",
")",
"build!",
"do",
"if",
"content",
"or",
"block_given?",
"@_crafted",
"<<",
"\"<#{name}#{Tools.format_attributes(attributes)}>\"",
"if",
"block_given?",
"value",
"=",
"yield",
"content",
"=",
"value",
"if",
"!",
"@_appended",
"or",
"value",
".",
"kind_of?",
"String",
"end",
"content",
"=",
"content",
".",
"to_s",
"@_crafted",
"<<",
"Tools",
".",
"escape",
"(",
"content",
")",
"if",
"content",
"!=",
"\"\"",
"@_crafted",
"<<",
"\"</#{name}>\"",
"else",
"@_crafted",
"<<",
"\"<#{name}#{Tools.format_attributes(attributes)}/>\"",
"end",
"end",
"end"
]
| Write an element with the given name, content and attributes. If
there is no content and no block is given, a self-closing element is
created. Provide an empty string as content to create an empty,
non-self-closing element. | [
"Write",
"an",
"element",
"with",
"the",
"given",
"name",
"content",
"and",
"attributes",
".",
"If",
"there",
"is",
"no",
"content",
"and",
"no",
"block",
"is",
"given",
"a",
"self",
"-",
"closing",
"element",
"is",
"created",
".",
"Provide",
"an",
"empty",
"string",
"as",
"content",
"to",
"create",
"an",
"empty",
"non",
"-",
"self",
"-",
"closing",
"element",
"."
]
| fe2fcaee92f72f614ff2af2e9ba62175aabbb5bd | https://github.com/voormedia/crafty/blob/fe2fcaee92f72f614ff2af2e9ba62175aabbb5bd/lib/crafty/tools.rb#L54-L69 | train |
mindset/scorm | lib/scorm/package.rb | Scorm.Package.extract! | def extract!(force = false)
return if @options[:dry_run] && !force
# If opening an already extracted package; do nothing.
if not package?
return
end
# Create the path to the course
FileUtils.mkdir_p(@path)
Zip::ZipFile::foreach(@package) do |entry|
entry_path = File.join(@path, entry.name)
entry_dir = File.dirname(entry_path)
FileUtils.mkdir_p(entry_dir) unless File.exists?(entry_dir)
entry.extract(entry_path)
end
end | ruby | def extract!(force = false)
return if @options[:dry_run] && !force
# If opening an already extracted package; do nothing.
if not package?
return
end
# Create the path to the course
FileUtils.mkdir_p(@path)
Zip::ZipFile::foreach(@package) do |entry|
entry_path = File.join(@path, entry.name)
entry_dir = File.dirname(entry_path)
FileUtils.mkdir_p(entry_dir) unless File.exists?(entry_dir)
entry.extract(entry_path)
end
end | [
"def",
"extract!",
"(",
"force",
"=",
"false",
")",
"return",
"if",
"@options",
"[",
":dry_run",
"]",
"&&",
"!",
"force",
"if",
"not",
"package?",
"return",
"end",
"FileUtils",
".",
"mkdir_p",
"(",
"@path",
")",
"Zip",
"::",
"ZipFile",
"::",
"foreach",
"(",
"@package",
")",
"do",
"|",
"entry",
"|",
"entry_path",
"=",
"File",
".",
"join",
"(",
"@path",
",",
"entry",
".",
"name",
")",
"entry_dir",
"=",
"File",
".",
"dirname",
"(",
"entry_path",
")",
"FileUtils",
".",
"mkdir_p",
"(",
"entry_dir",
")",
"unless",
"File",
".",
"exists?",
"(",
"entry_dir",
")",
"entry",
".",
"extract",
"(",
"entry_path",
")",
"end",
"end"
]
| Extracts the content of the package to the course repository. This will be
done automatically when opening a package so this method will rarely be
used. If the +dry_run+ option was set to +true+ when the package was
opened nothing will happen. This behavior can be overridden with the
+force+ parameter. | [
"Extracts",
"the",
"content",
"of",
"the",
"package",
"to",
"the",
"course",
"repository",
".",
"This",
"will",
"be",
"done",
"automatically",
"when",
"opening",
"a",
"package",
"so",
"this",
"method",
"will",
"rarely",
"be",
"used",
".",
"If",
"the",
"+",
"dry_run",
"+",
"option",
"was",
"set",
"to",
"+",
"true",
"+",
"when",
"the",
"package",
"was",
"opened",
"nothing",
"will",
"happen",
".",
"This",
"behavior",
"can",
"be",
"overridden",
"with",
"the",
"+",
"force",
"+",
"parameter",
"."
]
| b1cb060c1e38d215231bb50829e9cc686c2b5710 | https://github.com/mindset/scorm/blob/b1cb060c1e38d215231bb50829e9cc686c2b5710/lib/scorm/package.rb#L123-L140 | train |
mindset/scorm | lib/scorm/package.rb | Scorm.Package.path_to | def path_to(relative_filename, relative = false)
if relative
File.join(@name, relative_filename)
else
File.join(@path, relative_filename)
end
end | ruby | def path_to(relative_filename, relative = false)
if relative
File.join(@name, relative_filename)
else
File.join(@path, relative_filename)
end
end | [
"def",
"path_to",
"(",
"relative_filename",
",",
"relative",
"=",
"false",
")",
"if",
"relative",
"File",
".",
"join",
"(",
"@name",
",",
"relative_filename",
")",
"else",
"File",
".",
"join",
"(",
"@path",
",",
"relative_filename",
")",
"end",
"end"
]
| Computes the absolute path to a file in an extracted package given its
relative path. The argument +relative+ can be used to get the path
relative to the course repository.
Ex.
<tt>pkg.path => '/var/lms/courses/MyCourse/'</tt>
<tt>pkg.course_repository => '/var/lms/courses/'</tt>
<tt>path_to('images/myimg.jpg') => '/var/lms/courses/MyCourse/images/myimg.jpg'</tt>
<tt>path_to('images/myimg.jpg', true) => 'MyCourse/images/myimg.jpg'</tt> | [
"Computes",
"the",
"absolute",
"path",
"to",
"a",
"file",
"in",
"an",
"extracted",
"package",
"given",
"its",
"relative",
"path",
".",
"The",
"argument",
"+",
"relative",
"+",
"can",
"be",
"used",
"to",
"get",
"the",
"path",
"relative",
"to",
"the",
"course",
"repository",
"."
]
| b1cb060c1e38d215231bb50829e9cc686c2b5710 | https://github.com/mindset/scorm/blob/b1cb060c1e38d215231bb50829e9cc686c2b5710/lib/scorm/package.rb#L186-L192 | train |
notonthehighstreet/svelte | lib/svelte/swagger_builder.rb | Svelte.SwaggerBuilder.make_resource | def make_resource
resource = Module.new
paths.each do |path|
new_module = PathBuilder.build(path: path, module_constant: resource)
path.operations.each do |operation|
OperationBuilder.build(operation: operation,
module_constant: new_module,
configuration: configuration)
end
end
Service.const_set(module_name, resource)
end | ruby | def make_resource
resource = Module.new
paths.each do |path|
new_module = PathBuilder.build(path: path, module_constant: resource)
path.operations.each do |operation|
OperationBuilder.build(operation: operation,
module_constant: new_module,
configuration: configuration)
end
end
Service.const_set(module_name, resource)
end | [
"def",
"make_resource",
"resource",
"=",
"Module",
".",
"new",
"paths",
".",
"each",
"do",
"|",
"path",
"|",
"new_module",
"=",
"PathBuilder",
".",
"build",
"(",
"path",
":",
"path",
",",
"module_constant",
":",
"resource",
")",
"path",
".",
"operations",
".",
"each",
"do",
"|",
"operation",
"|",
"OperationBuilder",
".",
"build",
"(",
"operation",
":",
"operation",
",",
"module_constant",
":",
"new_module",
",",
"configuration",
":",
"configuration",
")",
"end",
"end",
"Service",
".",
"const_set",
"(",
"module_name",
",",
"resource",
")",
"end"
]
| Creates a new SwaggerBuilder
@param raw_hash [Hash] Swagger API definition
@param module_name [String] name of the constant you want built
@param options [Hash] Swagger API options. It will be used to build the
[Configuration]. Supports the `:host` value for now.
Dynamically creates a new resource on top of `Svelte::Service` with the
name `module_name`, based on the Swagger API description provided
in `raw_hash`
@return [Module] the module built | [
"Creates",
"a",
"new",
"SwaggerBuilder"
]
| 75abb1a8d65372c7df27bfa1921e55efe48839ac | https://github.com/notonthehighstreet/svelte/blob/75abb1a8d65372c7df27bfa1921e55efe48839ac/lib/svelte/swagger_builder.rb#L22-L33 | train |
notonthehighstreet/svelte | lib/svelte/model_factory.rb | Svelte.ModelFactory.define_models | def define_models(json)
return unless json
models = {}
model_definitions = json['definitions']
model_definitions.each do |model_name, parameters|
attributes = parameters['properties'].keys
model = Class.new do
attr_reader(*attributes.map(&:to_sym))
parameters['properties'].each do |attribute, options|
define_method("#{attribute}=", lambda do |value|
if public_send(attribute).nil? || !public_send(attribute).present?
permitted_values = options.fetch('enum', [])
required = parameters.fetch('required', []).include?(attribute)
instance_variable_set(
"@#{attribute}",
Parameter.new(options['type'],
permitted_values: permitted_values,
required: required)
)
end
instance_variable_get("@#{attribute}").value = value
end)
end
end
define_initialize_on(model: model)
define_attributes_on(model: model)
define_required_attributes_on(model: model)
define_json_for_model_on(model: model)
define_nested_models_on(model: model)
define_as_json_on(model: model)
define_to_json_on(model: model)
define_validate_on(model: model)
define_valid_on(model: model)
model.instance_variable_set('@json_for_model', parameters.freeze)
constant_name_for_model = StringManipulator.constant_name_for(model_name)
models[constant_name_for_model] = model
end
models.each do |model_name, model|
const_set(model_name, model)
end
end | ruby | def define_models(json)
return unless json
models = {}
model_definitions = json['definitions']
model_definitions.each do |model_name, parameters|
attributes = parameters['properties'].keys
model = Class.new do
attr_reader(*attributes.map(&:to_sym))
parameters['properties'].each do |attribute, options|
define_method("#{attribute}=", lambda do |value|
if public_send(attribute).nil? || !public_send(attribute).present?
permitted_values = options.fetch('enum', [])
required = parameters.fetch('required', []).include?(attribute)
instance_variable_set(
"@#{attribute}",
Parameter.new(options['type'],
permitted_values: permitted_values,
required: required)
)
end
instance_variable_get("@#{attribute}").value = value
end)
end
end
define_initialize_on(model: model)
define_attributes_on(model: model)
define_required_attributes_on(model: model)
define_json_for_model_on(model: model)
define_nested_models_on(model: model)
define_as_json_on(model: model)
define_to_json_on(model: model)
define_validate_on(model: model)
define_valid_on(model: model)
model.instance_variable_set('@json_for_model', parameters.freeze)
constant_name_for_model = StringManipulator.constant_name_for(model_name)
models[constant_name_for_model] = model
end
models.each do |model_name, model|
const_set(model_name, model)
end
end | [
"def",
"define_models",
"(",
"json",
")",
"return",
"unless",
"json",
"models",
"=",
"{",
"}",
"model_definitions",
"=",
"json",
"[",
"'definitions'",
"]",
"model_definitions",
".",
"each",
"do",
"|",
"model_name",
",",
"parameters",
"|",
"attributes",
"=",
"parameters",
"[",
"'properties'",
"]",
".",
"keys",
"model",
"=",
"Class",
".",
"new",
"do",
"attr_reader",
"(",
"*",
"attributes",
".",
"map",
"(",
"&",
":to_sym",
")",
")",
"parameters",
"[",
"'properties'",
"]",
".",
"each",
"do",
"|",
"attribute",
",",
"options",
"|",
"define_method",
"(",
"\"#{attribute}=\"",
",",
"lambda",
"do",
"|",
"value",
"|",
"if",
"public_send",
"(",
"attribute",
")",
".",
"nil?",
"||",
"!",
"public_send",
"(",
"attribute",
")",
".",
"present?",
"permitted_values",
"=",
"options",
".",
"fetch",
"(",
"'enum'",
",",
"[",
"]",
")",
"required",
"=",
"parameters",
".",
"fetch",
"(",
"'required'",
",",
"[",
"]",
")",
".",
"include?",
"(",
"attribute",
")",
"instance_variable_set",
"(",
"\"@#{attribute}\"",
",",
"Parameter",
".",
"new",
"(",
"options",
"[",
"'type'",
"]",
",",
"permitted_values",
":",
"permitted_values",
",",
"required",
":",
"required",
")",
")",
"end",
"instance_variable_get",
"(",
"\"@#{attribute}\"",
")",
".",
"value",
"=",
"value",
"end",
")",
"end",
"end",
"define_initialize_on",
"(",
"model",
":",
"model",
")",
"define_attributes_on",
"(",
"model",
":",
"model",
")",
"define_required_attributes_on",
"(",
"model",
":",
"model",
")",
"define_json_for_model_on",
"(",
"model",
":",
"model",
")",
"define_nested_models_on",
"(",
"model",
":",
"model",
")",
"define_as_json_on",
"(",
"model",
":",
"model",
")",
"define_to_json_on",
"(",
"model",
":",
"model",
")",
"define_validate_on",
"(",
"model",
":",
"model",
")",
"define_valid_on",
"(",
"model",
":",
"model",
")",
"model",
".",
"instance_variable_set",
"(",
"'@json_for_model'",
",",
"parameters",
".",
"freeze",
")",
"constant_name_for_model",
"=",
"StringManipulator",
".",
"constant_name_for",
"(",
"model_name",
")",
"models",
"[",
"constant_name_for_model",
"]",
"=",
"model",
"end",
"models",
".",
"each",
"do",
"|",
"model_name",
",",
"model",
"|",
"const_set",
"(",
"model_name",
",",
"model",
")",
"end",
"end"
]
| Creates typed Ruby objects from JSON definitions. These definitions are
found in the Swagger JSON spec as a top-level key, "definitions".
@param json [Hash] hash of a swagger models definition
@return [Hash] A hash of model names to models created | [
"Creates",
"typed",
"Ruby",
"objects",
"from",
"JSON",
"definitions",
".",
"These",
"definitions",
"are",
"found",
"in",
"the",
"Swagger",
"JSON",
"spec",
"as",
"a",
"top",
"-",
"level",
"key",
"definitions",
"."
]
| 75abb1a8d65372c7df27bfa1921e55efe48839ac | https://github.com/notonthehighstreet/svelte/blob/75abb1a8d65372c7df27bfa1921e55efe48839ac/lib/svelte/model_factory.rb#L12-L58 | train |
zigotto/googl | lib/googl.rb | Googl.OAuth2.server | def server(client_id, client_secret, redirect_uri)
Googl::OAuth2::Server.new(client_id, client_secret, redirect_uri)
end | ruby | def server(client_id, client_secret, redirect_uri)
Googl::OAuth2::Server.new(client_id, client_secret, redirect_uri)
end | [
"def",
"server",
"(",
"client_id",
",",
"client_secret",
",",
"redirect_uri",
")",
"Googl",
"::",
"OAuth2",
"::",
"Server",
".",
"new",
"(",
"client_id",
",",
"client_secret",
",",
"redirect_uri",
")",
"end"
]
| OAuth 2.0 for server-side web applications
The server-side flow for web applications with servers that can securely store persistent information
client = Googl::OAuth2.server("client_id", "client_secret", "redirect_uri") | [
"OAuth",
"2",
".",
"0",
"for",
"server",
"-",
"side",
"web",
"applications"
]
| cb917a05c70bebb0deda556f2c931dd0830a4f2e | https://github.com/zigotto/googl/blob/cb917a05c70bebb0deda556f2c931dd0830a4f2e/lib/googl.rb#L128-L130 | train |
cryptosphere/cryptor | lib/cryptor/encoding.rb | Cryptor.Encoding.decode | def decode(string)
padding_size = string.bytesize % 4
padded_string = padding_size > 0 ? string + '=' * (4 - padding_size) : string
Base64.urlsafe_decode64(padded_string)
end | ruby | def decode(string)
padding_size = string.bytesize % 4
padded_string = padding_size > 0 ? string + '=' * (4 - padding_size) : string
Base64.urlsafe_decode64(padded_string)
end | [
"def",
"decode",
"(",
"string",
")",
"padding_size",
"=",
"string",
".",
"bytesize",
"%",
"4",
"padded_string",
"=",
"padding_size",
">",
"0",
"?",
"string",
"+",
"'='",
"*",
"(",
"4",
"-",
"padding_size",
")",
":",
"string",
"Base64",
".",
"urlsafe_decode64",
"(",
"padded_string",
")",
"end"
]
| Decode an unpadded URL-safe Base64 string
@param string [String] URL-safe Base64 string to be decoded (sans '=' padding)
@return [String] decoded string | [
"Decode",
"an",
"unpadded",
"URL",
"-",
"safe",
"Base64",
"string"
]
| 44a1263b2dede1c35b56419725bb47c213bf38d3 | https://github.com/cryptosphere/cryptor/blob/44a1263b2dede1c35b56419725bb47c213bf38d3/lib/cryptor/encoding.rb#L20-L25 | train |
notonthehighstreet/svelte | lib/svelte/path.rb | Svelte.Path.operations | def operations
validate_operations
@operations ||= @raw_operations.map do |operation, properties|
Operation.new(verb: operation, properties: properties, path: self)
end
end | ruby | def operations
validate_operations
@operations ||= @raw_operations.map do |operation, properties|
Operation.new(verb: operation, properties: properties, path: self)
end
end | [
"def",
"operations",
"validate_operations",
"@operations",
"||=",
"@raw_operations",
".",
"map",
"do",
"|",
"operation",
",",
"properties",
"|",
"Operation",
".",
"new",
"(",
"verb",
":",
"operation",
",",
"properties",
":",
"properties",
",",
"path",
":",
"self",
")",
"end",
"end"
]
| Creates a new Path.
@param path [String] path i.e. `'/store/inventory'`
@param operations [Hash] path operations
Path operations
@return [Array<Operation>] list of operations for the path | [
"Creates",
"a",
"new",
"Path",
"."
]
| 75abb1a8d65372c7df27bfa1921e55efe48839ac | https://github.com/notonthehighstreet/svelte/blob/75abb1a8d65372c7df27bfa1921e55efe48839ac/lib/svelte/path.rb#L17-L22 | train |
ombulabs/harvesting | lib/harvesting/client.rb | Harvesting.Client.create | def create(entity)
url = "#{DEFAULT_HOST}/#{entity.path}"
uri = URI(url)
response = http_response(:post, uri, body: entity.to_hash)
entity.attributes = JSON.parse(response.body)
entity
end | ruby | def create(entity)
url = "#{DEFAULT_HOST}/#{entity.path}"
uri = URI(url)
response = http_response(:post, uri, body: entity.to_hash)
entity.attributes = JSON.parse(response.body)
entity
end | [
"def",
"create",
"(",
"entity",
")",
"url",
"=",
"\"#{DEFAULT_HOST}/#{entity.path}\"",
"uri",
"=",
"URI",
"(",
"url",
")",
"response",
"=",
"http_response",
"(",
":post",
",",
"uri",
",",
"body",
":",
"entity",
".",
"to_hash",
")",
"entity",
".",
"attributes",
"=",
"JSON",
".",
"parse",
"(",
"response",
".",
"body",
")",
"entity",
"end"
]
| Creates an `entity` in your Harvest account.
@param entity [Harvesting::Models::Base] A new record in your Harvest account
@return [Harvesting::Models::Base] A subclass of `Harvesting::Models::Base` updated with the response from Harvest | [
"Creates",
"an",
"entity",
"in",
"your",
"Harvest",
"account",
"."
]
| b60135184cb0eba5ef10660560c59b63e97e025e | https://github.com/ombulabs/harvesting/blob/b60135184cb0eba5ef10660560c59b63e97e025e/lib/harvesting/client.rb#L93-L99 | train |
ombulabs/harvesting | lib/harvesting/client.rb | Harvesting.Client.delete | def delete(entity)
url = "#{DEFAULT_HOST}/#{entity.path}"
uri = URI(url)
response = http_response(:delete, uri)
raise UnprocessableRequest(response.to_s) unless response.code.to_i == 200
JSON.parse(response.body)
end | ruby | def delete(entity)
url = "#{DEFAULT_HOST}/#{entity.path}"
uri = URI(url)
response = http_response(:delete, uri)
raise UnprocessableRequest(response.to_s) unless response.code.to_i == 200
JSON.parse(response.body)
end | [
"def",
"delete",
"(",
"entity",
")",
"url",
"=",
"\"#{DEFAULT_HOST}/#{entity.path}\"",
"uri",
"=",
"URI",
"(",
"url",
")",
"response",
"=",
"http_response",
"(",
":delete",
",",
"uri",
")",
"raise",
"UnprocessableRequest",
"(",
"response",
".",
"to_s",
")",
"unless",
"response",
".",
"code",
".",
"to_i",
"==",
"200",
"JSON",
".",
"parse",
"(",
"response",
".",
"body",
")",
"end"
]
| It removes an `entity` from your Harvest account.
@param entity [Harvesting::Models::Base] A record to be removed from your Harvest account
@return [Hash]
@raise [UnprocessableRequest] When HTTP response is not 200 OK | [
"It",
"removes",
"an",
"entity",
"from",
"your",
"Harvest",
"account",
"."
]
| b60135184cb0eba5ef10660560c59b63e97e025e | https://github.com/ombulabs/harvesting/blob/b60135184cb0eba5ef10660560c59b63e97e025e/lib/harvesting/client.rb#L118-L124 | train |
ombulabs/harvesting | lib/harvesting/client.rb | Harvesting.Client.get | def get(path, opts = {})
url = "#{DEFAULT_HOST}/#{path}"
url += "?#{opts.map {|k, v| "#{k}=#{v}"}.join("&")}" if opts.any?
uri = URI(url)
response = http_response(:get, uri)
JSON.parse(response.body)
end | ruby | def get(path, opts = {})
url = "#{DEFAULT_HOST}/#{path}"
url += "?#{opts.map {|k, v| "#{k}=#{v}"}.join("&")}" if opts.any?
uri = URI(url)
response = http_response(:get, uri)
JSON.parse(response.body)
end | [
"def",
"get",
"(",
"path",
",",
"opts",
"=",
"{",
"}",
")",
"url",
"=",
"\"#{DEFAULT_HOST}/#{path}\"",
"url",
"+=",
"\"?#{opts.map {|k, v| \"#{k}=#{v}\"}.join(\"&\")}\"",
"if",
"opts",
".",
"any?",
"uri",
"=",
"URI",
"(",
"url",
")",
"response",
"=",
"http_response",
"(",
":get",
",",
"uri",
")",
"JSON",
".",
"parse",
"(",
"response",
".",
"body",
")",
"end"
]
| Performs a GET request and returned the parsed JSON as a Hash.
@param path [String] path to be combined with `DEFAULT_HOST`
@param opts [Hash] key/values will get passed as HTTP (GET) parameters
@return [Hash] | [
"Performs",
"a",
"GET",
"request",
"and",
"returned",
"the",
"parsed",
"JSON",
"as",
"a",
"Hash",
"."
]
| b60135184cb0eba5ef10660560c59b63e97e025e | https://github.com/ombulabs/harvesting/blob/b60135184cb0eba5ef10660560c59b63e97e025e/lib/harvesting/client.rb#L131-L137 | train |
ruby-jokes/job_interview | lib/job_interview/knapsack.rb | JobInterview.Knapsack.knapsack | def knapsack(items, capacity, algorithm = :dynamic)
if algorithm == :memoize
knapsack_memoize(items, capacity)
elsif algorithm == :dynamic
knapsack_dynamic_programming(items, capacity)
end
end | ruby | def knapsack(items, capacity, algorithm = :dynamic)
if algorithm == :memoize
knapsack_memoize(items, capacity)
elsif algorithm == :dynamic
knapsack_dynamic_programming(items, capacity)
end
end | [
"def",
"knapsack",
"(",
"items",
",",
"capacity",
",",
"algorithm",
"=",
":dynamic",
")",
"if",
"algorithm",
"==",
":memoize",
"knapsack_memoize",
"(",
"items",
",",
"capacity",
")",
"elsif",
"algorithm",
"==",
":dynamic",
"knapsack_dynamic_programming",
"(",
"items",
",",
"capacity",
")",
"end",
"end"
]
| Given a set of items, each with a weight and a value, determines
the maximum profit you can have while keeping the overall weight
smaller than the capacity of the knapsack.
@param items [Array<Array>] An array of pairs (weight, profit) representing the items
@param capacity [Integer] The capacity of the knapsack
@param algorithm [:memoize, :dynamic] The algorithm used to solve this, defaults to :dynamic | [
"Given",
"a",
"set",
"of",
"items",
"each",
"with",
"a",
"weight",
"and",
"a",
"value",
"determines",
"the",
"maximum",
"profit",
"you",
"can",
"have",
"while",
"keeping",
"the",
"overall",
"weight",
"smaller",
"than",
"the",
"capacity",
"of",
"the",
"knapsack",
"."
]
| d66ed33d61b63c9ec82a9ed2debd008e947ac448 | https://github.com/ruby-jokes/job_interview/blob/d66ed33d61b63c9ec82a9ed2debd008e947ac448/lib/job_interview/knapsack.rb#L12-L18 | train |
dspinhirne/netaddr-rb | lib/ipv4net.rb | NetAddr.IPv4Net.prev_sib | def prev_sib()
if (self.network.addr == 0)
return nil
end
shift = 32 - self.netmask.prefix_len
addr = ((self.network.addr>>shift) - 1) << shift
return IPv4Net.new(IPv4.new(addr), self.netmask)
end | ruby | def prev_sib()
if (self.network.addr == 0)
return nil
end
shift = 32 - self.netmask.prefix_len
addr = ((self.network.addr>>shift) - 1) << shift
return IPv4Net.new(IPv4.new(addr), self.netmask)
end | [
"def",
"prev_sib",
"(",
")",
"if",
"(",
"self",
".",
"network",
".",
"addr",
"==",
"0",
")",
"return",
"nil",
"end",
"shift",
"=",
"32",
"-",
"self",
".",
"netmask",
".",
"prefix_len",
"addr",
"=",
"(",
"(",
"self",
".",
"network",
".",
"addr",
">>",
"shift",
")",
"-",
"1",
")",
"<<",
"shift",
"return",
"IPv4Net",
".",
"new",
"(",
"IPv4",
".",
"new",
"(",
"addr",
")",
",",
"self",
".",
"netmask",
")",
"end"
]
| prev_sib returns the network immediately preceding this one or nil if this network is 0.0.0.0. | [
"prev_sib",
"returns",
"the",
"network",
"immediately",
"preceding",
"this",
"one",
"or",
"nil",
"if",
"this",
"network",
"is",
"0",
".",
"0",
".",
"0",
".",
"0",
"."
]
| 38a4a64300a2a9d228bcaf436bea8f368bc20fc5 | https://github.com/dspinhirne/netaddr-rb/blob/38a4a64300a2a9d228bcaf436bea8f368bc20fc5/lib/ipv4net.rb#L142-L150 | train |
dspinhirne/netaddr-rb | lib/ipv4net.rb | NetAddr.IPv4Net.summ | def summ(other)
if (!other.kind_of?(IPv4Net))
raise ArgumentError, "Expected an IPv4Net object for 'other' but got a #{other.class}."
end
# netmasks must be identical
if (self.netmask.prefix_len != other.netmask.prefix_len)
return nil
end
# merge-able networks will be identical if you right shift them by the number of bits in the hostmask + 1
shift = 32 - self.netmask.prefix_len + 1
addr = self.network.addr >> shift
otherAddr = other.network.addr >> shift
if (addr != otherAddr)
return nil
end
return self.resize(self.netmask.prefix_len - 1)
end | ruby | def summ(other)
if (!other.kind_of?(IPv4Net))
raise ArgumentError, "Expected an IPv4Net object for 'other' but got a #{other.class}."
end
# netmasks must be identical
if (self.netmask.prefix_len != other.netmask.prefix_len)
return nil
end
# merge-able networks will be identical if you right shift them by the number of bits in the hostmask + 1
shift = 32 - self.netmask.prefix_len + 1
addr = self.network.addr >> shift
otherAddr = other.network.addr >> shift
if (addr != otherAddr)
return nil
end
return self.resize(self.netmask.prefix_len - 1)
end | [
"def",
"summ",
"(",
"other",
")",
"if",
"(",
"!",
"other",
".",
"kind_of?",
"(",
"IPv4Net",
")",
")",
"raise",
"ArgumentError",
",",
"\"Expected an IPv4Net object for 'other' but got a #{other.class}.\"",
"end",
"if",
"(",
"self",
".",
"netmask",
".",
"prefix_len",
"!=",
"other",
".",
"netmask",
".",
"prefix_len",
")",
"return",
"nil",
"end",
"shift",
"=",
"32",
"-",
"self",
".",
"netmask",
".",
"prefix_len",
"+",
"1",
"addr",
"=",
"self",
".",
"network",
".",
"addr",
">>",
"shift",
"otherAddr",
"=",
"other",
".",
"network",
".",
"addr",
">>",
"shift",
"if",
"(",
"addr",
"!=",
"otherAddr",
")",
"return",
"nil",
"end",
"return",
"self",
".",
"resize",
"(",
"self",
".",
"netmask",
".",
"prefix_len",
"-",
"1",
")",
"end"
]
| summ creates a summary address from this IPv4Net and another.
It returns nil if the two networks are incapable of being summarized. | [
"summ",
"creates",
"a",
"summary",
"address",
"from",
"this",
"IPv4Net",
"and",
"another",
".",
"It",
"returns",
"nil",
"if",
"the",
"two",
"networks",
"are",
"incapable",
"of",
"being",
"summarized",
"."
]
| 38a4a64300a2a9d228bcaf436bea8f368bc20fc5 | https://github.com/dspinhirne/netaddr-rb/blob/38a4a64300a2a9d228bcaf436bea8f368bc20fc5/lib/ipv4net.rb#L198-L216 | train |
dspinhirne/netaddr-rb | lib/ipv6net.rb | NetAddr.IPv6Net.contains | def contains(ip)
if (!ip.kind_of?(IPv6))
raise ArgumentError, "Expected an IPv6 object for 'ip' but got a #{ip.class}."
end
if (@base.addr == ip.addr & @m128.mask)
return true
end
return false
end | ruby | def contains(ip)
if (!ip.kind_of?(IPv6))
raise ArgumentError, "Expected an IPv6 object for 'ip' but got a #{ip.class}."
end
if (@base.addr == ip.addr & @m128.mask)
return true
end
return false
end | [
"def",
"contains",
"(",
"ip",
")",
"if",
"(",
"!",
"ip",
".",
"kind_of?",
"(",
"IPv6",
")",
")",
"raise",
"ArgumentError",
",",
"\"Expected an IPv6 object for 'ip' but got a #{ip.class}.\"",
"end",
"if",
"(",
"@base",
".",
"addr",
"==",
"ip",
".",
"addr",
"&",
"@m128",
".",
"mask",
")",
"return",
"true",
"end",
"return",
"false",
"end"
]
| contains returns true if the IPv6Net contains the IPv6 | [
"contains",
"returns",
"true",
"if",
"the",
"IPv6Net",
"contains",
"the",
"IPv6"
]
| 38a4a64300a2a9d228bcaf436bea8f368bc20fc5 | https://github.com/dspinhirne/netaddr-rb/blob/38a4a64300a2a9d228bcaf436bea8f368bc20fc5/lib/ipv6net.rb#L61-L69 | train |
dspinhirne/netaddr-rb | lib/eui64.rb | NetAddr.EUI64.bytes | def bytes()
return [
(@addr >> 56 & 0xff).to_s(16).rjust(2, "0"),
(@addr >> 48 & 0xff).to_s(16).rjust(2, "0"),
(@addr >> 40 & 0xff).to_s(16).rjust(2, "0"),
(@addr >> 32 & 0xff).to_s(16).rjust(2, "0"),
(@addr >> 24 & 0xff).to_s(16).rjust(2, "0"),
(@addr >> 16 & 0xff).to_s(16).rjust(2, "0"),
(@addr >> 8 & 0xff).to_s(16).rjust(2, "0"),
(@addr & 0xff).to_s(16).rjust(2, "0"),
]
end | ruby | def bytes()
return [
(@addr >> 56 & 0xff).to_s(16).rjust(2, "0"),
(@addr >> 48 & 0xff).to_s(16).rjust(2, "0"),
(@addr >> 40 & 0xff).to_s(16).rjust(2, "0"),
(@addr >> 32 & 0xff).to_s(16).rjust(2, "0"),
(@addr >> 24 & 0xff).to_s(16).rjust(2, "0"),
(@addr >> 16 & 0xff).to_s(16).rjust(2, "0"),
(@addr >> 8 & 0xff).to_s(16).rjust(2, "0"),
(@addr & 0xff).to_s(16).rjust(2, "0"),
]
end | [
"def",
"bytes",
"(",
")",
"return",
"[",
"(",
"@addr",
">>",
"56",
"&",
"0xff",
")",
".",
"to_s",
"(",
"16",
")",
".",
"rjust",
"(",
"2",
",",
"\"0\"",
")",
",",
"(",
"@addr",
">>",
"48",
"&",
"0xff",
")",
".",
"to_s",
"(",
"16",
")",
".",
"rjust",
"(",
"2",
",",
"\"0\"",
")",
",",
"(",
"@addr",
">>",
"40",
"&",
"0xff",
")",
".",
"to_s",
"(",
"16",
")",
".",
"rjust",
"(",
"2",
",",
"\"0\"",
")",
",",
"(",
"@addr",
">>",
"32",
"&",
"0xff",
")",
".",
"to_s",
"(",
"16",
")",
".",
"rjust",
"(",
"2",
",",
"\"0\"",
")",
",",
"(",
"@addr",
">>",
"24",
"&",
"0xff",
")",
".",
"to_s",
"(",
"16",
")",
".",
"rjust",
"(",
"2",
",",
"\"0\"",
")",
",",
"(",
"@addr",
">>",
"16",
"&",
"0xff",
")",
".",
"to_s",
"(",
"16",
")",
".",
"rjust",
"(",
"2",
",",
"\"0\"",
")",
",",
"(",
"@addr",
">>",
"8",
"&",
"0xff",
")",
".",
"to_s",
"(",
"16",
")",
".",
"rjust",
"(",
"2",
",",
"\"0\"",
")",
",",
"(",
"@addr",
"&",
"0xff",
")",
".",
"to_s",
"(",
"16",
")",
".",
"rjust",
"(",
"2",
",",
"\"0\"",
")",
",",
"]",
"end"
]
| bytes returns a list containing each byte of the EUI64 as a String. | [
"bytes",
"returns",
"a",
"list",
"containing",
"each",
"byte",
"of",
"the",
"EUI64",
"as",
"a",
"String",
"."
]
| 38a4a64300a2a9d228bcaf436bea8f368bc20fc5 | https://github.com/dspinhirne/netaddr-rb/blob/38a4a64300a2a9d228bcaf436bea8f368bc20fc5/lib/eui64.rb#L41-L52 | train |
piotrmurach/tty-config | lib/tty/config.rb | TTY.Config.set | def set(*keys, value: nil, &block)
assert_either_value_or_block(value, block)
keys = convert_to_keys(keys)
key = flatten_keys(keys)
value_to_eval = block || value
if validators.key?(key)
if callable_without_params?(value_to_eval)
value_to_eval = delay_validation(key, value_to_eval)
else
assert_valid(key, value)
end
end
deepest_setting = deep_set(@settings, *keys[0...-1])
deepest_setting[keys.last] = value_to_eval
deepest_setting[keys.last]
end | ruby | def set(*keys, value: nil, &block)
assert_either_value_or_block(value, block)
keys = convert_to_keys(keys)
key = flatten_keys(keys)
value_to_eval = block || value
if validators.key?(key)
if callable_without_params?(value_to_eval)
value_to_eval = delay_validation(key, value_to_eval)
else
assert_valid(key, value)
end
end
deepest_setting = deep_set(@settings, *keys[0...-1])
deepest_setting[keys.last] = value_to_eval
deepest_setting[keys.last]
end | [
"def",
"set",
"(",
"*",
"keys",
",",
"value",
":",
"nil",
",",
"&",
"block",
")",
"assert_either_value_or_block",
"(",
"value",
",",
"block",
")",
"keys",
"=",
"convert_to_keys",
"(",
"keys",
")",
"key",
"=",
"flatten_keys",
"(",
"keys",
")",
"value_to_eval",
"=",
"block",
"||",
"value",
"if",
"validators",
".",
"key?",
"(",
"key",
")",
"if",
"callable_without_params?",
"(",
"value_to_eval",
")",
"value_to_eval",
"=",
"delay_validation",
"(",
"key",
",",
"value_to_eval",
")",
"else",
"assert_valid",
"(",
"key",
",",
"value",
")",
"end",
"end",
"deepest_setting",
"=",
"deep_set",
"(",
"@settings",
",",
"*",
"keys",
"[",
"0",
"...",
"-",
"1",
"]",
")",
"deepest_setting",
"[",
"keys",
".",
"last",
"]",
"=",
"value_to_eval",
"deepest_setting",
"[",
"keys",
".",
"last",
"]",
"end"
]
| Set a value for a composite key and overrides any existing keys.
Keys are case-insensitive
@api public | [
"Set",
"a",
"value",
"for",
"a",
"composite",
"key",
"and",
"overrides",
"any",
"existing",
"keys",
".",
"Keys",
"are",
"case",
"-",
"insensitive"
]
| 08c4109cdfa3e7caed1368174ef4c4cb96239f4e | https://github.com/piotrmurach/tty-config/blob/08c4109cdfa3e7caed1368174ef4c4cb96239f4e/lib/tty/config.rb#L179-L197 | train |
piotrmurach/tty-config | lib/tty/config.rb | TTY.Config.set_if_empty | def set_if_empty(*keys, value: nil, &block)
return unless deep_find(@settings, keys.last.to_s).nil?
block ? set(*keys, &block) : set(*keys, value: value)
end | ruby | def set_if_empty(*keys, value: nil, &block)
return unless deep_find(@settings, keys.last.to_s).nil?
block ? set(*keys, &block) : set(*keys, value: value)
end | [
"def",
"set_if_empty",
"(",
"*",
"keys",
",",
"value",
":",
"nil",
",",
"&",
"block",
")",
"return",
"unless",
"deep_find",
"(",
"@settings",
",",
"keys",
".",
"last",
".",
"to_s",
")",
".",
"nil?",
"block",
"?",
"set",
"(",
"*",
"keys",
",",
"&",
"block",
")",
":",
"set",
"(",
"*",
"keys",
",",
"value",
":",
"value",
")",
"end"
]
| Set a value for a composite key if not present already
@param [Array[String|Symbol]] keys
the keys to set value for
@api public | [
"Set",
"a",
"value",
"for",
"a",
"composite",
"key",
"if",
"not",
"present",
"already"
]
| 08c4109cdfa3e7caed1368174ef4c4cb96239f4e | https://github.com/piotrmurach/tty-config/blob/08c4109cdfa3e7caed1368174ef4c4cb96239f4e/lib/tty/config.rb#L205-L208 | train |
piotrmurach/tty-config | lib/tty/config.rb | TTY.Config.set_from_env | def set_from_env(*keys, &block)
assert_keys_with_block(convert_to_keys(keys), block)
key = flatten_keys(keys)
env_key = block.nil? ? key : block.()
env_key = to_env_key(env_key)
@envs[key.to_s.downcase] = env_key
end | ruby | def set_from_env(*keys, &block)
assert_keys_with_block(convert_to_keys(keys), block)
key = flatten_keys(keys)
env_key = block.nil? ? key : block.()
env_key = to_env_key(env_key)
@envs[key.to_s.downcase] = env_key
end | [
"def",
"set_from_env",
"(",
"*",
"keys",
",",
"&",
"block",
")",
"assert_keys_with_block",
"(",
"convert_to_keys",
"(",
"keys",
")",
",",
"block",
")",
"key",
"=",
"flatten_keys",
"(",
"keys",
")",
"env_key",
"=",
"block",
".",
"nil?",
"?",
"key",
":",
"block",
".",
"(",
")",
"env_key",
"=",
"to_env_key",
"(",
"env_key",
")",
"@envs",
"[",
"key",
".",
"to_s",
".",
"downcase",
"]",
"=",
"env_key",
"end"
]
| Bind a key to ENV variable
@example
set_from_env(:host)
set_from_env(:foo, :bar) { 'HOST' }
@param [Array[String]] keys
the keys to bind to ENV variables
@api public | [
"Bind",
"a",
"key",
"to",
"ENV",
"variable"
]
| 08c4109cdfa3e7caed1368174ef4c4cb96239f4e | https://github.com/piotrmurach/tty-config/blob/08c4109cdfa3e7caed1368174ef4c4cb96239f4e/lib/tty/config.rb#L220-L226 | train |
piotrmurach/tty-config | lib/tty/config.rb | TTY.Config.fetch | def fetch(*keys, default: nil, &block)
# check alias
real_key = @aliases[flatten_keys(keys)]
keys = real_key.split(key_delim) if real_key
keys = convert_to_keys(keys)
env_key = autoload_env? ? to_env_key(keys[0]) : @envs[flatten_keys(keys)]
# first try settings
value = deep_fetch(@settings, *keys)
# then try ENV var
if value.nil? && env_key
value = ENV[env_key]
end
# then try default
value = block || default if value.nil?
while callable_without_params?(value)
value = value.call
end
value
end | ruby | def fetch(*keys, default: nil, &block)
# check alias
real_key = @aliases[flatten_keys(keys)]
keys = real_key.split(key_delim) if real_key
keys = convert_to_keys(keys)
env_key = autoload_env? ? to_env_key(keys[0]) : @envs[flatten_keys(keys)]
# first try settings
value = deep_fetch(@settings, *keys)
# then try ENV var
if value.nil? && env_key
value = ENV[env_key]
end
# then try default
value = block || default if value.nil?
while callable_without_params?(value)
value = value.call
end
value
end | [
"def",
"fetch",
"(",
"*",
"keys",
",",
"default",
":",
"nil",
",",
"&",
"block",
")",
"real_key",
"=",
"@aliases",
"[",
"flatten_keys",
"(",
"keys",
")",
"]",
"keys",
"=",
"real_key",
".",
"split",
"(",
"key_delim",
")",
"if",
"real_key",
"keys",
"=",
"convert_to_keys",
"(",
"keys",
")",
"env_key",
"=",
"autoload_env?",
"?",
"to_env_key",
"(",
"keys",
"[",
"0",
"]",
")",
":",
"@envs",
"[",
"flatten_keys",
"(",
"keys",
")",
"]",
"value",
"=",
"deep_fetch",
"(",
"@settings",
",",
"*",
"keys",
")",
"if",
"value",
".",
"nil?",
"&&",
"env_key",
"value",
"=",
"ENV",
"[",
"env_key",
"]",
"end",
"value",
"=",
"block",
"||",
"default",
"if",
"value",
".",
"nil?",
"while",
"callable_without_params?",
"(",
"value",
")",
"value",
"=",
"value",
".",
"call",
"end",
"value",
"end"
]
| Fetch value under a composite key
@param [Array[String|Symbol]] keys
the keys to get value at
@param [Object] default
@api public | [
"Fetch",
"value",
"under",
"a",
"composite",
"key"
]
| 08c4109cdfa3e7caed1368174ef4c4cb96239f4e | https://github.com/piotrmurach/tty-config/blob/08c4109cdfa3e7caed1368174ef4c4cb96239f4e/lib/tty/config.rb#L245-L265 | train |
piotrmurach/tty-config | lib/tty/config.rb | TTY.Config.append | def append(*values, to: nil)
keys = Array(to)
set(*keys, value: Array(fetch(*keys)) + values)
end | ruby | def append(*values, to: nil)
keys = Array(to)
set(*keys, value: Array(fetch(*keys)) + values)
end | [
"def",
"append",
"(",
"*",
"values",
",",
"to",
":",
"nil",
")",
"keys",
"=",
"Array",
"(",
"to",
")",
"set",
"(",
"*",
"keys",
",",
"value",
":",
"Array",
"(",
"fetch",
"(",
"*",
"keys",
")",
")",
"+",
"values",
")",
"end"
]
| Append values to an already existing nested key
@param [Array[String|Symbol]] values
the values to append
@api public | [
"Append",
"values",
"to",
"an",
"already",
"existing",
"nested",
"key"
]
| 08c4109cdfa3e7caed1368174ef4c4cb96239f4e | https://github.com/piotrmurach/tty-config/blob/08c4109cdfa3e7caed1368174ef4c4cb96239f4e/lib/tty/config.rb#L282-L285 | train |
piotrmurach/tty-config | lib/tty/config.rb | TTY.Config.remove | def remove(*values, from: nil)
keys = Array(from)
set(*keys, value: Array(fetch(*keys)) - values)
end | ruby | def remove(*values, from: nil)
keys = Array(from)
set(*keys, value: Array(fetch(*keys)) - values)
end | [
"def",
"remove",
"(",
"*",
"values",
",",
"from",
":",
"nil",
")",
"keys",
"=",
"Array",
"(",
"from",
")",
"set",
"(",
"*",
"keys",
",",
"value",
":",
"Array",
"(",
"fetch",
"(",
"*",
"keys",
")",
")",
"-",
"values",
")",
"end"
]
| Remove a set of values from a nested key
@param [Array[String|Symbol]] keys
the keys for a value removal
@api public | [
"Remove",
"a",
"set",
"of",
"values",
"from",
"a",
"nested",
"key"
]
| 08c4109cdfa3e7caed1368174ef4c4cb96239f4e | https://github.com/piotrmurach/tty-config/blob/08c4109cdfa3e7caed1368174ef4c4cb96239f4e/lib/tty/config.rb#L293-L296 | train |
piotrmurach/tty-config | lib/tty/config.rb | TTY.Config.alias_setting | def alias_setting(*keys, to: nil)
flat_setting = flatten_keys(keys)
alias_keys = Array(to)
alias_key = flatten_keys(alias_keys)
if alias_key == flat_setting
raise ArgumentError, 'Alias matches setting key'
end
if fetch(alias_key)
raise ArgumentError, 'Setting already exists with an alias ' \
"'#{alias_keys.map(&:inspect).join(', ')}'"
end
@aliases[alias_key] = flat_setting
end | ruby | def alias_setting(*keys, to: nil)
flat_setting = flatten_keys(keys)
alias_keys = Array(to)
alias_key = flatten_keys(alias_keys)
if alias_key == flat_setting
raise ArgumentError, 'Alias matches setting key'
end
if fetch(alias_key)
raise ArgumentError, 'Setting already exists with an alias ' \
"'#{alias_keys.map(&:inspect).join(', ')}'"
end
@aliases[alias_key] = flat_setting
end | [
"def",
"alias_setting",
"(",
"*",
"keys",
",",
"to",
":",
"nil",
")",
"flat_setting",
"=",
"flatten_keys",
"(",
"keys",
")",
"alias_keys",
"=",
"Array",
"(",
"to",
")",
"alias_key",
"=",
"flatten_keys",
"(",
"alias_keys",
")",
"if",
"alias_key",
"==",
"flat_setting",
"raise",
"ArgumentError",
",",
"'Alias matches setting key'",
"end",
"if",
"fetch",
"(",
"alias_key",
")",
"raise",
"ArgumentError",
",",
"'Setting already exists with an alias '",
"\"'#{alias_keys.map(&:inspect).join(', ')}'\"",
"end",
"@aliases",
"[",
"alias_key",
"]",
"=",
"flat_setting",
"end"
]
| Define an alias to a nested key
@example
alias_setting(:foo, to: :bar)
@param [Array[String]] keys
the alias key
@api public | [
"Define",
"an",
"alias",
"to",
"a",
"nested",
"key"
]
| 08c4109cdfa3e7caed1368174ef4c4cb96239f4e | https://github.com/piotrmurach/tty-config/blob/08c4109cdfa3e7caed1368174ef4c4cb96239f4e/lib/tty/config.rb#L318-L333 | train |
piotrmurach/tty-config | lib/tty/config.rb | TTY.Config.validate | def validate(*keys, &validator)
key = flatten_keys(keys)
values = validators[key] || []
values << validator
validators[key] = values
end | ruby | def validate(*keys, &validator)
key = flatten_keys(keys)
values = validators[key] || []
values << validator
validators[key] = values
end | [
"def",
"validate",
"(",
"*",
"keys",
",",
"&",
"validator",
")",
"key",
"=",
"flatten_keys",
"(",
"keys",
")",
"values",
"=",
"validators",
"[",
"key",
"]",
"||",
"[",
"]",
"values",
"<<",
"validator",
"validators",
"[",
"key",
"]",
"=",
"values",
"end"
]
| Register a validation rule for a nested key
@param [Array[String]] keys
a deep nested keys
@param [Proc] validator
the logic to use to validate given nested key
@api public | [
"Register",
"a",
"validation",
"rule",
"for",
"a",
"nested",
"key"
]
| 08c4109cdfa3e7caed1368174ef4c4cb96239f4e | https://github.com/piotrmurach/tty-config/blob/08c4109cdfa3e7caed1368174ef4c4cb96239f4e/lib/tty/config.rb#L343-L348 | train |
piotrmurach/tty-config | lib/tty/config.rb | TTY.Config.read | def read(file = find_file, format: :auto)
if file.nil?
raise ReadError, 'No file found to read configuration from!'
elsif !::File.exist?(file)
raise ReadError, "Configuration file `#{file}` does not exist!"
end
merge(unmarshal(file, format: format))
end | ruby | def read(file = find_file, format: :auto)
if file.nil?
raise ReadError, 'No file found to read configuration from!'
elsif !::File.exist?(file)
raise ReadError, "Configuration file `#{file}` does not exist!"
end
merge(unmarshal(file, format: format))
end | [
"def",
"read",
"(",
"file",
"=",
"find_file",
",",
"format",
":",
":auto",
")",
"if",
"file",
".",
"nil?",
"raise",
"ReadError",
",",
"'No file found to read configuration from!'",
"elsif",
"!",
"::",
"File",
".",
"exist?",
"(",
"file",
")",
"raise",
"ReadError",
",",
"\"Configuration file `#{file}` does not exist!\"",
"end",
"merge",
"(",
"unmarshal",
"(",
"file",
",",
"format",
":",
"format",
")",
")",
"end"
]
| Find and read a configuration file.
If the file doesn't exist or if there is an error loading it
the TTY::Config::ReadError will be raised.
@param [String] file
the path to the configuration file to be read
@param [String] format
the format to read configuration in
@raise [TTY::Config::ReadError]
@api public | [
"Find",
"and",
"read",
"a",
"configuration",
"file",
"."
]
| 08c4109cdfa3e7caed1368174ef4c4cb96239f4e | https://github.com/piotrmurach/tty-config/blob/08c4109cdfa3e7caed1368174ef4c4cb96239f4e/lib/tty/config.rb#L386-L394 | train |
piotrmurach/tty-config | lib/tty/config.rb | TTY.Config.write | def write(file = find_file, force: false, format: :auto)
if file && ::File.exist?(file)
if !force
raise WriteError, "File `#{file}` already exists. " \
'Use :force option to overwrite.'
elsif !::File.writable?(file)
raise WriteError, "Cannot write to #{file}."
end
end
if file.nil?
dir = @location_paths.empty? ? Dir.pwd : @location_paths.first
file = ::File.join(dir, "#{filename}#{@extname}")
end
content = marshal(file, @settings, format: format)
::File.write(file, content)
end | ruby | def write(file = find_file, force: false, format: :auto)
if file && ::File.exist?(file)
if !force
raise WriteError, "File `#{file}` already exists. " \
'Use :force option to overwrite.'
elsif !::File.writable?(file)
raise WriteError, "Cannot write to #{file}."
end
end
if file.nil?
dir = @location_paths.empty? ? Dir.pwd : @location_paths.first
file = ::File.join(dir, "#{filename}#{@extname}")
end
content = marshal(file, @settings, format: format)
::File.write(file, content)
end | [
"def",
"write",
"(",
"file",
"=",
"find_file",
",",
"force",
":",
"false",
",",
"format",
":",
":auto",
")",
"if",
"file",
"&&",
"::",
"File",
".",
"exist?",
"(",
"file",
")",
"if",
"!",
"force",
"raise",
"WriteError",
",",
"\"File `#{file}` already exists. \"",
"'Use :force option to overwrite.'",
"elsif",
"!",
"::",
"File",
".",
"writable?",
"(",
"file",
")",
"raise",
"WriteError",
",",
"\"Cannot write to #{file}.\"",
"end",
"end",
"if",
"file",
".",
"nil?",
"dir",
"=",
"@location_paths",
".",
"empty?",
"?",
"Dir",
".",
"pwd",
":",
"@location_paths",
".",
"first",
"file",
"=",
"::",
"File",
".",
"join",
"(",
"dir",
",",
"\"#{filename}#{@extname}\"",
")",
"end",
"content",
"=",
"marshal",
"(",
"file",
",",
"@settings",
",",
"format",
":",
"format",
")",
"::",
"File",
".",
"write",
"(",
"file",
",",
"content",
")",
"end"
]
| Write current configuration to a file.
@param [String] file
the path to a file
@api public | [
"Write",
"current",
"configuration",
"to",
"a",
"file",
"."
]
| 08c4109cdfa3e7caed1368174ef4c4cb96239f4e | https://github.com/piotrmurach/tty-config/blob/08c4109cdfa3e7caed1368174ef4c4cb96239f4e/lib/tty/config.rb#L402-L419 | train |
piotrmurach/tty-config | lib/tty/config.rb | TTY.Config.assert_either_value_or_block | def assert_either_value_or_block(value, block)
if value.nil? && block.nil?
raise ArgumentError, 'Need to set either value or block'
elsif !(value.nil? || block.nil?)
raise ArgumentError, "Can't set both value and block"
end
end | ruby | def assert_either_value_or_block(value, block)
if value.nil? && block.nil?
raise ArgumentError, 'Need to set either value or block'
elsif !(value.nil? || block.nil?)
raise ArgumentError, "Can't set both value and block"
end
end | [
"def",
"assert_either_value_or_block",
"(",
"value",
",",
"block",
")",
"if",
"value",
".",
"nil?",
"&&",
"block",
".",
"nil?",
"raise",
"ArgumentError",
",",
"'Need to set either value or block'",
"elsif",
"!",
"(",
"value",
".",
"nil?",
"||",
"block",
".",
"nil?",
")",
"raise",
"ArgumentError",
",",
"\"Can't set both value and block\"",
"end",
"end"
]
| Ensure that value is set either through parameter or block
@api private | [
"Ensure",
"that",
"value",
"is",
"set",
"either",
"through",
"parameter",
"or",
"block"
]
| 08c4109cdfa3e7caed1368174ef4c4cb96239f4e | https://github.com/piotrmurach/tty-config/blob/08c4109cdfa3e7caed1368174ef4c4cb96239f4e/lib/tty/config.rb#L434-L440 | train |
piotrmurach/tty-config | lib/tty/config.rb | TTY.Config.assert_valid | def assert_valid(key, value)
validators[key].each do |validator|
validator.call(key, value)
end
end | ruby | def assert_valid(key, value)
validators[key].each do |validator|
validator.call(key, value)
end
end | [
"def",
"assert_valid",
"(",
"key",
",",
"value",
")",
"validators",
"[",
"key",
"]",
".",
"each",
"do",
"|",
"validator",
"|",
"validator",
".",
"call",
"(",
"key",
",",
"value",
")",
"end",
"end"
]
| Check if key passes all registered validations for a key
@param [String] key
@param [Object] value
@api private | [
"Check",
"if",
"key",
"passes",
"all",
"registered",
"validations",
"for",
"a",
"key"
]
| 08c4109cdfa3e7caed1368174ef4c4cb96239f4e | https://github.com/piotrmurach/tty-config/blob/08c4109cdfa3e7caed1368174ef4c4cb96239f4e/lib/tty/config.rb#L473-L477 | train |
piotrmurach/tty-config | lib/tty/config.rb | TTY.Config.deep_set | def deep_set(settings, *keys)
return settings if keys.empty?
key, *rest = *keys
value = settings[key]
if value.nil? && rest.empty?
settings[key] = {}
elsif value.nil? && !rest.empty?
settings[key] = {}
deep_set(settings[key], *rest)
else # nested hash value present
settings[key] = value
deep_set(settings[key], *rest)
end
end | ruby | def deep_set(settings, *keys)
return settings if keys.empty?
key, *rest = *keys
value = settings[key]
if value.nil? && rest.empty?
settings[key] = {}
elsif value.nil? && !rest.empty?
settings[key] = {}
deep_set(settings[key], *rest)
else # nested hash value present
settings[key] = value
deep_set(settings[key], *rest)
end
end | [
"def",
"deep_set",
"(",
"settings",
",",
"*",
"keys",
")",
"return",
"settings",
"if",
"keys",
".",
"empty?",
"key",
",",
"*",
"rest",
"=",
"*",
"keys",
"value",
"=",
"settings",
"[",
"key",
"]",
"if",
"value",
".",
"nil?",
"&&",
"rest",
".",
"empty?",
"settings",
"[",
"key",
"]",
"=",
"{",
"}",
"elsif",
"value",
".",
"nil?",
"&&",
"!",
"rest",
".",
"empty?",
"settings",
"[",
"key",
"]",
"=",
"{",
"}",
"deep_set",
"(",
"settings",
"[",
"key",
"]",
",",
"*",
"rest",
")",
"else",
"settings",
"[",
"key",
"]",
"=",
"value",
"deep_set",
"(",
"settings",
"[",
"key",
"]",
",",
"*",
"rest",
")",
"end",
"end"
]
| Set value under deeply nested keys
The scan starts with the top level key and follows
a sequence of keys. In case where intermediate keys do
not exist, a new hash is created.
@param [Hash] settings
@param [Array[Object]]
the keys to nest
@api private | [
"Set",
"value",
"under",
"deeply",
"nested",
"keys"
]
| 08c4109cdfa3e7caed1368174ef4c4cb96239f4e | https://github.com/piotrmurach/tty-config/blob/08c4109cdfa3e7caed1368174ef4c4cb96239f4e/lib/tty/config.rb#L497-L511 | train |
piotrmurach/tty-config | lib/tty/config.rb | TTY.Config.deep_fetch | def deep_fetch(settings, *keys)
key, *rest = keys
value = settings.fetch(key.to_s, settings[key.to_sym])
if value.nil? || rest.empty?
value
else
deep_fetch(value, *rest)
end
end | ruby | def deep_fetch(settings, *keys)
key, *rest = keys
value = settings.fetch(key.to_s, settings[key.to_sym])
if value.nil? || rest.empty?
value
else
deep_fetch(value, *rest)
end
end | [
"def",
"deep_fetch",
"(",
"settings",
",",
"*",
"keys",
")",
"key",
",",
"*",
"rest",
"=",
"keys",
"value",
"=",
"settings",
".",
"fetch",
"(",
"key",
".",
"to_s",
",",
"settings",
"[",
"key",
".",
"to_sym",
"]",
")",
"if",
"value",
".",
"nil?",
"||",
"rest",
".",
"empty?",
"value",
"else",
"deep_fetch",
"(",
"value",
",",
"*",
"rest",
")",
"end",
"end"
]
| Fetch value under deeply nested keys with indiffernt key access
@param [Hash] settings
@param [Array[Object]] keys
@api private | [
"Fetch",
"value",
"under",
"deeply",
"nested",
"keys",
"with",
"indiffernt",
"key",
"access"
]
| 08c4109cdfa3e7caed1368174ef4c4cb96239f4e | https://github.com/piotrmurach/tty-config/blob/08c4109cdfa3e7caed1368174ef4c4cb96239f4e/lib/tty/config.rb#L547-L555 | train |
piotrmurach/tty-config | lib/tty/config.rb | TTY.Config.marshal | def marshal(file, data, format: :auto)
file_ext = ::File.extname(file)
ext = (format == :auto ? file_ext : ".#{format}")
self.extname = file_ext
self.filename = ::File.basename(file, file_ext)
case ext
when *EXTENSIONS[:yaml]
load_write_dep('yaml', ext)
YAML.dump(self.class.normalize_hash(data, :to_s))
when *EXTENSIONS[:json]
load_write_dep('json', ext)
JSON.pretty_generate(data)
when *EXTENSIONS[:toml]
load_write_dep('toml', ext)
TOML::Generator.new(data).body
when *EXTENSIONS[:ini]
Config.generate(data)
else
raise WriteError, "Config file format `#{ext}` is not supported."
end
end | ruby | def marshal(file, data, format: :auto)
file_ext = ::File.extname(file)
ext = (format == :auto ? file_ext : ".#{format}")
self.extname = file_ext
self.filename = ::File.basename(file, file_ext)
case ext
when *EXTENSIONS[:yaml]
load_write_dep('yaml', ext)
YAML.dump(self.class.normalize_hash(data, :to_s))
when *EXTENSIONS[:json]
load_write_dep('json', ext)
JSON.pretty_generate(data)
when *EXTENSIONS[:toml]
load_write_dep('toml', ext)
TOML::Generator.new(data).body
when *EXTENSIONS[:ini]
Config.generate(data)
else
raise WriteError, "Config file format `#{ext}` is not supported."
end
end | [
"def",
"marshal",
"(",
"file",
",",
"data",
",",
"format",
":",
":auto",
")",
"file_ext",
"=",
"::",
"File",
".",
"extname",
"(",
"file",
")",
"ext",
"=",
"(",
"format",
"==",
":auto",
"?",
"file_ext",
":",
"\".#{format}\"",
")",
"self",
".",
"extname",
"=",
"file_ext",
"self",
".",
"filename",
"=",
"::",
"File",
".",
"basename",
"(",
"file",
",",
"file_ext",
")",
"case",
"ext",
"when",
"*",
"EXTENSIONS",
"[",
":yaml",
"]",
"load_write_dep",
"(",
"'yaml'",
",",
"ext",
")",
"YAML",
".",
"dump",
"(",
"self",
".",
"class",
".",
"normalize_hash",
"(",
"data",
",",
":to_s",
")",
")",
"when",
"*",
"EXTENSIONS",
"[",
":json",
"]",
"load_write_dep",
"(",
"'json'",
",",
"ext",
")",
"JSON",
".",
"pretty_generate",
"(",
"data",
")",
"when",
"*",
"EXTENSIONS",
"[",
":toml",
"]",
"load_write_dep",
"(",
"'toml'",
",",
"ext",
")",
"TOML",
"::",
"Generator",
".",
"new",
"(",
"data",
")",
".",
"body",
"when",
"*",
"EXTENSIONS",
"[",
":ini",
"]",
"Config",
".",
"generate",
"(",
"data",
")",
"else",
"raise",
"WriteError",
",",
"\"Config file format `#{ext}` is not supported.\"",
"end",
"end"
]
| Marshal data hash into a configuration file content
@return [String]
@api private | [
"Marshal",
"data",
"hash",
"into",
"a",
"configuration",
"file",
"content"
]
| 08c4109cdfa3e7caed1368174ef4c4cb96239f4e | https://github.com/piotrmurach/tty-config/blob/08c4109cdfa3e7caed1368174ef4c4cb96239f4e/lib/tty/config.rb#L637-L658 | train |
lgromanowski/acme-plugin | lib/acme_plugin.rb | AcmePlugin.CertGenerator.save_certificate | def save_certificate(certificate)
return unless certificate
return HerokuOutput.new(common_domain_name, certificate).output unless ENV['DYNO'].nil?
output_dir = File.join(Rails.root, @options[:output_cert_dir])
return FileOutput.new(common_domain_name, certificate, output_dir).output if File.directory?(output_dir)
Rails.logger.error("Output directory: '#{output_dir}' does not exist!")
end | ruby | def save_certificate(certificate)
return unless certificate
return HerokuOutput.new(common_domain_name, certificate).output unless ENV['DYNO'].nil?
output_dir = File.join(Rails.root, @options[:output_cert_dir])
return FileOutput.new(common_domain_name, certificate, output_dir).output if File.directory?(output_dir)
Rails.logger.error("Output directory: '#{output_dir}' does not exist!")
end | [
"def",
"save_certificate",
"(",
"certificate",
")",
"return",
"unless",
"certificate",
"return",
"HerokuOutput",
".",
"new",
"(",
"common_domain_name",
",",
"certificate",
")",
".",
"output",
"unless",
"ENV",
"[",
"'DYNO'",
"]",
".",
"nil?",
"output_dir",
"=",
"File",
".",
"join",
"(",
"Rails",
".",
"root",
",",
"@options",
"[",
":output_cert_dir",
"]",
")",
"return",
"FileOutput",
".",
"new",
"(",
"common_domain_name",
",",
"certificate",
",",
"output_dir",
")",
".",
"output",
"if",
"File",
".",
"directory?",
"(",
"output_dir",
")",
"Rails",
".",
"logger",
".",
"error",
"(",
"\"Output directory: '#{output_dir}' does not exist!\"",
")",
"end"
]
| Save the certificate and key | [
"Save",
"the",
"certificate",
"and",
"key"
]
| 1a0875d509cb658045b0ae9c76b1d32d09c3d0ab | https://github.com/lgromanowski/acme-plugin/blob/1a0875d509cb658045b0ae9c76b1d32d09c3d0ab/lib/acme_plugin.rb#L138-L144 | train |
junegunn/jdbc-helper | lib/jdbc-helper/wrapper/table_wrapper.rb | JDBCHelper.TableWrapper.count | def count *where
sql, *binds = SQLHelper.count :table => name, :where => @query_where + where, :prepared => true
pstmt = prepare :count, sql
pstmt.query(*binds).to_a[0][0].to_i
end | ruby | def count *where
sql, *binds = SQLHelper.count :table => name, :where => @query_where + where, :prepared => true
pstmt = prepare :count, sql
pstmt.query(*binds).to_a[0][0].to_i
end | [
"def",
"count",
"*",
"where",
"sql",
",",
"*",
"binds",
"=",
"SQLHelper",
".",
"count",
":table",
"=>",
"name",
",",
":where",
"=>",
"@query_where",
"+",
"where",
",",
":prepared",
"=>",
"true",
"pstmt",
"=",
"prepare",
":count",
",",
"sql",
"pstmt",
".",
"query",
"(",
"*",
"binds",
")",
".",
"to_a",
"[",
"0",
"]",
"[",
"0",
"]",
".",
"to_i",
"end"
]
| Retrieves the count of the table
@param [List of Hash/String] where Filter conditions
@return [Fixnum] Count of the records. | [
"Retrieves",
"the",
"count",
"of",
"the",
"table"
]
| 0c0e7142ca7faab93db68d526753032ab2dc652f | https://github.com/junegunn/jdbc-helper/blob/0c0e7142ca7faab93db68d526753032ab2dc652f/lib/jdbc-helper/wrapper/table_wrapper.rb#L52-L56 | train |
junegunn/jdbc-helper | lib/jdbc-helper/wrapper/table_wrapper.rb | JDBCHelper.TableWrapper.insert_ignore | def insert_ignore data_hash = {}
sql, *binds = SQLHelper.insert_ignore :table => name,
:data => @query_default.merge(data_hash),
:prepared => true
pstmt = prepare :insert, sql
pstmt.set_fetch_size @fetch_size if @fetch_size
pstmt.send @update_method, *binds
end | ruby | def insert_ignore data_hash = {}
sql, *binds = SQLHelper.insert_ignore :table => name,
:data => @query_default.merge(data_hash),
:prepared => true
pstmt = prepare :insert, sql
pstmt.set_fetch_size @fetch_size if @fetch_size
pstmt.send @update_method, *binds
end | [
"def",
"insert_ignore",
"data_hash",
"=",
"{",
"}",
"sql",
",",
"*",
"binds",
"=",
"SQLHelper",
".",
"insert_ignore",
":table",
"=>",
"name",
",",
":data",
"=>",
"@query_default",
".",
"merge",
"(",
"data_hash",
")",
",",
":prepared",
"=>",
"true",
"pstmt",
"=",
"prepare",
":insert",
",",
"sql",
"pstmt",
".",
"set_fetch_size",
"@fetch_size",
"if",
"@fetch_size",
"pstmt",
".",
"send",
"@update_method",
",",
"*",
"binds",
"end"
]
| Inserts a record into the table with the given hash.
Skip insertion when duplicate record is found.
@note This is not SQL standard. Only works if the database supports insert ignore syntax.
@param [Hash] data_hash Column values in Hash
@return [Fixnum] Number of affected records | [
"Inserts",
"a",
"record",
"into",
"the",
"table",
"with",
"the",
"given",
"hash",
".",
"Skip",
"insertion",
"when",
"duplicate",
"record",
"is",
"found",
"."
]
| 0c0e7142ca7faab93db68d526753032ab2dc652f | https://github.com/junegunn/jdbc-helper/blob/0c0e7142ca7faab93db68d526753032ab2dc652f/lib/jdbc-helper/wrapper/table_wrapper.rb#L81-L88 | train |
junegunn/jdbc-helper | lib/jdbc-helper/wrapper/table_wrapper.rb | JDBCHelper.TableWrapper.replace | def replace data_hash = {}
sql, *binds = SQLHelper.replace :table => name,
:data => @query_default.merge(data_hash),
:prepared => true
pstmt = prepare :insert, sql
pstmt.send @update_method, *binds
end | ruby | def replace data_hash = {}
sql, *binds = SQLHelper.replace :table => name,
:data => @query_default.merge(data_hash),
:prepared => true
pstmt = prepare :insert, sql
pstmt.send @update_method, *binds
end | [
"def",
"replace",
"data_hash",
"=",
"{",
"}",
"sql",
",",
"*",
"binds",
"=",
"SQLHelper",
".",
"replace",
":table",
"=>",
"name",
",",
":data",
"=>",
"@query_default",
".",
"merge",
"(",
"data_hash",
")",
",",
":prepared",
"=>",
"true",
"pstmt",
"=",
"prepare",
":insert",
",",
"sql",
"pstmt",
".",
"send",
"@update_method",
",",
"*",
"binds",
"end"
]
| Replaces a record in the table with the new one with the same unique key.
@note This is not SQL standard. Only works if the database supports replace syntax.
@param [Hash] data_hash Column values in Hash
@return [Fixnum] Number of affected records | [
"Replaces",
"a",
"record",
"in",
"the",
"table",
"with",
"the",
"new",
"one",
"with",
"the",
"same",
"unique",
"key",
"."
]
| 0c0e7142ca7faab93db68d526753032ab2dc652f | https://github.com/junegunn/jdbc-helper/blob/0c0e7142ca7faab93db68d526753032ab2dc652f/lib/jdbc-helper/wrapper/table_wrapper.rb#L94-L100 | train |
junegunn/jdbc-helper | lib/jdbc-helper/wrapper/table_wrapper.rb | JDBCHelper.TableWrapper.delete | def delete *where
sql, *binds = SQLHelper.delete(:table => name, :where => @query_where + where, :prepared => true)
pstmt = prepare :delete, sql
pstmt.send @update_method, *binds
end | ruby | def delete *where
sql, *binds = SQLHelper.delete(:table => name, :where => @query_where + where, :prepared => true)
pstmt = prepare :delete, sql
pstmt.send @update_method, *binds
end | [
"def",
"delete",
"*",
"where",
"sql",
",",
"*",
"binds",
"=",
"SQLHelper",
".",
"delete",
"(",
":table",
"=>",
"name",
",",
":where",
"=>",
"@query_where",
"+",
"where",
",",
":prepared",
"=>",
"true",
")",
"pstmt",
"=",
"prepare",
":delete",
",",
"sql",
"pstmt",
".",
"send",
"@update_method",
",",
"*",
"binds",
"end"
]
| Deletes records matching given condtion
@param [List of Hash/String] where Delete filters
@return [Fixnum] Number of affected records | [
"Deletes",
"records",
"matching",
"given",
"condtion"
]
| 0c0e7142ca7faab93db68d526753032ab2dc652f | https://github.com/junegunn/jdbc-helper/blob/0c0e7142ca7faab93db68d526753032ab2dc652f/lib/jdbc-helper/wrapper/table_wrapper.rb#L122-L126 | train |
junegunn/jdbc-helper | lib/jdbc-helper/wrapper/table_wrapper.rb | JDBCHelper.TableWrapper.select | def select *fields, &block
obj = self.dup
obj.instance_variable_set :@query_select, fields unless fields.empty?
ret obj, &block
end | ruby | def select *fields, &block
obj = self.dup
obj.instance_variable_set :@query_select, fields unless fields.empty?
ret obj, &block
end | [
"def",
"select",
"*",
"fields",
",",
"&",
"block",
"obj",
"=",
"self",
".",
"dup",
"obj",
".",
"instance_variable_set",
":@query_select",
",",
"fields",
"unless",
"fields",
".",
"empty?",
"ret",
"obj",
",",
"&",
"block",
"end"
]
| Returns a new TableWrapper object which can be used to execute a select
statement for the table selecting only the specified fields.
If a block is given, executes the select statement and yields each row to the block.
@param [*String/*Symbol] fields List of fields to select
@return [JDBCHelper::TableWrapper]
@since 0.4.0 | [
"Returns",
"a",
"new",
"TableWrapper",
"object",
"which",
"can",
"be",
"used",
"to",
"execute",
"a",
"select",
"statement",
"for",
"the",
"table",
"selecting",
"only",
"the",
"specified",
"fields",
".",
"If",
"a",
"block",
"is",
"given",
"executes",
"the",
"select",
"statement",
"and",
"yields",
"each",
"row",
"to",
"the",
"block",
"."
]
| 0c0e7142ca7faab93db68d526753032ab2dc652f | https://github.com/junegunn/jdbc-helper/blob/0c0e7142ca7faab93db68d526753032ab2dc652f/lib/jdbc-helper/wrapper/table_wrapper.rb#L155-L159 | train |
junegunn/jdbc-helper | lib/jdbc-helper/wrapper/table_wrapper.rb | JDBCHelper.TableWrapper.where | def where *conditions, &block
raise ArgumentError.new("Wrong number of arguments") if conditions.empty?
obj = self.dup
obj.instance_variable_set :@query_where, @query_where + conditions
ret obj, &block
end | ruby | def where *conditions, &block
raise ArgumentError.new("Wrong number of arguments") if conditions.empty?
obj = self.dup
obj.instance_variable_set :@query_where, @query_where + conditions
ret obj, &block
end | [
"def",
"where",
"*",
"conditions",
",",
"&",
"block",
"raise",
"ArgumentError",
".",
"new",
"(",
"\"Wrong number of arguments\"",
")",
"if",
"conditions",
".",
"empty?",
"obj",
"=",
"self",
".",
"dup",
"obj",
".",
"instance_variable_set",
":@query_where",
",",
"@query_where",
"+",
"conditions",
"ret",
"obj",
",",
"&",
"block",
"end"
]
| Returns a new TableWrapper object which can be used to execute a select
statement for the table with the specified filter conditions.
If a block is given, executes the select statement and yields each row to the block.
@param [List of Hash/String] conditions Filter conditions
@return [JDBCHelper::TableWrapper]
@since 0.4.0 | [
"Returns",
"a",
"new",
"TableWrapper",
"object",
"which",
"can",
"be",
"used",
"to",
"execute",
"a",
"select",
"statement",
"for",
"the",
"table",
"with",
"the",
"specified",
"filter",
"conditions",
".",
"If",
"a",
"block",
"is",
"given",
"executes",
"the",
"select",
"statement",
"and",
"yields",
"each",
"row",
"to",
"the",
"block",
"."
]
| 0c0e7142ca7faab93db68d526753032ab2dc652f | https://github.com/junegunn/jdbc-helper/blob/0c0e7142ca7faab93db68d526753032ab2dc652f/lib/jdbc-helper/wrapper/table_wrapper.rb#L168-L174 | train |
junegunn/jdbc-helper | lib/jdbc-helper/wrapper/table_wrapper.rb | JDBCHelper.TableWrapper.order | def order *criteria, &block
raise ArgumentError.new("Wrong number of arguments") if criteria.empty?
obj = self.dup
obj.instance_variable_set :@query_order, criteria
ret obj, &block
end | ruby | def order *criteria, &block
raise ArgumentError.new("Wrong number of arguments") if criteria.empty?
obj = self.dup
obj.instance_variable_set :@query_order, criteria
ret obj, &block
end | [
"def",
"order",
"*",
"criteria",
",",
"&",
"block",
"raise",
"ArgumentError",
".",
"new",
"(",
"\"Wrong number of arguments\"",
")",
"if",
"criteria",
".",
"empty?",
"obj",
"=",
"self",
".",
"dup",
"obj",
".",
"instance_variable_set",
":@query_order",
",",
"criteria",
"ret",
"obj",
",",
"&",
"block",
"end"
]
| Returns a new TableWrapper object which can be used to execute a select
statement for the table with the given sorting criteria.
If a block is given, executes the select statement and yields each row to the block.
@param [*String/*Symbol] criteria Sorting criteria
@return [JDBCHelper::TableWrapper]
@since 0.4.0 | [
"Returns",
"a",
"new",
"TableWrapper",
"object",
"which",
"can",
"be",
"used",
"to",
"execute",
"a",
"select",
"statement",
"for",
"the",
"table",
"with",
"the",
"given",
"sorting",
"criteria",
".",
"If",
"a",
"block",
"is",
"given",
"executes",
"the",
"select",
"statement",
"and",
"yields",
"each",
"row",
"to",
"the",
"block",
"."
]
| 0c0e7142ca7faab93db68d526753032ab2dc652f | https://github.com/junegunn/jdbc-helper/blob/0c0e7142ca7faab93db68d526753032ab2dc652f/lib/jdbc-helper/wrapper/table_wrapper.rb#L192-L197 | train |
junegunn/jdbc-helper | lib/jdbc-helper/wrapper/table_wrapper.rb | JDBCHelper.TableWrapper.default | def default data_hash, &block
raise ArgumentError.new("Hash required") unless data_hash.kind_of? Hash
obj = self.dup
obj.instance_variable_set :@query_default, @query_default.merge(data_hash)
ret obj, &block
end | ruby | def default data_hash, &block
raise ArgumentError.new("Hash required") unless data_hash.kind_of? Hash
obj = self.dup
obj.instance_variable_set :@query_default, @query_default.merge(data_hash)
ret obj, &block
end | [
"def",
"default",
"data_hash",
",",
"&",
"block",
"raise",
"ArgumentError",
".",
"new",
"(",
"\"Hash required\"",
")",
"unless",
"data_hash",
".",
"kind_of?",
"Hash",
"obj",
"=",
"self",
".",
"dup",
"obj",
".",
"instance_variable_set",
":@query_default",
",",
"@query_default",
".",
"merge",
"(",
"data_hash",
")",
"ret",
"obj",
",",
"&",
"block",
"end"
]
| Returns a new TableWrapper object with default values, which will be applied to
the subsequent inserts and updates.
@param [Hash] data_hash Default values
@return [JDBCHelper::TableWrapper]
@since 0.4.5 | [
"Returns",
"a",
"new",
"TableWrapper",
"object",
"with",
"default",
"values",
"which",
"will",
"be",
"applied",
"to",
"the",
"subsequent",
"inserts",
"and",
"updates",
"."
]
| 0c0e7142ca7faab93db68d526753032ab2dc652f | https://github.com/junegunn/jdbc-helper/blob/0c0e7142ca7faab93db68d526753032ab2dc652f/lib/jdbc-helper/wrapper/table_wrapper.rb#L204-L210 | train |
junegunn/jdbc-helper | lib/jdbc-helper/wrapper/table_wrapper.rb | JDBCHelper.TableWrapper.fetch_size | def fetch_size fsz, &block
obj = self.dup
obj.instance_variable_set :@fetch_size, fsz
ret obj, &block
end | ruby | def fetch_size fsz, &block
obj = self.dup
obj.instance_variable_set :@fetch_size, fsz
ret obj, &block
end | [
"def",
"fetch_size",
"fsz",
",",
"&",
"block",
"obj",
"=",
"self",
".",
"dup",
"obj",
".",
"instance_variable_set",
":@fetch_size",
",",
"fsz",
"ret",
"obj",
",",
"&",
"block",
"end"
]
| Returns a new TableWrapper object with the given fetch size.
If a block is given, executes the select statement and yields each row to the block.
@param [Fixnum] fsz Fetch size
@return [JDBCHelper::TableWrapper]
@since 0.7.7 | [
"Returns",
"a",
"new",
"TableWrapper",
"object",
"with",
"the",
"given",
"fetch",
"size",
".",
"If",
"a",
"block",
"is",
"given",
"executes",
"the",
"select",
"statement",
"and",
"yields",
"each",
"row",
"to",
"the",
"block",
"."
]
| 0c0e7142ca7faab93db68d526753032ab2dc652f | https://github.com/junegunn/jdbc-helper/blob/0c0e7142ca7faab93db68d526753032ab2dc652f/lib/jdbc-helper/wrapper/table_wrapper.rb#L217-L221 | train |
junegunn/jdbc-helper | lib/jdbc-helper/wrapper/table_wrapper.rb | JDBCHelper.TableWrapper.each | def each &block
sql, *binds = SQLHelper.select(
:prepared => true,
:table => name,
:project => @query_select,
:where => @query_where,
:order => @query_order,
:limit => @query_limit)
pstmt = prepare :select, sql
pstmt.enumerate(*binds, &block)
end | ruby | def each &block
sql, *binds = SQLHelper.select(
:prepared => true,
:table => name,
:project => @query_select,
:where => @query_where,
:order => @query_order,
:limit => @query_limit)
pstmt = prepare :select, sql
pstmt.enumerate(*binds, &block)
end | [
"def",
"each",
"&",
"block",
"sql",
",",
"*",
"binds",
"=",
"SQLHelper",
".",
"select",
"(",
":prepared",
"=>",
"true",
",",
":table",
"=>",
"name",
",",
":project",
"=>",
"@query_select",
",",
":where",
"=>",
"@query_where",
",",
":order",
"=>",
"@query_order",
",",
":limit",
"=>",
"@query_limit",
")",
"pstmt",
"=",
"prepare",
":select",
",",
"sql",
"pstmt",
".",
"enumerate",
"(",
"*",
"binds",
",",
"&",
"block",
")",
"end"
]
| Executes a select SQL for the table and returns an Enumerable object,
or yields each row if block is given.
@return [JDBCHelper::Connection::ResultSet]
@since 0.4.0 | [
"Executes",
"a",
"select",
"SQL",
"for",
"the",
"table",
"and",
"returns",
"an",
"Enumerable",
"object",
"or",
"yields",
"each",
"row",
"if",
"block",
"is",
"given",
"."
]
| 0c0e7142ca7faab93db68d526753032ab2dc652f | https://github.com/junegunn/jdbc-helper/blob/0c0e7142ca7faab93db68d526753032ab2dc652f/lib/jdbc-helper/wrapper/table_wrapper.rb#L227-L237 | train |
junegunn/jdbc-helper | lib/jdbc-helper/wrapper/table_wrapper.rb | JDBCHelper.TableWrapper.clear_batch | def clear_batch *types
types = [:insert, :update, :delete] if types.empty?
types.each do |type|
raise ArgumentError.new("Invalid type: #{type}") unless @pstmts.has_key?(type)
@pstmts[type].values.each(&:clear_batch)
end
nil
end | ruby | def clear_batch *types
types = [:insert, :update, :delete] if types.empty?
types.each do |type|
raise ArgumentError.new("Invalid type: #{type}") unless @pstmts.has_key?(type)
@pstmts[type].values.each(&:clear_batch)
end
nil
end | [
"def",
"clear_batch",
"*",
"types",
"types",
"=",
"[",
":insert",
",",
":update",
",",
":delete",
"]",
"if",
"types",
".",
"empty?",
"types",
".",
"each",
"do",
"|",
"type",
"|",
"raise",
"ArgumentError",
".",
"new",
"(",
"\"Invalid type: #{type}\"",
")",
"unless",
"@pstmts",
".",
"has_key?",
"(",
"type",
")",
"@pstmts",
"[",
"type",
"]",
".",
"values",
".",
"each",
"(",
"&",
":clear_batch",
")",
"end",
"nil",
"end"
]
| Clear batched operations.
@param [*Symbol] types Types of batched operations to clear.
If not given, :insert, :update and :delete.
@return [nil] | [
"Clear",
"batched",
"operations",
"."
]
| 0c0e7142ca7faab93db68d526753032ab2dc652f | https://github.com/junegunn/jdbc-helper/blob/0c0e7142ca7faab93db68d526753032ab2dc652f/lib/jdbc-helper/wrapper/table_wrapper.rb#L267-L274 | train |
junegunn/jdbc-helper | lib/jdbc-helper/wrapper/table_wrapper.rb | JDBCHelper.TableWrapper.close | def close
@pstmts.each do |typ, hash|
hash.each do |sql, pstmt|
pstmt.close if pstmt
end
@pstmts[typ] = {}
end
end | ruby | def close
@pstmts.each do |typ, hash|
hash.each do |sql, pstmt|
pstmt.close if pstmt
end
@pstmts[typ] = {}
end
end | [
"def",
"close",
"@pstmts",
".",
"each",
"do",
"|",
"typ",
",",
"hash",
"|",
"hash",
".",
"each",
"do",
"|",
"sql",
",",
"pstmt",
"|",
"pstmt",
".",
"close",
"if",
"pstmt",
"end",
"@pstmts",
"[",
"typ",
"]",
"=",
"{",
"}",
"end",
"end"
]
| Closes the prepared statements
@since 0.5.0 | [
"Closes",
"the",
"prepared",
"statements"
]
| 0c0e7142ca7faab93db68d526753032ab2dc652f | https://github.com/junegunn/jdbc-helper/blob/0c0e7142ca7faab93db68d526753032ab2dc652f/lib/jdbc-helper/wrapper/table_wrapper.rb#L329-L336 | train |
junegunn/jdbc-helper | lib/jdbc-helper/wrapper/function_wrapper.rb | JDBCHelper.FunctionWrapper.call | def call(*args)
pstmt = @connection.prepare("select #{name}(#{args.map{'?'}.join ','})#{@suffix}")
begin
pstmt.query(*args).to_a[0][0]
ensure
pstmt.close
end
end | ruby | def call(*args)
pstmt = @connection.prepare("select #{name}(#{args.map{'?'}.join ','})#{@suffix}")
begin
pstmt.query(*args).to_a[0][0]
ensure
pstmt.close
end
end | [
"def",
"call",
"(",
"*",
"args",
")",
"pstmt",
"=",
"@connection",
".",
"prepare",
"(",
"\"select #{name}(#{args.map{'?'}.join ','})#{@suffix}\"",
")",
"begin",
"pstmt",
".",
"query",
"(",
"*",
"args",
")",
".",
"to_a",
"[",
"0",
"]",
"[",
"0",
"]",
"ensure",
"pstmt",
".",
"close",
"end",
"end"
]
| Returns the result of the function call with the given parameters | [
"Returns",
"the",
"result",
"of",
"the",
"function",
"call",
"with",
"the",
"given",
"parameters"
]
| 0c0e7142ca7faab93db68d526753032ab2dc652f | https://github.com/junegunn/jdbc-helper/blob/0c0e7142ca7faab93db68d526753032ab2dc652f/lib/jdbc-helper/wrapper/function_wrapper.rb#L27-L34 | train |
junegunn/jdbc-helper | lib/jdbc-helper/wrapper/procedure_wrapper.rb | JDBCHelper.ProcedureWrapper.call | def call(*args)
params = build_params args
cstmt = @connection.prepare_call "{call #{name}(#{Array.new(@cols.length){'?'}.join ', '})}"
begin
process_result( args, cstmt.call(*params) )
ensure
cstmt.close
end
end | ruby | def call(*args)
params = build_params args
cstmt = @connection.prepare_call "{call #{name}(#{Array.new(@cols.length){'?'}.join ', '})}"
begin
process_result( args, cstmt.call(*params) )
ensure
cstmt.close
end
end | [
"def",
"call",
"(",
"*",
"args",
")",
"params",
"=",
"build_params",
"args",
"cstmt",
"=",
"@connection",
".",
"prepare_call",
"\"{call #{name}(#{Array.new(@cols.length){'?'}.join ', '})}\"",
"begin",
"process_result",
"(",
"args",
",",
"cstmt",
".",
"call",
"(",
"*",
"params",
")",
")",
"ensure",
"cstmt",
".",
"close",
"end",
"end"
]
| Executes the procedure and returns the values of INOUT & OUT parameters in Hash
@return [Hash] | [
"Executes",
"the",
"procedure",
"and",
"returns",
"the",
"values",
"of",
"INOUT",
"&",
"OUT",
"parameters",
"in",
"Hash"
]
| 0c0e7142ca7faab93db68d526753032ab2dc652f | https://github.com/junegunn/jdbc-helper/blob/0c0e7142ca7faab93db68d526753032ab2dc652f/lib/jdbc-helper/wrapper/procedure_wrapper.rb#L21-L29 | train |
fernet/fernet-rb | lib/fernet/bit_packing.rb | Fernet.BitPacking.unpack_int64_bigendian | def unpack_int64_bigendian(bytes)
bytes.each_byte.to_a.reverse.each_with_index.
reduce(0) { |val, (byte, index)| val | (byte << (index * 8)) }
end | ruby | def unpack_int64_bigendian(bytes)
bytes.each_byte.to_a.reverse.each_with_index.
reduce(0) { |val, (byte, index)| val | (byte << (index * 8)) }
end | [
"def",
"unpack_int64_bigendian",
"(",
"bytes",
")",
"bytes",
".",
"each_byte",
".",
"to_a",
".",
"reverse",
".",
"each_with_index",
".",
"reduce",
"(",
"0",
")",
"{",
"|",
"val",
",",
"(",
"byte",
",",
"index",
")",
"|",
"val",
"|",
"(",
"byte",
"<<",
"(",
"index",
"*",
"8",
")",
")",
"}",
"end"
]
| Internal - unpacks a string of big endian, 64 bit integers
bytes - an array of ints
Returns the original byte sequence as a string | [
"Internal",
"-",
"unpacks",
"a",
"string",
"of",
"big",
"endian",
"64",
"bit",
"integers"
]
| 90b1c8358abeeae14ddb4cdda677297e1938652c | https://github.com/fernet/fernet-rb/blob/90b1c8358abeeae14ddb4cdda677297e1938652c/lib/fernet/bit_packing.rb#L23-L26 | train |
junegunn/jdbc-helper | lib/jdbc-helper/connection.rb | JDBCHelper.Connection.transaction | def transaction
check_closed
raise ArgumentError.new("Transaction block not given") unless block_given?
tx = Transaction.send :new, @conn
ac = @conn.get_auto_commit
status = :unknown
begin
@conn.set_auto_commit false
yield tx
@conn.commit
status = :committed
rescue Transaction::Commit
status = :committed
rescue Transaction::Rollback
status = :rolledback
ensure
@conn.rollback if status == :unknown && @conn.get_auto_commit == false
@conn.set_auto_commit ac
end
status == :committed
end | ruby | def transaction
check_closed
raise ArgumentError.new("Transaction block not given") unless block_given?
tx = Transaction.send :new, @conn
ac = @conn.get_auto_commit
status = :unknown
begin
@conn.set_auto_commit false
yield tx
@conn.commit
status = :committed
rescue Transaction::Commit
status = :committed
rescue Transaction::Rollback
status = :rolledback
ensure
@conn.rollback if status == :unknown && @conn.get_auto_commit == false
@conn.set_auto_commit ac
end
status == :committed
end | [
"def",
"transaction",
"check_closed",
"raise",
"ArgumentError",
".",
"new",
"(",
"\"Transaction block not given\"",
")",
"unless",
"block_given?",
"tx",
"=",
"Transaction",
".",
"send",
":new",
",",
"@conn",
"ac",
"=",
"@conn",
".",
"get_auto_commit",
"status",
"=",
":unknown",
"begin",
"@conn",
".",
"set_auto_commit",
"false",
"yield",
"tx",
"@conn",
".",
"commit",
"status",
"=",
":committed",
"rescue",
"Transaction",
"::",
"Commit",
"status",
"=",
":committed",
"rescue",
"Transaction",
"::",
"Rollback",
"status",
"=",
":rolledback",
"ensure",
"@conn",
".",
"rollback",
"if",
"status",
"==",
":unknown",
"&&",
"@conn",
".",
"get_auto_commit",
"==",
"false",
"@conn",
".",
"set_auto_commit",
"ac",
"end",
"status",
"==",
":committed",
"end"
]
| Executes the given code block as a transaction. Returns true if the transaction is committed.
A transaction object is passed to the block, which only has commit and rollback methods.
The execution breaks out of the code block when either of the methods is called.
@yield [JDBCHelper::Connection::Transaction] Responds to commit and rollback.
@return [Boolean] True if committed | [
"Executes",
"the",
"given",
"code",
"block",
"as",
"a",
"transaction",
".",
"Returns",
"true",
"if",
"the",
"transaction",
"is",
"committed",
".",
"A",
"transaction",
"object",
"is",
"passed",
"to",
"the",
"block",
"which",
"only",
"has",
"commit",
"and",
"rollback",
"methods",
".",
"The",
"execution",
"breaks",
"out",
"of",
"the",
"code",
"block",
"when",
"either",
"of",
"the",
"methods",
"is",
"called",
"."
]
| 0c0e7142ca7faab93db68d526753032ab2dc652f | https://github.com/junegunn/jdbc-helper/blob/0c0e7142ca7faab93db68d526753032ab2dc652f/lib/jdbc-helper/connection.rb#L231-L252 | train |
junegunn/jdbc-helper | lib/jdbc-helper/connection.rb | JDBCHelper.Connection.execute | def execute(qstr)
check_closed
stmt = @spool.take
begin
if stmt.execute(qstr)
ResultSet.send(:new, stmt.getResultSet) { @spool.give stmt }
else
rset = stmt.getUpdateCount
@spool.give stmt
rset
end
rescue Exception => e
@spool.give stmt
raise
end
end | ruby | def execute(qstr)
check_closed
stmt = @spool.take
begin
if stmt.execute(qstr)
ResultSet.send(:new, stmt.getResultSet) { @spool.give stmt }
else
rset = stmt.getUpdateCount
@spool.give stmt
rset
end
rescue Exception => e
@spool.give stmt
raise
end
end | [
"def",
"execute",
"(",
"qstr",
")",
"check_closed",
"stmt",
"=",
"@spool",
".",
"take",
"begin",
"if",
"stmt",
".",
"execute",
"(",
"qstr",
")",
"ResultSet",
".",
"send",
"(",
":new",
",",
"stmt",
".",
"getResultSet",
")",
"{",
"@spool",
".",
"give",
"stmt",
"}",
"else",
"rset",
"=",
"stmt",
".",
"getUpdateCount",
"@spool",
".",
"give",
"stmt",
"rset",
"end",
"rescue",
"Exception",
"=>",
"e",
"@spool",
".",
"give",
"stmt",
"raise",
"end",
"end"
]
| Executes an SQL and returns the count of the update rows or a ResultSet object
depending on the type of the given statement.
If a ResultSet is returned, it must be enumerated or closed.
@param [String] qstr SQL string
@return [Fixnum|ResultSet] | [
"Executes",
"an",
"SQL",
"and",
"returns",
"the",
"count",
"of",
"the",
"update",
"rows",
"or",
"a",
"ResultSet",
"object",
"depending",
"on",
"the",
"type",
"of",
"the",
"given",
"statement",
".",
"If",
"a",
"ResultSet",
"is",
"returned",
"it",
"must",
"be",
"enumerated",
"or",
"closed",
"."
]
| 0c0e7142ca7faab93db68d526753032ab2dc652f | https://github.com/junegunn/jdbc-helper/blob/0c0e7142ca7faab93db68d526753032ab2dc652f/lib/jdbc-helper/connection.rb#L259-L275 | train |
junegunn/jdbc-helper | lib/jdbc-helper/connection.rb | JDBCHelper.Connection.query | def query(qstr, &blk)
check_closed
stmt = @spool.take
begin
rset = stmt.execute_query(qstr)
rescue Exception => e
@spool.give stmt
raise
end
enum = ResultSet.send(:new, rset) { @spool.give stmt }
if block_given?
enum.each do |row|
yield row
end
else
enum
end
end | ruby | def query(qstr, &blk)
check_closed
stmt = @spool.take
begin
rset = stmt.execute_query(qstr)
rescue Exception => e
@spool.give stmt
raise
end
enum = ResultSet.send(:new, rset) { @spool.give stmt }
if block_given?
enum.each do |row|
yield row
end
else
enum
end
end | [
"def",
"query",
"(",
"qstr",
",",
"&",
"blk",
")",
"check_closed",
"stmt",
"=",
"@spool",
".",
"take",
"begin",
"rset",
"=",
"stmt",
".",
"execute_query",
"(",
"qstr",
")",
"rescue",
"Exception",
"=>",
"e",
"@spool",
".",
"give",
"stmt",
"raise",
"end",
"enum",
"=",
"ResultSet",
".",
"send",
"(",
":new",
",",
"rset",
")",
"{",
"@spool",
".",
"give",
"stmt",
"}",
"if",
"block_given?",
"enum",
".",
"each",
"do",
"|",
"row",
"|",
"yield",
"row",
"end",
"else",
"enum",
"end",
"end"
]
| Executes a select query.
When a code block is given, each row of the result is passed to the block one by one.
If not given, ResultSet is returned, which can be used to enumerate through the result set.
ResultSet is closed automatically when all the rows in the result set is consumed.
@example Nested querying
conn.query("SELECT a FROM T") do | trow |
conn.query("SELECT * FROM U_#{trow.a}").each_slice(10) do | urows |
# ...
end
end
@param [String] qstr SQL string
@yield [JDBCHelper::Connection::Row]
@return [Array] | [
"Executes",
"a",
"select",
"query",
".",
"When",
"a",
"code",
"block",
"is",
"given",
"each",
"row",
"of",
"the",
"result",
"is",
"passed",
"to",
"the",
"block",
"one",
"by",
"one",
".",
"If",
"not",
"given",
"ResultSet",
"is",
"returned",
"which",
"can",
"be",
"used",
"to",
"enumerate",
"through",
"the",
"result",
"set",
".",
"ResultSet",
"is",
"closed",
"automatically",
"when",
"all",
"the",
"rows",
"in",
"the",
"result",
"set",
"is",
"consumed",
"."
]
| 0c0e7142ca7faab93db68d526753032ab2dc652f | https://github.com/junegunn/jdbc-helper/blob/0c0e7142ca7faab93db68d526753032ab2dc652f/lib/jdbc-helper/connection.rb#L302-L321 | train |
junegunn/jdbc-helper | lib/jdbc-helper/connection.rb | JDBCHelper.Connection.execute_batch | def execute_batch
check_closed
cnt = 0
if @bstmt
cnt += @bstmt.execute_batch.inject(:+) || 0
@spool.give @bstmt
@bstmt = nil
end
@pstmts.each do |pstmt|
cnt += pstmt.execute_batch
end
cnt
end | ruby | def execute_batch
check_closed
cnt = 0
if @bstmt
cnt += @bstmt.execute_batch.inject(:+) || 0
@spool.give @bstmt
@bstmt = nil
end
@pstmts.each do |pstmt|
cnt += pstmt.execute_batch
end
cnt
end | [
"def",
"execute_batch",
"check_closed",
"cnt",
"=",
"0",
"if",
"@bstmt",
"cnt",
"+=",
"@bstmt",
".",
"execute_batch",
".",
"inject",
"(",
":+",
")",
"||",
"0",
"@spool",
".",
"give",
"@bstmt",
"@bstmt",
"=",
"nil",
"end",
"@pstmts",
".",
"each",
"do",
"|",
"pstmt",
"|",
"cnt",
"+=",
"pstmt",
".",
"execute_batch",
"end",
"cnt",
"end"
]
| Executes batched statements including prepared statements. No effect when no statement is added
@return [Fixnum] Sum of all update counts | [
"Executes",
"batched",
"statements",
"including",
"prepared",
"statements",
".",
"No",
"effect",
"when",
"no",
"statement",
"is",
"added"
]
| 0c0e7142ca7faab93db68d526753032ab2dc652f | https://github.com/junegunn/jdbc-helper/blob/0c0e7142ca7faab93db68d526753032ab2dc652f/lib/jdbc-helper/connection.rb#L337-L353 | train |
junegunn/jdbc-helper | lib/jdbc-helper/connection.rb | JDBCHelper.Connection.table | def table table_name
table = JDBCHelper::TableWrapper.new(self, table_name)
table = table.fetch_size(@fetch_size) if @fetch_size
@table_wrappers[table_name] ||= table
end | ruby | def table table_name
table = JDBCHelper::TableWrapper.new(self, table_name)
table = table.fetch_size(@fetch_size) if @fetch_size
@table_wrappers[table_name] ||= table
end | [
"def",
"table",
"table_name",
"table",
"=",
"JDBCHelper",
"::",
"TableWrapper",
".",
"new",
"(",
"self",
",",
"table_name",
")",
"table",
"=",
"table",
".",
"fetch_size",
"(",
"@fetch_size",
")",
"if",
"@fetch_size",
"@table_wrappers",
"[",
"table_name",
"]",
"||=",
"table",
"end"
]
| Returns a table wrapper for the given table name
@since 0.2.0
@param [String/Symbol] table_name Name of the table to be wrapped
@return [JDBCHelper::TableWrapper] | [
"Returns",
"a",
"table",
"wrapper",
"for",
"the",
"given",
"table",
"name"
]
| 0c0e7142ca7faab93db68d526753032ab2dc652f | https://github.com/junegunn/jdbc-helper/blob/0c0e7142ca7faab93db68d526753032ab2dc652f/lib/jdbc-helper/connection.rb#L406-L410 | train |
chargify/chargify_api_ares | lib/chargify_api_ares/resources/subscription.rb | Chargify.Subscription.save | def save
self.attributes.stringify_keys!
self.attributes.delete('customer')
self.attributes.delete('product')
self.attributes.delete('credit_card')
self.attributes.delete('bank_account')
self.attributes.delete('paypal_account')
self.attributes, options = extract_uniqueness_token(attributes)
self.prefix_options.merge!(options)
super
end | ruby | def save
self.attributes.stringify_keys!
self.attributes.delete('customer')
self.attributes.delete('product')
self.attributes.delete('credit_card')
self.attributes.delete('bank_account')
self.attributes.delete('paypal_account')
self.attributes, options = extract_uniqueness_token(attributes)
self.prefix_options.merge!(options)
super
end | [
"def",
"save",
"self",
".",
"attributes",
".",
"stringify_keys!",
"self",
".",
"attributes",
".",
"delete",
"(",
"'customer'",
")",
"self",
".",
"attributes",
".",
"delete",
"(",
"'product'",
")",
"self",
".",
"attributes",
".",
"delete",
"(",
"'credit_card'",
")",
"self",
".",
"attributes",
".",
"delete",
"(",
"'bank_account'",
")",
"self",
".",
"attributes",
".",
"delete",
"(",
"'paypal_account'",
")",
"self",
".",
"attributes",
",",
"options",
"=",
"extract_uniqueness_token",
"(",
"attributes",
")",
"self",
".",
"prefix_options",
".",
"merge!",
"(",
"options",
")",
"super",
"end"
]
| Strip off nested attributes of associations before saving, or type-mismatch errors will occur | [
"Strip",
"off",
"nested",
"attributes",
"of",
"associations",
"before",
"saving",
"or",
"type",
"-",
"mismatch",
"errors",
"will",
"occur"
]
| b0c2c7d2bec9213982868cf43a2c83fa1bf78880 | https://github.com/chargify/chargify_api_ares/blob/b0c2c7d2bec9213982868cf43a2c83fa1bf78880/lib/chargify_api_ares/resources/subscription.rb#L11-L22 | train |
gbiczo/oxcelix | lib/oxcelix/workbook.rb | Oxcelix.Workbook.unpack | def unpack(filename)
@destination = Dir.mktmpdir
Zip::File.open(filename){ |zip_file|
zip_file.each{ |f|
f_path=File.join(@destination, f.name)
FileUtils.mkdir_p(File.dirname(f_path))
zip_file.extract(f, f_path) unless File.exists?(f_path)
}
}
end | ruby | def unpack(filename)
@destination = Dir.mktmpdir
Zip::File.open(filename){ |zip_file|
zip_file.each{ |f|
f_path=File.join(@destination, f.name)
FileUtils.mkdir_p(File.dirname(f_path))
zip_file.extract(f, f_path) unless File.exists?(f_path)
}
}
end | [
"def",
"unpack",
"(",
"filename",
")",
"@destination",
"=",
"Dir",
".",
"mktmpdir",
"Zip",
"::",
"File",
".",
"open",
"(",
"filename",
")",
"{",
"|",
"zip_file",
"|",
"zip_file",
".",
"each",
"{",
"|",
"f",
"|",
"f_path",
"=",
"File",
".",
"join",
"(",
"@destination",
",",
"f",
".",
"name",
")",
"FileUtils",
".",
"mkdir_p",
"(",
"File",
".",
"dirname",
"(",
"f_path",
")",
")",
"zip_file",
".",
"extract",
"(",
"f",
",",
"f_path",
")",
"unless",
"File",
".",
"exists?",
"(",
"f_path",
")",
"}",
"}",
"end"
]
| Unzips the excel file to a temporary directory. The directory will be removed at the end of the parsing stage when invoked
by initialize, otherwise at exit.
@param [String] filename the name of the Excel file to be unpacked | [
"Unzips",
"the",
"excel",
"file",
"to",
"a",
"temporary",
"directory",
".",
"The",
"directory",
"will",
"be",
"removed",
"at",
"the",
"end",
"of",
"the",
"parsing",
"stage",
"when",
"invoked",
"by",
"initialize",
"otherwise",
"at",
"exit",
"."
]
| 144378e62c5288781db53345ec9d400dc7a70dc3 | https://github.com/gbiczo/oxcelix/blob/144378e62c5288781db53345ec9d400dc7a70dc3/lib/oxcelix/workbook.rb#L72-L81 | train |
gbiczo/oxcelix | lib/oxcelix/workbook.rb | Oxcelix.Workbook.parse | def parse(options={})
@sheets.each do |x|
if !options[:paginate].nil?
lines = options[:paginate][0]; page = options[:paginate][1]
sheet = PagSheet.new(lines, page)
elsif !options[:cellrange].nil?
range = options[:cellrange]
sheet = Cellrange.new(range)
else
sheet = Xlsheet.new()
end
File.open(@destination+"/xl/#{x[:filename]}", 'r') do |f|
Ox.sax_parse(sheet, f)
end
comments = mkcomments(x[:comments])
sheet.cellarray.each do |sh|
sh.numformat = @styles.styleary[sh.style.to_i]
if sh.type=="s"
sh.value = @sharedstrings[sh.value.to_i]
end
if !comments.nil?
comm=comments.select {|c| c[:ref]==(sh.xlcoords)}
if comm.size > 0
sh.comment=comm[0][:comment]
end
comments.delete_if{|c| c[:ref]==(sh.xlcoords)}
end
end
x[:cells] = sheet.cellarray
x[:mergedcells] = sheet.mergedcells
end
matrixto options
end | ruby | def parse(options={})
@sheets.each do |x|
if !options[:paginate].nil?
lines = options[:paginate][0]; page = options[:paginate][1]
sheet = PagSheet.new(lines, page)
elsif !options[:cellrange].nil?
range = options[:cellrange]
sheet = Cellrange.new(range)
else
sheet = Xlsheet.new()
end
File.open(@destination+"/xl/#{x[:filename]}", 'r') do |f|
Ox.sax_parse(sheet, f)
end
comments = mkcomments(x[:comments])
sheet.cellarray.each do |sh|
sh.numformat = @styles.styleary[sh.style.to_i]
if sh.type=="s"
sh.value = @sharedstrings[sh.value.to_i]
end
if !comments.nil?
comm=comments.select {|c| c[:ref]==(sh.xlcoords)}
if comm.size > 0
sh.comment=comm[0][:comment]
end
comments.delete_if{|c| c[:ref]==(sh.xlcoords)}
end
end
x[:cells] = sheet.cellarray
x[:mergedcells] = sheet.mergedcells
end
matrixto options
end | [
"def",
"parse",
"(",
"options",
"=",
"{",
"}",
")",
"@sheets",
".",
"each",
"do",
"|",
"x",
"|",
"if",
"!",
"options",
"[",
":paginate",
"]",
".",
"nil?",
"lines",
"=",
"options",
"[",
":paginate",
"]",
"[",
"0",
"]",
";",
"page",
"=",
"options",
"[",
":paginate",
"]",
"[",
"1",
"]",
"sheet",
"=",
"PagSheet",
".",
"new",
"(",
"lines",
",",
"page",
")",
"elsif",
"!",
"options",
"[",
":cellrange",
"]",
".",
"nil?",
"range",
"=",
"options",
"[",
":cellrange",
"]",
"sheet",
"=",
"Cellrange",
".",
"new",
"(",
"range",
")",
"else",
"sheet",
"=",
"Xlsheet",
".",
"new",
"(",
")",
"end",
"File",
".",
"open",
"(",
"@destination",
"+",
"\"/xl/#{x[:filename]}\"",
",",
"'r'",
")",
"do",
"|",
"f",
"|",
"Ox",
".",
"sax_parse",
"(",
"sheet",
",",
"f",
")",
"end",
"comments",
"=",
"mkcomments",
"(",
"x",
"[",
":comments",
"]",
")",
"sheet",
".",
"cellarray",
".",
"each",
"do",
"|",
"sh",
"|",
"sh",
".",
"numformat",
"=",
"@styles",
".",
"styleary",
"[",
"sh",
".",
"style",
".",
"to_i",
"]",
"if",
"sh",
".",
"type",
"==",
"\"s\"",
"sh",
".",
"value",
"=",
"@sharedstrings",
"[",
"sh",
".",
"value",
".",
"to_i",
"]",
"end",
"if",
"!",
"comments",
".",
"nil?",
"comm",
"=",
"comments",
".",
"select",
"{",
"|",
"c",
"|",
"c",
"[",
":ref",
"]",
"==",
"(",
"sh",
".",
"xlcoords",
")",
"}",
"if",
"comm",
".",
"size",
">",
"0",
"sh",
".",
"comment",
"=",
"comm",
"[",
"0",
"]",
"[",
":comment",
"]",
"end",
"comments",
".",
"delete_if",
"{",
"|",
"c",
"|",
"c",
"[",
":ref",
"]",
"==",
"(",
"sh",
".",
"xlcoords",
")",
"}",
"end",
"end",
"x",
"[",
":cells",
"]",
"=",
"sheet",
".",
"cellarray",
"x",
"[",
":mergedcells",
"]",
"=",
"sheet",
".",
"mergedcells",
"end",
"matrixto",
"options",
"end"
]
| Parses sheet data by feeding the output of the Xlsheet SAX parser into the arrays representing the sheets.
@param [Hash] options Options that affect the parser. | [
"Parses",
"sheet",
"data",
"by",
"feeding",
"the",
"output",
"of",
"the",
"Xlsheet",
"SAX",
"parser",
"into",
"the",
"arrays",
"representing",
"the",
"sheets",
"."
]
| 144378e62c5288781db53345ec9d400dc7a70dc3 | https://github.com/gbiczo/oxcelix/blob/144378e62c5288781db53345ec9d400dc7a70dc3/lib/oxcelix/workbook.rb#L103-L136 | train |
gbiczo/oxcelix | lib/oxcelix/workbook.rb | Oxcelix.Workbook.commentsrel | def commentsrel
unless Dir[@destination + '/xl/worksheets/_rels'].empty?
Find.find(@destination + '/xl/worksheets/_rels') do |path|
if File.basename(path).split(".").last=='rels'
a=IO.read(path)
f=Ox::load(a)
f.locate("Relationships/*").each do |x|
if x[:Target].include?"comments"
@sheets.each do |s|
if "worksheets/" + File.basename(path,".rels")==s[:filename]
s[:comments]=x[:Target]
end
end
end
end
end
end
else
@sheets.each do |s|
s[:comments]=nil
end
end
end | ruby | def commentsrel
unless Dir[@destination + '/xl/worksheets/_rels'].empty?
Find.find(@destination + '/xl/worksheets/_rels') do |path|
if File.basename(path).split(".").last=='rels'
a=IO.read(path)
f=Ox::load(a)
f.locate("Relationships/*").each do |x|
if x[:Target].include?"comments"
@sheets.each do |s|
if "worksheets/" + File.basename(path,".rels")==s[:filename]
s[:comments]=x[:Target]
end
end
end
end
end
end
else
@sheets.each do |s|
s[:comments]=nil
end
end
end | [
"def",
"commentsrel",
"unless",
"Dir",
"[",
"@destination",
"+",
"'/xl/worksheets/_rels'",
"]",
".",
"empty?",
"Find",
".",
"find",
"(",
"@destination",
"+",
"'/xl/worksheets/_rels'",
")",
"do",
"|",
"path",
"|",
"if",
"File",
".",
"basename",
"(",
"path",
")",
".",
"split",
"(",
"\".\"",
")",
".",
"last",
"==",
"'rels'",
"a",
"=",
"IO",
".",
"read",
"(",
"path",
")",
"f",
"=",
"Ox",
"::",
"load",
"(",
"a",
")",
"f",
".",
"locate",
"(",
"\"Relationships/*\"",
")",
".",
"each",
"do",
"|",
"x",
"|",
"if",
"x",
"[",
":Target",
"]",
".",
"include?",
"\"comments\"",
"@sheets",
".",
"each",
"do",
"|",
"s",
"|",
"if",
"\"worksheets/\"",
"+",
"File",
".",
"basename",
"(",
"path",
",",
"\".rels\"",
")",
"==",
"s",
"[",
":filename",
"]",
"s",
"[",
":comments",
"]",
"=",
"x",
"[",
":Target",
"]",
"end",
"end",
"end",
"end",
"end",
"end",
"else",
"@sheets",
".",
"each",
"do",
"|",
"s",
"|",
"s",
"[",
":comments",
"]",
"=",
"nil",
"end",
"end",
"end"
]
| Build the relationship between sheets and the XML files storing the comments
to the actual sheet. | [
"Build",
"the",
"relationship",
"between",
"sheets",
"and",
"the",
"XML",
"files",
"storing",
"the",
"comments",
"to",
"the",
"actual",
"sheet",
"."
]
| 144378e62c5288781db53345ec9d400dc7a70dc3 | https://github.com/gbiczo/oxcelix/blob/144378e62c5288781db53345ec9d400dc7a70dc3/lib/oxcelix/workbook.rb#L192-L214 | train |
gbiczo/oxcelix | lib/oxcelix/workbook.rb | Oxcelix.Workbook.shstrings | def shstrings
strings = Sharedstrings.new()
File.open(@destination + '/xl/sharedStrings.xml', 'r') do |f|
Ox.sax_parse(strings, f)
end
@sharedstrings=strings.stringarray
end | ruby | def shstrings
strings = Sharedstrings.new()
File.open(@destination + '/xl/sharedStrings.xml', 'r') do |f|
Ox.sax_parse(strings, f)
end
@sharedstrings=strings.stringarray
end | [
"def",
"shstrings",
"strings",
"=",
"Sharedstrings",
".",
"new",
"(",
")",
"File",
".",
"open",
"(",
"@destination",
"+",
"'/xl/sharedStrings.xml'",
",",
"'r'",
")",
"do",
"|",
"f",
"|",
"Ox",
".",
"sax_parse",
"(",
"strings",
",",
"f",
")",
"end",
"@sharedstrings",
"=",
"strings",
".",
"stringarray",
"end"
]
| Invokes the Sharedstrings helper class | [
"Invokes",
"the",
"Sharedstrings",
"helper",
"class"
]
| 144378e62c5288781db53345ec9d400dc7a70dc3 | https://github.com/gbiczo/oxcelix/blob/144378e62c5288781db53345ec9d400dc7a70dc3/lib/oxcelix/workbook.rb#L217-L223 | train |
gbiczo/oxcelix | lib/oxcelix/workbook.rb | Oxcelix.Workbook.mkcomments | def mkcomments(commentfile)
unless commentfile.nil?
comms = Comments.new()
File.open(@destination + '/xl/'+commentfile.gsub('../', ''), 'r') do |f|
Ox.sax_parse(comms, f)
end
return comms.commarray
end
end | ruby | def mkcomments(commentfile)
unless commentfile.nil?
comms = Comments.new()
File.open(@destination + '/xl/'+commentfile.gsub('../', ''), 'r') do |f|
Ox.sax_parse(comms, f)
end
return comms.commarray
end
end | [
"def",
"mkcomments",
"(",
"commentfile",
")",
"unless",
"commentfile",
".",
"nil?",
"comms",
"=",
"Comments",
".",
"new",
"(",
")",
"File",
".",
"open",
"(",
"@destination",
"+",
"'/xl/'",
"+",
"commentfile",
".",
"gsub",
"(",
"'../'",
",",
"''",
")",
",",
"'r'",
")",
"do",
"|",
"f",
"|",
"Ox",
".",
"sax_parse",
"(",
"comms",
",",
"f",
")",
"end",
"return",
"comms",
".",
"commarray",
"end",
"end"
]
| Parses the comments related to the actual sheet.
@param [String] commentfile
@return [Array] a collection of comments relative to the Excel sheet currently processed | [
"Parses",
"the",
"comments",
"related",
"to",
"the",
"actual",
"sheet",
"."
]
| 144378e62c5288781db53345ec9d400dc7a70dc3 | https://github.com/gbiczo/oxcelix/blob/144378e62c5288781db53345ec9d400dc7a70dc3/lib/oxcelix/workbook.rb#L228-L236 | train |
gbiczo/oxcelix | lib/oxcelix/workbook.rb | Oxcelix.Workbook.mergevalues | def mergevalues(m, col, row, valuecell)
if valuecell != nil
valuecell.xlcoords=(col.col_name)+(row+1).to_s
m[row, col]=valuecell
return m, valuecell
else
valuecell=Cell.new
valuecell.xlcoords=(col.col_name)+(row+1).to_s
m[row, col]=valuecell
return m, valuecell
end
end | ruby | def mergevalues(m, col, row, valuecell)
if valuecell != nil
valuecell.xlcoords=(col.col_name)+(row+1).to_s
m[row, col]=valuecell
return m, valuecell
else
valuecell=Cell.new
valuecell.xlcoords=(col.col_name)+(row+1).to_s
m[row, col]=valuecell
return m, valuecell
end
end | [
"def",
"mergevalues",
"(",
"m",
",",
"col",
",",
"row",
",",
"valuecell",
")",
"if",
"valuecell",
"!=",
"nil",
"valuecell",
".",
"xlcoords",
"=",
"(",
"col",
".",
"col_name",
")",
"+",
"(",
"row",
"+",
"1",
")",
".",
"to_s",
"m",
"[",
"row",
",",
"col",
"]",
"=",
"valuecell",
"return",
"m",
",",
"valuecell",
"else",
"valuecell",
"=",
"Cell",
".",
"new",
"valuecell",
".",
"xlcoords",
"=",
"(",
"col",
".",
"col_name",
")",
"+",
"(",
"row",
"+",
"1",
")",
".",
"to_s",
"m",
"[",
"row",
",",
"col",
"]",
"=",
"valuecell",
"return",
"m",
",",
"valuecell",
"end",
"end"
]
| Replace the empty values of the mergegroup with cell values or nil.
@param [Matrix] m the Sheet object
@param [Integer] col Column of the actual cell
@param [Integer] row Row of the actual cell
@param [Cell] valuecell A Cell containing the value to be copied over the mergegroup
@return [Matrix, Cell] the sheet and the new (empty) cell or nil. | [
"Replace",
"the",
"empty",
"values",
"of",
"the",
"mergegroup",
"with",
"cell",
"values",
"or",
"nil",
"."
]
| 144378e62c5288781db53345ec9d400dc7a70dc3 | https://github.com/gbiczo/oxcelix/blob/144378e62c5288781db53345ec9d400dc7a70dc3/lib/oxcelix/workbook.rb#L311-L322 | train |
gbiczo/oxcelix | lib/oxcelix/numformats.rb | Oxcelix.Numformats.datetime | def datetime formatcode
deminutified = formatcode.downcase.gsub(/(?<hrs>H|h)(?<div>.)m/, '\k<hrs>\k<div>i')
.gsub(/im/, 'ii')
.gsub(/m(?<div>.)(?<secs>s)/, 'i\k<div>\k<secs>')
.gsub(/mi/, 'ii')
return deminutified.gsub(/[yMmDdHhSsi]*/, Dtmap)
end | ruby | def datetime formatcode
deminutified = formatcode.downcase.gsub(/(?<hrs>H|h)(?<div>.)m/, '\k<hrs>\k<div>i')
.gsub(/im/, 'ii')
.gsub(/m(?<div>.)(?<secs>s)/, 'i\k<div>\k<secs>')
.gsub(/mi/, 'ii')
return deminutified.gsub(/[yMmDdHhSsi]*/, Dtmap)
end | [
"def",
"datetime",
"formatcode",
"deminutified",
"=",
"formatcode",
".",
"downcase",
".",
"gsub",
"(",
"/",
"/",
",",
"'\\k<hrs>\\k<div>i'",
")",
".",
"gsub",
"(",
"/",
"/",
",",
"'ii'",
")",
".",
"gsub",
"(",
"/",
"/",
",",
"'i\\k<div>\\k<secs>'",
")",
".",
"gsub",
"(",
"/",
"/",
",",
"'ii'",
")",
"return",
"deminutified",
".",
"gsub",
"(",
"/",
"/",
",",
"Dtmap",
")",
"end"
]
| Convert excel-style date formats into ruby DateTime strftime format strings
@param [String] formatcode an Excel number format string.
@return [String] a DateTime::strftime format string. | [
"Convert",
"excel",
"-",
"style",
"date",
"formats",
"into",
"ruby",
"DateTime",
"strftime",
"format",
"strings"
]
| 144378e62c5288781db53345ec9d400dc7a70dc3 | https://github.com/gbiczo/oxcelix/blob/144378e62c5288781db53345ec9d400dc7a70dc3/lib/oxcelix/numformats.rb#L67-L73 | train |
gbiczo/oxcelix | lib/oxcelix/numformats.rb | Oxcelix.Numberhelper.to_ru | def to_ru
if [email protected]? || Numformats::Formatarray[@numformat.to_i][:xl] == nil || Numformats::Formatarray[@numformat.to_i][:xl].downcase == "general"
return @value
end
if Numformats::Formatarray[@numformat.to_i][:cls] == 'date'
return DateTime.new(1899, 12, 30) + (eval @value)
elsif Numformats::Formatarray[@numformat.to_i][:cls] == 'numeric' || Numformats::Formatarray[@numformat.to_i][:cls] == 'rational'
return eval @value rescue @value
end
end | ruby | def to_ru
if [email protected]? || Numformats::Formatarray[@numformat.to_i][:xl] == nil || Numformats::Formatarray[@numformat.to_i][:xl].downcase == "general"
return @value
end
if Numformats::Formatarray[@numformat.to_i][:cls] == 'date'
return DateTime.new(1899, 12, 30) + (eval @value)
elsif Numformats::Formatarray[@numformat.to_i][:cls] == 'numeric' || Numformats::Formatarray[@numformat.to_i][:cls] == 'rational'
return eval @value rescue @value
end
end | [
"def",
"to_ru",
"if",
"!",
"@value",
".",
"numeric?",
"||",
"Numformats",
"::",
"Formatarray",
"[",
"@numformat",
".",
"to_i",
"]",
"[",
":xl",
"]",
"==",
"nil",
"||",
"Numformats",
"::",
"Formatarray",
"[",
"@numformat",
".",
"to_i",
"]",
"[",
":xl",
"]",
".",
"downcase",
"==",
"\"general\"",
"return",
"@value",
"end",
"if",
"Numformats",
"::",
"Formatarray",
"[",
"@numformat",
".",
"to_i",
"]",
"[",
":cls",
"]",
"==",
"'date'",
"return",
"DateTime",
".",
"new",
"(",
"1899",
",",
"12",
",",
"30",
")",
"+",
"(",
"eval",
"@value",
")",
"elsif",
"Numformats",
"::",
"Formatarray",
"[",
"@numformat",
".",
"to_i",
"]",
"[",
":cls",
"]",
"==",
"'numeric'",
"||",
"Numformats",
"::",
"Formatarray",
"[",
"@numformat",
".",
"to_i",
"]",
"[",
":cls",
"]",
"==",
"'rational'",
"return",
"eval",
"@value",
"rescue",
"@value",
"end",
"end"
]
| Get the cell's value and excel format string and return a string, a ruby Numeric or a DateTime object accordingly
@return [Object] A ruby object that holds and represents the value stored in the cell. Conversion is based on cell formatting.
@example Get the value of a cell:
c = w.sheets[0]["B3"] # => <Oxcelix::Cell:0x00000002a5b368 @xlcoords="A3", @style="84", @type="n", @value="41155", @numformat=14>
c.to_ru # => <DateTime: 2012-09-03T00:00:00+00:00 ((2456174j,0s,0n),+0s,2299161j)> | [
"Get",
"the",
"cell",
"s",
"value",
"and",
"excel",
"format",
"string",
"and",
"return",
"a",
"string",
"a",
"ruby",
"Numeric",
"or",
"a",
"DateTime",
"object",
"accordingly"
]
| 144378e62c5288781db53345ec9d400dc7a70dc3 | https://github.com/gbiczo/oxcelix/blob/144378e62c5288781db53345ec9d400dc7a70dc3/lib/oxcelix/numformats.rb#L85-L94 | train |
gbiczo/oxcelix | lib/oxcelix/numformats.rb | Oxcelix.Numberhelper.to_fmt | def to_fmt
begin
if Numformats::Formatarray[@numformat.to_i][:cls] == 'date'
self.to_ru.strftime(Numformats::Formatarray[@numformat][:ostring]) rescue @value
elsif Numformats::Formatarray[@numformat.to_i][:cls] == 'numeric' || Numformats::Formatarray[@numformat.to_i][:cls] == 'rational'
sprintf(Numformats::Formatarray[@numformat][:ostring], self.to_ru) rescue @value
else
return @value
end
end
end | ruby | def to_fmt
begin
if Numformats::Formatarray[@numformat.to_i][:cls] == 'date'
self.to_ru.strftime(Numformats::Formatarray[@numformat][:ostring]) rescue @value
elsif Numformats::Formatarray[@numformat.to_i][:cls] == 'numeric' || Numformats::Formatarray[@numformat.to_i][:cls] == 'rational'
sprintf(Numformats::Formatarray[@numformat][:ostring], self.to_ru) rescue @value
else
return @value
end
end
end | [
"def",
"to_fmt",
"begin",
"if",
"Numformats",
"::",
"Formatarray",
"[",
"@numformat",
".",
"to_i",
"]",
"[",
":cls",
"]",
"==",
"'date'",
"self",
".",
"to_ru",
".",
"strftime",
"(",
"Numformats",
"::",
"Formatarray",
"[",
"@numformat",
"]",
"[",
":ostring",
"]",
")",
"rescue",
"@value",
"elsif",
"Numformats",
"::",
"Formatarray",
"[",
"@numformat",
".",
"to_i",
"]",
"[",
":cls",
"]",
"==",
"'numeric'",
"||",
"Numformats",
"::",
"Formatarray",
"[",
"@numformat",
".",
"to_i",
"]",
"[",
":cls",
"]",
"==",
"'rational'",
"sprintf",
"(",
"Numformats",
"::",
"Formatarray",
"[",
"@numformat",
"]",
"[",
":ostring",
"]",
",",
"self",
".",
"to_ru",
")",
"rescue",
"@value",
"else",
"return",
"@value",
"end",
"end",
"end"
]
| Get the cell's value, convert it with to_ru and finally, format it based on the value's type.
@return [String] Value gets formatted depending on its class. If it is a DateTime, the #DateTime.strftime method is used,
if it holds a number, the #Kernel::sprintf is run.
@example Get the formatted value of a cell:
c = w.sheets[0]["B3"] # => <Oxcelix::Cell:0x00000002a5b368 @xlcoords="A3", @style="84", @type="n", @value="41155", @numformat=14>
c.to_fmt # => "3/9/2012" | [
"Get",
"the",
"cell",
"s",
"value",
"convert",
"it",
"with",
"to_ru",
"and",
"finally",
"format",
"it",
"based",
"on",
"the",
"value",
"s",
"type",
"."
]
| 144378e62c5288781db53345ec9d400dc7a70dc3 | https://github.com/gbiczo/oxcelix/blob/144378e62c5288781db53345ec9d400dc7a70dc3/lib/oxcelix/numformats.rb#L103-L113 | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.