id
int32 0
24.9k
| repo
stringlengths 5
58
| path
stringlengths 9
168
| func_name
stringlengths 9
130
| original_string
stringlengths 66
10.5k
| language
stringclasses 1
value | code
stringlengths 66
10.5k
| code_tokens
list | docstring
stringlengths 8
16k
| docstring_tokens
list | sha
stringlengths 40
40
| url
stringlengths 94
266
|
---|---|---|---|---|---|---|---|---|---|---|---|
7,300 |
PRX/pmp
|
lib/pmp/collection_document.rb
|
PMP.CollectionDocument.request
|
def request(method, url, body=nil) # :nodoc:
unless ['/', ''].include?(URI::parse(url).path)
setup_oauth_token
end
begin
raw = connection(current_options.merge({url: url})).send(method) do |req|
if [:post, :put].include?(method.to_sym) && !body.blank?
req.body = PMP::CollectionDocument.to_persist_json(body)
end
end
rescue Faraday::Error::ResourceNotFound => not_found_ex
if (method.to_sym == :get)
raw = OpenStruct.new(body: nil, status: 404)
else
raise not_found_ex
end
end
# may not need this, but remember how we made this response
PMP::Response.new(raw, {method: method, url: url, body: body})
end
|
ruby
|
def request(method, url, body=nil) # :nodoc:
unless ['/', ''].include?(URI::parse(url).path)
setup_oauth_token
end
begin
raw = connection(current_options.merge({url: url})).send(method) do |req|
if [:post, :put].include?(method.to_sym) && !body.blank?
req.body = PMP::CollectionDocument.to_persist_json(body)
end
end
rescue Faraday::Error::ResourceNotFound => not_found_ex
if (method.to_sym == :get)
raw = OpenStruct.new(body: nil, status: 404)
else
raise not_found_ex
end
end
# may not need this, but remember how we made this response
PMP::Response.new(raw, {method: method, url: url, body: body})
end
|
[
"def",
"request",
"(",
"method",
",",
"url",
",",
"body",
"=",
"nil",
")",
"# :nodoc:",
"unless",
"[",
"'/'",
",",
"''",
"]",
".",
"include?",
"(",
"URI",
"::",
"parse",
"(",
"url",
")",
".",
"path",
")",
"setup_oauth_token",
"end",
"begin",
"raw",
"=",
"connection",
"(",
"current_options",
".",
"merge",
"(",
"{",
"url",
":",
"url",
"}",
")",
")",
".",
"send",
"(",
"method",
")",
"do",
"|",
"req",
"|",
"if",
"[",
":post",
",",
":put",
"]",
".",
"include?",
"(",
"method",
".",
"to_sym",
")",
"&&",
"!",
"body",
".",
"blank?",
"req",
".",
"body",
"=",
"PMP",
"::",
"CollectionDocument",
".",
"to_persist_json",
"(",
"body",
")",
"end",
"end",
"rescue",
"Faraday",
"::",
"Error",
"::",
"ResourceNotFound",
"=>",
"not_found_ex",
"if",
"(",
"method",
".",
"to_sym",
"==",
":get",
")",
"raw",
"=",
"OpenStruct",
".",
"new",
"(",
"body",
":",
"nil",
",",
"status",
":",
"404",
")",
"else",
"raise",
"not_found_ex",
"end",
"end",
"# may not need this, but remember how we made this response",
"PMP",
"::",
"Response",
".",
"new",
"(",
"raw",
",",
"{",
"method",
":",
"method",
",",
"url",
":",
"url",
",",
"body",
":",
"body",
"}",
")",
"end"
] |
url includes any params - full url
|
[
"url",
"includes",
"any",
"params",
"-",
"full",
"url"
] |
b0628529405f90dfb59166f8c6966752f8216260
|
https://github.com/PRX/pmp/blob/b0628529405f90dfb59166f8c6966752f8216260/lib/pmp/collection_document.rb#L168-L190
|
7,301 |
dingxizheng/mongoid_likes
|
lib/mongoid/likes/liker.rb
|
Mongoid.Liker.like
|
def like(likeable)
if !self.disliked?(likeable) and @@likeable_model_names.include? likeable.class.to_s.downcase
likeable.likers << self
self.save
else
false
end
end
|
ruby
|
def like(likeable)
if !self.disliked?(likeable) and @@likeable_model_names.include? likeable.class.to_s.downcase
likeable.likers << self
self.save
else
false
end
end
|
[
"def",
"like",
"(",
"likeable",
")",
"if",
"!",
"self",
".",
"disliked?",
"(",
"likeable",
")",
"and",
"@@likeable_model_names",
".",
"include?",
"likeable",
".",
"class",
".",
"to_s",
".",
"downcase",
"likeable",
".",
"likers",
"<<",
"self",
"self",
".",
"save",
"else",
"false",
"end",
"end"
] |
user likes a likeable
example
===========
user.like(likeable)
|
[
"user",
"likes",
"a",
"likeable"
] |
6c9bc703421f1e24ad3b7eac9a1a47cc93d737b2
|
https://github.com/dingxizheng/mongoid_likes/blob/6c9bc703421f1e24ad3b7eac9a1a47cc93d737b2/lib/mongoid/likes/liker.rb#L72-L79
|
7,302 |
dingxizheng/mongoid_likes
|
lib/mongoid/likes/liker.rb
|
Mongoid.Liker.unlike
|
def unlike(likeable)
if @@likeable_model_names.include? likeable.class.to_s.downcase
likeable.likers.delete self
self.save
else
false
end
end
|
ruby
|
def unlike(likeable)
if @@likeable_model_names.include? likeable.class.to_s.downcase
likeable.likers.delete self
self.save
else
false
end
end
|
[
"def",
"unlike",
"(",
"likeable",
")",
"if",
"@@likeable_model_names",
".",
"include?",
"likeable",
".",
"class",
".",
"to_s",
".",
"downcase",
"likeable",
".",
"likers",
".",
"delete",
"self",
"self",
".",
"save",
"else",
"false",
"end",
"end"
] |
user unlike a likeable
example
===========
user.unlike(likeable)
|
[
"user",
"unlike",
"a",
"likeable"
] |
6c9bc703421f1e24ad3b7eac9a1a47cc93d737b2
|
https://github.com/dingxizheng/mongoid_likes/blob/6c9bc703421f1e24ad3b7eac9a1a47cc93d737b2/lib/mongoid/likes/liker.rb#L88-L95
|
7,303 |
jimmyz/ruby-fs-stack
|
lib/ruby-fs-stack/familytree/person.rb
|
Org::Familysearch::Ws::Familytree::V2::Schema.Person.birth
|
def birth
birth = births.find{|b|!b.selected.nil?}
birth ||= births[0]
birth
end
|
ruby
|
def birth
birth = births.find{|b|!b.selected.nil?}
birth ||= births[0]
birth
end
|
[
"def",
"birth",
"birth",
"=",
"births",
".",
"find",
"{",
"|",
"b",
"|",
"!",
"b",
".",
"selected",
".",
"nil?",
"}",
"birth",
"||=",
"births",
"[",
"0",
"]",
"birth",
"end"
] |
It should return the selected birth assertion unless it is
not set in which case it will return the first
|
[
"It",
"should",
"return",
"the",
"selected",
"birth",
"assertion",
"unless",
"it",
"is",
"not",
"set",
"in",
"which",
"case",
"it",
"will",
"return",
"the",
"first"
] |
11281818635984971026e750d32a5c4599557dd1
|
https://github.com/jimmyz/ruby-fs-stack/blob/11281818635984971026e750d32a5c4599557dd1/lib/ruby-fs-stack/familytree/person.rb#L134-L138
|
7,304 |
jimmyz/ruby-fs-stack
|
lib/ruby-fs-stack/familytree/person.rb
|
Org::Familysearch::Ws::Familytree::V2::Schema.Person.death
|
def death
death = deaths.find{|b|!b.selected.nil?}
death ||= deaths[0]
death
end
|
ruby
|
def death
death = deaths.find{|b|!b.selected.nil?}
death ||= deaths[0]
death
end
|
[
"def",
"death",
"death",
"=",
"deaths",
".",
"find",
"{",
"|",
"b",
"|",
"!",
"b",
".",
"selected",
".",
"nil?",
"}",
"death",
"||=",
"deaths",
"[",
"0",
"]",
"death",
"end"
] |
It should return the selected death assertion unless it is
not set in which case it will return the first
|
[
"It",
"should",
"return",
"the",
"selected",
"death",
"assertion",
"unless",
"it",
"is",
"not",
"set",
"in",
"which",
"case",
"it",
"will",
"return",
"the",
"first"
] |
11281818635984971026e750d32a5c4599557dd1
|
https://github.com/jimmyz/ruby-fs-stack/blob/11281818635984971026e750d32a5c4599557dd1/lib/ruby-fs-stack/familytree/person.rb#L146-L150
|
7,305 |
jimmyz/ruby-fs-stack
|
lib/ruby-fs-stack/familytree/person.rb
|
Org::Familysearch::Ws::Familytree::V2::Schema.Person.select_mother_summary
|
def select_mother_summary(person_id)
add_parents!
couple = parents[0] || ParentsReference.new
couple.select_parent(person_id,'Female')
parents[0] = couple
end
|
ruby
|
def select_mother_summary(person_id)
add_parents!
couple = parents[0] || ParentsReference.new
couple.select_parent(person_id,'Female')
parents[0] = couple
end
|
[
"def",
"select_mother_summary",
"(",
"person_id",
")",
"add_parents!",
"couple",
"=",
"parents",
"[",
"0",
"]",
"||",
"ParentsReference",
".",
"new",
"couple",
".",
"select_parent",
"(",
"person_id",
",",
"'Female'",
")",
"parents",
"[",
"0",
"]",
"=",
"couple",
"end"
] |
Select the mother for the summary view. This should be called on a Person record that
contains a person id and version.
Make sure you set both the mother and father before saving the person. Otherwise you will
set a single parent as the summary.
====Params
<tt>person_id</tt> - the person id of the mother that you would like to set as the summary
===Example
person = com.familytree_v2.person 'KWQS-BBR', :names => 'none', :genders => 'none', :events => 'none'
person.select_mother_summary('KWQS-BBQ')
person.select_father_summary('KWQS-BBT')
com.familytree_v2.save_person person
This is the recommended approach, to start with a "Version" person (no names, genders, or events)
|
[
"Select",
"the",
"mother",
"for",
"the",
"summary",
"view",
".",
"This",
"should",
"be",
"called",
"on",
"a",
"Person",
"record",
"that",
"contains",
"a",
"person",
"id",
"and",
"version",
"."
] |
11281818635984971026e750d32a5c4599557dd1
|
https://github.com/jimmyz/ruby-fs-stack/blob/11281818635984971026e750d32a5c4599557dd1/lib/ruby-fs-stack/familytree/person.rb#L240-L245
|
7,306 |
jimmyz/ruby-fs-stack
|
lib/ruby-fs-stack/familytree/person.rb
|
Org::Familysearch::Ws::Familytree::V2::Schema.Person.select_father_summary
|
def select_father_summary(person_id)
add_parents!
couple = parents[0] || ParentsReference.new
couple.select_parent(person_id,'Male')
parents[0] = couple
end
|
ruby
|
def select_father_summary(person_id)
add_parents!
couple = parents[0] || ParentsReference.new
couple.select_parent(person_id,'Male')
parents[0] = couple
end
|
[
"def",
"select_father_summary",
"(",
"person_id",
")",
"add_parents!",
"couple",
"=",
"parents",
"[",
"0",
"]",
"||",
"ParentsReference",
".",
"new",
"couple",
".",
"select_parent",
"(",
"person_id",
",",
"'Male'",
")",
"parents",
"[",
"0",
"]",
"=",
"couple",
"end"
] |
Select the father for the summary view. This should be called on a Person record that
contains a person id and version.
Make sure you set both the mother and father before saving the person. Otherwise you will
set a single parent as the summary.
====Params
<tt>person_id</tt> - the person id of the father that you would like to set as the summary
===Example
person = com.familytree_v2.person 'KWQS-BBR', :names => 'none', :genders => 'none', :events => 'none'
person.select_father_summary('KWQS-BBQ')
person.select_mother_summary('KWQS-BBT')
com.familytree_v2.save_person person
This is the recommended approach, to start with a "Version" person (no names, genders, or events)
|
[
"Select",
"the",
"father",
"for",
"the",
"summary",
"view",
".",
"This",
"should",
"be",
"called",
"on",
"a",
"Person",
"record",
"that",
"contains",
"a",
"person",
"id",
"and",
"version",
"."
] |
11281818635984971026e750d32a5c4599557dd1
|
https://github.com/jimmyz/ruby-fs-stack/blob/11281818635984971026e750d32a5c4599557dd1/lib/ruby-fs-stack/familytree/person.rb#L263-L268
|
7,307 |
jimmyz/ruby-fs-stack
|
lib/ruby-fs-stack/familytree/person.rb
|
Org::Familysearch::Ws::Familytree::V2::Schema.Person.select_spouse_summary
|
def select_spouse_summary(person_id)
add_families!
family = FamilyReference.new
family.select_spouse(person_id)
families << family
end
|
ruby
|
def select_spouse_summary(person_id)
add_families!
family = FamilyReference.new
family.select_spouse(person_id)
families << family
end
|
[
"def",
"select_spouse_summary",
"(",
"person_id",
")",
"add_families!",
"family",
"=",
"FamilyReference",
".",
"new",
"family",
".",
"select_spouse",
"(",
"person_id",
")",
"families",
"<<",
"family",
"end"
] |
Select the spouse for the summary view. This should be called on a Person record that
contains a person id and version.
====Params
<tt>person_id</tt> - the person id of the spouse that you would like to set as the summary
===Example
person = com.familytree_v2.person 'KWQS-BBR', :names => 'none', :genders => 'none', :events => 'none'
person.select_spouse_summary('KWQS-BBQ')
com.familytree_v2.save_person person
This is the recommended approach, to start with a "Version" person (no names, genders, or events)
|
[
"Select",
"the",
"spouse",
"for",
"the",
"summary",
"view",
".",
"This",
"should",
"be",
"called",
"on",
"a",
"Person",
"record",
"that",
"contains",
"a",
"person",
"id",
"and",
"version",
"."
] |
11281818635984971026e750d32a5c4599557dd1
|
https://github.com/jimmyz/ruby-fs-stack/blob/11281818635984971026e750d32a5c4599557dd1/lib/ruby-fs-stack/familytree/person.rb#L282-L287
|
7,308 |
jimmyz/ruby-fs-stack
|
lib/ruby-fs-stack/familytree/person.rb
|
Org::Familysearch::Ws::Familytree::V2::Schema.Person.add_sealing_to_parents
|
def add_sealing_to_parents(options)
raise ArgumentError, ":mother option is required" if options[:mother].nil?
raise ArgumentError, ":father option is required" if options[:father].nil?
add_assertions!
options[:type] = OrdinanceType::Sealing_to_Parents
assertions.add_ordinance(options)
end
|
ruby
|
def add_sealing_to_parents(options)
raise ArgumentError, ":mother option is required" if options[:mother].nil?
raise ArgumentError, ":father option is required" if options[:father].nil?
add_assertions!
options[:type] = OrdinanceType::Sealing_to_Parents
assertions.add_ordinance(options)
end
|
[
"def",
"add_sealing_to_parents",
"(",
"options",
")",
"raise",
"ArgumentError",
",",
"\":mother option is required\"",
"if",
"options",
"[",
":mother",
"]",
".",
"nil?",
"raise",
"ArgumentError",
",",
"\":father option is required\"",
"if",
"options",
"[",
":father",
"]",
".",
"nil?",
"add_assertions!",
"options",
"[",
":type",
"]",
"=",
"OrdinanceType",
"::",
"Sealing_to_Parents",
"assertions",
".",
"add_ordinance",
"(",
"options",
")",
"end"
] |
Add a sealing to parents ordinance
====Params
* <tt>options</tt> - accepts a :date, :place, :temple, :mother, and :father option
====Example
person.add_sealing_to_parents :date => '14 Aug 2009', :temple => 'SGEOR', :place => 'Salt Lake City, Utah'
|
[
"Add",
"a",
"sealing",
"to",
"parents",
"ordinance"
] |
11281818635984971026e750d32a5c4599557dd1
|
https://github.com/jimmyz/ruby-fs-stack/blob/11281818635984971026e750d32a5c4599557dd1/lib/ruby-fs-stack/familytree/person.rb#L377-L383
|
7,309 |
jimmyz/ruby-fs-stack
|
lib/ruby-fs-stack/familytree/person.rb
|
Org::Familysearch::Ws::Familytree::V2::Schema.Person.select_relationship_ordinances
|
def select_relationship_ordinances(options)
raise ArgumentError, ":id required" if options[:id].nil?
if self.relationships
spouse_relationship = self.relationships.spouses.find{|s|s.id == options[:id]}
if spouse_relationship && spouse_relationship.assertions && spouse_relationship.assertions.ordinances
spouse_relationship.assertions.ordinances
else
[]
end
end
end
|
ruby
|
def select_relationship_ordinances(options)
raise ArgumentError, ":id required" if options[:id].nil?
if self.relationships
spouse_relationship = self.relationships.spouses.find{|s|s.id == options[:id]}
if spouse_relationship && spouse_relationship.assertions && spouse_relationship.assertions.ordinances
spouse_relationship.assertions.ordinances
else
[]
end
end
end
|
[
"def",
"select_relationship_ordinances",
"(",
"options",
")",
"raise",
"ArgumentError",
",",
"\":id required\"",
"if",
"options",
"[",
":id",
"]",
".",
"nil?",
"if",
"self",
".",
"relationships",
"spouse_relationship",
"=",
"self",
".",
"relationships",
".",
"spouses",
".",
"find",
"{",
"|",
"s",
"|",
"s",
".",
"id",
"==",
"options",
"[",
":id",
"]",
"}",
"if",
"spouse_relationship",
"&&",
"spouse_relationship",
".",
"assertions",
"&&",
"spouse_relationship",
".",
"assertions",
".",
"ordinances",
"spouse_relationship",
".",
"assertions",
".",
"ordinances",
"else",
"[",
"]",
"end",
"end",
"end"
] |
only ordinance type is Sealing_to_Spouse
|
[
"only",
"ordinance",
"type",
"is",
"Sealing_to_Spouse"
] |
11281818635984971026e750d32a5c4599557dd1
|
https://github.com/jimmyz/ruby-fs-stack/blob/11281818635984971026e750d32a5c4599557dd1/lib/ruby-fs-stack/familytree/person.rb#L482-L492
|
7,310 |
martinpoljak/em-files
|
lib/em-files.rb
|
EM.File.read
|
def read(length = nil, filter = nil, &block)
buffer = ""
pos = 0
# Arguments
if length.kind_of? Proc
filter = length
end
worker = Proc::new do
# Sets length for read
if not length.nil?
rlen = length - buffer.length
if rlen > @rw_len
rlen = @rw_len
end
else
rlen = @rw_len
end
# Reads
begin
chunk = @native.read(rlen)
if not filter.nil?
chunk = filter.call(chunk)
end
buffer << chunk
rescue Errno::EBADF
if @native.kind_of? ::File
self.reopen!
@native.seek(pos)
redo
else
raise
end
end
pos = @native.pos
# Returns or continues work
if @native.eof? or (buffer.length == length)
if not block.nil?
yield buffer # returns result
end
else
EM::next_tick { worker.call() } # continues work
end
end
worker.call()
end
|
ruby
|
def read(length = nil, filter = nil, &block)
buffer = ""
pos = 0
# Arguments
if length.kind_of? Proc
filter = length
end
worker = Proc::new do
# Sets length for read
if not length.nil?
rlen = length - buffer.length
if rlen > @rw_len
rlen = @rw_len
end
else
rlen = @rw_len
end
# Reads
begin
chunk = @native.read(rlen)
if not filter.nil?
chunk = filter.call(chunk)
end
buffer << chunk
rescue Errno::EBADF
if @native.kind_of? ::File
self.reopen!
@native.seek(pos)
redo
else
raise
end
end
pos = @native.pos
# Returns or continues work
if @native.eof? or (buffer.length == length)
if not block.nil?
yield buffer # returns result
end
else
EM::next_tick { worker.call() } # continues work
end
end
worker.call()
end
|
[
"def",
"read",
"(",
"length",
"=",
"nil",
",",
"filter",
"=",
"nil",
",",
"&",
"block",
")",
"buffer",
"=",
"\"\"",
"pos",
"=",
"0",
"# Arguments",
"if",
"length",
".",
"kind_of?",
"Proc",
"filter",
"=",
"length",
"end",
"worker",
"=",
"Proc",
"::",
"new",
"do",
"# Sets length for read",
"if",
"not",
"length",
".",
"nil?",
"rlen",
"=",
"length",
"-",
"buffer",
".",
"length",
"if",
"rlen",
">",
"@rw_len",
"rlen",
"=",
"@rw_len",
"end",
"else",
"rlen",
"=",
"@rw_len",
"end",
"# Reads",
"begin",
"chunk",
"=",
"@native",
".",
"read",
"(",
"rlen",
")",
"if",
"not",
"filter",
".",
"nil?",
"chunk",
"=",
"filter",
".",
"call",
"(",
"chunk",
")",
"end",
"buffer",
"<<",
"chunk",
"rescue",
"Errno",
"::",
"EBADF",
"if",
"@native",
".",
"kind_of?",
"::",
"File",
"self",
".",
"reopen!",
"@native",
".",
"seek",
"(",
"pos",
")",
"redo",
"else",
"raise",
"end",
"end",
"pos",
"=",
"@native",
".",
"pos",
"# Returns or continues work",
"if",
"@native",
".",
"eof?",
"or",
"(",
"buffer",
".",
"length",
"==",
"length",
")",
"if",
"not",
"block",
".",
"nil?",
"yield",
"buffer",
"# returns result",
"end",
"else",
"EM",
"::",
"next_tick",
"{",
"worker",
".",
"call",
"(",
")",
"}",
"# continues work",
"end",
"end",
"worker",
".",
"call",
"(",
")",
"end"
] |
Constructor. If IO object is given instead of filepath, uses
it as native one and +mode+ argument is ignored.
@param [String, IO, StringIO] filepath path to file or IO object
@param [String] mode file access mode (see equivalent Ruby method)
@param [Integer] rwsize size of block operated during one tick
Reads data from file.
It will reopen the file if +EBADF: Bad file descriptor+ of
+File+ class IO object will occur.
@overload read(length, &block)
Reads specified amount of data from file.
@param [Integer] length length for read from file
@param [Proc] filter filter which for postprocessing each
read chunk
@param [Proc] block callback for returning the result
@yield [String] read data
@overload read(&block)
Reads whole content of file.
@param [Proc] filter filter which for processing each block
@param [Proc] block callback for returning the result
@yield [String] read data
|
[
"Constructor",
".",
"If",
"IO",
"object",
"is",
"given",
"instead",
"of",
"filepath",
"uses",
"it",
"as",
"native",
"one",
"and",
"+",
"mode",
"+",
"argument",
"is",
"ignored",
"."
] |
177666c2395d58432a10941282a4c687bad765d2
|
https://github.com/martinpoljak/em-files/blob/177666c2395d58432a10941282a4c687bad765d2/lib/em-files.rb#L174-L227
|
7,311 |
martinpoljak/em-files
|
lib/em-files.rb
|
EM.File.write
|
def write(data, filter = nil, &block)
pos = 0
if data.kind_of? IO
io = data
else
io = StringIO::new(data)
end
worker = Proc::new do
# Writes
begin
chunk = io.read(@rw_len)
if not filter.nil?
chunk = filter.call(chunk)
end
@native.write(chunk)
rescue Errno::EBADF
if @native.kind_of? File
self.reopen!
@native.seek(pos)
redo
else
raise
end
end
pos = @native.pos
# Returns or continues work
if io.eof?
if not block.nil?
yield pos # returns result
end
else
EM::next_tick { worker.call() } # continues work
end
end
worker.call()
end
|
ruby
|
def write(data, filter = nil, &block)
pos = 0
if data.kind_of? IO
io = data
else
io = StringIO::new(data)
end
worker = Proc::new do
# Writes
begin
chunk = io.read(@rw_len)
if not filter.nil?
chunk = filter.call(chunk)
end
@native.write(chunk)
rescue Errno::EBADF
if @native.kind_of? File
self.reopen!
@native.seek(pos)
redo
else
raise
end
end
pos = @native.pos
# Returns or continues work
if io.eof?
if not block.nil?
yield pos # returns result
end
else
EM::next_tick { worker.call() } # continues work
end
end
worker.call()
end
|
[
"def",
"write",
"(",
"data",
",",
"filter",
"=",
"nil",
",",
"&",
"block",
")",
"pos",
"=",
"0",
"if",
"data",
".",
"kind_of?",
"IO",
"io",
"=",
"data",
"else",
"io",
"=",
"StringIO",
"::",
"new",
"(",
"data",
")",
"end",
"worker",
"=",
"Proc",
"::",
"new",
"do",
"# Writes",
"begin",
"chunk",
"=",
"io",
".",
"read",
"(",
"@rw_len",
")",
"if",
"not",
"filter",
".",
"nil?",
"chunk",
"=",
"filter",
".",
"call",
"(",
"chunk",
")",
"end",
"@native",
".",
"write",
"(",
"chunk",
")",
"rescue",
"Errno",
"::",
"EBADF",
"if",
"@native",
".",
"kind_of?",
"File",
"self",
".",
"reopen!",
"@native",
".",
"seek",
"(",
"pos",
")",
"redo",
"else",
"raise",
"end",
"end",
"pos",
"=",
"@native",
".",
"pos",
"# Returns or continues work",
"if",
"io",
".",
"eof?",
"if",
"not",
"block",
".",
"nil?",
"yield",
"pos",
"# returns result",
"end",
"else",
"EM",
"::",
"next_tick",
"{",
"worker",
".",
"call",
"(",
")",
"}",
"# continues work",
"end",
"end",
"worker",
".",
"call",
"(",
")",
"end"
] |
Writes data to file. Supports writing both strings or copying
from another IO object. Returns length of written data to
callback if filename given or current position of output
string if IO used.
It will reopen the file if +EBADF: Bad file descriptor+ of
+File+ class IO object will occur on +File+ object.
@param [String, IO, StringIO] data data for write or IO object
@param [Proc] filter filter which for preprocessing each
written chunk
@param [Proc] block callback called when finish and for giving
back the length of written data
@yield [Integer] length of really written data
|
[
"Writes",
"data",
"to",
"file",
".",
"Supports",
"writing",
"both",
"strings",
"or",
"copying",
"from",
"another",
"IO",
"object",
".",
"Returns",
"length",
"of",
"written",
"data",
"to",
"callback",
"if",
"filename",
"given",
"or",
"current",
"position",
"of",
"output",
"string",
"if",
"IO",
"used",
"."
] |
177666c2395d58432a10941282a4c687bad765d2
|
https://github.com/martinpoljak/em-files/blob/177666c2395d58432a10941282a4c687bad765d2/lib/em-files.rb#L254-L296
|
7,312 |
tatey/simple_mock
|
lib/simple_mock/tracer.rb
|
SimpleMock.Tracer.verify
|
def verify
differences = expected_calls.keys - actual_calls.keys
if differences.any?
raise MockExpectationError, "expected #{differences.first.inspect}"
else
true
end
end
|
ruby
|
def verify
differences = expected_calls.keys - actual_calls.keys
if differences.any?
raise MockExpectationError, "expected #{differences.first.inspect}"
else
true
end
end
|
[
"def",
"verify",
"differences",
"=",
"expected_calls",
".",
"keys",
"-",
"actual_calls",
".",
"keys",
"if",
"differences",
".",
"any?",
"raise",
"MockExpectationError",
",",
"\"expected #{differences.first.inspect}\"",
"else",
"true",
"end",
"end"
] |
Verify that all methods were called as expected. Raises
+MockExpectationError+ if not called as expected.
|
[
"Verify",
"that",
"all",
"methods",
"were",
"called",
"as",
"expected",
".",
"Raises",
"+",
"MockExpectationError",
"+",
"if",
"not",
"called",
"as",
"expected",
"."
] |
3081f714228903745d66f32cc6186946a9f2524e
|
https://github.com/tatey/simple_mock/blob/3081f714228903745d66f32cc6186946a9f2524e/lib/simple_mock/tracer.rb#L27-L34
|
7,313 |
bblack16/bblib-ruby
|
lib/bblib/core/classes/task_timer.rb
|
BBLib.TaskTimer.time
|
def time(task = :default, type = :current)
return nil unless tasks.keys.include?(task)
numbers = tasks[task][:history].map { |v| v[:time] }
case type
when :current
return nil unless tasks[task][:current]
Time.now.to_f - tasks[task][:current]
when :min, :max, :first, :last
numbers.send(type)
when :avg
numbers.size.zero? ? nil : numbers.inject { |sum, n| sum + n }.to_f / numbers.size
when :sum
numbers.inject { |sum, n| sum + n }
when :all
numbers
when :count
numbers.size
end
end
|
ruby
|
def time(task = :default, type = :current)
return nil unless tasks.keys.include?(task)
numbers = tasks[task][:history].map { |v| v[:time] }
case type
when :current
return nil unless tasks[task][:current]
Time.now.to_f - tasks[task][:current]
when :min, :max, :first, :last
numbers.send(type)
when :avg
numbers.size.zero? ? nil : numbers.inject { |sum, n| sum + n }.to_f / numbers.size
when :sum
numbers.inject { |sum, n| sum + n }
when :all
numbers
when :count
numbers.size
end
end
|
[
"def",
"time",
"(",
"task",
"=",
":default",
",",
"type",
"=",
":current",
")",
"return",
"nil",
"unless",
"tasks",
".",
"keys",
".",
"include?",
"(",
"task",
")",
"numbers",
"=",
"tasks",
"[",
"task",
"]",
"[",
":history",
"]",
".",
"map",
"{",
"|",
"v",
"|",
"v",
"[",
":time",
"]",
"}",
"case",
"type",
"when",
":current",
"return",
"nil",
"unless",
"tasks",
"[",
"task",
"]",
"[",
":current",
"]",
"Time",
".",
"now",
".",
"to_f",
"-",
"tasks",
"[",
"task",
"]",
"[",
":current",
"]",
"when",
":min",
",",
":max",
",",
":first",
",",
":last",
"numbers",
".",
"send",
"(",
"type",
")",
"when",
":avg",
"numbers",
".",
"size",
".",
"zero?",
"?",
"nil",
":",
"numbers",
".",
"inject",
"{",
"|",
"sum",
",",
"n",
"|",
"sum",
"+",
"n",
"}",
".",
"to_f",
"/",
"numbers",
".",
"size",
"when",
":sum",
"numbers",
".",
"inject",
"{",
"|",
"sum",
",",
"n",
"|",
"sum",
"+",
"n",
"}",
"when",
":all",
"numbers",
"when",
":count",
"numbers",
".",
"size",
"end",
"end"
] |
Returns an aggregated metric for a given type.
@param [Symbol] task The key value of the task to retrieve
@param [Symbol] type The metric to return.
Options are :avg, :min, :max, :first, :last, :sum, :all and :count.
@return [Float, Integer, Array] Returns either the aggregation (Numeric) or an Array in the case of :all.
|
[
"Returns",
"an",
"aggregated",
"metric",
"for",
"a",
"given",
"type",
"."
] |
274eedeb583cc56243884fd041645488d5bd08a9
|
https://github.com/bblack16/bblib-ruby/blob/274eedeb583cc56243884fd041645488d5bd08a9/lib/bblib/core/classes/task_timer.rb#L21-L39
|
7,314 |
bblack16/bblib-ruby
|
lib/bblib/core/classes/task_timer.rb
|
BBLib.TaskTimer.clear
|
def clear(task = :default)
return nil unless tasks.keys.include?(task)
stop task
tasks[task][:history].clear
end
|
ruby
|
def clear(task = :default)
return nil unless tasks.keys.include?(task)
stop task
tasks[task][:history].clear
end
|
[
"def",
"clear",
"(",
"task",
"=",
":default",
")",
"return",
"nil",
"unless",
"tasks",
".",
"keys",
".",
"include?",
"(",
"task",
")",
"stop",
"task",
"tasks",
"[",
"task",
"]",
"[",
":history",
"]",
".",
"clear",
"end"
] |
Removes all history for a given task
@param [Symbol] task The name of the task to clear history from.
@return [NilClass] Returns nil
|
[
"Removes",
"all",
"history",
"for",
"a",
"given",
"task"
] |
274eedeb583cc56243884fd041645488d5bd08a9
|
https://github.com/bblack16/bblib-ruby/blob/274eedeb583cc56243884fd041645488d5bd08a9/lib/bblib/core/classes/task_timer.rb#L45-L49
|
7,315 |
bblack16/bblib-ruby
|
lib/bblib/core/classes/task_timer.rb
|
BBLib.TaskTimer.start
|
def start(task = :default)
tasks[task] = { history: [], current: nil } unless tasks.keys.include?(task)
stop task if tasks[task][:current]
tasks[task][:current] = Time.now.to_f
0
end
|
ruby
|
def start(task = :default)
tasks[task] = { history: [], current: nil } unless tasks.keys.include?(task)
stop task if tasks[task][:current]
tasks[task][:current] = Time.now.to_f
0
end
|
[
"def",
"start",
"(",
"task",
"=",
":default",
")",
"tasks",
"[",
"task",
"]",
"=",
"{",
"history",
":",
"[",
"]",
",",
"current",
":",
"nil",
"}",
"unless",
"tasks",
".",
"keys",
".",
"include?",
"(",
"task",
")",
"stop",
"task",
"if",
"tasks",
"[",
"task",
"]",
"[",
":current",
"]",
"tasks",
"[",
"task",
"]",
"[",
":current",
"]",
"=",
"Time",
".",
"now",
".",
"to_f",
"0",
"end"
] |
Start a new timer for the referenced task. If a timer is already running for that task it will be stopped first.
@param [Symbol] task The name of the task to start.
@return [Integer] Returns 0
|
[
"Start",
"a",
"new",
"timer",
"for",
"the",
"referenced",
"task",
".",
"If",
"a",
"timer",
"is",
"already",
"running",
"for",
"that",
"task",
"it",
"will",
"be",
"stopped",
"first",
"."
] |
274eedeb583cc56243884fd041645488d5bd08a9
|
https://github.com/bblack16/bblib-ruby/blob/274eedeb583cc56243884fd041645488d5bd08a9/lib/bblib/core/classes/task_timer.rb#L55-L60
|
7,316 |
bblack16/bblib-ruby
|
lib/bblib/core/classes/task_timer.rb
|
BBLib.TaskTimer.stop
|
def stop(task = :default)
return nil unless tasks.keys.include?(task) && active?(task)
time_taken = Time.now.to_f - tasks[task][:current].to_f
tasks[task][:history] << { start: tasks[task][:current], stop: Time.now.to_f, time: time_taken }
tasks[task][:current] = nil
if retention && tasks[task][:history].size > retention then tasks[task][:history].shift end
time_taken
end
|
ruby
|
def stop(task = :default)
return nil unless tasks.keys.include?(task) && active?(task)
time_taken = Time.now.to_f - tasks[task][:current].to_f
tasks[task][:history] << { start: tasks[task][:current], stop: Time.now.to_f, time: time_taken }
tasks[task][:current] = nil
if retention && tasks[task][:history].size > retention then tasks[task][:history].shift end
time_taken
end
|
[
"def",
"stop",
"(",
"task",
"=",
":default",
")",
"return",
"nil",
"unless",
"tasks",
".",
"keys",
".",
"include?",
"(",
"task",
")",
"&&",
"active?",
"(",
"task",
")",
"time_taken",
"=",
"Time",
".",
"now",
".",
"to_f",
"-",
"tasks",
"[",
"task",
"]",
"[",
":current",
"]",
".",
"to_f",
"tasks",
"[",
"task",
"]",
"[",
":history",
"]",
"<<",
"{",
"start",
":",
"tasks",
"[",
"task",
"]",
"[",
":current",
"]",
",",
"stop",
":",
"Time",
".",
"now",
".",
"to_f",
",",
"time",
":",
"time_taken",
"}",
"tasks",
"[",
"task",
"]",
"[",
":current",
"]",
"=",
"nil",
"if",
"retention",
"&&",
"tasks",
"[",
"task",
"]",
"[",
":history",
"]",
".",
"size",
">",
"retention",
"then",
"tasks",
"[",
"task",
"]",
"[",
":history",
"]",
".",
"shift",
"end",
"time_taken",
"end"
] |
Stop the referenced timer.
@param [Symbol] task The name of the task to stop.
@return [Float, NilClass] The amount of time the task had been running or nil if no matching task was found.
|
[
"Stop",
"the",
"referenced",
"timer",
"."
] |
274eedeb583cc56243884fd041645488d5bd08a9
|
https://github.com/bblack16/bblib-ruby/blob/274eedeb583cc56243884fd041645488d5bd08a9/lib/bblib/core/classes/task_timer.rb#L66-L73
|
7,317 |
elm-city-craftworks/rails_setup
|
lib/rails_setup/environment.rb
|
RailsSetup.Environment.create_file
|
def create_file(file, name, requires_edit=false)
FileUtils.cp(file + '.example', file)
if requires_edit
puts "Update #{file} and run `bundle exec rake setup` to continue".color(:red)
system(ENV['EDITOR'], file) unless ENV['EDITOR'].blank?
exit
end
end
|
ruby
|
def create_file(file, name, requires_edit=false)
FileUtils.cp(file + '.example', file)
if requires_edit
puts "Update #{file} and run `bundle exec rake setup` to continue".color(:red)
system(ENV['EDITOR'], file) unless ENV['EDITOR'].blank?
exit
end
end
|
[
"def",
"create_file",
"(",
"file",
",",
"name",
",",
"requires_edit",
"=",
"false",
")",
"FileUtils",
".",
"cp",
"(",
"file",
"+",
"'.example'",
",",
"file",
")",
"if",
"requires_edit",
"puts",
"\"Update #{file} and run `bundle exec rake setup` to continue\"",
".",
"color",
"(",
":red",
")",
"system",
"(",
"ENV",
"[",
"'EDITOR'",
"]",
",",
"file",
")",
"unless",
"ENV",
"[",
"'EDITOR'",
"]",
".",
"blank?",
"exit",
"end",
"end"
] |
Creates a file based on a '.example' version saved in the same folder
Will optionally open the new file in the default editor after creation
|
[
"Creates",
"a",
"file",
"based",
"on",
"a",
".",
"example",
"version",
"saved",
"in",
"the",
"same",
"folder",
"Will",
"optionally",
"open",
"the",
"new",
"file",
"in",
"the",
"default",
"editor",
"after",
"creation"
] |
77c15fb51565aaa666db2571e37e077e94b1a1c0
|
https://github.com/elm-city-craftworks/rails_setup/blob/77c15fb51565aaa666db2571e37e077e94b1a1c0/lib/rails_setup/environment.rb#L55-L63
|
7,318 |
elm-city-craftworks/rails_setup
|
lib/rails_setup/environment.rb
|
RailsSetup.Environment.find_or_create_file
|
def find_or_create_file(file, name, requires_edit=false)
if File.exists?(file)
file
else
create_file(file, name, requires_edit)
end
end
|
ruby
|
def find_or_create_file(file, name, requires_edit=false)
if File.exists?(file)
file
else
create_file(file, name, requires_edit)
end
end
|
[
"def",
"find_or_create_file",
"(",
"file",
",",
"name",
",",
"requires_edit",
"=",
"false",
")",
"if",
"File",
".",
"exists?",
"(",
"file",
")",
"file",
"else",
"create_file",
"(",
"file",
",",
"name",
",",
"requires_edit",
")",
"end",
"end"
] |
Looks for the specificed file and creates it if it does not exist
|
[
"Looks",
"for",
"the",
"specificed",
"file",
"and",
"creates",
"it",
"if",
"it",
"does",
"not",
"exist"
] |
77c15fb51565aaa666db2571e37e077e94b1a1c0
|
https://github.com/elm-city-craftworks/rails_setup/blob/77c15fb51565aaa666db2571e37e077e94b1a1c0/lib/rails_setup/environment.rb#L67-L73
|
7,319 |
dprandzioch/avocado
|
lib/avodeploy/config.rb
|
AvoDeploy.Config.inherit_strategy
|
def inherit_strategy(strategy)
AvoDeploy::Deployment.instance.log.debug "Loading deployment strategy #{strategy.to_s}..."
strategy_file_path = File.dirname(__FILE__) + "/strategy/#{strategy.to_s}.rb"
if File.exist?(strategy_file_path)
require strategy_file_path
else
raise RuntimeError, "The requested strategy '#{strategy.to_s}' does not exist"
end
end
|
ruby
|
def inherit_strategy(strategy)
AvoDeploy::Deployment.instance.log.debug "Loading deployment strategy #{strategy.to_s}..."
strategy_file_path = File.dirname(__FILE__) + "/strategy/#{strategy.to_s}.rb"
if File.exist?(strategy_file_path)
require strategy_file_path
else
raise RuntimeError, "The requested strategy '#{strategy.to_s}' does not exist"
end
end
|
[
"def",
"inherit_strategy",
"(",
"strategy",
")",
"AvoDeploy",
"::",
"Deployment",
".",
"instance",
".",
"log",
".",
"debug",
"\"Loading deployment strategy #{strategy.to_s}...\"",
"strategy_file_path",
"=",
"File",
".",
"dirname",
"(",
"__FILE__",
")",
"+",
"\"/strategy/#{strategy.to_s}.rb\"",
"if",
"File",
".",
"exist?",
"(",
"strategy_file_path",
")",
"require",
"strategy_file_path",
"else",
"raise",
"RuntimeError",
",",
"\"The requested strategy '#{strategy.to_s}' does not exist\"",
"end",
"end"
] |
Loads a strategy. Because the strategy files are loaded in
the specified order, it's possible to override tasks.
This is how inheritance of strategies is realized.
@param strategy [Symbol] the strategy to load
|
[
"Loads",
"a",
"strategy",
".",
"Because",
"the",
"strategy",
"files",
"are",
"loaded",
"in",
"the",
"specified",
"order",
"it",
"s",
"possible",
"to",
"override",
"tasks",
".",
"This",
"is",
"how",
"inheritance",
"of",
"strategies",
"is",
"realized",
"."
] |
473dd86b0e2334fe5e7981227892ba5ca4b18bb3
|
https://github.com/dprandzioch/avocado/blob/473dd86b0e2334fe5e7981227892ba5ca4b18bb3/lib/avodeploy/config.rb#L54-L64
|
7,320 |
dprandzioch/avocado
|
lib/avodeploy/config.rb
|
AvoDeploy.Config.task
|
def task(name, options = {}, &block)
AvoDeploy::Deployment.instance.log.debug "registering task #{name}..."
AvoDeploy::Deployment.instance.task_manager.add_task(name, options, &block)
end
|
ruby
|
def task(name, options = {}, &block)
AvoDeploy::Deployment.instance.log.debug "registering task #{name}..."
AvoDeploy::Deployment.instance.task_manager.add_task(name, options, &block)
end
|
[
"def",
"task",
"(",
"name",
",",
"options",
"=",
"{",
"}",
",",
"&",
"block",
")",
"AvoDeploy",
"::",
"Deployment",
".",
"instance",
".",
"log",
".",
"debug",
"\"registering task #{name}...\"",
"AvoDeploy",
"::",
"Deployment",
".",
"instance",
".",
"task_manager",
".",
"add_task",
"(",
"name",
",",
"options",
",",
"block",
")",
"end"
] |
Defines a task
@param name [Symbol] task name
@param options [Hash] task options
@param block [Block] the code to be executed when the task is started
|
[
"Defines",
"a",
"task"
] |
473dd86b0e2334fe5e7981227892ba5ca4b18bb3
|
https://github.com/dprandzioch/avocado/blob/473dd86b0e2334fe5e7981227892ba5ca4b18bb3/lib/avodeploy/config.rb#L81-L84
|
7,321 |
dprandzioch/avocado
|
lib/avodeploy/config.rb
|
AvoDeploy.Config.setup_stage
|
def setup_stage(name, options = {}, &block)
stages[name] = ''
if options.has_key?(:desc)
stages[name] = options[:desc]
end
if name.to_s == get(:stage).to_s
@loaded_stage = name
instance_eval(&block)
end
end
|
ruby
|
def setup_stage(name, options = {}, &block)
stages[name] = ''
if options.has_key?(:desc)
stages[name] = options[:desc]
end
if name.to_s == get(:stage).to_s
@loaded_stage = name
instance_eval(&block)
end
end
|
[
"def",
"setup_stage",
"(",
"name",
",",
"options",
"=",
"{",
"}",
",",
"&",
"block",
")",
"stages",
"[",
"name",
"]",
"=",
"''",
"if",
"options",
".",
"has_key?",
"(",
":desc",
")",
"stages",
"[",
"name",
"]",
"=",
"options",
"[",
":desc",
"]",
"end",
"if",
"name",
".",
"to_s",
"==",
"get",
"(",
":stage",
")",
".",
"to_s",
"@loaded_stage",
"=",
"name",
"instance_eval",
"(",
"block",
")",
"end",
"end"
] |
Defines a stage
@param name [Symbol] stage name
@param options [Hash] stage options
@param block [Block] the stage configuration
|
[
"Defines",
"a",
"stage"
] |
473dd86b0e2334fe5e7981227892ba5ca4b18bb3
|
https://github.com/dprandzioch/avocado/blob/473dd86b0e2334fe5e7981227892ba5ca4b18bb3/lib/avodeploy/config.rb#L91-L103
|
7,322 |
jns/Aims
|
lib/aims/vectorize.rb
|
Aims.Vectorize.dot
|
def dot(a, b)
unless a.size == b.size
raise "Vectors must be the same length"
end
# Make element-by-element array of pairs
(a.to_a).zip(b.to_a).inject(0) {|tot, pair| tot = tot + pair[0]*pair[1]}
end
|
ruby
|
def dot(a, b)
unless a.size == b.size
raise "Vectors must be the same length"
end
# Make element-by-element array of pairs
(a.to_a).zip(b.to_a).inject(0) {|tot, pair| tot = tot + pair[0]*pair[1]}
end
|
[
"def",
"dot",
"(",
"a",
",",
"b",
")",
"unless",
"a",
".",
"size",
"==",
"b",
".",
"size",
"raise",
"\"Vectors must be the same length\"",
"end",
"# Make element-by-element array of pairs",
"(",
"a",
".",
"to_a",
")",
".",
"zip",
"(",
"b",
".",
"to_a",
")",
".",
"inject",
"(",
"0",
")",
"{",
"|",
"tot",
",",
"pair",
"|",
"tot",
"=",
"tot",
"+",
"pair",
"[",
"0",
"]",
"*",
"pair",
"[",
"1",
"]",
"}",
"end"
] |
Dot product of two n-element arrays
|
[
"Dot",
"product",
"of",
"two",
"n",
"-",
"element",
"arrays"
] |
2dcb6c02cd05b2d0c8ab72be4e85d60375df296c
|
https://github.com/jns/Aims/blob/2dcb6c02cd05b2d0c8ab72be4e85d60375df296c/lib/aims/vectorize.rb#L5-L12
|
7,323 |
jns/Aims
|
lib/aims/vectorize.rb
|
Aims.Vectorize.cross
|
def cross(b,c)
unless b.size == 3 and c.size == 3
raise "Vectors must be of length 3"
end
Vector[b[1]*c[2] - b[2]*c[1], b[2]*c[0] - b[0]*c[2], b[0]*c[1] - b[1]*c[0]]
end
|
ruby
|
def cross(b,c)
unless b.size == 3 and c.size == 3
raise "Vectors must be of length 3"
end
Vector[b[1]*c[2] - b[2]*c[1], b[2]*c[0] - b[0]*c[2], b[0]*c[1] - b[1]*c[0]]
end
|
[
"def",
"cross",
"(",
"b",
",",
"c",
")",
"unless",
"b",
".",
"size",
"==",
"3",
"and",
"c",
".",
"size",
"==",
"3",
"raise",
"\"Vectors must be of length 3\"",
"end",
"Vector",
"[",
"b",
"[",
"1",
"]",
"*",
"c",
"[",
"2",
"]",
"-",
"b",
"[",
"2",
"]",
"*",
"c",
"[",
"1",
"]",
",",
"b",
"[",
"2",
"]",
"*",
"c",
"[",
"0",
"]",
"-",
"b",
"[",
"0",
"]",
"*",
"c",
"[",
"2",
"]",
",",
"b",
"[",
"0",
"]",
"*",
"c",
"[",
"1",
"]",
"-",
"b",
"[",
"1",
"]",
"*",
"c",
"[",
"0",
"]",
"]",
"end"
] |
Cross product of two arrays of length 3
|
[
"Cross",
"product",
"of",
"two",
"arrays",
"of",
"length",
"3"
] |
2dcb6c02cd05b2d0c8ab72be4e85d60375df296c
|
https://github.com/jns/Aims/blob/2dcb6c02cd05b2d0c8ab72be4e85d60375df296c/lib/aims/vectorize.rb#L15-L20
|
7,324 |
arvicco/poster
|
lib/poster/encoding.rb
|
Poster.Encoding.xml_encode
|
def xml_encode string
puts string.each_char.size
string.each_char.map do |p|
case
when CONVERTIBLES[p]
CONVERTIBLES[p]
when XML_ENTITIES[p]
"&##{XML_ENTITIES[p]};"
else
p
end
end.reduce(:+)
end
|
ruby
|
def xml_encode string
puts string.each_char.size
string.each_char.map do |p|
case
when CONVERTIBLES[p]
CONVERTIBLES[p]
when XML_ENTITIES[p]
"&##{XML_ENTITIES[p]};"
else
p
end
end.reduce(:+)
end
|
[
"def",
"xml_encode",
"string",
"puts",
"string",
".",
"each_char",
".",
"size",
"string",
".",
"each_char",
".",
"map",
"do",
"|",
"p",
"|",
"case",
"when",
"CONVERTIBLES",
"[",
"p",
"]",
"CONVERTIBLES",
"[",
"p",
"]",
"when",
"XML_ENTITIES",
"[",
"p",
"]",
"\"&##{XML_ENTITIES[p]};\"",
"else",
"p",
"end",
"end",
".",
"reduce",
"(",
":+",
")",
"end"
] |
Encode Russian UTF-8 string to XML Entities format,
converting weird Unicode chars along the way
|
[
"Encode",
"Russian",
"UTF",
"-",
"8",
"string",
"to",
"XML",
"Entities",
"format",
"converting",
"weird",
"Unicode",
"chars",
"along",
"the",
"way"
] |
a5f22f7cb02116ab4dc5b7f2bdb672306b3dac63
|
https://github.com/arvicco/poster/blob/a5f22f7cb02116ab4dc5b7f2bdb672306b3dac63/lib/poster/encoding.rb#L127-L139
|
7,325 |
chrisjones-tripletri/action_command
|
lib/action_command/result.rb
|
ActionCommand.Result.debug
|
def debug(msg = nil)
if @logger
msg = build_log(msg || yield, ActionCommand::LOG_KIND_DEBUG)
@logger.info(format_log(msg))
end
end
|
ruby
|
def debug(msg = nil)
if @logger
msg = build_log(msg || yield, ActionCommand::LOG_KIND_DEBUG)
@logger.info(format_log(msg))
end
end
|
[
"def",
"debug",
"(",
"msg",
"=",
"nil",
")",
"if",
"@logger",
"msg",
"=",
"build_log",
"(",
"msg",
"||",
"yield",
",",
"ActionCommand",
"::",
"LOG_KIND_DEBUG",
")",
"@logger",
".",
"info",
"(",
"format_log",
"(",
"msg",
")",
")",
"end",
"end"
] |
display an debugging message to the logger, if there is one.
@yield return a message or hash
|
[
"display",
"an",
"debugging",
"message",
"to",
"the",
"logger",
"if",
"there",
"is",
"one",
"."
] |
9b9a8ba30e407ca6d88a62a164d1dc22ba149874
|
https://github.com/chrisjones-tripletri/action_command/blob/9b9a8ba30e407ca6d88a62a164d1dc22ba149874/lib/action_command/result.rb#L31-L36
|
7,326 |
chrisjones-tripletri/action_command
|
lib/action_command/result.rb
|
ActionCommand.Result.info
|
def info(msg = nil)
if @logger
msg = build_log(msg || yield, ActionCommand::LOG_KIND_INFO)
@logger.info(format_log(msg))
end
end
|
ruby
|
def info(msg = nil)
if @logger
msg = build_log(msg || yield, ActionCommand::LOG_KIND_INFO)
@logger.info(format_log(msg))
end
end
|
[
"def",
"info",
"(",
"msg",
"=",
"nil",
")",
"if",
"@logger",
"msg",
"=",
"build_log",
"(",
"msg",
"||",
"yield",
",",
"ActionCommand",
"::",
"LOG_KIND_INFO",
")",
"@logger",
".",
"info",
"(",
"format_log",
"(",
"msg",
")",
")",
"end",
"end"
] |
display an informational message to the logger, if there is one.
@yield return a message or hash
|
[
"display",
"an",
"informational",
"message",
"to",
"the",
"logger",
"if",
"there",
"is",
"one",
"."
] |
9b9a8ba30e407ca6d88a62a164d1dc22ba149874
|
https://github.com/chrisjones-tripletri/action_command/blob/9b9a8ba30e407ca6d88a62a164d1dc22ba149874/lib/action_command/result.rb#L40-L45
|
7,327 |
chrisjones-tripletri/action_command
|
lib/action_command/result.rb
|
ActionCommand.Result.error
|
def error(msg)
if @logger
msg = build_log(msg, ActionCommand::LOG_KIND_ERROR)
@logger.error(format_log(msg))
end
end
|
ruby
|
def error(msg)
if @logger
msg = build_log(msg, ActionCommand::LOG_KIND_ERROR)
@logger.error(format_log(msg))
end
end
|
[
"def",
"error",
"(",
"msg",
")",
"if",
"@logger",
"msg",
"=",
"build_log",
"(",
"msg",
",",
"ActionCommand",
"::",
"LOG_KIND_ERROR",
")",
"@logger",
".",
"error",
"(",
"format_log",
"(",
"msg",
")",
")",
"end",
"end"
] |
display an error message to the logger, if there is one.
|
[
"display",
"an",
"error",
"message",
"to",
"the",
"logger",
"if",
"there",
"is",
"one",
"."
] |
9b9a8ba30e407ca6d88a62a164d1dc22ba149874
|
https://github.com/chrisjones-tripletri/action_command/blob/9b9a8ba30e407ca6d88a62a164d1dc22ba149874/lib/action_command/result.rb#L48-L53
|
7,328 |
chrisjones-tripletri/action_command
|
lib/action_command/result.rb
|
ActionCommand.Result.push
|
def push(key, cmd)
return unless key
old_cur = current
if old_cur.key?(key)
@values << old_cur[key]
else
@values << {}
old_cur[key] = @values.last
end
@stack << { key: key, cmd: cmd } if @logger
end
|
ruby
|
def push(key, cmd)
return unless key
old_cur = current
if old_cur.key?(key)
@values << old_cur[key]
else
@values << {}
old_cur[key] = @values.last
end
@stack << { key: key, cmd: cmd } if @logger
end
|
[
"def",
"push",
"(",
"key",
",",
"cmd",
")",
"return",
"unless",
"key",
"old_cur",
"=",
"current",
"if",
"old_cur",
".",
"key?",
"(",
"key",
")",
"@values",
"<<",
"old_cur",
"[",
"key",
"]",
"else",
"@values",
"<<",
"{",
"}",
"old_cur",
"[",
"key",
"]",
"=",
"@values",
".",
"last",
"end",
"@stack",
"<<",
"{",
"key",
":",
"key",
",",
"cmd",
":",
"cmd",
"}",
"if",
"@logger",
"end"
] |
adds results under the subkey until pop is called
|
[
"adds",
"results",
"under",
"the",
"subkey",
"until",
"pop",
"is",
"called"
] |
9b9a8ba30e407ca6d88a62a164d1dc22ba149874
|
https://github.com/chrisjones-tripletri/action_command/blob/9b9a8ba30e407ca6d88a62a164d1dc22ba149874/lib/action_command/result.rb#L86-L96
|
7,329 |
chrisjones-tripletri/action_command
|
lib/action_command/result.rb
|
ActionCommand.Result.log_input
|
def log_input(params)
return unless @logger
output = params.reject { |k, _v| internal_key?(k) }
log_info_hash(output, ActionCommand::LOG_KIND_COMMAND_INPUT)
end
|
ruby
|
def log_input(params)
return unless @logger
output = params.reject { |k, _v| internal_key?(k) }
log_info_hash(output, ActionCommand::LOG_KIND_COMMAND_INPUT)
end
|
[
"def",
"log_input",
"(",
"params",
")",
"return",
"unless",
"@logger",
"output",
"=",
"params",
".",
"reject",
"{",
"|",
"k",
",",
"_v",
"|",
"internal_key?",
"(",
"k",
")",
"}",
"log_info_hash",
"(",
"output",
",",
"ActionCommand",
"::",
"LOG_KIND_COMMAND_INPUT",
")",
"end"
] |
Used internally to log the input parameters to a command
|
[
"Used",
"internally",
"to",
"log",
"the",
"input",
"parameters",
"to",
"a",
"command"
] |
9b9a8ba30e407ca6d88a62a164d1dc22ba149874
|
https://github.com/chrisjones-tripletri/action_command/blob/9b9a8ba30e407ca6d88a62a164d1dc22ba149874/lib/action_command/result.rb#L131-L135
|
7,330 |
chrisjones-tripletri/action_command
|
lib/action_command/result.rb
|
ActionCommand.Result.log_output
|
def log_output
return unless @logger
# only log the first level parameters, subcommands will log
# their own output.
output = current.reject { |k, v| v.is_a?(Hash) || internal_key?(k) }
log_info_hash(output, ActionCommand::LOG_KIND_COMMAND_OUTPUT)
end
|
ruby
|
def log_output
return unless @logger
# only log the first level parameters, subcommands will log
# their own output.
output = current.reject { |k, v| v.is_a?(Hash) || internal_key?(k) }
log_info_hash(output, ActionCommand::LOG_KIND_COMMAND_OUTPUT)
end
|
[
"def",
"log_output",
"return",
"unless",
"@logger",
"# only log the first level parameters, subcommands will log",
"# their own output.",
"output",
"=",
"current",
".",
"reject",
"{",
"|",
"k",
",",
"v",
"|",
"v",
".",
"is_a?",
"(",
"Hash",
")",
"||",
"internal_key?",
"(",
"k",
")",
"}",
"log_info_hash",
"(",
"output",
",",
"ActionCommand",
"::",
"LOG_KIND_COMMAND_OUTPUT",
")",
"end"
] |
Used internally to log the output parameters for a command.
|
[
"Used",
"internally",
"to",
"log",
"the",
"output",
"parameters",
"for",
"a",
"command",
"."
] |
9b9a8ba30e407ca6d88a62a164d1dc22ba149874
|
https://github.com/chrisjones-tripletri/action_command/blob/9b9a8ba30e407ca6d88a62a164d1dc22ba149874/lib/action_command/result.rb#L138-L144
|
7,331 |
triglav-dataflow/triglav-agent-framework-ruby
|
lib/triglav/agent/status.rb
|
Triglav::Agent.Status.merge!
|
def merge!(*args)
val = args.pop
keys = args.flatten
StorageFile.merge!(path, [*@parents, *keys], val)
end
|
ruby
|
def merge!(*args)
val = args.pop
keys = args.flatten
StorageFile.merge!(path, [*@parents, *keys], val)
end
|
[
"def",
"merge!",
"(",
"*",
"args",
")",
"val",
"=",
"args",
".",
"pop",
"keys",
"=",
"args",
".",
"flatten",
"StorageFile",
".",
"merge!",
"(",
"path",
",",
"[",
"@parents",
",",
"keys",
"]",
",",
"val",
")",
"end"
] |
Merge Hash value with existing Hash value.
merge!(val)
merge!(key, val)
merge!(key1, key2, val)
merge!([key], val)
merge!([key1, key2], val)
|
[
"Merge",
"Hash",
"value",
"with",
"existing",
"Hash",
"value",
"."
] |
a2517253a2b151b8ece3c22f389e5a2c38d93a88
|
https://github.com/triglav-dataflow/triglav-agent-framework-ruby/blob/a2517253a2b151b8ece3c22f389e5a2c38d93a88/lib/triglav/agent/status.rb#L36-L40
|
7,332 |
rit-sse-mycroft/template-ruby
|
lib/mycroft/helpers.rb
|
Mycroft.Helpers.parse_message
|
def parse_message(msg)
msg = msg.to_s
re = /([A-Z_]+) ({.*})$/
msg_split = re.match(msg)
if msg_split.nil?
re = /^([A-Z_]+)$/
msg_split = re.match(msg)
raise "Error: Malformed Message" if not msg_split
type = msg_split[1]
data = {}
else
type = msg_split[1]
data = JSON.parse(msg_split[2])
end
{type: type, data: data}
end
|
ruby
|
def parse_message(msg)
msg = msg.to_s
re = /([A-Z_]+) ({.*})$/
msg_split = re.match(msg)
if msg_split.nil?
re = /^([A-Z_]+)$/
msg_split = re.match(msg)
raise "Error: Malformed Message" if not msg_split
type = msg_split[1]
data = {}
else
type = msg_split[1]
data = JSON.parse(msg_split[2])
end
{type: type, data: data}
end
|
[
"def",
"parse_message",
"(",
"msg",
")",
"msg",
"=",
"msg",
".",
"to_s",
"re",
"=",
"/",
"/",
"msg_split",
"=",
"re",
".",
"match",
"(",
"msg",
")",
"if",
"msg_split",
".",
"nil?",
"re",
"=",
"/",
"/",
"msg_split",
"=",
"re",
".",
"match",
"(",
"msg",
")",
"raise",
"\"Error: Malformed Message\"",
"if",
"not",
"msg_split",
"type",
"=",
"msg_split",
"[",
"1",
"]",
"data",
"=",
"{",
"}",
"else",
"type",
"=",
"msg_split",
"[",
"1",
"]",
"data",
"=",
"JSON",
".",
"parse",
"(",
"msg_split",
"[",
"2",
"]",
")",
"end",
"{",
"type",
":",
"type",
",",
"data",
":",
"data",
"}",
"end"
] |
Parses a message
|
[
"Parses",
"a",
"message"
] |
60ede42375b4647b9770bc9a03e614f8d90233ac
|
https://github.com/rit-sse-mycroft/template-ruby/blob/60ede42375b4647b9770bc9a03e614f8d90233ac/lib/mycroft/helpers.rb#L5-L20
|
7,333 |
rit-sse-mycroft/template-ruby
|
lib/mycroft/helpers.rb
|
Mycroft.Helpers.send_message
|
def send_message(type, message=nil)
message = message.nil? ? message = '' : message.to_json
body = type + ' ' + message
body.strip!
length = body.bytesize
@client.write("#{length}\n#{body}")
end
|
ruby
|
def send_message(type, message=nil)
message = message.nil? ? message = '' : message.to_json
body = type + ' ' + message
body.strip!
length = body.bytesize
@client.write("#{length}\n#{body}")
end
|
[
"def",
"send_message",
"(",
"type",
",",
"message",
"=",
"nil",
")",
"message",
"=",
"message",
".",
"nil?",
"?",
"message",
"=",
"''",
":",
"message",
".",
"to_json",
"body",
"=",
"type",
"+",
"' '",
"+",
"message",
"body",
".",
"strip!",
"length",
"=",
"body",
".",
"bytesize",
"@client",
".",
"write",
"(",
"\"#{length}\\n#{body}\"",
")",
"end"
] |
Sends a message of a specific type
|
[
"Sends",
"a",
"message",
"of",
"a",
"specific",
"type"
] |
60ede42375b4647b9770bc9a03e614f8d90233ac
|
https://github.com/rit-sse-mycroft/template-ruby/blob/60ede42375b4647b9770bc9a03e614f8d90233ac/lib/mycroft/helpers.rb#L23-L29
|
7,334 |
triglav-dataflow/triglav-agent-framework-ruby
|
lib/triglav/agent/api_client.rb
|
Triglav::Agent.ApiClient.list_aggregated_resources
|
def list_aggregated_resources(uri_prefix)
$logger.debug { "ApiClient#list_aggregated_resources(#{uri_prefix.inspect})" }
resources_api = TriglavClient::ResourcesApi.new(@api_client)
handle_error { resources_api.list_aggregated_resources(uri_prefix) }
end
|
ruby
|
def list_aggregated_resources(uri_prefix)
$logger.debug { "ApiClient#list_aggregated_resources(#{uri_prefix.inspect})" }
resources_api = TriglavClient::ResourcesApi.new(@api_client)
handle_error { resources_api.list_aggregated_resources(uri_prefix) }
end
|
[
"def",
"list_aggregated_resources",
"(",
"uri_prefix",
")",
"$logger",
".",
"debug",
"{",
"\"ApiClient#list_aggregated_resources(#{uri_prefix.inspect})\"",
"}",
"resources_api",
"=",
"TriglavClient",
"::",
"ResourcesApi",
".",
"new",
"(",
"@api_client",
")",
"handle_error",
"{",
"resources_api",
".",
"list_aggregated_resources",
"(",
"uri_prefix",
")",
"}",
"end"
] |
List resources required to be monitored
@param [String] uri_prefix
@return [Array of TriglavClient::ResourceEachResponse] array of resources
@see TriglavClient::ResourceEachResponse
|
[
"List",
"resources",
"required",
"to",
"be",
"monitored"
] |
a2517253a2b151b8ece3c22f389e5a2c38d93a88
|
https://github.com/triglav-dataflow/triglav-agent-framework-ruby/blob/a2517253a2b151b8ece3c22f389e5a2c38d93a88/lib/triglav/agent/api_client.rb#L59-L63
|
7,335 |
daws/exact_target_sdk
|
lib/exact_target_sdk/api_object.rb
|
ExactTargetSDK.APIObject.render_properties!
|
def render_properties!(xml)
self.class.properties.each do |property, options|
next unless instance_variable_get("@_set_#{property}")
property_value = self.send(property)
render_property!(property, property_value, xml, options)
end
end
|
ruby
|
def render_properties!(xml)
self.class.properties.each do |property, options|
next unless instance_variable_get("@_set_#{property}")
property_value = self.send(property)
render_property!(property, property_value, xml, options)
end
end
|
[
"def",
"render_properties!",
"(",
"xml",
")",
"self",
".",
"class",
".",
"properties",
".",
"each",
"do",
"|",
"property",
",",
"options",
"|",
"next",
"unless",
"instance_variable_get",
"(",
"\"@_set_#{property}\"",
")",
"property_value",
"=",
"self",
".",
"send",
"(",
"property",
")",
"render_property!",
"(",
"property",
",",
"property_value",
",",
"xml",
",",
"options",
")",
"end",
"end"
] |
By default, loops through all registered properties, and renders
each that has been explicitly set.
May be overridden.
|
[
"By",
"default",
"loops",
"through",
"all",
"registered",
"properties",
"and",
"renders",
"each",
"that",
"has",
"been",
"explicitly",
"set",
"."
] |
64fde8f61356a5f0c75586a10b07d175adfeac12
|
https://github.com/daws/exact_target_sdk/blob/64fde8f61356a5f0c75586a10b07d175adfeac12/lib/exact_target_sdk/api_object.rb#L130-L136
|
7,336 |
hinrik/ircsupport
|
lib/ircsupport/parser.rb
|
IRCSupport.Parser.compose
|
def compose(line)
raise ArgumentError, "You must specify a command" if !line.command
raw_line = ''
raw_line << ":#{line.prefix} " if line.prefix
raw_line << line.command
if line.args
line.args.each_with_index do |arg, idx|
raw_line << ' '
if idx != line.args.count-1 and arg.match(@@space)
raise ArgumentError, "Only the last argument may contain spaces"
end
if idx == line.args.count-1
raw_line << ':' if arg.match(@@space)
end
raw_line << arg
end
end
return raw_line
end
|
ruby
|
def compose(line)
raise ArgumentError, "You must specify a command" if !line.command
raw_line = ''
raw_line << ":#{line.prefix} " if line.prefix
raw_line << line.command
if line.args
line.args.each_with_index do |arg, idx|
raw_line << ' '
if idx != line.args.count-1 and arg.match(@@space)
raise ArgumentError, "Only the last argument may contain spaces"
end
if idx == line.args.count-1
raw_line << ':' if arg.match(@@space)
end
raw_line << arg
end
end
return raw_line
end
|
[
"def",
"compose",
"(",
"line",
")",
"raise",
"ArgumentError",
",",
"\"You must specify a command\"",
"if",
"!",
"line",
".",
"command",
"raw_line",
"=",
"''",
"raw_line",
"<<",
"\":#{line.prefix} \"",
"if",
"line",
".",
"prefix",
"raw_line",
"<<",
"line",
".",
"command",
"if",
"line",
".",
"args",
"line",
".",
"args",
".",
"each_with_index",
"do",
"|",
"arg",
",",
"idx",
"|",
"raw_line",
"<<",
"' '",
"if",
"idx",
"!=",
"line",
".",
"args",
".",
"count",
"-",
"1",
"and",
"arg",
".",
"match",
"(",
"@@space",
")",
"raise",
"ArgumentError",
",",
"\"Only the last argument may contain spaces\"",
"end",
"if",
"idx",
"==",
"line",
".",
"args",
".",
"count",
"-",
"1",
"raw_line",
"<<",
"':'",
"if",
"arg",
".",
"match",
"(",
"@@space",
")",
"end",
"raw_line",
"<<",
"arg",
"end",
"end",
"return",
"raw_line",
"end"
] |
Compose an IRC protocol line.
@param [IRCSupport::Line] line An IRC protocol line object
(as returned by {#decompose}).
@return [String] An IRC protocol line.
|
[
"Compose",
"an",
"IRC",
"protocol",
"line",
"."
] |
d028b7d5ccc604a6af175ee2264c18d25b1f7dff
|
https://github.com/hinrik/ircsupport/blob/d028b7d5ccc604a6af175ee2264c18d25b1f7dff/lib/ircsupport/parser.rb#L136-L156
|
7,337 |
hinrik/ircsupport
|
lib/ircsupport/parser.rb
|
IRCSupport.Parser.parse
|
def parse(raw_line)
line = decompose(raw_line)
if line.command =~ /^(PRIVMSG|NOTICE)$/ && line.args[1] =~ /\x01/
return handle_ctcp_message(line)
end
msg_class = case
when line.command =~ /^\d{3}$/
begin
constantize("IRCSupport::Message::Numeric#{line.command}")
rescue
constantize("IRCSupport::Message::Numeric")
end
when line.command == "MODE"
if @isupport['CHANTYPES'].include?(line.args[0][0])
constantize("IRCSupport::Message::ChannelModeChange")
else
constantize("IRCSupport::Message::UserModeChange")
end
when line.command == "NOTICE" && (!line.prefix || line.prefix !~ /!/)
constantize("IRCSupport::Message::ServerNotice")
when line.command == "CAP" && %w{LS LIST ACK}.include?(line.args[0])
constantize("IRCSupport::Message::CAP::#{line.args[0]}")
else
begin
constantize("IRCSupport::Message::#{line.command.capitalize}")
rescue
constantize("IRCSupport::Message")
end
end
message = msg_class.new(line, @isupport, @capabilities)
case message.type
when :'005'
@isupport.merge! message.isupport
when :cap_ack
message.capabilities.each do |capability, options|
if options.include?(:disable)
@capabilities = @capabilities - [capability]
elsif options.include?(:enable)
@capabilities = @capabilities + [capability]
end
end
end
return message
end
|
ruby
|
def parse(raw_line)
line = decompose(raw_line)
if line.command =~ /^(PRIVMSG|NOTICE)$/ && line.args[1] =~ /\x01/
return handle_ctcp_message(line)
end
msg_class = case
when line.command =~ /^\d{3}$/
begin
constantize("IRCSupport::Message::Numeric#{line.command}")
rescue
constantize("IRCSupport::Message::Numeric")
end
when line.command == "MODE"
if @isupport['CHANTYPES'].include?(line.args[0][0])
constantize("IRCSupport::Message::ChannelModeChange")
else
constantize("IRCSupport::Message::UserModeChange")
end
when line.command == "NOTICE" && (!line.prefix || line.prefix !~ /!/)
constantize("IRCSupport::Message::ServerNotice")
when line.command == "CAP" && %w{LS LIST ACK}.include?(line.args[0])
constantize("IRCSupport::Message::CAP::#{line.args[0]}")
else
begin
constantize("IRCSupport::Message::#{line.command.capitalize}")
rescue
constantize("IRCSupport::Message")
end
end
message = msg_class.new(line, @isupport, @capabilities)
case message.type
when :'005'
@isupport.merge! message.isupport
when :cap_ack
message.capabilities.each do |capability, options|
if options.include?(:disable)
@capabilities = @capabilities - [capability]
elsif options.include?(:enable)
@capabilities = @capabilities + [capability]
end
end
end
return message
end
|
[
"def",
"parse",
"(",
"raw_line",
")",
"line",
"=",
"decompose",
"(",
"raw_line",
")",
"if",
"line",
".",
"command",
"=~",
"/",
"/",
"&&",
"line",
".",
"args",
"[",
"1",
"]",
"=~",
"/",
"\\x01",
"/",
"return",
"handle_ctcp_message",
"(",
"line",
")",
"end",
"msg_class",
"=",
"case",
"when",
"line",
".",
"command",
"=~",
"/",
"\\d",
"/",
"begin",
"constantize",
"(",
"\"IRCSupport::Message::Numeric#{line.command}\"",
")",
"rescue",
"constantize",
"(",
"\"IRCSupport::Message::Numeric\"",
")",
"end",
"when",
"line",
".",
"command",
"==",
"\"MODE\"",
"if",
"@isupport",
"[",
"'CHANTYPES'",
"]",
".",
"include?",
"(",
"line",
".",
"args",
"[",
"0",
"]",
"[",
"0",
"]",
")",
"constantize",
"(",
"\"IRCSupport::Message::ChannelModeChange\"",
")",
"else",
"constantize",
"(",
"\"IRCSupport::Message::UserModeChange\"",
")",
"end",
"when",
"line",
".",
"command",
"==",
"\"NOTICE\"",
"&&",
"(",
"!",
"line",
".",
"prefix",
"||",
"line",
".",
"prefix",
"!~",
"/",
"/",
")",
"constantize",
"(",
"\"IRCSupport::Message::ServerNotice\"",
")",
"when",
"line",
".",
"command",
"==",
"\"CAP\"",
"&&",
"%w{",
"LS",
"LIST",
"ACK",
"}",
".",
"include?",
"(",
"line",
".",
"args",
"[",
"0",
"]",
")",
"constantize",
"(",
"\"IRCSupport::Message::CAP::#{line.args[0]}\"",
")",
"else",
"begin",
"constantize",
"(",
"\"IRCSupport::Message::#{line.command.capitalize}\"",
")",
"rescue",
"constantize",
"(",
"\"IRCSupport::Message\"",
")",
"end",
"end",
"message",
"=",
"msg_class",
".",
"new",
"(",
"line",
",",
"@isupport",
",",
"@capabilities",
")",
"case",
"message",
".",
"type",
"when",
":'",
"'",
"@isupport",
".",
"merge!",
"message",
".",
"isupport",
"when",
":cap_ack",
"message",
".",
"capabilities",
".",
"each",
"do",
"|",
"capability",
",",
"options",
"|",
"if",
"options",
".",
"include?",
"(",
":disable",
")",
"@capabilities",
"=",
"@capabilities",
"-",
"[",
"capability",
"]",
"elsif",
"options",
".",
"include?",
"(",
":enable",
")",
"@capabilities",
"=",
"@capabilities",
"+",
"[",
"capability",
"]",
"end",
"end",
"end",
"return",
"message",
"end"
] |
Parse an IRC protocol line into a complete message object.
@param [String] raw_line An IRC protocol line.
@return [IRCSupport::Message] A parsed message object.
|
[
"Parse",
"an",
"IRC",
"protocol",
"line",
"into",
"a",
"complete",
"message",
"object",
"."
] |
d028b7d5ccc604a6af175ee2264c18d25b1f7dff
|
https://github.com/hinrik/ircsupport/blob/d028b7d5ccc604a6af175ee2264c18d25b1f7dff/lib/ircsupport/parser.rb#L161-L209
|
7,338 |
robfors/ruby-sumac
|
lib/sumac/handshake.rb
|
Sumac.Handshake.send_initialization_message
|
def send_initialization_message
entry_properties = @connection.objects.convert_object_to_properties(@connection.local_entry)
message = Messages::Initialization.build(entry: entry_properties)
@connection.messenger.send(message)
end
|
ruby
|
def send_initialization_message
entry_properties = @connection.objects.convert_object_to_properties(@connection.local_entry)
message = Messages::Initialization.build(entry: entry_properties)
@connection.messenger.send(message)
end
|
[
"def",
"send_initialization_message",
"entry_properties",
"=",
"@connection",
".",
"objects",
".",
"convert_object_to_properties",
"(",
"@connection",
".",
"local_entry",
")",
"message",
"=",
"Messages",
"::",
"Initialization",
".",
"build",
"(",
"entry",
":",
"entry_properties",
")",
"@connection",
".",
"messenger",
".",
"send",
"(",
"message",
")",
"end"
] |
Build and send an initialization message.
@note make sure [email protected]_entry+ is sendable before calling this
@return [void]
|
[
"Build",
"and",
"send",
"an",
"initialization",
"message",
"."
] |
524fa68b7d1bb10a74baa69cd594ab2b8cae20a3
|
https://github.com/robfors/ruby-sumac/blob/524fa68b7d1bb10a74baa69cd594ab2b8cae20a3/lib/sumac/handshake.rb#L24-L28
|
7,339 |
robfors/ruby-sumac
|
lib/sumac/handshake.rb
|
Sumac.Handshake.process_initialization_message
|
def process_initialization_message(message)
entry = @connection.objects.convert_properties_to_object(message.entry)
@connection.remote_entry.set(entry)
end
|
ruby
|
def process_initialization_message(message)
entry = @connection.objects.convert_properties_to_object(message.entry)
@connection.remote_entry.set(entry)
end
|
[
"def",
"process_initialization_message",
"(",
"message",
")",
"entry",
"=",
"@connection",
".",
"objects",
".",
"convert_properties_to_object",
"(",
"message",
".",
"entry",
")",
"@connection",
".",
"remote_entry",
".",
"set",
"(",
"entry",
")",
"end"
] |
Processes a initialization message from the remote endpoint.
@param message [Messages::Initialization]
@raise [ProtocolError] if a {LocalObject} does not exist with id received for the entry object
@return [void]
|
[
"Processes",
"a",
"initialization",
"message",
"from",
"the",
"remote",
"endpoint",
"."
] |
524fa68b7d1bb10a74baa69cd594ab2b8cae20a3
|
https://github.com/robfors/ruby-sumac/blob/524fa68b7d1bb10a74baa69cd594ab2b8cae20a3/lib/sumac/handshake.rb#L42-L45
|
7,340 |
westlakedesign/stripe_webhooks
|
app/models/stripe_webhooks/callback.rb
|
StripeWebhooks.Callback.run_once
|
def run_once(event)
unless StripeWebhooks::PerformedCallback.exists?(stripe_event_id: event.id, label: label)
run(event)
StripeWebhooks::PerformedCallback.create(stripe_event_id: event.id, label: label)
end
end
|
ruby
|
def run_once(event)
unless StripeWebhooks::PerformedCallback.exists?(stripe_event_id: event.id, label: label)
run(event)
StripeWebhooks::PerformedCallback.create(stripe_event_id: event.id, label: label)
end
end
|
[
"def",
"run_once",
"(",
"event",
")",
"unless",
"StripeWebhooks",
"::",
"PerformedCallback",
".",
"exists?",
"(",
"stripe_event_id",
":",
"event",
".",
"id",
",",
"label",
":",
"label",
")",
"run",
"(",
"event",
")",
"StripeWebhooks",
"::",
"PerformedCallback",
".",
"create",
"(",
"stripe_event_id",
":",
"event",
".",
"id",
",",
"label",
":",
"label",
")",
"end",
"end"
] |
Run the callback only if we have not run it once before
|
[
"Run",
"the",
"callback",
"only",
"if",
"we",
"have",
"not",
"run",
"it",
"once",
"before"
] |
a6f5088fc1b3827c12571ccc0f3ac303ec372b08
|
https://github.com/westlakedesign/stripe_webhooks/blob/a6f5088fc1b3827c12571ccc0f3ac303ec372b08/app/models/stripe_webhooks/callback.rb#L56-L61
|
7,341 |
jinx/migrate
|
lib/jinx/migration/migrator.rb
|
Jinx.Migrator.migrate
|
def migrate(&block)
unless block_given? then
return migrate { |tgt, row| tgt }
end
# If there is an extract, then wrap the migration in an extract
# writer block.
if @extract then
if String === @extract then
logger.debug { "Opening migration extract #{@extract}..." }
FileUtils::mkdir_p(File.dirname(@extract))
if @extract_hdrs then
logger.debug { "Migration extract headers: #{@extract_hdrs.join(', ')}." }
CsvIO.open(@extract, :mode => 'w', :headers => @extract_hdrs) do |io|
@extract = io
return migrate(&block)
end
else
File.open(@extract, 'w') do |io|
@extract = io
return migrate(&block)
end
end
end
# Copy the extract into a local variable and clear the extract i.v.
# prior to a recursive call with an extract writer block.
io, @extract = @extract, nil
return migrate do |tgt, row|
res = yield(tgt, row)
tgt.extract(io)
res
end
end
begin
migrate_rows(&block)
ensure
@rejects.close if @rejects
remove_migration_methods
end
end
|
ruby
|
def migrate(&block)
unless block_given? then
return migrate { |tgt, row| tgt }
end
# If there is an extract, then wrap the migration in an extract
# writer block.
if @extract then
if String === @extract then
logger.debug { "Opening migration extract #{@extract}..." }
FileUtils::mkdir_p(File.dirname(@extract))
if @extract_hdrs then
logger.debug { "Migration extract headers: #{@extract_hdrs.join(', ')}." }
CsvIO.open(@extract, :mode => 'w', :headers => @extract_hdrs) do |io|
@extract = io
return migrate(&block)
end
else
File.open(@extract, 'w') do |io|
@extract = io
return migrate(&block)
end
end
end
# Copy the extract into a local variable and clear the extract i.v.
# prior to a recursive call with an extract writer block.
io, @extract = @extract, nil
return migrate do |tgt, row|
res = yield(tgt, row)
tgt.extract(io)
res
end
end
begin
migrate_rows(&block)
ensure
@rejects.close if @rejects
remove_migration_methods
end
end
|
[
"def",
"migrate",
"(",
"&",
"block",
")",
"unless",
"block_given?",
"then",
"return",
"migrate",
"{",
"|",
"tgt",
",",
"row",
"|",
"tgt",
"}",
"end",
"# If there is an extract, then wrap the migration in an extract",
"# writer block.",
"if",
"@extract",
"then",
"if",
"String",
"===",
"@extract",
"then",
"logger",
".",
"debug",
"{",
"\"Opening migration extract #{@extract}...\"",
"}",
"FileUtils",
"::",
"mkdir_p",
"(",
"File",
".",
"dirname",
"(",
"@extract",
")",
")",
"if",
"@extract_hdrs",
"then",
"logger",
".",
"debug",
"{",
"\"Migration extract headers: #{@extract_hdrs.join(', ')}.\"",
"}",
"CsvIO",
".",
"open",
"(",
"@extract",
",",
":mode",
"=>",
"'w'",
",",
":headers",
"=>",
"@extract_hdrs",
")",
"do",
"|",
"io",
"|",
"@extract",
"=",
"io",
"return",
"migrate",
"(",
"block",
")",
"end",
"else",
"File",
".",
"open",
"(",
"@extract",
",",
"'w'",
")",
"do",
"|",
"io",
"|",
"@extract",
"=",
"io",
"return",
"migrate",
"(",
"block",
")",
"end",
"end",
"end",
"# Copy the extract into a local variable and clear the extract i.v.",
"# prior to a recursive call with an extract writer block.",
"io",
",",
"@extract",
"=",
"@extract",
",",
"nil",
"return",
"migrate",
"do",
"|",
"tgt",
",",
"row",
"|",
"res",
"=",
"yield",
"(",
"tgt",
",",
"row",
")",
"tgt",
".",
"extract",
"(",
"io",
")",
"res",
"end",
"end",
"begin",
"migrate_rows",
"(",
"block",
")",
"ensure",
"@rejects",
".",
"close",
"if",
"@rejects",
"remove_migration_methods",
"end",
"end"
] |
Creates a new Migrator from the given options.
@param [{Symbol => Object}] opts the migration options
@option opts [Class] :target the required target domain class
@option opts [<String>, String] :mapping the required input field => caTissue attribute mapping file(s)
@option opts [String, Migration::Reader] :input the required input file name or an adapter which
implements the {Migration::Reader} methods
@option opts [<String>, String] :defaults the optional caTissue attribute => value default mapping file(s)
@option opts [<String>, String] :filters the optional caTissue attribute input value => caTissue value filter file(s)
@option opts [<String>, String] :shims the optional shim file(s) to load
@option opts [String] :unique the optional flag which ensures that migrator calls the +uniquify+ method on
those migrated objects whose class includes the +Unique+ module
@option opts [String] :create the optional flag indicating that existing target objects are ignored
@option opts [String] :bad the optional invalid record file
@option opts [String, IO] :extract the optional extract file or object that responds to +<<+
@option opts [<String>] :extract_headers the optional extract CSV field headers
@option opts [Integer] :from the optional starting source record number to process
@option opts [Integer] :to the optional ending source record number to process
@option opts [Boolean] :quiet the optional flag which suppress output messages
@option opts [Boolean] :verbose the optional flag to print the migration progress
Imports this migrator's CSV file and calls the given block on each migrated target
domain object. If no block is given, then this method returns an array of the
migrated target objects.
@yield [target, row] operates on the migration target
@yieldparam [Resource] target the migrated target domain object
@yieldparam [{Symbol => Object}] row the migration source record
|
[
"Creates",
"a",
"new",
"Migrator",
"from",
"the",
"given",
"options",
"."
] |
309957a470d72da3bd074f8173dbbe2f12449883
|
https://github.com/jinx/migrate/blob/309957a470d72da3bd074f8173dbbe2f12449883/lib/jinx/migration/migrator.rb#L56-L94
|
7,342 |
jinx/migrate
|
lib/jinx/migration/migrator.rb
|
Jinx.Migrator.remove_migration_methods
|
def remove_migration_methods
# remove the migrate_<attribute> methods
@mgt_mths.each do | klass, hash|
hash.each_value do |sym|
while klass.method_defined?(sym)
klass.instance_method(sym).owner.module_eval { remove_method(sym) }
end
end
end
# remove the migrate method
@creatable_classes.each do |klass|
while (k = klass.instance_method(:migrate).owner) < Migratable
k.module_eval { remove_method(:migrate) }
end
end
# remove the target extract method
remove_extract_method(@target) if @extract
end
|
ruby
|
def remove_migration_methods
# remove the migrate_<attribute> methods
@mgt_mths.each do | klass, hash|
hash.each_value do |sym|
while klass.method_defined?(sym)
klass.instance_method(sym).owner.module_eval { remove_method(sym) }
end
end
end
# remove the migrate method
@creatable_classes.each do |klass|
while (k = klass.instance_method(:migrate).owner) < Migratable
k.module_eval { remove_method(:migrate) }
end
end
# remove the target extract method
remove_extract_method(@target) if @extract
end
|
[
"def",
"remove_migration_methods",
"# remove the migrate_<attribute> methods",
"@mgt_mths",
".",
"each",
"do",
"|",
"klass",
",",
"hash",
"|",
"hash",
".",
"each_value",
"do",
"|",
"sym",
"|",
"while",
"klass",
".",
"method_defined?",
"(",
"sym",
")",
"klass",
".",
"instance_method",
"(",
"sym",
")",
".",
"owner",
".",
"module_eval",
"{",
"remove_method",
"(",
"sym",
")",
"}",
"end",
"end",
"end",
"# remove the migrate method",
"@creatable_classes",
".",
"each",
"do",
"|",
"klass",
"|",
"while",
"(",
"k",
"=",
"klass",
".",
"instance_method",
"(",
":migrate",
")",
".",
"owner",
")",
"<",
"Migratable",
"k",
".",
"module_eval",
"{",
"remove_method",
"(",
":migrate",
")",
"}",
"end",
"end",
"# remove the target extract method",
"remove_extract_method",
"(",
"@target",
")",
"if",
"@extract",
"end"
] |
Cleans up after the migration by removing the methods injected by migration
shims.
|
[
"Cleans",
"up",
"after",
"the",
"migration",
"by",
"removing",
"the",
"methods",
"injected",
"by",
"migration",
"shims",
"."
] |
309957a470d72da3bd074f8173dbbe2f12449883
|
https://github.com/jinx/migrate/blob/309957a470d72da3bd074f8173dbbe2f12449883/lib/jinx/migration/migrator.rb#L106-L123
|
7,343 |
jinx/migrate
|
lib/jinx/migration/migrator.rb
|
Jinx.Migrator.load_shims
|
def load_shims(files)
logger.debug { "Loading the migration shims with load path #{$:.pp_s}..." }
files.enumerate do |file|
load file
logger.info { "The migrator loaded the shim file #{file}." }
end
end
|
ruby
|
def load_shims(files)
logger.debug { "Loading the migration shims with load path #{$:.pp_s}..." }
files.enumerate do |file|
load file
logger.info { "The migrator loaded the shim file #{file}." }
end
end
|
[
"def",
"load_shims",
"(",
"files",
")",
"logger",
".",
"debug",
"{",
"\"Loading the migration shims with load path #{$:.pp_s}...\"",
"}",
"files",
".",
"enumerate",
"do",
"|",
"file",
"|",
"load",
"file",
"logger",
".",
"info",
"{",
"\"The migrator loaded the shim file #{file}.\"",
"}",
"end",
"end"
] |
Loads the shim files.
@param [<String>, String] files the file or file array
|
[
"Loads",
"the",
"shim",
"files",
"."
] |
309957a470d72da3bd074f8173dbbe2f12449883
|
https://github.com/jinx/migrate/blob/309957a470d72da3bd074f8173dbbe2f12449883/lib/jinx/migration/migrator.rb#L421-L427
|
7,344 |
jinx/migrate
|
lib/jinx/migration/migrator.rb
|
Jinx.Migrator.migrate_rows
|
def migrate_rows
# open an CSV output for rejects if the bad option is set
if @bad_file then
@rejects = open_rejects(@bad_file)
logger.info("Unmigrated records will be written to #{File.expand_path(@bad_file)}.")
end
@rec_cnt = mgt_cnt = 0
logger.info { "Migrating #{@input}..." }
puts "Migrating #{@input}..." if @verbose
@reader.each do |row|
# the one-based current record number
rec_no = @rec_cnt + 1
# skip if the row precedes the from option
if rec_no == @from and @rec_cnt > 0 then
logger.info("Skipped the initial #{@rec_cnt} records.")
elsif rec_no == @to then
logger.info("Ending the migration after processing record #{@rec_cnt}.")
return
elsif rec_no < @from then
@rec_cnt += 1
next
end
begin
# migrate the row
logger.debug { "Migrating record #{rec_no}..." }
tgt = migrate_row(row)
# call the block on the migrated target
if tgt then
logger.debug { "The migrator built #{tgt} with the following content:\n#{tgt.dump}" }
yield(tgt, row)
end
rescue Exception => e
logger.error("Migration error on record #{rec_no} - #{e.message}:\n#{e.backtrace.pp_s}")
# If there is a reject file, then don't propagate the error.
raise unless @rejects
# try to clear the migration state
clear(tgt) rescue nil
# clear the target
tgt = nil
end
if tgt then
# replace the log message below with the commented alternative to detect a memory leak
logger.info { "Migrated record #{rec_no}." }
#memory_usage = `ps -o rss= -p #{Process.pid}`.to_f / 1024 # in megabytes
#logger.debug { "Migrated rec #{@rec_cnt}; memory usage: #{sprintf("%.1f", memory_usage)} MB." }
mgt_cnt += 1
if @verbose then print_progress(mgt_cnt) end
# clear the migration state
clear(tgt)
elsif @rejects then
# If there is a rejects file then warn, write the reject and continue.
logger.warn("Migration not performed on record #{rec_no}.")
@rejects << row
@rejects.flush
logger.debug("Invalid record #{rec_no} was written to the rejects file #{@bad_file}.")
else
raise MigrationError.new("Migration not performed on record #{rec_no}")
end
# Bump the record count.
@rec_cnt += 1
end
logger.info("Migrated #{mgt_cnt} of #{@rec_cnt} records.")
if @verbose then
puts
puts "Migrated #{mgt_cnt} of #{@rec_cnt} records."
end
end
|
ruby
|
def migrate_rows
# open an CSV output for rejects if the bad option is set
if @bad_file then
@rejects = open_rejects(@bad_file)
logger.info("Unmigrated records will be written to #{File.expand_path(@bad_file)}.")
end
@rec_cnt = mgt_cnt = 0
logger.info { "Migrating #{@input}..." }
puts "Migrating #{@input}..." if @verbose
@reader.each do |row|
# the one-based current record number
rec_no = @rec_cnt + 1
# skip if the row precedes the from option
if rec_no == @from and @rec_cnt > 0 then
logger.info("Skipped the initial #{@rec_cnt} records.")
elsif rec_no == @to then
logger.info("Ending the migration after processing record #{@rec_cnt}.")
return
elsif rec_no < @from then
@rec_cnt += 1
next
end
begin
# migrate the row
logger.debug { "Migrating record #{rec_no}..." }
tgt = migrate_row(row)
# call the block on the migrated target
if tgt then
logger.debug { "The migrator built #{tgt} with the following content:\n#{tgt.dump}" }
yield(tgt, row)
end
rescue Exception => e
logger.error("Migration error on record #{rec_no} - #{e.message}:\n#{e.backtrace.pp_s}")
# If there is a reject file, then don't propagate the error.
raise unless @rejects
# try to clear the migration state
clear(tgt) rescue nil
# clear the target
tgt = nil
end
if tgt then
# replace the log message below with the commented alternative to detect a memory leak
logger.info { "Migrated record #{rec_no}." }
#memory_usage = `ps -o rss= -p #{Process.pid}`.to_f / 1024 # in megabytes
#logger.debug { "Migrated rec #{@rec_cnt}; memory usage: #{sprintf("%.1f", memory_usage)} MB." }
mgt_cnt += 1
if @verbose then print_progress(mgt_cnt) end
# clear the migration state
clear(tgt)
elsif @rejects then
# If there is a rejects file then warn, write the reject and continue.
logger.warn("Migration not performed on record #{rec_no}.")
@rejects << row
@rejects.flush
logger.debug("Invalid record #{rec_no} was written to the rejects file #{@bad_file}.")
else
raise MigrationError.new("Migration not performed on record #{rec_no}")
end
# Bump the record count.
@rec_cnt += 1
end
logger.info("Migrated #{mgt_cnt} of #{@rec_cnt} records.")
if @verbose then
puts
puts "Migrated #{mgt_cnt} of #{@rec_cnt} records."
end
end
|
[
"def",
"migrate_rows",
"# open an CSV output for rejects if the bad option is set",
"if",
"@bad_file",
"then",
"@rejects",
"=",
"open_rejects",
"(",
"@bad_file",
")",
"logger",
".",
"info",
"(",
"\"Unmigrated records will be written to #{File.expand_path(@bad_file)}.\"",
")",
"end",
"@rec_cnt",
"=",
"mgt_cnt",
"=",
"0",
"logger",
".",
"info",
"{",
"\"Migrating #{@input}...\"",
"}",
"puts",
"\"Migrating #{@input}...\"",
"if",
"@verbose",
"@reader",
".",
"each",
"do",
"|",
"row",
"|",
"# the one-based current record number",
"rec_no",
"=",
"@rec_cnt",
"+",
"1",
"# skip if the row precedes the from option",
"if",
"rec_no",
"==",
"@from",
"and",
"@rec_cnt",
">",
"0",
"then",
"logger",
".",
"info",
"(",
"\"Skipped the initial #{@rec_cnt} records.\"",
")",
"elsif",
"rec_no",
"==",
"@to",
"then",
"logger",
".",
"info",
"(",
"\"Ending the migration after processing record #{@rec_cnt}.\"",
")",
"return",
"elsif",
"rec_no",
"<",
"@from",
"then",
"@rec_cnt",
"+=",
"1",
"next",
"end",
"begin",
"# migrate the row",
"logger",
".",
"debug",
"{",
"\"Migrating record #{rec_no}...\"",
"}",
"tgt",
"=",
"migrate_row",
"(",
"row",
")",
"# call the block on the migrated target",
"if",
"tgt",
"then",
"logger",
".",
"debug",
"{",
"\"The migrator built #{tgt} with the following content:\\n#{tgt.dump}\"",
"}",
"yield",
"(",
"tgt",
",",
"row",
")",
"end",
"rescue",
"Exception",
"=>",
"e",
"logger",
".",
"error",
"(",
"\"Migration error on record #{rec_no} - #{e.message}:\\n#{e.backtrace.pp_s}\"",
")",
"# If there is a reject file, then don't propagate the error.",
"raise",
"unless",
"@rejects",
"# try to clear the migration state",
"clear",
"(",
"tgt",
")",
"rescue",
"nil",
"# clear the target",
"tgt",
"=",
"nil",
"end",
"if",
"tgt",
"then",
"# replace the log message below with the commented alternative to detect a memory leak",
"logger",
".",
"info",
"{",
"\"Migrated record #{rec_no}.\"",
"}",
"#memory_usage = `ps -o rss= -p #{Process.pid}`.to_f / 1024 # in megabytes",
"#logger.debug { \"Migrated rec #{@rec_cnt}; memory usage: #{sprintf(\"%.1f\", memory_usage)} MB.\" }",
"mgt_cnt",
"+=",
"1",
"if",
"@verbose",
"then",
"print_progress",
"(",
"mgt_cnt",
")",
"end",
"# clear the migration state",
"clear",
"(",
"tgt",
")",
"elsif",
"@rejects",
"then",
"# If there is a rejects file then warn, write the reject and continue.",
"logger",
".",
"warn",
"(",
"\"Migration not performed on record #{rec_no}.\"",
")",
"@rejects",
"<<",
"row",
"@rejects",
".",
"flush",
"logger",
".",
"debug",
"(",
"\"Invalid record #{rec_no} was written to the rejects file #{@bad_file}.\"",
")",
"else",
"raise",
"MigrationError",
".",
"new",
"(",
"\"Migration not performed on record #{rec_no}\"",
")",
"end",
"# Bump the record count.",
"@rec_cnt",
"+=",
"1",
"end",
"logger",
".",
"info",
"(",
"\"Migrated #{mgt_cnt} of #{@rec_cnt} records.\"",
")",
"if",
"@verbose",
"then",
"puts",
"puts",
"\"Migrated #{mgt_cnt} of #{@rec_cnt} records.\"",
"end",
"end"
] |
Migrates all rows in the input.
@yield (see #migrate)
@yieldparam (see #migrate)
|
[
"Migrates",
"all",
"rows",
"in",
"the",
"input",
"."
] |
309957a470d72da3bd074f8173dbbe2f12449883
|
https://github.com/jinx/migrate/blob/309957a470d72da3bd074f8173dbbe2f12449883/lib/jinx/migration/migrator.rb#L433-L500
|
7,345 |
jinx/migrate
|
lib/jinx/migration/migrator.rb
|
Jinx.Migrator.open_rejects
|
def open_rejects(file)
# Make the parent directory.
FileUtils.mkdir_p(File.dirname(file))
# Open the file.
FasterCSV.open(file, 'w', :headers => true, :header_converters => :symbol, :write_headers => true)
end
|
ruby
|
def open_rejects(file)
# Make the parent directory.
FileUtils.mkdir_p(File.dirname(file))
# Open the file.
FasterCSV.open(file, 'w', :headers => true, :header_converters => :symbol, :write_headers => true)
end
|
[
"def",
"open_rejects",
"(",
"file",
")",
"# Make the parent directory.",
"FileUtils",
".",
"mkdir_p",
"(",
"File",
".",
"dirname",
"(",
"file",
")",
")",
"# Open the file.",
"FasterCSV",
".",
"open",
"(",
"file",
",",
"'w'",
",",
":headers",
"=>",
"true",
",",
":header_converters",
"=>",
":symbol",
",",
":write_headers",
"=>",
"true",
")",
"end"
] |
Makes the rejects CSV output file.
@param [String] file the output file
@return [IO] the reject stream
|
[
"Makes",
"the",
"rejects",
"CSV",
"output",
"file",
"."
] |
309957a470d72da3bd074f8173dbbe2f12449883
|
https://github.com/jinx/migrate/blob/309957a470d72da3bd074f8173dbbe2f12449883/lib/jinx/migration/migrator.rb#L506-L511
|
7,346 |
jinx/migrate
|
lib/jinx/migration/migrator.rb
|
Jinx.Migrator.migrate_row
|
def migrate_row(row)
# create an instance for each creatable class
created = Set.new
# the migrated objects
migrated = @creatable_classes.map { |klass| create_instance(klass, row, created) }
# migrate each object from the input row
migrated.each do |obj|
# First uniquify the object if necessary.
if @unique and Unique === obj then
logger.debug { "The migrator is making #{obj} unique..." }
obj.uniquify
end
obj.migrate(row, migrated)
end
# the valid migrated objects
@migrated = migrate_valid_references(row, migrated)
# the candidate target objects
tgts = @migrated.select { |obj| @target_class === obj }
if tgts.size > 1 then
raise MigrationError.new("Ambiguous #{@target_class} targets #{tgts.to_series}")
end
target = tgts.first || return
logger.debug { "Migrated target #{target}." }
target
end
|
ruby
|
def migrate_row(row)
# create an instance for each creatable class
created = Set.new
# the migrated objects
migrated = @creatable_classes.map { |klass| create_instance(klass, row, created) }
# migrate each object from the input row
migrated.each do |obj|
# First uniquify the object if necessary.
if @unique and Unique === obj then
logger.debug { "The migrator is making #{obj} unique..." }
obj.uniquify
end
obj.migrate(row, migrated)
end
# the valid migrated objects
@migrated = migrate_valid_references(row, migrated)
# the candidate target objects
tgts = @migrated.select { |obj| @target_class === obj }
if tgts.size > 1 then
raise MigrationError.new("Ambiguous #{@target_class} targets #{tgts.to_series}")
end
target = tgts.first || return
logger.debug { "Migrated target #{target}." }
target
end
|
[
"def",
"migrate_row",
"(",
"row",
")",
"# create an instance for each creatable class",
"created",
"=",
"Set",
".",
"new",
"# the migrated objects",
"migrated",
"=",
"@creatable_classes",
".",
"map",
"{",
"|",
"klass",
"|",
"create_instance",
"(",
"klass",
",",
"row",
",",
"created",
")",
"}",
"# migrate each object from the input row",
"migrated",
".",
"each",
"do",
"|",
"obj",
"|",
"# First uniquify the object if necessary.",
"if",
"@unique",
"and",
"Unique",
"===",
"obj",
"then",
"logger",
".",
"debug",
"{",
"\"The migrator is making #{obj} unique...\"",
"}",
"obj",
".",
"uniquify",
"end",
"obj",
".",
"migrate",
"(",
"row",
",",
"migrated",
")",
"end",
"# the valid migrated objects",
"@migrated",
"=",
"migrate_valid_references",
"(",
"row",
",",
"migrated",
")",
"# the candidate target objects",
"tgts",
"=",
"@migrated",
".",
"select",
"{",
"|",
"obj",
"|",
"@target_class",
"===",
"obj",
"}",
"if",
"tgts",
".",
"size",
">",
"1",
"then",
"raise",
"MigrationError",
".",
"new",
"(",
"\"Ambiguous #{@target_class} targets #{tgts.to_series}\"",
")",
"end",
"target",
"=",
"tgts",
".",
"first",
"||",
"return",
"logger",
".",
"debug",
"{",
"\"Migrated target #{target}.\"",
"}",
"target",
"end"
] |
Imports the given CSV row into a target object.
@param [{Symbol => Object}] row the input row field => value hash
@return the migrated target object if the migration is valid, nil otherwise
|
[
"Imports",
"the",
"given",
"CSV",
"row",
"into",
"a",
"target",
"object",
"."
] |
309957a470d72da3bd074f8173dbbe2f12449883
|
https://github.com/jinx/migrate/blob/309957a470d72da3bd074f8173dbbe2f12449883/lib/jinx/migration/migrator.rb#L535-L560
|
7,347 |
jinx/migrate
|
lib/jinx/migration/migrator.rb
|
Jinx.Migrator.migrate_valid_references
|
def migrate_valid_references(row, migrated)
# Split the valid and invalid objects. The iteration is in reverse dependency order,
# since invalidating a dependent can invalidate the owner.
ordered = migrated.transitive_closure(:dependents)
ordered.keep_if { |obj| migrated.include?(obj) }.reverse!
valid, invalid = ordered.partition do |obj|
if migration_valid?(obj) then
obj.migrate_references(row, migrated, @target_class, @attr_flt_hash[obj.class])
true
else
obj.class.owner_attributes.each { |pa| obj.clear_attribute(pa) }
false
end
end
# Go back through the valid objects in dependency order to invalidate dependents
# whose owner is invalid.
valid.reverse.each do |obj|
unless owner_valid?(obj, valid, invalid) then
invalid << valid.delete(obj)
logger.debug { "The migrator invalidated #{obj} since it does not have a valid owner." }
end
end
# Go back through the valid objects in reverse dependency order to invalidate owners
# created only to hold a dependent which was subsequently invalidated.
valid.reject do |obj|
if @owners.include?(obj.class) and obj.dependents.all? { |dep| invalid.include?(dep) } then
# clear all references from the invalidated owner
obj.class.domain_attributes.each { |pa| obj.clear_attribute(pa) }
invalid << obj
logger.debug { "The migrator invalidated #{obj.qp} since it was created solely to hold subsequently invalidated dependents." }
true
end
end
end
|
ruby
|
def migrate_valid_references(row, migrated)
# Split the valid and invalid objects. The iteration is in reverse dependency order,
# since invalidating a dependent can invalidate the owner.
ordered = migrated.transitive_closure(:dependents)
ordered.keep_if { |obj| migrated.include?(obj) }.reverse!
valid, invalid = ordered.partition do |obj|
if migration_valid?(obj) then
obj.migrate_references(row, migrated, @target_class, @attr_flt_hash[obj.class])
true
else
obj.class.owner_attributes.each { |pa| obj.clear_attribute(pa) }
false
end
end
# Go back through the valid objects in dependency order to invalidate dependents
# whose owner is invalid.
valid.reverse.each do |obj|
unless owner_valid?(obj, valid, invalid) then
invalid << valid.delete(obj)
logger.debug { "The migrator invalidated #{obj} since it does not have a valid owner." }
end
end
# Go back through the valid objects in reverse dependency order to invalidate owners
# created only to hold a dependent which was subsequently invalidated.
valid.reject do |obj|
if @owners.include?(obj.class) and obj.dependents.all? { |dep| invalid.include?(dep) } then
# clear all references from the invalidated owner
obj.class.domain_attributes.each { |pa| obj.clear_attribute(pa) }
invalid << obj
logger.debug { "The migrator invalidated #{obj.qp} since it was created solely to hold subsequently invalidated dependents." }
true
end
end
end
|
[
"def",
"migrate_valid_references",
"(",
"row",
",",
"migrated",
")",
"# Split the valid and invalid objects. The iteration is in reverse dependency order,",
"# since invalidating a dependent can invalidate the owner.",
"ordered",
"=",
"migrated",
".",
"transitive_closure",
"(",
":dependents",
")",
"ordered",
".",
"keep_if",
"{",
"|",
"obj",
"|",
"migrated",
".",
"include?",
"(",
"obj",
")",
"}",
".",
"reverse!",
"valid",
",",
"invalid",
"=",
"ordered",
".",
"partition",
"do",
"|",
"obj",
"|",
"if",
"migration_valid?",
"(",
"obj",
")",
"then",
"obj",
".",
"migrate_references",
"(",
"row",
",",
"migrated",
",",
"@target_class",
",",
"@attr_flt_hash",
"[",
"obj",
".",
"class",
"]",
")",
"true",
"else",
"obj",
".",
"class",
".",
"owner_attributes",
".",
"each",
"{",
"|",
"pa",
"|",
"obj",
".",
"clear_attribute",
"(",
"pa",
")",
"}",
"false",
"end",
"end",
"# Go back through the valid objects in dependency order to invalidate dependents",
"# whose owner is invalid.",
"valid",
".",
"reverse",
".",
"each",
"do",
"|",
"obj",
"|",
"unless",
"owner_valid?",
"(",
"obj",
",",
"valid",
",",
"invalid",
")",
"then",
"invalid",
"<<",
"valid",
".",
"delete",
"(",
"obj",
")",
"logger",
".",
"debug",
"{",
"\"The migrator invalidated #{obj} since it does not have a valid owner.\"",
"}",
"end",
"end",
"# Go back through the valid objects in reverse dependency order to invalidate owners",
"# created only to hold a dependent which was subsequently invalidated.",
"valid",
".",
"reject",
"do",
"|",
"obj",
"|",
"if",
"@owners",
".",
"include?",
"(",
"obj",
".",
"class",
")",
"and",
"obj",
".",
"dependents",
".",
"all?",
"{",
"|",
"dep",
"|",
"invalid",
".",
"include?",
"(",
"dep",
")",
"}",
"then",
"# clear all references from the invalidated owner",
"obj",
".",
"class",
".",
"domain_attributes",
".",
"each",
"{",
"|",
"pa",
"|",
"obj",
".",
"clear_attribute",
"(",
"pa",
")",
"}",
"invalid",
"<<",
"obj",
"logger",
".",
"debug",
"{",
"\"The migrator invalidated #{obj.qp} since it was created solely to hold subsequently invalidated dependents.\"",
"}",
"true",
"end",
"end",
"end"
] |
Sets the migration references for each valid migrated object.
@param row (see #migrate_row)
@param [Array] migrated the migrated objects
@return [Array] the valid migrated objects
|
[
"Sets",
"the",
"migration",
"references",
"for",
"each",
"valid",
"migrated",
"object",
"."
] |
309957a470d72da3bd074f8173dbbe2f12449883
|
https://github.com/jinx/migrate/blob/309957a470d72da3bd074f8173dbbe2f12449883/lib/jinx/migration/migrator.rb#L567-L602
|
7,348 |
jinx/migrate
|
lib/jinx/migration/migrator.rb
|
Jinx.Migrator.create_instance
|
def create_instance(klass, row, created)
# the new object
logger.debug { "The migrator is building #{klass.qp}..." }
created << obj = klass.new
migrate_properties(obj, row, created)
add_defaults(obj, row, created)
logger.debug { "The migrator built #{obj}." }
obj
end
|
ruby
|
def create_instance(klass, row, created)
# the new object
logger.debug { "The migrator is building #{klass.qp}..." }
created << obj = klass.new
migrate_properties(obj, row, created)
add_defaults(obj, row, created)
logger.debug { "The migrator built #{obj}." }
obj
end
|
[
"def",
"create_instance",
"(",
"klass",
",",
"row",
",",
"created",
")",
"# the new object",
"logger",
".",
"debug",
"{",
"\"The migrator is building #{klass.qp}...\"",
"}",
"created",
"<<",
"obj",
"=",
"klass",
".",
"new",
"migrate_properties",
"(",
"obj",
",",
"row",
",",
"created",
")",
"add_defaults",
"(",
"obj",
",",
"row",
",",
"created",
")",
"logger",
".",
"debug",
"{",
"\"The migrator built #{obj}.\"",
"}",
"obj",
"end"
] |
Creates an instance of the given klass from the given row.
The new klass instance and all intermediate migrated instances are added to the
created set.
@param [Class] klass
@param [{Symbol => Object}] row the input row
@param [<Resource>] created the migrated instances for this row
@return [Resource] the new instance
|
[
"Creates",
"an",
"instance",
"of",
"the",
"given",
"klass",
"from",
"the",
"given",
"row",
".",
"The",
"new",
"klass",
"instance",
"and",
"all",
"intermediate",
"migrated",
"instances",
"are",
"added",
"to",
"the",
"created",
"set",
"."
] |
309957a470d72da3bd074f8173dbbe2f12449883
|
https://github.com/jinx/migrate/blob/309957a470d72da3bd074f8173dbbe2f12449883/lib/jinx/migration/migrator.rb#L637-L645
|
7,349 |
jinx/migrate
|
lib/jinx/migration/migrator.rb
|
Jinx.Migrator.migrate_properties
|
def migrate_properties(obj, row, created)
# for each input header which maps to a migratable target attribute metadata path,
# set the target attribute, creating intermediate objects as needed.
@cls_paths_hash[obj.class].each do |path|
header = @header_map[path][obj.class]
# the input value
value = row[header]
value.strip! if String === value
next if value.nil?
# fill the reference path
ref = fill_path(obj, path[0...-1], row, created)
# set the attribute
migrate_property(ref, path.last, value, row)
end
end
|
ruby
|
def migrate_properties(obj, row, created)
# for each input header which maps to a migratable target attribute metadata path,
# set the target attribute, creating intermediate objects as needed.
@cls_paths_hash[obj.class].each do |path|
header = @header_map[path][obj.class]
# the input value
value = row[header]
value.strip! if String === value
next if value.nil?
# fill the reference path
ref = fill_path(obj, path[0...-1], row, created)
# set the attribute
migrate_property(ref, path.last, value, row)
end
end
|
[
"def",
"migrate_properties",
"(",
"obj",
",",
"row",
",",
"created",
")",
"# for each input header which maps to a migratable target attribute metadata path,",
"# set the target attribute, creating intermediate objects as needed.",
"@cls_paths_hash",
"[",
"obj",
".",
"class",
"]",
".",
"each",
"do",
"|",
"path",
"|",
"header",
"=",
"@header_map",
"[",
"path",
"]",
"[",
"obj",
".",
"class",
"]",
"# the input value",
"value",
"=",
"row",
"[",
"header",
"]",
"value",
".",
"strip!",
"if",
"String",
"===",
"value",
"next",
"if",
"value",
".",
"nil?",
"# fill the reference path",
"ref",
"=",
"fill_path",
"(",
"obj",
",",
"path",
"[",
"0",
"...",
"-",
"1",
"]",
",",
"row",
",",
"created",
")",
"# set the attribute",
"migrate_property",
"(",
"ref",
",",
"path",
".",
"last",
",",
"value",
",",
"row",
")",
"end",
"end"
] |
Migrates each input field to the associated domain object attribute.
String input values are stripped. Missing input values are ignored.
@param [Resource] the migration object
@param row (see #create)
@param [<Resource>] created (see #create)
|
[
"Migrates",
"each",
"input",
"field",
"to",
"the",
"associated",
"domain",
"object",
"attribute",
".",
"String",
"input",
"values",
"are",
"stripped",
".",
"Missing",
"input",
"values",
"are",
"ignored",
"."
] |
309957a470d72da3bd074f8173dbbe2f12449883
|
https://github.com/jinx/migrate/blob/309957a470d72da3bd074f8173dbbe2f12449883/lib/jinx/migration/migrator.rb#L653-L667
|
7,350 |
jinx/migrate
|
lib/jinx/migration/migrator.rb
|
Jinx.Migrator.fill_path
|
def fill_path(obj, path, row, created)
# create the intermediate objects as needed (or return obj if path is empty)
path.inject(obj) do |parent, prop|
# the referenced object
parent.send(prop.reader) or create_reference(parent, prop, row, created)
end
end
|
ruby
|
def fill_path(obj, path, row, created)
# create the intermediate objects as needed (or return obj if path is empty)
path.inject(obj) do |parent, prop|
# the referenced object
parent.send(prop.reader) or create_reference(parent, prop, row, created)
end
end
|
[
"def",
"fill_path",
"(",
"obj",
",",
"path",
",",
"row",
",",
"created",
")",
"# create the intermediate objects as needed (or return obj if path is empty)",
"path",
".",
"inject",
"(",
"obj",
")",
"do",
"|",
"parent",
",",
"prop",
"|",
"# the referenced object",
"parent",
".",
"send",
"(",
"prop",
".",
"reader",
")",
"or",
"create_reference",
"(",
"parent",
",",
"prop",
",",
"row",
",",
"created",
")",
"end",
"end"
] |
Fills the given reference Property path starting at obj.
@param row (see #create)
@param created (see #create)
@return the last domain object in the path
|
[
"Fills",
"the",
"given",
"reference",
"Property",
"path",
"starting",
"at",
"obj",
"."
] |
309957a470d72da3bd074f8173dbbe2f12449883
|
https://github.com/jinx/migrate/blob/309957a470d72da3bd074f8173dbbe2f12449883/lib/jinx/migration/migrator.rb#L687-L693
|
7,351 |
jinx/migrate
|
lib/jinx/migration/migrator.rb
|
Jinx.Migrator.create_reference
|
def create_reference(obj, property, row, created)
if property.type.abstract? then
raise MigrationError.new("Cannot create #{obj.qp} #{property} with abstract type #{property.type}")
end
ref = property.type.new
ref.migrate(row, Array::EMPTY_ARRAY)
obj.send(property.writer, ref)
created << ref
logger.debug { "The migrator created #{obj.qp} #{property} #{ref}." }
ref
end
|
ruby
|
def create_reference(obj, property, row, created)
if property.type.abstract? then
raise MigrationError.new("Cannot create #{obj.qp} #{property} with abstract type #{property.type}")
end
ref = property.type.new
ref.migrate(row, Array::EMPTY_ARRAY)
obj.send(property.writer, ref)
created << ref
logger.debug { "The migrator created #{obj.qp} #{property} #{ref}." }
ref
end
|
[
"def",
"create_reference",
"(",
"obj",
",",
"property",
",",
"row",
",",
"created",
")",
"if",
"property",
".",
"type",
".",
"abstract?",
"then",
"raise",
"MigrationError",
".",
"new",
"(",
"\"Cannot create #{obj.qp} #{property} with abstract type #{property.type}\"",
")",
"end",
"ref",
"=",
"property",
".",
"type",
".",
"new",
"ref",
".",
"migrate",
"(",
"row",
",",
"Array",
"::",
"EMPTY_ARRAY",
")",
"obj",
".",
"send",
"(",
"property",
".",
"writer",
",",
"ref",
")",
"created",
"<<",
"ref",
"logger",
".",
"debug",
"{",
"\"The migrator created #{obj.qp} #{property} #{ref}.\"",
"}",
"ref",
"end"
] |
Sets the given migrated object's reference attribute to a new referenced domain object.
@param [Resource] obj the domain object being migrated
@param [Property] property the property being migrated
@param row (see #create)
@param created (see #create)
@return the new object
|
[
"Sets",
"the",
"given",
"migrated",
"object",
"s",
"reference",
"attribute",
"to",
"a",
"new",
"referenced",
"domain",
"object",
"."
] |
309957a470d72da3bd074f8173dbbe2f12449883
|
https://github.com/jinx/migrate/blob/309957a470d72da3bd074f8173dbbe2f12449883/lib/jinx/migration/migrator.rb#L702-L712
|
7,352 |
jinx/migrate
|
lib/jinx/migration/migrator.rb
|
Jinx.Migrator.load_defaults_files
|
def load_defaults_files(files)
# collect the class => path => value entries from each defaults file
hash = LazyHash.new { Hash.new }
files.enumerate { |file| load_defaults_file(file, hash) }
hash
end
|
ruby
|
def load_defaults_files(files)
# collect the class => path => value entries from each defaults file
hash = LazyHash.new { Hash.new }
files.enumerate { |file| load_defaults_file(file, hash) }
hash
end
|
[
"def",
"load_defaults_files",
"(",
"files",
")",
"# collect the class => path => value entries from each defaults file",
"hash",
"=",
"LazyHash",
".",
"new",
"{",
"Hash",
".",
"new",
"}",
"files",
".",
"enumerate",
"{",
"|",
"file",
"|",
"load_defaults_file",
"(",
"file",
",",
"hash",
")",
"}",
"hash",
"end"
] |
Loads the defaults configuration files.
@param [<String>, String] files the file or file array to load
@return [<Class => <String => Object>>] the class => path => default value entries
|
[
"Loads",
"the",
"defaults",
"configuration",
"files",
"."
] |
309957a470d72da3bd074f8173dbbe2f12449883
|
https://github.com/jinx/migrate/blob/309957a470d72da3bd074f8173dbbe2f12449883/lib/jinx/migration/migrator.rb#L838-L843
|
7,353 |
jinx/migrate
|
lib/jinx/migration/migrator.rb
|
Jinx.Migrator.load_defaults_file
|
def load_defaults_file(file, hash)
begin
config = YAML::load_file(file)
rescue
raise MigrationError.new("Could not read defaults file #{file}: " + $!)
end
# collect the class => path => value entries
config.each do |path_s, value|
next if value.nil_or_empty?
klass, path = create_attribute_path(path_s)
hash[klass][path] = value
end
end
|
ruby
|
def load_defaults_file(file, hash)
begin
config = YAML::load_file(file)
rescue
raise MigrationError.new("Could not read defaults file #{file}: " + $!)
end
# collect the class => path => value entries
config.each do |path_s, value|
next if value.nil_or_empty?
klass, path = create_attribute_path(path_s)
hash[klass][path] = value
end
end
|
[
"def",
"load_defaults_file",
"(",
"file",
",",
"hash",
")",
"begin",
"config",
"=",
"YAML",
"::",
"load_file",
"(",
"file",
")",
"rescue",
"raise",
"MigrationError",
".",
"new",
"(",
"\"Could not read defaults file #{file}: \"",
"+",
"$!",
")",
"end",
"# collect the class => path => value entries",
"config",
".",
"each",
"do",
"|",
"path_s",
",",
"value",
"|",
"next",
"if",
"value",
".",
"nil_or_empty?",
"klass",
",",
"path",
"=",
"create_attribute_path",
"(",
"path_s",
")",
"hash",
"[",
"klass",
"]",
"[",
"path",
"]",
"=",
"value",
"end",
"end"
] |
Loads the defaults config file into the given hash.
@param [String] file the file to load
@param [<Class => <String => Object>>] hash the class => path => default value entries
|
[
"Loads",
"the",
"defaults",
"config",
"file",
"into",
"the",
"given",
"hash",
"."
] |
309957a470d72da3bd074f8173dbbe2f12449883
|
https://github.com/jinx/migrate/blob/309957a470d72da3bd074f8173dbbe2f12449883/lib/jinx/migration/migrator.rb#L849-L861
|
7,354 |
jinx/migrate
|
lib/jinx/migration/migrator.rb
|
Jinx.Migrator.load_filter_files
|
def load_filter_files(files)
# collect the class => path => value entries from each defaults file
hash = {}
files.enumerate { |file| load_filter_file(file, hash) }
logger.debug { "The migrator loaded the filters #{hash.qp}." }
hash
end
|
ruby
|
def load_filter_files(files)
# collect the class => path => value entries from each defaults file
hash = {}
files.enumerate { |file| load_filter_file(file, hash) }
logger.debug { "The migrator loaded the filters #{hash.qp}." }
hash
end
|
[
"def",
"load_filter_files",
"(",
"files",
")",
"# collect the class => path => value entries from each defaults file",
"hash",
"=",
"{",
"}",
"files",
".",
"enumerate",
"{",
"|",
"file",
"|",
"load_filter_file",
"(",
"file",
",",
"hash",
")",
"}",
"logger",
".",
"debug",
"{",
"\"The migrator loaded the filters #{hash.qp}.\"",
"}",
"hash",
"end"
] |
Loads the filter config files.
@param [<String>, String] files the file or file array to load
@return [<Class => <String => Object>>] the class => path => default value entries
|
[
"Loads",
"the",
"filter",
"config",
"files",
"."
] |
309957a470d72da3bd074f8173dbbe2f12449883
|
https://github.com/jinx/migrate/blob/309957a470d72da3bd074f8173dbbe2f12449883/lib/jinx/migration/migrator.rb#L866-L872
|
7,355 |
jinx/migrate
|
lib/jinx/migration/migrator.rb
|
Jinx.Migrator.load_filter_file
|
def load_filter_file(file, hash)
# collect the class => attribute => filter entries
logger.debug { "Loading the migration filter configuration #{file}..." }
begin
config = YAML::load_file(file)
rescue
raise MigrationError.new("Could not read filter file #{file}: " + $!)
end
config.each do |path_s, flt|
next if flt.nil_or_empty?
klass, path = create_attribute_path(path_s)
if path.empty? then
raise MigrationError.new("Migration filter configuration path does not include a property: #{path_s}")
elsif path.size > 1 then
raise MigrationError.new("Migration filter configuration path with more than one property is not supported: #{path_s}")
end
pa = klass.standard_attribute(path.first.to_sym)
flt_hash = hash[klass] ||= {}
flt_hash[pa] = flt
end
end
|
ruby
|
def load_filter_file(file, hash)
# collect the class => attribute => filter entries
logger.debug { "Loading the migration filter configuration #{file}..." }
begin
config = YAML::load_file(file)
rescue
raise MigrationError.new("Could not read filter file #{file}: " + $!)
end
config.each do |path_s, flt|
next if flt.nil_or_empty?
klass, path = create_attribute_path(path_s)
if path.empty? then
raise MigrationError.new("Migration filter configuration path does not include a property: #{path_s}")
elsif path.size > 1 then
raise MigrationError.new("Migration filter configuration path with more than one property is not supported: #{path_s}")
end
pa = klass.standard_attribute(path.first.to_sym)
flt_hash = hash[klass] ||= {}
flt_hash[pa] = flt
end
end
|
[
"def",
"load_filter_file",
"(",
"file",
",",
"hash",
")",
"# collect the class => attribute => filter entries",
"logger",
".",
"debug",
"{",
"\"Loading the migration filter configuration #{file}...\"",
"}",
"begin",
"config",
"=",
"YAML",
"::",
"load_file",
"(",
"file",
")",
"rescue",
"raise",
"MigrationError",
".",
"new",
"(",
"\"Could not read filter file #{file}: \"",
"+",
"$!",
")",
"end",
"config",
".",
"each",
"do",
"|",
"path_s",
",",
"flt",
"|",
"next",
"if",
"flt",
".",
"nil_or_empty?",
"klass",
",",
"path",
"=",
"create_attribute_path",
"(",
"path_s",
")",
"if",
"path",
".",
"empty?",
"then",
"raise",
"MigrationError",
".",
"new",
"(",
"\"Migration filter configuration path does not include a property: #{path_s}\"",
")",
"elsif",
"path",
".",
"size",
">",
"1",
"then",
"raise",
"MigrationError",
".",
"new",
"(",
"\"Migration filter configuration path with more than one property is not supported: #{path_s}\"",
")",
"end",
"pa",
"=",
"klass",
".",
"standard_attribute",
"(",
"path",
".",
"first",
".",
"to_sym",
")",
"flt_hash",
"=",
"hash",
"[",
"klass",
"]",
"||=",
"{",
"}",
"flt_hash",
"[",
"pa",
"]",
"=",
"flt",
"end",
"end"
] |
Loads the filter config file into the given hash.
@param [String] file the file to load
@param [<Class => <String => <Object => Object>>>] hash the class => path => input value => caTissue value entries
|
[
"Loads",
"the",
"filter",
"config",
"file",
"into",
"the",
"given",
"hash",
"."
] |
309957a470d72da3bd074f8173dbbe2f12449883
|
https://github.com/jinx/migrate/blob/309957a470d72da3bd074f8173dbbe2f12449883/lib/jinx/migration/migrator.rb#L878-L898
|
7,356 |
mitukiii/cha
|
lib/cha/api.rb
|
Cha.API.create_room
|
def create_room(name, members_admin_ids, params = {})
members_admin_ids = array_to_string(members_admin_ids)
if value = params[:members_member_ids]
params[:members_member_ids] = array_to_string(value)
end
if value = params[:members_readonly_ids]
params[:members_readonly_ids] = array_to_string(value)
end
params = params.merge(name: name, members_admin_ids: members_admin_ids)
post('rooms', params)
end
|
ruby
|
def create_room(name, members_admin_ids, params = {})
members_admin_ids = array_to_string(members_admin_ids)
if value = params[:members_member_ids]
params[:members_member_ids] = array_to_string(value)
end
if value = params[:members_readonly_ids]
params[:members_readonly_ids] = array_to_string(value)
end
params = params.merge(name: name, members_admin_ids: members_admin_ids)
post('rooms', params)
end
|
[
"def",
"create_room",
"(",
"name",
",",
"members_admin_ids",
",",
"params",
"=",
"{",
"}",
")",
"members_admin_ids",
"=",
"array_to_string",
"(",
"members_admin_ids",
")",
"if",
"value",
"=",
"params",
"[",
":members_member_ids",
"]",
"params",
"[",
":members_member_ids",
"]",
"=",
"array_to_string",
"(",
"value",
")",
"end",
"if",
"value",
"=",
"params",
"[",
":members_readonly_ids",
"]",
"params",
"[",
":members_readonly_ids",
"]",
"=",
"array_to_string",
"(",
"value",
")",
"end",
"params",
"=",
"params",
".",
"merge",
"(",
"name",
":",
"name",
",",
"members_admin_ids",
":",
"members_admin_ids",
")",
"post",
"(",
"'rooms'",
",",
"params",
")",
"end"
] |
Create new chat room
@param name [String] Name of chat room
@param members_admin_ids [Array<Integer>]
Array of member ID that want to admin authority
@param params [Hash] Hash of optional parameter
@option params [String] :description (nil) Summary of chat room
@option params [Symbol] :icon_preset (nil) Kind of Icon of chat room
(group, check, document, meeting, event, project, business, study,
security, star, idea, heart, magcup, beer, music, sports, travel)
@option params [Array<Integer>] :members_member_ids (nil)
Array of member ID that want to member authority
@option params [Array<Integer>] :members_readonly_ids (nil)
Array of member ID that want to read only
@return [Hashie::Mash]
|
[
"Create",
"new",
"chat",
"room"
] |
1e4d708a95cbeab270c701f0c77d4546194c297d
|
https://github.com/mitukiii/cha/blob/1e4d708a95cbeab270c701f0c77d4546194c297d/lib/cha/api.rb#L60-L70
|
7,357 |
mitukiii/cha
|
lib/cha/api.rb
|
Cha.API.update_room_members
|
def update_room_members(room_id, members_admin_ids, params = {})
members_admin_ids = array_to_string(members_admin_ids)
if value = params[:members_member_ids]
params[:members_member_ids] = array_to_string(value)
end
if value = params[:members_readonly_ids]
params[:members_readonly_ids] = array_to_string(value)
end
params = params.merge(members_admin_ids: members_admin_ids)
put("rooms/#{room_id}/members", params)
end
|
ruby
|
def update_room_members(room_id, members_admin_ids, params = {})
members_admin_ids = array_to_string(members_admin_ids)
if value = params[:members_member_ids]
params[:members_member_ids] = array_to_string(value)
end
if value = params[:members_readonly_ids]
params[:members_readonly_ids] = array_to_string(value)
end
params = params.merge(members_admin_ids: members_admin_ids)
put("rooms/#{room_id}/members", params)
end
|
[
"def",
"update_room_members",
"(",
"room_id",
",",
"members_admin_ids",
",",
"params",
"=",
"{",
"}",
")",
"members_admin_ids",
"=",
"array_to_string",
"(",
"members_admin_ids",
")",
"if",
"value",
"=",
"params",
"[",
":members_member_ids",
"]",
"params",
"[",
":members_member_ids",
"]",
"=",
"array_to_string",
"(",
"value",
")",
"end",
"if",
"value",
"=",
"params",
"[",
":members_readonly_ids",
"]",
"params",
"[",
":members_readonly_ids",
"]",
"=",
"array_to_string",
"(",
"value",
")",
"end",
"params",
"=",
"params",
".",
"merge",
"(",
"members_admin_ids",
":",
"members_admin_ids",
")",
"put",
"(",
"\"rooms/#{room_id}/members\"",
",",
"params",
")",
"end"
] |
Update chat room members
@param room_id [Integer] ID of chat room
@param members_admin_ids [Array<Integer>]
Array of member ID that want to admin authority
@param params [Hash] Hash of optional parameter
@option params [Array<Integer>] :members_member_ids (nil)
Array of member ID that want to member authority
@option params [Array<Integer>] :members_readonly_ids (nil)
Array of member ID that want to read only
@return [Hahsie::Mash]
|
[
"Update",
"chat",
"room",
"members"
] |
1e4d708a95cbeab270c701f0c77d4546194c297d
|
https://github.com/mitukiii/cha/blob/1e4d708a95cbeab270c701f0c77d4546194c297d/lib/cha/api.rb#L122-L132
|
7,358 |
mitukiii/cha
|
lib/cha/api.rb
|
Cha.API.create_room_task
|
def create_room_task(room_id, body, to_ids, params = {})
to_ids = array_to_string(to_ids)
if value = params[:limit]
params[:limit] = time_to_integer(value)
end
post("rooms/#{room_id}/tasks", params.merge(body: body, to_ids: to_ids))
end
|
ruby
|
def create_room_task(room_id, body, to_ids, params = {})
to_ids = array_to_string(to_ids)
if value = params[:limit]
params[:limit] = time_to_integer(value)
end
post("rooms/#{room_id}/tasks", params.merge(body: body, to_ids: to_ids))
end
|
[
"def",
"create_room_task",
"(",
"room_id",
",",
"body",
",",
"to_ids",
",",
"params",
"=",
"{",
"}",
")",
"to_ids",
"=",
"array_to_string",
"(",
"to_ids",
")",
"if",
"value",
"=",
"params",
"[",
":limit",
"]",
"params",
"[",
":limit",
"]",
"=",
"time_to_integer",
"(",
"value",
")",
"end",
"post",
"(",
"\"rooms/#{room_id}/tasks\"",
",",
"params",
".",
"merge",
"(",
"body",
":",
"body",
",",
"to_ids",
":",
"to_ids",
")",
")",
"end"
] |
Create new task of chat room
@param room_id [Integer] ID of chat room
@param body [String] Contents of task
@param to_ids [Array<Integer>] Array of account ID of person in charge
@param params [Hash] Hash of optional parameter
@option params [Integer, Time] :limit (nil) Deadline of task (unix time)
@return [Hashie::Mash]
|
[
"Create",
"new",
"task",
"of",
"chat",
"room"
] |
1e4d708a95cbeab270c701f0c77d4546194c297d
|
https://github.com/mitukiii/cha/blob/1e4d708a95cbeab270c701f0c77d4546194c297d/lib/cha/api.rb#L186-L192
|
7,359 |
mitukiii/cha
|
lib/cha/api.rb
|
Cha.API.room_file
|
def room_file(room_id, file_id, params = {})
unless (value = params[:create_download_url]).nil?
params[:create_download_url] = boolean_to_integer(value)
end
get("rooms/#{room_id}/files/#{file_id}", params)
end
|
ruby
|
def room_file(room_id, file_id, params = {})
unless (value = params[:create_download_url]).nil?
params[:create_download_url] = boolean_to_integer(value)
end
get("rooms/#{room_id}/files/#{file_id}", params)
end
|
[
"def",
"room_file",
"(",
"room_id",
",",
"file_id",
",",
"params",
"=",
"{",
"}",
")",
"unless",
"(",
"value",
"=",
"params",
"[",
":create_download_url",
"]",
")",
".",
"nil?",
"params",
"[",
":create_download_url",
"]",
"=",
"boolean_to_integer",
"(",
"value",
")",
"end",
"get",
"(",
"\"rooms/#{room_id}/files/#{file_id}\"",
",",
"params",
")",
"end"
] |
Get file information
@param room_id [Integer] ID of chat room
@param file_id [Integer] ID of file
@param params [Hash] Hash of optional parameter
@option params [Boolean] :create_download_url (false)
Create URL for download
|
[
"Get",
"file",
"information"
] |
1e4d708a95cbeab270c701f0c77d4546194c297d
|
https://github.com/mitukiii/cha/blob/1e4d708a95cbeab270c701f0c77d4546194c297d/lib/cha/api.rb#L220-L225
|
7,360 |
knaveofdiamonds/uk_working_days
|
lib/uk_working_days/easter.rb
|
UkWorkingDays.Easter.easter
|
def easter(year)
golden_number = (year % 19) + 1
if year <= 1752 then
# Julian calendar
dominical_number = (year + (year / 4) + 5) % 7
paschal_full_moon = (3 - (11 * golden_number) - 7) % 30
else
# Gregorian calendar
dominical_number = (year + (year / 4) - (year / 100) + (year / 400)) % 7
solar_correction = (year - 1600) / 100 - (year - 1600) / 400
lunar_correction = (((year - 1400) / 100) * 8) / 25
paschal_full_moon = (3 - 11 * golden_number + solar_correction - lunar_correction) % 30
end
dominical_number += 7 until dominical_number > 0
paschal_full_moon += 30 until paschal_full_moon > 0
paschal_full_moon -= 1 if paschal_full_moon == 29 or (paschal_full_moon == 28 and golden_number > 11)
difference = (4 - paschal_full_moon - dominical_number) % 7
difference += 7 if difference < 0
day_easter = paschal_full_moon + difference + 1
day_easter < 11 ? new(year, 3, day_easter + 21) : new(year, 4, day_easter - 10)
end
|
ruby
|
def easter(year)
golden_number = (year % 19) + 1
if year <= 1752 then
# Julian calendar
dominical_number = (year + (year / 4) + 5) % 7
paschal_full_moon = (3 - (11 * golden_number) - 7) % 30
else
# Gregorian calendar
dominical_number = (year + (year / 4) - (year / 100) + (year / 400)) % 7
solar_correction = (year - 1600) / 100 - (year - 1600) / 400
lunar_correction = (((year - 1400) / 100) * 8) / 25
paschal_full_moon = (3 - 11 * golden_number + solar_correction - lunar_correction) % 30
end
dominical_number += 7 until dominical_number > 0
paschal_full_moon += 30 until paschal_full_moon > 0
paschal_full_moon -= 1 if paschal_full_moon == 29 or (paschal_full_moon == 28 and golden_number > 11)
difference = (4 - paschal_full_moon - dominical_number) % 7
difference += 7 if difference < 0
day_easter = paschal_full_moon + difference + 1
day_easter < 11 ? new(year, 3, day_easter + 21) : new(year, 4, day_easter - 10)
end
|
[
"def",
"easter",
"(",
"year",
")",
"golden_number",
"=",
"(",
"year",
"%",
"19",
")",
"+",
"1",
"if",
"year",
"<=",
"1752",
"then",
"# Julian calendar",
"dominical_number",
"=",
"(",
"year",
"+",
"(",
"year",
"/",
"4",
")",
"+",
"5",
")",
"%",
"7",
"paschal_full_moon",
"=",
"(",
"3",
"-",
"(",
"11",
"*",
"golden_number",
")",
"-",
"7",
")",
"%",
"30",
"else",
"# Gregorian calendar",
"dominical_number",
"=",
"(",
"year",
"+",
"(",
"year",
"/",
"4",
")",
"-",
"(",
"year",
"/",
"100",
")",
"+",
"(",
"year",
"/",
"400",
")",
")",
"%",
"7",
"solar_correction",
"=",
"(",
"year",
"-",
"1600",
")",
"/",
"100",
"-",
"(",
"year",
"-",
"1600",
")",
"/",
"400",
"lunar_correction",
"=",
"(",
"(",
"(",
"year",
"-",
"1400",
")",
"/",
"100",
")",
"*",
"8",
")",
"/",
"25",
"paschal_full_moon",
"=",
"(",
"3",
"-",
"11",
"*",
"golden_number",
"+",
"solar_correction",
"-",
"lunar_correction",
")",
"%",
"30",
"end",
"dominical_number",
"+=",
"7",
"until",
"dominical_number",
">",
"0",
"paschal_full_moon",
"+=",
"30",
"until",
"paschal_full_moon",
">",
"0",
"paschal_full_moon",
"-=",
"1",
"if",
"paschal_full_moon",
"==",
"29",
"or",
"(",
"paschal_full_moon",
"==",
"28",
"and",
"golden_number",
">",
"11",
")",
"difference",
"=",
"(",
"4",
"-",
"paschal_full_moon",
"-",
"dominical_number",
")",
"%",
"7",
"difference",
"+=",
"7",
"if",
"difference",
"<",
"0",
"day_easter",
"=",
"paschal_full_moon",
"+",
"difference",
"+",
"1",
"day_easter",
"<",
"11",
"?",
"new",
"(",
"year",
",",
"3",
",",
"day_easter",
"+",
"21",
")",
":",
"new",
"(",
"year",
",",
"4",
",",
"day_easter",
"-",
"10",
")",
"end"
] |
Calculate easter sunday for the given year
|
[
"Calculate",
"easter",
"sunday",
"for",
"the",
"given",
"year"
] |
cd97bec608019418a877ee2b348871b701e0751b
|
https://github.com/knaveofdiamonds/uk_working_days/blob/cd97bec608019418a877ee2b348871b701e0751b/lib/uk_working_days/easter.rb#L15-L41
|
7,361 |
starrhorne/konfig
|
lib/konfig/evaluator.rb
|
Konfig.Evaluator.names_by_value
|
def names_by_value(a)
a = @data[a] if a.is_a?(String) || a.is_a?(Symbol)
Hash[ a.map { |i| i.reverse } ]
end
|
ruby
|
def names_by_value(a)
a = @data[a] if a.is_a?(String) || a.is_a?(Symbol)
Hash[ a.map { |i| i.reverse } ]
end
|
[
"def",
"names_by_value",
"(",
"a",
")",
"a",
"=",
"@data",
"[",
"a",
"]",
"if",
"a",
".",
"is_a?",
"(",
"String",
")",
"||",
"a",
".",
"is_a?",
"(",
"Symbol",
")",
"Hash",
"[",
"a",
".",
"map",
"{",
"|",
"i",
"|",
"i",
".",
"reverse",
"}",
"]",
"end"
] |
Converts an options-style nested array into a hash
for easy name lookup
@param [Array] a an array like [['name', 'val']]
@return [Hash] a hash like { val => name }
|
[
"Converts",
"an",
"options",
"-",
"style",
"nested",
"array",
"into",
"a",
"hash",
"for",
"easy",
"name",
"lookup"
] |
5d655945586a489868bb868243d9c0da18c90228
|
https://github.com/starrhorne/konfig/blob/5d655945586a489868bb868243d9c0da18c90228/lib/konfig/evaluator.rb#L26-L29
|
7,362 |
rndstr/halffare
|
lib/halffare/stats.rb
|
Halffare.Stats.read
|
def read(filename, months=nil)
@orders = []
start = months ? (Date.today << months.to_i).strftime('%Y-%m-%d') : nil
file = File.open(filename, "r:UTF-8") do |f|
while line = f.gets
order = Halffare::Model::Order.new(line)
if (start.nil? || line[0,10] >= start) && (order.note != Fetch::ORDER_NOTE_FILE_CREATED)
@orders.push(order)
end
end
end
log_info "read #{@orders.length} orders from #{filename}"
if @orders.length == 0
if start.nil?
log_notice "no orders found"
else
log_notice "no orders found after #{start}, maybe tweak the --months param"
end
end
end
|
ruby
|
def read(filename, months=nil)
@orders = []
start = months ? (Date.today << months.to_i).strftime('%Y-%m-%d') : nil
file = File.open(filename, "r:UTF-8") do |f|
while line = f.gets
order = Halffare::Model::Order.new(line)
if (start.nil? || line[0,10] >= start) && (order.note != Fetch::ORDER_NOTE_FILE_CREATED)
@orders.push(order)
end
end
end
log_info "read #{@orders.length} orders from #{filename}"
if @orders.length == 0
if start.nil?
log_notice "no orders found"
else
log_notice "no orders found after #{start}, maybe tweak the --months param"
end
end
end
|
[
"def",
"read",
"(",
"filename",
",",
"months",
"=",
"nil",
")",
"@orders",
"=",
"[",
"]",
"start",
"=",
"months",
"?",
"(",
"Date",
".",
"today",
"<<",
"months",
".",
"to_i",
")",
".",
"strftime",
"(",
"'%Y-%m-%d'",
")",
":",
"nil",
"file",
"=",
"File",
".",
"open",
"(",
"filename",
",",
"\"r:UTF-8\"",
")",
"do",
"|",
"f",
"|",
"while",
"line",
"=",
"f",
".",
"gets",
"order",
"=",
"Halffare",
"::",
"Model",
"::",
"Order",
".",
"new",
"(",
"line",
")",
"if",
"(",
"start",
".",
"nil?",
"||",
"line",
"[",
"0",
",",
"10",
"]",
">=",
"start",
")",
"&&",
"(",
"order",
".",
"note",
"!=",
"Fetch",
"::",
"ORDER_NOTE_FILE_CREATED",
")",
"@orders",
".",
"push",
"(",
"order",
")",
"end",
"end",
"end",
"log_info",
"\"read #{@orders.length} orders from #{filename}\"",
"if",
"@orders",
".",
"length",
"==",
"0",
"if",
"start",
".",
"nil?",
"log_notice",
"\"no orders found\"",
"else",
"log_notice",
"\"no orders found after #{start}, maybe tweak the --months param\"",
"end",
"end",
"end"
] |
Reads orders from `filename` that date back to max `months` months.
@param filename [String] The filename to read from
@param months [Integer, nil] Number of months look back or nil for all
|
[
"Reads",
"orders",
"from",
"filename",
"that",
"date",
"back",
"to",
"max",
"months",
"months",
"."
] |
2c4c7563a9e0834e5d2d93c15bd052bb67f8996a
|
https://github.com/rndstr/halffare/blob/2c4c7563a9e0834e5d2d93c15bd052bb67f8996a/lib/halffare/stats.rb#L8-L27
|
7,363 |
rndstr/halffare
|
lib/halffare/stats.rb
|
Halffare.Stats.calculate
|
def calculate(strategy, halffare)
@halfprice = 0
@fullprice = 0
if halffare
log_info "assuming order prices as half-fare"
else
log_info "assuming order prices as full"
end
log_notice "please note that you are using a strategy that involves guessing the real price" if ['guess', 'sbbguess'].include? strategy
strategy = price_factory(strategy)
strategy.halffare = halffare
log_info "using price strategy: #{strategy.class}"
price = Price.new(strategy)
log_info "calculating prices..."
@date_min = false
@date_max = false
@orders.each do |order|
if Halffare.debug
log_order(order)
end
halfprice, fullprice = price.get(order)
if Halffare.debug
if halfprice != 0 && fullprice != 0
log_result "FOUND: #{order.description} (#{order.price}): half=#{currency(halfprice)}, full=#{currency(fullprice)}"
if halffare
log_emphasize "You would pay (full price): #{currency(fullprice)}, you save #{currency(fullprice - order.price)}"
else
log_emphasize "You would pay (half-fare): #{currency(halfprice)}, you pay #{currency(order.price - halfprice)} more"
end
end
end
@halfprice += halfprice
@fullprice += fullprice
@date_min = order.travel_date if !@date_min || order.travel_date < @date_min
@date_max = order.travel_date if !@date_max || order.travel_date > @date_max
end
end
|
ruby
|
def calculate(strategy, halffare)
@halfprice = 0
@fullprice = 0
if halffare
log_info "assuming order prices as half-fare"
else
log_info "assuming order prices as full"
end
log_notice "please note that you are using a strategy that involves guessing the real price" if ['guess', 'sbbguess'].include? strategy
strategy = price_factory(strategy)
strategy.halffare = halffare
log_info "using price strategy: #{strategy.class}"
price = Price.new(strategy)
log_info "calculating prices..."
@date_min = false
@date_max = false
@orders.each do |order|
if Halffare.debug
log_order(order)
end
halfprice, fullprice = price.get(order)
if Halffare.debug
if halfprice != 0 && fullprice != 0
log_result "FOUND: #{order.description} (#{order.price}): half=#{currency(halfprice)}, full=#{currency(fullprice)}"
if halffare
log_emphasize "You would pay (full price): #{currency(fullprice)}, you save #{currency(fullprice - order.price)}"
else
log_emphasize "You would pay (half-fare): #{currency(halfprice)}, you pay #{currency(order.price - halfprice)} more"
end
end
end
@halfprice += halfprice
@fullprice += fullprice
@date_min = order.travel_date if !@date_min || order.travel_date < @date_min
@date_max = order.travel_date if !@date_max || order.travel_date > @date_max
end
end
|
[
"def",
"calculate",
"(",
"strategy",
",",
"halffare",
")",
"@halfprice",
"=",
"0",
"@fullprice",
"=",
"0",
"if",
"halffare",
"log_info",
"\"assuming order prices as half-fare\"",
"else",
"log_info",
"\"assuming order prices as full\"",
"end",
"log_notice",
"\"please note that you are using a strategy that involves guessing the real price\"",
"if",
"[",
"'guess'",
",",
"'sbbguess'",
"]",
".",
"include?",
"strategy",
"strategy",
"=",
"price_factory",
"(",
"strategy",
")",
"strategy",
".",
"halffare",
"=",
"halffare",
"log_info",
"\"using price strategy: #{strategy.class}\"",
"price",
"=",
"Price",
".",
"new",
"(",
"strategy",
")",
"log_info",
"\"calculating prices...\"",
"@date_min",
"=",
"false",
"@date_max",
"=",
"false",
"@orders",
".",
"each",
"do",
"|",
"order",
"|",
"if",
"Halffare",
".",
"debug",
"log_order",
"(",
"order",
")",
"end",
"halfprice",
",",
"fullprice",
"=",
"price",
".",
"get",
"(",
"order",
")",
"if",
"Halffare",
".",
"debug",
"if",
"halfprice",
"!=",
"0",
"&&",
"fullprice",
"!=",
"0",
"log_result",
"\"FOUND: #{order.description} (#{order.price}): half=#{currency(halfprice)}, full=#{currency(fullprice)}\"",
"if",
"halffare",
"log_emphasize",
"\"You would pay (full price): #{currency(fullprice)}, you save #{currency(fullprice - order.price)}\"",
"else",
"log_emphasize",
"\"You would pay (half-fare): #{currency(halfprice)}, you pay #{currency(order.price - halfprice)} more\"",
"end",
"end",
"end",
"@halfprice",
"+=",
"halfprice",
"@fullprice",
"+=",
"fullprice",
"@date_min",
"=",
"order",
".",
"travel_date",
"if",
"!",
"@date_min",
"||",
"order",
".",
"travel_date",
"<",
"@date_min",
"@date_max",
"=",
"order",
".",
"travel_date",
"if",
"!",
"@date_max",
"||",
"order",
".",
"travel_date",
">",
"@date_max",
"end",
"end"
] |
Calculates prices according to given strategy.
@param strategy [String] Strategy name
@param halffare [true, false] True if tickets were bought with a halffare card
|
[
"Calculates",
"prices",
"according",
"to",
"given",
"strategy",
"."
] |
2c4c7563a9e0834e5d2d93c15bd052bb67f8996a
|
https://github.com/rndstr/halffare/blob/2c4c7563a9e0834e5d2d93c15bd052bb67f8996a/lib/halffare/stats.rb#L38-L84
|
7,364 |
barkerest/shells
|
lib/shells/shell_base/output.rb
|
Shells.ShellBase.buffer_output
|
def buffer_output(&block) #:doc:
raise Shells::NotRunning unless running?
block ||= Proc.new { }
stdout_received do |data|
self.last_output = Time.now
append_stdout strip_ansi_escape(data), &block
end
stderr_received do |data|
self.last_output = Time.now
append_stderr strip_ansi_escape(data), &block
end
end
|
ruby
|
def buffer_output(&block) #:doc:
raise Shells::NotRunning unless running?
block ||= Proc.new { }
stdout_received do |data|
self.last_output = Time.now
append_stdout strip_ansi_escape(data), &block
end
stderr_received do |data|
self.last_output = Time.now
append_stderr strip_ansi_escape(data), &block
end
end
|
[
"def",
"buffer_output",
"(",
"&",
"block",
")",
"#:doc:\r",
"raise",
"Shells",
"::",
"NotRunning",
"unless",
"running?",
"block",
"||=",
"Proc",
".",
"new",
"{",
"}",
"stdout_received",
"do",
"|",
"data",
"|",
"self",
".",
"last_output",
"=",
"Time",
".",
"now",
"append_stdout",
"strip_ansi_escape",
"(",
"data",
")",
",",
"block",
"end",
"stderr_received",
"do",
"|",
"data",
"|",
"self",
".",
"last_output",
"=",
"Time",
".",
"now",
"append_stderr",
"strip_ansi_escape",
"(",
"data",
")",
",",
"block",
"end",
"end"
] |
Sets the block to call when data is received.
If no block is provided, then the shell will simply log all output from the program.
If a block is provided, it will be passed the data as it is received. If the block
returns a string, then that string will be sent to the shell.
This method is called internally in the +exec+ method, but there may be legitimate use
cases outside of that method as well.
|
[
"Sets",
"the",
"block",
"to",
"call",
"when",
"data",
"is",
"received",
"."
] |
674a0254f48cea01b0ae8979933f13892e398506
|
https://github.com/barkerest/shells/blob/674a0254f48cea01b0ae8979933f13892e398506/lib/shells/shell_base/output.rb#L122-L133
|
7,365 |
barkerest/shells
|
lib/shells/shell_base/output.rb
|
Shells.ShellBase.push_buffer
|
def push_buffer
raise Shells::NotRunning unless running?
# push the buffer so we can get the output of a command.
debug 'Pushing buffer >>'
sync do
output_stack.push [ stdout, stderr, output ]
self.stdout = ''
self.stderr = ''
self.output = ''
end
end
|
ruby
|
def push_buffer
raise Shells::NotRunning unless running?
# push the buffer so we can get the output of a command.
debug 'Pushing buffer >>'
sync do
output_stack.push [ stdout, stderr, output ]
self.stdout = ''
self.stderr = ''
self.output = ''
end
end
|
[
"def",
"push_buffer",
"raise",
"Shells",
"::",
"NotRunning",
"unless",
"running?",
"# push the buffer so we can get the output of a command.\r",
"debug",
"'Pushing buffer >>'",
"sync",
"do",
"output_stack",
".",
"push",
"[",
"stdout",
",",
"stderr",
",",
"output",
"]",
"self",
".",
"stdout",
"=",
"''",
"self",
".",
"stderr",
"=",
"''",
"self",
".",
"output",
"=",
"''",
"end",
"end"
] |
Pushes the buffers for output capture.
This method is called internally in the +exec+ method, but there may be legitimate use
cases outside of that method as well.
|
[
"Pushes",
"the",
"buffers",
"for",
"output",
"capture",
"."
] |
674a0254f48cea01b0ae8979933f13892e398506
|
https://github.com/barkerest/shells/blob/674a0254f48cea01b0ae8979933f13892e398506/lib/shells/shell_base/output.rb#L164-L174
|
7,366 |
barkerest/shells
|
lib/shells/shell_base/output.rb
|
Shells.ShellBase.pop_merge_buffer
|
def pop_merge_buffer
raise Shells::NotRunning unless running?
# almost a standard pop, however we want to merge history with current.
debug 'Merging buffer <<'
sync do
hist_stdout, hist_stderr, hist_output = (output_stack.pop || [])
if hist_stdout
self.stdout = hist_stdout + stdout
end
if hist_stderr
self.stderr = hist_stderr + stderr
end
if hist_output
self.output = hist_output + output
end
end
end
|
ruby
|
def pop_merge_buffer
raise Shells::NotRunning unless running?
# almost a standard pop, however we want to merge history with current.
debug 'Merging buffer <<'
sync do
hist_stdout, hist_stderr, hist_output = (output_stack.pop || [])
if hist_stdout
self.stdout = hist_stdout + stdout
end
if hist_stderr
self.stderr = hist_stderr + stderr
end
if hist_output
self.output = hist_output + output
end
end
end
|
[
"def",
"pop_merge_buffer",
"raise",
"Shells",
"::",
"NotRunning",
"unless",
"running?",
"# almost a standard pop, however we want to merge history with current.\r",
"debug",
"'Merging buffer <<'",
"sync",
"do",
"hist_stdout",
",",
"hist_stderr",
",",
"hist_output",
"=",
"(",
"output_stack",
".",
"pop",
"||",
"[",
"]",
")",
"if",
"hist_stdout",
"self",
".",
"stdout",
"=",
"hist_stdout",
"+",
"stdout",
"end",
"if",
"hist_stderr",
"self",
".",
"stderr",
"=",
"hist_stderr",
"+",
"stderr",
"end",
"if",
"hist_output",
"self",
".",
"output",
"=",
"hist_output",
"+",
"output",
"end",
"end",
"end"
] |
Pops the buffers and merges the captured output.
This method is called internally in the +exec+ method, but there may be legitimate use
cases outside of that method as well.
|
[
"Pops",
"the",
"buffers",
"and",
"merges",
"the",
"captured",
"output",
"."
] |
674a0254f48cea01b0ae8979933f13892e398506
|
https://github.com/barkerest/shells/blob/674a0254f48cea01b0ae8979933f13892e398506/lib/shells/shell_base/output.rb#L181-L197
|
7,367 |
barkerest/shells
|
lib/shells/shell_base/output.rb
|
Shells.ShellBase.pop_discard_buffer
|
def pop_discard_buffer
raise Shells::NotRunning unless running?
# a standard pop discarding current data and retrieving the history.
debug 'Discarding buffer <<'
sync do
hist_stdout, hist_stderr, hist_output = (output_stack.pop || [])
self.stdout = hist_stdout || ''
self.stderr = hist_stderr || ''
self.output = hist_output || ''
end
end
|
ruby
|
def pop_discard_buffer
raise Shells::NotRunning unless running?
# a standard pop discarding current data and retrieving the history.
debug 'Discarding buffer <<'
sync do
hist_stdout, hist_stderr, hist_output = (output_stack.pop || [])
self.stdout = hist_stdout || ''
self.stderr = hist_stderr || ''
self.output = hist_output || ''
end
end
|
[
"def",
"pop_discard_buffer",
"raise",
"Shells",
"::",
"NotRunning",
"unless",
"running?",
"# a standard pop discarding current data and retrieving the history.\r",
"debug",
"'Discarding buffer <<'",
"sync",
"do",
"hist_stdout",
",",
"hist_stderr",
",",
"hist_output",
"=",
"(",
"output_stack",
".",
"pop",
"||",
"[",
"]",
")",
"self",
".",
"stdout",
"=",
"hist_stdout",
"||",
"''",
"self",
".",
"stderr",
"=",
"hist_stderr",
"||",
"''",
"self",
".",
"output",
"=",
"hist_output",
"||",
"''",
"end",
"end"
] |
Pops the buffers and discards the captured output.
This method is used internally in the +get_exit_code+ method, but there may be legitimate use
cases outside of that method as well.
|
[
"Pops",
"the",
"buffers",
"and",
"discards",
"the",
"captured",
"output",
"."
] |
674a0254f48cea01b0ae8979933f13892e398506
|
https://github.com/barkerest/shells/blob/674a0254f48cea01b0ae8979933f13892e398506/lib/shells/shell_base/output.rb#L204-L214
|
7,368 |
devnull-tools/yummi
|
lib/yummi.rb
|
Yummi.BlockHandler.block_call
|
def block_call (context, &block)
args = []
block.parameters.each do |parameter|
args << context[parameter[1]]
end
block.call(*args)
end
|
ruby
|
def block_call (context, &block)
args = []
block.parameters.each do |parameter|
args << context[parameter[1]]
end
block.call(*args)
end
|
[
"def",
"block_call",
"(",
"context",
",",
"&",
"block",
")",
"args",
"=",
"[",
"]",
"block",
".",
"parameters",
".",
"each",
"do",
"|",
"parameter",
"|",
"args",
"<<",
"context",
"[",
"parameter",
"[",
"1",
"]",
"]",
"end",
"block",
".",
"call",
"(",
"args",
")",
"end"
] |
Calls the block resolving the parameters by getting the parameter name from the
given context.
=== Example
context = :max => 10, :curr => 5, ratio => 0.15
percentage = BlockHandler.call_block(context) { |max,curr| curr.to_f / max }
|
[
"Calls",
"the",
"block",
"resolving",
"the",
"parameters",
"by",
"getting",
"the",
"parameter",
"name",
"from",
"the",
"given",
"context",
"."
] |
b31cc1ef9a9f4ca1c22e0b77a84a1995bde5c2df
|
https://github.com/devnull-tools/yummi/blob/b31cc1ef9a9f4ca1c22e0b77a84a1995bde5c2df/lib/yummi.rb#L157-L163
|
7,369 |
devnull-tools/yummi
|
lib/yummi.rb
|
Yummi.GroupedComponent.call
|
def call (*args)
result = nil
@components.each do |component|
break if result and not @call_all
result = component.send @message, *args
end
result
end
|
ruby
|
def call (*args)
result = nil
@components.each do |component|
break if result and not @call_all
result = component.send @message, *args
end
result
end
|
[
"def",
"call",
"(",
"*",
"args",
")",
"result",
"=",
"nil",
"@components",
".",
"each",
"do",
"|",
"component",
"|",
"break",
"if",
"result",
"and",
"not",
"@call_all",
"result",
"=",
"component",
".",
"send",
"@message",
",",
"args",
"end",
"result",
"end"
] |
Calls the added components by sending the configured message and the given args.
|
[
"Calls",
"the",
"added",
"components",
"by",
"sending",
"the",
"configured",
"message",
"and",
"the",
"given",
"args",
"."
] |
b31cc1ef9a9f4ca1c22e0b77a84a1995bde5c2df
|
https://github.com/devnull-tools/yummi/blob/b31cc1ef9a9f4ca1c22e0b77a84a1995bde5c2df/lib/yummi.rb#L229-L236
|
7,370 |
GemHQ/coin-op
|
lib/coin-op/bit/input.rb
|
CoinOp::Bit.Input.script_sig=
|
def script_sig=(blob)
# This is only a setter because of the initial choice to do things
# eagerly. Can become an attr_accessor when we move to lazy eval.
script = Script.new(:blob => blob)
@script_sig = script.to_s
@native.script_sig = blob
end
|
ruby
|
def script_sig=(blob)
# This is only a setter because of the initial choice to do things
# eagerly. Can become an attr_accessor when we move to lazy eval.
script = Script.new(:blob => blob)
@script_sig = script.to_s
@native.script_sig = blob
end
|
[
"def",
"script_sig",
"=",
"(",
"blob",
")",
"# This is only a setter because of the initial choice to do things",
"# eagerly. Can become an attr_accessor when we move to lazy eval.",
"script",
"=",
"Script",
".",
"new",
"(",
":blob",
"=>",
"blob",
")",
"@script_sig",
"=",
"script",
".",
"to_s",
"@native",
".",
"script_sig",
"=",
"blob",
"end"
] |
Set the scriptSig for this input using a string of bytes.
|
[
"Set",
"the",
"scriptSig",
"for",
"this",
"input",
"using",
"a",
"string",
"of",
"bytes",
"."
] |
0b704b52d9826405cffb1606e914bf21b8dcc681
|
https://github.com/GemHQ/coin-op/blob/0b704b52d9826405cffb1606e914bf21b8dcc681/lib/coin-op/bit/input.rb#L61-L67
|
7,371 |
epuber-io/bade
|
lib/bade/parser.rb
|
Bade.Parser.append_node
|
def append_node(type, indent: @indents.length, add: false, value: nil)
# add necessary stack items to match required indent
@stacks << @stacks.last.dup while indent >= @stacks.length
parent = @stacks[indent].last
node = AST::NodeRegistrator.create(type, @lineno)
parent.children << node
node.value = value unless value.nil?
@stacks[indent] << node if add
node
end
|
ruby
|
def append_node(type, indent: @indents.length, add: false, value: nil)
# add necessary stack items to match required indent
@stacks << @stacks.last.dup while indent >= @stacks.length
parent = @stacks[indent].last
node = AST::NodeRegistrator.create(type, @lineno)
parent.children << node
node.value = value unless value.nil?
@stacks[indent] << node if add
node
end
|
[
"def",
"append_node",
"(",
"type",
",",
"indent",
":",
"@indents",
".",
"length",
",",
"add",
":",
"false",
",",
"value",
":",
"nil",
")",
"# add necessary stack items to match required indent",
"@stacks",
"<<",
"@stacks",
".",
"last",
".",
"dup",
"while",
"indent",
">=",
"@stacks",
".",
"length",
"parent",
"=",
"@stacks",
"[",
"indent",
"]",
".",
"last",
"node",
"=",
"AST",
"::",
"NodeRegistrator",
".",
"create",
"(",
"type",
",",
"@lineno",
")",
"parent",
".",
"children",
"<<",
"node",
"node",
".",
"value",
"=",
"value",
"unless",
"value",
".",
"nil?",
"@stacks",
"[",
"indent",
"]",
"<<",
"node",
"if",
"add",
"node",
"end"
] |
Append element to stacks and result tree
@param [Symbol] type
|
[
"Append",
"element",
"to",
"stacks",
"and",
"result",
"tree"
] |
fe128e0178d28b5a789d94b861ac6c6d2e4a3a8e
|
https://github.com/epuber-io/bade/blob/fe128e0178d28b5a789d94b861ac6c6d2e4a3a8e/lib/bade/parser.rb#L104-L117
|
7,372 |
JoshMcKin/hot_tub
|
lib/hot_tub/known_clients.rb
|
HotTub.KnownClients.clean_client
|
def clean_client(clnt)
if @clean_client
begin
perform_action(clnt,@clean_client)
rescue => e
HotTub.logger.error "[HotTub] There was an error cleaning one of your #{self.class.name} clients: #{e}" if HotTub.logger
end
end
clnt
end
|
ruby
|
def clean_client(clnt)
if @clean_client
begin
perform_action(clnt,@clean_client)
rescue => e
HotTub.logger.error "[HotTub] There was an error cleaning one of your #{self.class.name} clients: #{e}" if HotTub.logger
end
end
clnt
end
|
[
"def",
"clean_client",
"(",
"clnt",
")",
"if",
"@clean_client",
"begin",
"perform_action",
"(",
"clnt",
",",
"@clean_client",
")",
"rescue",
"=>",
"e",
"HotTub",
".",
"logger",
".",
"error",
"\"[HotTub] There was an error cleaning one of your #{self.class.name} clients: #{e}\"",
"if",
"HotTub",
".",
"logger",
"end",
"end",
"clnt",
"end"
] |
Attempts to clean the provided client, checking the options first for a clean block
then checking the known clients
|
[
"Attempts",
"to",
"clean",
"the",
"provided",
"client",
"checking",
"the",
"options",
"first",
"for",
"a",
"clean",
"block",
"then",
"checking",
"the",
"known",
"clients"
] |
44f22b0dfbca40bfe7cc4f7e6393122c88d7da0d
|
https://github.com/JoshMcKin/hot_tub/blob/44f22b0dfbca40bfe7cc4f7e6393122c88d7da0d/lib/hot_tub/known_clients.rb#L20-L29
|
7,373 |
JoshMcKin/hot_tub
|
lib/hot_tub/known_clients.rb
|
HotTub.KnownClients.close_client
|
def close_client(clnt)
@close_client = (known_client_action(clnt,:close) || false) if @close_client.nil?
if @close_client
begin
perform_action(clnt,@close_client)
rescue => e
HotTub.logger.error "[HotTub] There was an error closing one of your #{self.class.name} clients: #{e}" if HotTub.logger
end
end
nil
end
|
ruby
|
def close_client(clnt)
@close_client = (known_client_action(clnt,:close) || false) if @close_client.nil?
if @close_client
begin
perform_action(clnt,@close_client)
rescue => e
HotTub.logger.error "[HotTub] There was an error closing one of your #{self.class.name} clients: #{e}" if HotTub.logger
end
end
nil
end
|
[
"def",
"close_client",
"(",
"clnt",
")",
"@close_client",
"=",
"(",
"known_client_action",
"(",
"clnt",
",",
":close",
")",
"||",
"false",
")",
"if",
"@close_client",
".",
"nil?",
"if",
"@close_client",
"begin",
"perform_action",
"(",
"clnt",
",",
"@close_client",
")",
"rescue",
"=>",
"e",
"HotTub",
".",
"logger",
".",
"error",
"\"[HotTub] There was an error closing one of your #{self.class.name} clients: #{e}\"",
"if",
"HotTub",
".",
"logger",
"end",
"end",
"nil",
"end"
] |
Attempts to close the provided client, checking the options first for a close block
then checking the known clients
|
[
"Attempts",
"to",
"close",
"the",
"provided",
"client",
"checking",
"the",
"options",
"first",
"for",
"a",
"close",
"block",
"then",
"checking",
"the",
"known",
"clients"
] |
44f22b0dfbca40bfe7cc4f7e6393122c88d7da0d
|
https://github.com/JoshMcKin/hot_tub/blob/44f22b0dfbca40bfe7cc4f7e6393122c88d7da0d/lib/hot_tub/known_clients.rb#L33-L43
|
7,374 |
JoshMcKin/hot_tub
|
lib/hot_tub/known_clients.rb
|
HotTub.KnownClients.reap_client?
|
def reap_client?(clnt)
rc = false
if @reap_client
begin
rc = perform_action(clnt,@reap_client)
rescue => e
HotTub.logger.error "[HotTub] There was an error reaping one of your #{self.class.name} clients: #{e}" if HotTub.logger
end
end
rc
end
|
ruby
|
def reap_client?(clnt)
rc = false
if @reap_client
begin
rc = perform_action(clnt,@reap_client)
rescue => e
HotTub.logger.error "[HotTub] There was an error reaping one of your #{self.class.name} clients: #{e}" if HotTub.logger
end
end
rc
end
|
[
"def",
"reap_client?",
"(",
"clnt",
")",
"rc",
"=",
"false",
"if",
"@reap_client",
"begin",
"rc",
"=",
"perform_action",
"(",
"clnt",
",",
"@reap_client",
")",
"rescue",
"=>",
"e",
"HotTub",
".",
"logger",
".",
"error",
"\"[HotTub] There was an error reaping one of your #{self.class.name} clients: #{e}\"",
"if",
"HotTub",
".",
"logger",
"end",
"end",
"rc",
"end"
] |
Attempts to determine if a client should be reaped, block should return a boolean
|
[
"Attempts",
"to",
"determine",
"if",
"a",
"client",
"should",
"be",
"reaped",
"block",
"should",
"return",
"a",
"boolean"
] |
44f22b0dfbca40bfe7cc4f7e6393122c88d7da0d
|
https://github.com/JoshMcKin/hot_tub/blob/44f22b0dfbca40bfe7cc4f7e6393122c88d7da0d/lib/hot_tub/known_clients.rb#L46-L56
|
7,375 |
codescrum/bebox
|
lib/bebox/commands/commands_helper.rb
|
Bebox.CommandsHelper.get_environment
|
def get_environment(options)
environment = options[:environment]
# Ask for environment of node if flag environment not set
environment ||= choose_option(Environment.list(project_root), _('cli.choose_environment'))
# Check environment existence
Bebox::Environment.environment_exists?(project_root, environment) ? (return environment) : exit_now!(error(_('cli.not_exist_environment')%{environment: environment}))
end
|
ruby
|
def get_environment(options)
environment = options[:environment]
# Ask for environment of node if flag environment not set
environment ||= choose_option(Environment.list(project_root), _('cli.choose_environment'))
# Check environment existence
Bebox::Environment.environment_exists?(project_root, environment) ? (return environment) : exit_now!(error(_('cli.not_exist_environment')%{environment: environment}))
end
|
[
"def",
"get_environment",
"(",
"options",
")",
"environment",
"=",
"options",
"[",
":environment",
"]",
"# Ask for environment of node if flag environment not set",
"environment",
"||=",
"choose_option",
"(",
"Environment",
".",
"list",
"(",
"project_root",
")",
",",
"_",
"(",
"'cli.choose_environment'",
")",
")",
"# Check environment existence",
"Bebox",
"::",
"Environment",
".",
"environment_exists?",
"(",
"project_root",
",",
"environment",
")",
"?",
"(",
"return",
"environment",
")",
":",
"exit_now!",
"(",
"error",
"(",
"_",
"(",
"'cli.not_exist_environment'",
")",
"%",
"{",
"environment",
":",
"environment",
"}",
")",
")",
"end"
] |
Obtain the environment from command parameters or menu
|
[
"Obtain",
"the",
"environment",
"from",
"command",
"parameters",
"or",
"menu"
] |
0d19315847103341e599d32837ab0bd75524e5be
|
https://github.com/codescrum/bebox/blob/0d19315847103341e599d32837ab0bd75524e5be/lib/bebox/commands/commands_helper.rb#L8-L14
|
7,376 |
codescrum/bebox
|
lib/bebox/commands/commands_helper.rb
|
Bebox.CommandsHelper.default_environment
|
def default_environment
environments = Bebox::Environment.list(project_root)
if environments.count > 0
return environments.include?('vagrant') ? 'vagrant' : environments.first
else
return ''
end
end
|
ruby
|
def default_environment
environments = Bebox::Environment.list(project_root)
if environments.count > 0
return environments.include?('vagrant') ? 'vagrant' : environments.first
else
return ''
end
end
|
[
"def",
"default_environment",
"environments",
"=",
"Bebox",
"::",
"Environment",
".",
"list",
"(",
"project_root",
")",
"if",
"environments",
".",
"count",
">",
"0",
"return",
"environments",
".",
"include?",
"(",
"'vagrant'",
")",
"?",
"'vagrant'",
":",
"environments",
".",
"first",
"else",
"return",
"''",
"end",
"end"
] |
Obtain the default environment for a project
|
[
"Obtain",
"the",
"default",
"environment",
"for",
"a",
"project"
] |
0d19315847103341e599d32837ab0bd75524e5be
|
https://github.com/codescrum/bebox/blob/0d19315847103341e599d32837ab0bd75524e5be/lib/bebox/commands/commands_helper.rb#L17-L24
|
7,377 |
formatafacil/formatafacil
|
lib/formatafacil/artigo_tarefa.rb
|
Formatafacil.ArtigoTarefa.converte_configuracao_para_latex
|
def converte_configuracao_para_latex
@artigo_latex.merge!(@artigo)
['resumo','abstract','bibliografia'].each {|key|
Open3.popen3("pandoc --smart -f markdown -t latex --no-wrap") {|stdin, stdout, stderr, wait_thr|
pid = wait_thr.pid # pid of the started process.
stdin.write @artigo[key]
stdin.close
@artigo_latex[key] = stdout.read
}
}
end
|
ruby
|
def converte_configuracao_para_latex
@artigo_latex.merge!(@artigo)
['resumo','abstract','bibliografia'].each {|key|
Open3.popen3("pandoc --smart -f markdown -t latex --no-wrap") {|stdin, stdout, stderr, wait_thr|
pid = wait_thr.pid # pid of the started process.
stdin.write @artigo[key]
stdin.close
@artigo_latex[key] = stdout.read
}
}
end
|
[
"def",
"converte_configuracao_para_latex",
"@artigo_latex",
".",
"merge!",
"(",
"@artigo",
")",
"[",
"'resumo'",
",",
"'abstract'",
",",
"'bibliografia'",
"]",
".",
"each",
"{",
"|",
"key",
"|",
"Open3",
".",
"popen3",
"(",
"\"pandoc --smart -f markdown -t latex --no-wrap\"",
")",
"{",
"|",
"stdin",
",",
"stdout",
",",
"stderr",
",",
"wait_thr",
"|",
"pid",
"=",
"wait_thr",
".",
"pid",
"# pid of the started process.",
"stdin",
".",
"write",
"@artigo",
"[",
"key",
"]",
"stdin",
".",
"close",
"@artigo_latex",
"[",
"key",
"]",
"=",
"stdout",
".",
"read",
"}",
"}",
"end"
] |
Converte os arquivos de texto markdown para texto latex
|
[
"Converte",
"os",
"arquivos",
"de",
"texto",
"markdown",
"para",
"texto",
"latex"
] |
f3dcf72128ded4168215f1e947c75264d6d38b38
|
https://github.com/formatafacil/formatafacil/blob/f3dcf72128ded4168215f1e947c75264d6d38b38/lib/formatafacil/artigo_tarefa.rb#L295-L306
|
7,378 |
formatafacil/formatafacil
|
lib/formatafacil/artigo_tarefa.rb
|
Formatafacil.ArtigoTarefa.salva_configuracao_yaml_para_inclusao_em_pandoc
|
def salva_configuracao_yaml_para_inclusao_em_pandoc
File.open(@arquivo_saida_yaml, 'w'){ |file|
file.write("\n")
file.write @artigo_latex.to_yaml
file.write("---\n")
}
end
|
ruby
|
def salva_configuracao_yaml_para_inclusao_em_pandoc
File.open(@arquivo_saida_yaml, 'w'){ |file|
file.write("\n")
file.write @artigo_latex.to_yaml
file.write("---\n")
}
end
|
[
"def",
"salva_configuracao_yaml_para_inclusao_em_pandoc",
"File",
".",
"open",
"(",
"@arquivo_saida_yaml",
",",
"'w'",
")",
"{",
"|",
"file",
"|",
"file",
".",
"write",
"(",
"\"\\n\"",
")",
"file",
".",
"write",
"@artigo_latex",
".",
"to_yaml",
"file",
".",
"write",
"(",
"\"---\\n\"",
")",
"}",
"end"
] |
Precisa gerar arquivos com quebra de linha antes e depois
porque pandoc utiliza
|
[
"Precisa",
"gerar",
"arquivos",
"com",
"quebra",
"de",
"linha",
"antes",
"e",
"depois",
"porque",
"pandoc",
"utiliza"
] |
f3dcf72128ded4168215f1e947c75264d6d38b38
|
https://github.com/formatafacil/formatafacil/blob/f3dcf72128ded4168215f1e947c75264d6d38b38/lib/formatafacil/artigo_tarefa.rb#L340-L346
|
7,379 |
lingzhang-lyon/highwatermark
|
lib/highwatermark.rb
|
Highwatermark.HighWaterMark.last_records
|
def last_records(tag=@state_tag)
if @state_type == 'file'
return @data['last_records'][tag]
elsif @state_type =='memory'
return @data['last_records'][tag]
elsif @state_type =='redis'
begin
[email protected](tag)
return alertStart
rescue Exception => e
puts e.message
puts e.backtrace.inspect
end
end
end
|
ruby
|
def last_records(tag=@state_tag)
if @state_type == 'file'
return @data['last_records'][tag]
elsif @state_type =='memory'
return @data['last_records'][tag]
elsif @state_type =='redis'
begin
[email protected](tag)
return alertStart
rescue Exception => e
puts e.message
puts e.backtrace.inspect
end
end
end
|
[
"def",
"last_records",
"(",
"tag",
"=",
"@state_tag",
")",
"if",
"@state_type",
"==",
"'file'",
"return",
"@data",
"[",
"'last_records'",
"]",
"[",
"tag",
"]",
"elsif",
"@state_type",
"==",
"'memory'",
"return",
"@data",
"[",
"'last_records'",
"]",
"[",
"tag",
"]",
"elsif",
"@state_type",
"==",
"'redis'",
"begin",
"alertStart",
"=",
"@redis",
".",
"get",
"(",
"tag",
")",
"return",
"alertStart",
"rescue",
"Exception",
"=>",
"e",
"puts",
"e",
".",
"message",
"puts",
"e",
".",
"backtrace",
".",
"inspect",
"end",
"end",
"end"
] |
end of intitialize
|
[
"end",
"of",
"intitialize"
] |
704c7ea71a4ba638c4483e9e32eda853573b948d
|
https://github.com/lingzhang-lyon/highwatermark/blob/704c7ea71a4ba638c4483e9e32eda853573b948d/lib/highwatermark.rb#L90-L105
|
7,380 |
Montage-Inc/ruby-montage
|
lib/montage/query/query_parser.rb
|
Montage.QueryParser.get_query_operator
|
def get_query_operator(part)
operator = Montage::Operators.find_operator(part)
[operator.operator, operator.montage_operator]
end
|
ruby
|
def get_query_operator(part)
operator = Montage::Operators.find_operator(part)
[operator.operator, operator.montage_operator]
end
|
[
"def",
"get_query_operator",
"(",
"part",
")",
"operator",
"=",
"Montage",
"::",
"Operators",
".",
"find_operator",
"(",
"part",
")",
"[",
"operator",
".",
"operator",
",",
"operator",
".",
"montage_operator",
"]",
"end"
] |
Grabs the proper query operator from the string
* *Args* :
- +part+ -> The query string
* *Returns* :
- An array containing the supplied logical operator and the Montage
equivalent
* *Examples* :
@part = "tree_happiness_level > 9"
get_query_operator(@part)
=> [">", "$gt"]
|
[
"Grabs",
"the",
"proper",
"query",
"operator",
"from",
"the",
"string"
] |
2e6f7e591f2f87158994c17ad9619fa29b716bad
|
https://github.com/Montage-Inc/ruby-montage/blob/2e6f7e591f2f87158994c17ad9619fa29b716bad/lib/montage/query/query_parser.rb#L60-L63
|
7,381 |
Montage-Inc/ruby-montage
|
lib/montage/query/query_parser.rb
|
Montage.QueryParser.parse_part
|
def parse_part(part)
parsed_part = JSON.parse(part) rescue part
if is_i?(parsed_part)
parsed_part.to_i
elsif is_f?(parsed_part)
parsed_part.to_f
elsif parsed_part =~ /\(.*\)/
to_array(parsed_part)
elsif parsed_part.is_a?(Array)
parsed_part
else
parsed_part.gsub(/('|')/, "")
end
end
|
ruby
|
def parse_part(part)
parsed_part = JSON.parse(part) rescue part
if is_i?(parsed_part)
parsed_part.to_i
elsif is_f?(parsed_part)
parsed_part.to_f
elsif parsed_part =~ /\(.*\)/
to_array(parsed_part)
elsif parsed_part.is_a?(Array)
parsed_part
else
parsed_part.gsub(/('|')/, "")
end
end
|
[
"def",
"parse_part",
"(",
"part",
")",
"parsed_part",
"=",
"JSON",
".",
"parse",
"(",
"part",
")",
"rescue",
"part",
"if",
"is_i?",
"(",
"parsed_part",
")",
"parsed_part",
".",
"to_i",
"elsif",
"is_f?",
"(",
"parsed_part",
")",
"parsed_part",
".",
"to_f",
"elsif",
"parsed_part",
"=~",
"/",
"\\(",
"\\)",
"/",
"to_array",
"(",
"parsed_part",
")",
"elsif",
"parsed_part",
".",
"is_a?",
"(",
"Array",
")",
"parsed_part",
"else",
"parsed_part",
".",
"gsub",
"(",
"/",
"/",
",",
"\"\"",
")",
"end",
"end"
] |
Parse a single portion of the query string. String values representing
a float or integer are coerced into actual numerical values. Newline
characters are removed and single quotes are replaced with double quotes
* *Args* :
- +part+ -> The value element extracted from the query string
* *Returns* :
- A parsed form of the value element
* *Examples* :
@part = "9"
parse_part(@part)
=> 9
|
[
"Parse",
"a",
"single",
"portion",
"of",
"the",
"query",
"string",
".",
"String",
"values",
"representing",
"a",
"float",
"or",
"integer",
"are",
"coerced",
"into",
"actual",
"numerical",
"values",
".",
"Newline",
"characters",
"are",
"removed",
"and",
"single",
"quotes",
"are",
"replaced",
"with",
"double",
"quotes"
] |
2e6f7e591f2f87158994c17ad9619fa29b716bad
|
https://github.com/Montage-Inc/ruby-montage/blob/2e6f7e591f2f87158994c17ad9619fa29b716bad/lib/montage/query/query_parser.rb#L94-L108
|
7,382 |
Montage-Inc/ruby-montage
|
lib/montage/query/query_parser.rb
|
Montage.QueryParser.get_parts
|
def get_parts(str)
operator, montage_operator = get_query_operator(str)
fail QueryError, "Invalid Montage query operator!" unless montage_operator
column_name = get_column_name(str, operator)
fail QueryError, "Your query has an undetermined error" unless column_name
value = parse_part(parse_condition_set(str, operator))
[column_name, montage_operator, value]
end
|
ruby
|
def get_parts(str)
operator, montage_operator = get_query_operator(str)
fail QueryError, "Invalid Montage query operator!" unless montage_operator
column_name = get_column_name(str, operator)
fail QueryError, "Your query has an undetermined error" unless column_name
value = parse_part(parse_condition_set(str, operator))
[column_name, montage_operator, value]
end
|
[
"def",
"get_parts",
"(",
"str",
")",
"operator",
",",
"montage_operator",
"=",
"get_query_operator",
"(",
"str",
")",
"fail",
"QueryError",
",",
"\"Invalid Montage query operator!\"",
"unless",
"montage_operator",
"column_name",
"=",
"get_column_name",
"(",
"str",
",",
"operator",
")",
"fail",
"QueryError",
",",
"\"Your query has an undetermined error\"",
"unless",
"column_name",
"value",
"=",
"parse_part",
"(",
"parse_condition_set",
"(",
"str",
",",
"operator",
")",
")",
"[",
"column_name",
",",
"montage_operator",
",",
"value",
"]",
"end"
] |
Get all the parts of the query string
* *Args* :
- +str+ -> The query string
* *Returns* :
- An array containing the column name, the montage operator, and the
value for comparison.
* *Raises* :
- +QueryError+ -> When incomplete queries or queries without valid
operators are initialized
* *Examples* :
@part = "tree_happiness_level > 9"
get_parts(@part)
=> ["tree_happiness_level", "$gt", 9]
|
[
"Get",
"all",
"the",
"parts",
"of",
"the",
"query",
"string"
] |
2e6f7e591f2f87158994c17ad9619fa29b716bad
|
https://github.com/Montage-Inc/ruby-montage/blob/2e6f7e591f2f87158994c17ad9619fa29b716bad/lib/montage/query/query_parser.rb#L125-L137
|
7,383 |
Montage-Inc/ruby-montage
|
lib/montage/query/query_parser.rb
|
Montage.QueryParser.parse_hash
|
def parse_hash
query.map do |key, value|
new_value = value.is_a?(Array) ? ["$in", value] : value
[key.to_s, new_value]
end
end
|
ruby
|
def parse_hash
query.map do |key, value|
new_value = value.is_a?(Array) ? ["$in", value] : value
[key.to_s, new_value]
end
end
|
[
"def",
"parse_hash",
"query",
".",
"map",
"do",
"|",
"key",
",",
"value",
"|",
"new_value",
"=",
"value",
".",
"is_a?",
"(",
"Array",
")",
"?",
"[",
"\"$in\"",
",",
"value",
"]",
":",
"value",
"[",
"key",
".",
"to_s",
",",
"new_value",
"]",
"end",
"end"
] |
Parse a hash type query
* *Returns* :
- A ReQON compatible array
* *Examples* :
@test = Montage::QueryParser.new(tree_status: "happy")
@test.parse_hash
=> [["tree_status", "happy"]]
|
[
"Parse",
"a",
"hash",
"type",
"query"
] |
2e6f7e591f2f87158994c17ad9619fa29b716bad
|
https://github.com/Montage-Inc/ruby-montage/blob/2e6f7e591f2f87158994c17ad9619fa29b716bad/lib/montage/query/query_parser.rb#L148-L153
|
7,384 |
Montage-Inc/ruby-montage
|
lib/montage/query/query_parser.rb
|
Montage.QueryParser.parse_string
|
def parse_string
query.split(/\band\b(?=(?:[^']|'[^']*')*$)/i).map do |part|
column_name, operator, value = get_parts(part)
if operator == ""
["#{column_name}", value]
else
["#{column_name}", ["#{operator}", value]]
end
end
end
|
ruby
|
def parse_string
query.split(/\band\b(?=(?:[^']|'[^']*')*$)/i).map do |part|
column_name, operator, value = get_parts(part)
if operator == ""
["#{column_name}", value]
else
["#{column_name}", ["#{operator}", value]]
end
end
end
|
[
"def",
"parse_string",
"query",
".",
"split",
"(",
"/",
"\\b",
"\\b",
"/i",
")",
".",
"map",
"do",
"|",
"part",
"|",
"column_name",
",",
"operator",
",",
"value",
"=",
"get_parts",
"(",
"part",
")",
"if",
"operator",
"==",
"\"\"",
"[",
"\"#{column_name}\"",
",",
"value",
"]",
"else",
"[",
"\"#{column_name}\"",
",",
"[",
"\"#{operator}\"",
",",
"value",
"]",
"]",
"end",
"end",
"end"
] |
Parse a string type query. Splits multiple conditions on case insensitive
"and" strings that do not fall within single quotations. Note that the
Montage equals operator is supplied as a blank string
* *Returns* :
- A ReQON compatible array
* *Examples* :
@test = Montage::QueryParser.new("tree_happiness_level > 9")
@test.parse_string
=> [["tree_happiness_level", ["$__gt", 9]]]
|
[
"Parse",
"a",
"string",
"type",
"query",
".",
"Splits",
"multiple",
"conditions",
"on",
"case",
"insensitive",
"and",
"strings",
"that",
"do",
"not",
"fall",
"within",
"single",
"quotations",
".",
"Note",
"that",
"the",
"Montage",
"equals",
"operator",
"is",
"supplied",
"as",
"a",
"blank",
"string"
] |
2e6f7e591f2f87158994c17ad9619fa29b716bad
|
https://github.com/Montage-Inc/ruby-montage/blob/2e6f7e591f2f87158994c17ad9619fa29b716bad/lib/montage/query/query_parser.rb#L166-L175
|
7,385 |
Montage-Inc/ruby-montage
|
lib/montage/query/query_parser.rb
|
Montage.QueryParser.to_array
|
def to_array(value)
values = value.gsub(/('|\(|\))/, "").split(',')
type = [:is_i?, :is_f?].find(Proc.new { :is_s? }) { |t| send(t, values.first) }
values.map { |v| v.send(TYPE_MAP[type]) }
end
|
ruby
|
def to_array(value)
values = value.gsub(/('|\(|\))/, "").split(',')
type = [:is_i?, :is_f?].find(Proc.new { :is_s? }) { |t| send(t, values.first) }
values.map { |v| v.send(TYPE_MAP[type]) }
end
|
[
"def",
"to_array",
"(",
"value",
")",
"values",
"=",
"value",
".",
"gsub",
"(",
"/",
"\\(",
"\\)",
"/",
",",
"\"\"",
")",
".",
"split",
"(",
"','",
")",
"type",
"=",
"[",
":is_i?",
",",
":is_f?",
"]",
".",
"find",
"(",
"Proc",
".",
"new",
"{",
":is_s?",
"}",
")",
"{",
"|",
"t",
"|",
"send",
"(",
"t",
",",
"values",
".",
"first",
")",
"}",
"values",
".",
"map",
"{",
"|",
"v",
"|",
"v",
".",
"send",
"(",
"TYPE_MAP",
"[",
"type",
"]",
")",
"}",
"end"
] |
Takes a string value and splits it into an array
Will coerce all values into the type of the first type
* *Args* :
- +value+ -> A string value
* *Returns* :
- A array form of the value argument
* *Examples* :
@part = "(1, 2, 3)"
to_array(@part)
=> [1, 2, 3]
|
[
"Takes",
"a",
"string",
"value",
"and",
"splits",
"it",
"into",
"an",
"array",
"Will",
"coerce",
"all",
"values",
"into",
"the",
"type",
"of",
"the",
"first",
"type"
] |
2e6f7e591f2f87158994c17ad9619fa29b716bad
|
https://github.com/Montage-Inc/ruby-montage/blob/2e6f7e591f2f87158994c17ad9619fa29b716bad/lib/montage/query/query_parser.rb#L199-L203
|
7,386 |
KatanaCode/evvnt
|
lib/evvnt/nested_resources.rb
|
Evvnt.NestedResources.belongs_to
|
def belongs_to(parent_resource)
parent_resource = parent_resource.to_sym
parent_resources << parent_resource unless parent_resource.in?(parent_resources)
end
|
ruby
|
def belongs_to(parent_resource)
parent_resource = parent_resource.to_sym
parent_resources << parent_resource unless parent_resource.in?(parent_resources)
end
|
[
"def",
"belongs_to",
"(",
"parent_resource",
")",
"parent_resource",
"=",
"parent_resource",
".",
"to_sym",
"parent_resources",
"<<",
"parent_resource",
"unless",
"parent_resource",
".",
"in?",
"(",
"parent_resources",
")",
"end"
] |
Tell a class that it's resources may be nested within another named resource
parent_resource - A Symbol with the name of the parent resource.
|
[
"Tell",
"a",
"class",
"that",
"it",
"s",
"resources",
"may",
"be",
"nested",
"within",
"another",
"named",
"resource"
] |
e13f6d84af09a71819356620fb25685a6cd159c9
|
https://github.com/KatanaCode/evvnt/blob/e13f6d84af09a71819356620fb25685a6cd159c9/lib/evvnt/nested_resources.rb#L21-L24
|
7,387 |
atomicobject/kinetic-ruby
|
lib/kinetic_server.rb
|
KineticRuby.Client.receive
|
def receive(max_len=nil)
max_len ||= 1024
begin
data = @socket.recv(max_len)
rescue IO::WaitReadable
@logger.logv 'Retrying receive...'
IO.select([@socket])
retry
rescue Exception => e
if e.class != 'IOError' && e.message != 'closed stream'
@logger.log_exception(e, 'EXCEPTION during receive!')
end
end
if (data.nil? || data.empty?)
@logger.log "Client #{@socket.inspect} disconnected!"
data = ''
else
@logger.log "Received #{data.length} bytes"
end
return data
end
|
ruby
|
def receive(max_len=nil)
max_len ||= 1024
begin
data = @socket.recv(max_len)
rescue IO::WaitReadable
@logger.logv 'Retrying receive...'
IO.select([@socket])
retry
rescue Exception => e
if e.class != 'IOError' && e.message != 'closed stream'
@logger.log_exception(e, 'EXCEPTION during receive!')
end
end
if (data.nil? || data.empty?)
@logger.log "Client #{@socket.inspect} disconnected!"
data = ''
else
@logger.log "Received #{data.length} bytes"
end
return data
end
|
[
"def",
"receive",
"(",
"max_len",
"=",
"nil",
")",
"max_len",
"||=",
"1024",
"begin",
"data",
"=",
"@socket",
".",
"recv",
"(",
"max_len",
")",
"rescue",
"IO",
"::",
"WaitReadable",
"@logger",
".",
"logv",
"'Retrying receive...'",
"IO",
".",
"select",
"(",
"[",
"@socket",
"]",
")",
"retry",
"rescue",
"Exception",
"=>",
"e",
"if",
"e",
".",
"class",
"!=",
"'IOError'",
"&&",
"e",
".",
"message",
"!=",
"'closed stream'",
"@logger",
".",
"log_exception",
"(",
"e",
",",
"'EXCEPTION during receive!'",
")",
"end",
"end",
"if",
"(",
"data",
".",
"nil?",
"||",
"data",
".",
"empty?",
")",
"@logger",
".",
"log",
"\"Client #{@socket.inspect} disconnected!\"",
"data",
"=",
"''",
"else",
"@logger",
".",
"log",
"\"Received #{data.length} bytes\"",
"end",
"return",
"data",
"end"
] |
Wait to receive data from the client
@param max_len Maximum number of bytes to receive
@returns Received data (length <= max_len) or nil upon failure
|
[
"Wait",
"to",
"receive",
"data",
"from",
"the",
"client"
] |
bc2a6331d75d30071f365d506e0a6abe2e808dc6
|
https://github.com/atomicobject/kinetic-ruby/blob/bc2a6331d75d30071f365d506e0a6abe2e808dc6/lib/kinetic_server.rb#L37-L60
|
7,388 |
barkerest/incline
|
lib/incline/validators/ip_address_validator.rb
|
Incline.IpAddressValidator.validate_each
|
def validate_each(record, attribute, value)
begin
unless value.blank?
IPAddr.new(value)
if options[:no_mask]
if value =~ /\//
record.errors[attribute] << (options[:message] || 'must not contain a mask')
end
elsif options[:require_mask]
unless value =~ /\//
record.errors[attribute] << (options[:message] || 'must contain a mask')
end
end
end
rescue IPAddr::InvalidAddressError
record.errors[attribute] << (options[:message] || 'is not a valid IP address')
end
end
|
ruby
|
def validate_each(record, attribute, value)
begin
unless value.blank?
IPAddr.new(value)
if options[:no_mask]
if value =~ /\//
record.errors[attribute] << (options[:message] || 'must not contain a mask')
end
elsif options[:require_mask]
unless value =~ /\//
record.errors[attribute] << (options[:message] || 'must contain a mask')
end
end
end
rescue IPAddr::InvalidAddressError
record.errors[attribute] << (options[:message] || 'is not a valid IP address')
end
end
|
[
"def",
"validate_each",
"(",
"record",
",",
"attribute",
",",
"value",
")",
"begin",
"unless",
"value",
".",
"blank?",
"IPAddr",
".",
"new",
"(",
"value",
")",
"if",
"options",
"[",
":no_mask",
"]",
"if",
"value",
"=~",
"/",
"\\/",
"/",
"record",
".",
"errors",
"[",
"attribute",
"]",
"<<",
"(",
"options",
"[",
":message",
"]",
"||",
"'must not contain a mask'",
")",
"end",
"elsif",
"options",
"[",
":require_mask",
"]",
"unless",
"value",
"=~",
"/",
"\\/",
"/",
"record",
".",
"errors",
"[",
"attribute",
"]",
"<<",
"(",
"options",
"[",
":message",
"]",
"||",
"'must contain a mask'",
")",
"end",
"end",
"end",
"rescue",
"IPAddr",
"::",
"InvalidAddressError",
"record",
".",
"errors",
"[",
"attribute",
"]",
"<<",
"(",
"options",
"[",
":message",
"]",
"||",
"'is not a valid IP address'",
")",
"end",
"end"
] |
Validates attributes to determine if the values contain valid IP addresses.
Set the :no_mask option to restrict the IP address to singular addresses only.
|
[
"Validates",
"attributes",
"to",
"determine",
"if",
"the",
"values",
"contain",
"valid",
"IP",
"addresses",
"."
] |
1ff08db7aa8ab7f86b223268b700bc67d15bb8aa
|
https://github.com/barkerest/incline/blob/1ff08db7aa8ab7f86b223268b700bc67d15bb8aa/lib/incline/validators/ip_address_validator.rb#L12-L29
|
7,389 |
salesking/sk_sdk
|
lib/sk_sdk/ar_patches/ar3/base.rb
|
ActiveResource.Base.load_attributes_from_response
|
def load_attributes_from_response(response)
if (response['Transfer-Encoding'] == 'chunked' || (!response['Content-Length'].blank? && response['Content-Length'] != "0")) && !response.body.nil? && response.body.strip.size > 0
load( self.class.format.decode(response.body)[self.class.element_name] )
#fix double nested items .. active resource SUCKS soooo bad
if self.respond_to?(:items)
new_items = []
self.items.each { |item| new_items << item.attributes.first[1] }
self.items = new_items
end
@persisted = true
end
end
|
ruby
|
def load_attributes_from_response(response)
if (response['Transfer-Encoding'] == 'chunked' || (!response['Content-Length'].blank? && response['Content-Length'] != "0")) && !response.body.nil? && response.body.strip.size > 0
load( self.class.format.decode(response.body)[self.class.element_name] )
#fix double nested items .. active resource SUCKS soooo bad
if self.respond_to?(:items)
new_items = []
self.items.each { |item| new_items << item.attributes.first[1] }
self.items = new_items
end
@persisted = true
end
end
|
[
"def",
"load_attributes_from_response",
"(",
"response",
")",
"if",
"(",
"response",
"[",
"'Transfer-Encoding'",
"]",
"==",
"'chunked'",
"||",
"(",
"!",
"response",
"[",
"'Content-Length'",
"]",
".",
"blank?",
"&&",
"response",
"[",
"'Content-Length'",
"]",
"!=",
"\"0\"",
")",
")",
"&&",
"!",
"response",
".",
"body",
".",
"nil?",
"&&",
"response",
".",
"body",
".",
"strip",
".",
"size",
">",
"0",
"load",
"(",
"self",
".",
"class",
".",
"format",
".",
"decode",
"(",
"response",
".",
"body",
")",
"[",
"self",
".",
"class",
".",
"element_name",
"]",
")",
"#fix double nested items .. active resource SUCKS soooo bad",
"if",
"self",
".",
"respond_to?",
"(",
":items",
")",
"new_items",
"=",
"[",
"]",
"self",
".",
"items",
".",
"each",
"{",
"|",
"item",
"|",
"new_items",
"<<",
"item",
".",
"attributes",
".",
"first",
"[",
"1",
"]",
"}",
"self",
".",
"items",
"=",
"new_items",
"end",
"@persisted",
"=",
"true",
"end",
"end"
] |
override ARes method to parse only the client part
|
[
"override",
"ARes",
"method",
"to",
"parse",
"only",
"the",
"client",
"part"
] |
03170b2807cc4e1f1ba44c704c308370c6563dbc
|
https://github.com/salesking/sk_sdk/blob/03170b2807cc4e1f1ba44c704c308370c6563dbc/lib/sk_sdk/ar_patches/ar3/base.rb#L8-L19
|
7,390 |
roberthoner/encrypted_store
|
lib/encrypted_store/config.rb
|
EncryptedStore.Config.method_missing
|
def method_missing(meth, *args, &block)
meth_str = meth.to_s
if /^(\w+)\=$/.match(meth_str)
_set($1, *args, &block)
elsif args.length > 0 || block_given?
_add(meth, *args, &block)
elsif /^(\w+)\?$/.match(meth_str)
!!_get($1)
else
_get_or_create_namespace(meth)
end
end
|
ruby
|
def method_missing(meth, *args, &block)
meth_str = meth.to_s
if /^(\w+)\=$/.match(meth_str)
_set($1, *args, &block)
elsif args.length > 0 || block_given?
_add(meth, *args, &block)
elsif /^(\w+)\?$/.match(meth_str)
!!_get($1)
else
_get_or_create_namespace(meth)
end
end
|
[
"def",
"method_missing",
"(",
"meth",
",",
"*",
"args",
",",
"&",
"block",
")",
"meth_str",
"=",
"meth",
".",
"to_s",
"if",
"/",
"\\w",
"\\=",
"/",
".",
"match",
"(",
"meth_str",
")",
"_set",
"(",
"$1",
",",
"args",
",",
"block",
")",
"elsif",
"args",
".",
"length",
">",
"0",
"||",
"block_given?",
"_add",
"(",
"meth",
",",
"args",
",",
"block",
")",
"elsif",
"/",
"\\w",
"\\?",
"/",
".",
"match",
"(",
"meth_str",
")",
"!",
"!",
"_get",
"(",
"$1",
")",
"else",
"_get_or_create_namespace",
"(",
"meth",
")",
"end",
"end"
] |
Deep dup all the values.
|
[
"Deep",
"dup",
"all",
"the",
"values",
"."
] |
89e78eb19e0cb710b08b71209e42eda085dcaa8a
|
https://github.com/roberthoner/encrypted_store/blob/89e78eb19e0cb710b08b71209e42eda085dcaa8a/lib/encrypted_store/config.rb#L59-L71
|
7,391 |
nrser/nrser.rb
|
lib/nrser/errors/attr_error.rb
|
NRSER.AttrError.default_message
|
def default_message
message = []
if value? && name?
message << format_message( value.class, "object", value.inspect,
"has invalid ##{ name } attribute" )
end
if expected?
message << format_message( "expected", expected )
end
if actual?
message << format_message( "found", actual )
end
if message.empty?
super
else
message.join ', '
end
end
|
ruby
|
def default_message
message = []
if value? && name?
message << format_message( value.class, "object", value.inspect,
"has invalid ##{ name } attribute" )
end
if expected?
message << format_message( "expected", expected )
end
if actual?
message << format_message( "found", actual )
end
if message.empty?
super
else
message.join ', '
end
end
|
[
"def",
"default_message",
"message",
"=",
"[",
"]",
"if",
"value?",
"&&",
"name?",
"message",
"<<",
"format_message",
"(",
"value",
".",
"class",
",",
"\"object\"",
",",
"value",
".",
"inspect",
",",
"\"has invalid ##{ name } attribute\"",
")",
"end",
"if",
"expected?",
"message",
"<<",
"format_message",
"(",
"\"expected\"",
",",
"expected",
")",
"end",
"if",
"actual?",
"message",
"<<",
"format_message",
"(",
"\"found\"",
",",
"actual",
")",
"end",
"if",
"message",
".",
"empty?",
"super",
"else",
"message",
".",
"join",
"', '",
"end",
"end"
] |
Create a default message if none was provided.
Uses whatever recognized {#context} values are present, falling back
to {NicerError#default_message} if none are.
@return [String]
|
[
"Create",
"a",
"default",
"message",
"if",
"none",
"was",
"provided",
"."
] |
7db9a729ec65894dfac13fd50851beae8b809738
|
https://github.com/nrser/nrser.rb/blob/7db9a729ec65894dfac13fd50851beae8b809738/lib/nrser/errors/attr_error.rb#L137-L158
|
7,392 |
nafu/aws_sns_manager
|
lib/aws_sns_manager/client.rb
|
AwsSnsManager.Client.message
|
def message(text, options = {}, env = :prod, type = :normal)
if type == :normal
data = normal_notification(text, options)
elsif type == :silent
data = silent_notification(text, options)
elsif type == :nosound
data = nosound_notification(text, options)
end
return dev_json(data) if env == :dev
prod_json(data)
end
|
ruby
|
def message(text, options = {}, env = :prod, type = :normal)
if type == :normal
data = normal_notification(text, options)
elsif type == :silent
data = silent_notification(text, options)
elsif type == :nosound
data = nosound_notification(text, options)
end
return dev_json(data) if env == :dev
prod_json(data)
end
|
[
"def",
"message",
"(",
"text",
",",
"options",
"=",
"{",
"}",
",",
"env",
"=",
":prod",
",",
"type",
"=",
":normal",
")",
"if",
"type",
"==",
":normal",
"data",
"=",
"normal_notification",
"(",
"text",
",",
"options",
")",
"elsif",
"type",
"==",
":silent",
"data",
"=",
"silent_notification",
"(",
"text",
",",
"options",
")",
"elsif",
"type",
"==",
":nosound",
"data",
"=",
"nosound_notification",
"(",
"text",
",",
"options",
")",
"end",
"return",
"dev_json",
"(",
"data",
")",
"if",
"env",
"==",
":dev",
"prod_json",
"(",
"data",
")",
"end"
] |
Return json payload
+text+:: Text you want to send
+options+:: Options you want on payload
+env+:: Environments :prod, :dev
+type+:: Notification type :normal, :silent, :nosound
|
[
"Return",
"json",
"payload"
] |
9ec6ce1799d1195108e95a1efa2dd21437220a3e
|
https://github.com/nafu/aws_sns_manager/blob/9ec6ce1799d1195108e95a1efa2dd21437220a3e/lib/aws_sns_manager/client.rb#L37-L47
|
7,393 |
rightscale/right_amqp
|
lib/right_amqp/ha_client/broker_client.rb
|
RightAMQP.BrokerClient.subscribe
|
def subscribe(queue, exchange = nil, options = {}, &block)
raise ArgumentError, "Must call this method with a block" unless block
return false unless usable?
return true unless @queues.select { |q| q.name == queue[:name] }.empty?
to_exchange = if exchange
if options[:exchange2]
" to exchanges #{exchange[:name]} and #{options[:exchange2][:name]}"
else
" to exchange #{exchange[:name]}"
end
end
queue_options = queue[:options] || {}
exchange_options = (exchange && exchange[:options]) || {}
begin
logger.info("[setup] Subscribing queue #{queue[:name]}#{to_exchange} on broker #{@alias}")
q = @channel.queue(queue[:name], queue_options)
@queues << q
if exchange
x = @channel.__send__(exchange[:type], exchange[:name], exchange_options)
binding = q.bind(x, options[:key] ? {:key => options[:key]} : {})
if (exchange2 = options[:exchange2])
q.bind(@channel.__send__(exchange2[:type], exchange2[:name], exchange2[:options] || {}))
end
q = binding
end
q.subscribe(options[:ack] ? {:ack => true} : {}) do |header, message|
begin
if (pool = (options[:fiber_pool] || @options[:fiber_pool]))
pool.spawn { receive(queue[:name], header, message, options, &block) }
else
receive(queue[:name], header, message, options, &block)
end
rescue StandardError => e
header.ack if options[:ack]
logger.exception("Failed setting up to receive message from queue #{queue.inspect} " +
"on broker #{@alias}", e, :trace)
@exception_stats.track("receive", e)
update_non_delivery_stats("receive failure", e)
end
end
rescue StandardError => e
logger.exception("Failed subscribing queue #{queue.inspect}#{to_exchange} on broker #{@alias}", e, :trace)
@exception_stats.track("subscribe", e)
false
end
end
|
ruby
|
def subscribe(queue, exchange = nil, options = {}, &block)
raise ArgumentError, "Must call this method with a block" unless block
return false unless usable?
return true unless @queues.select { |q| q.name == queue[:name] }.empty?
to_exchange = if exchange
if options[:exchange2]
" to exchanges #{exchange[:name]} and #{options[:exchange2][:name]}"
else
" to exchange #{exchange[:name]}"
end
end
queue_options = queue[:options] || {}
exchange_options = (exchange && exchange[:options]) || {}
begin
logger.info("[setup] Subscribing queue #{queue[:name]}#{to_exchange} on broker #{@alias}")
q = @channel.queue(queue[:name], queue_options)
@queues << q
if exchange
x = @channel.__send__(exchange[:type], exchange[:name], exchange_options)
binding = q.bind(x, options[:key] ? {:key => options[:key]} : {})
if (exchange2 = options[:exchange2])
q.bind(@channel.__send__(exchange2[:type], exchange2[:name], exchange2[:options] || {}))
end
q = binding
end
q.subscribe(options[:ack] ? {:ack => true} : {}) do |header, message|
begin
if (pool = (options[:fiber_pool] || @options[:fiber_pool]))
pool.spawn { receive(queue[:name], header, message, options, &block) }
else
receive(queue[:name], header, message, options, &block)
end
rescue StandardError => e
header.ack if options[:ack]
logger.exception("Failed setting up to receive message from queue #{queue.inspect} " +
"on broker #{@alias}", e, :trace)
@exception_stats.track("receive", e)
update_non_delivery_stats("receive failure", e)
end
end
rescue StandardError => e
logger.exception("Failed subscribing queue #{queue.inspect}#{to_exchange} on broker #{@alias}", e, :trace)
@exception_stats.track("subscribe", e)
false
end
end
|
[
"def",
"subscribe",
"(",
"queue",
",",
"exchange",
"=",
"nil",
",",
"options",
"=",
"{",
"}",
",",
"&",
"block",
")",
"raise",
"ArgumentError",
",",
"\"Must call this method with a block\"",
"unless",
"block",
"return",
"false",
"unless",
"usable?",
"return",
"true",
"unless",
"@queues",
".",
"select",
"{",
"|",
"q",
"|",
"q",
".",
"name",
"==",
"queue",
"[",
":name",
"]",
"}",
".",
"empty?",
"to_exchange",
"=",
"if",
"exchange",
"if",
"options",
"[",
":exchange2",
"]",
"\" to exchanges #{exchange[:name]} and #{options[:exchange2][:name]}\"",
"else",
"\" to exchange #{exchange[:name]}\"",
"end",
"end",
"queue_options",
"=",
"queue",
"[",
":options",
"]",
"||",
"{",
"}",
"exchange_options",
"=",
"(",
"exchange",
"&&",
"exchange",
"[",
":options",
"]",
")",
"||",
"{",
"}",
"begin",
"logger",
".",
"info",
"(",
"\"[setup] Subscribing queue #{queue[:name]}#{to_exchange} on broker #{@alias}\"",
")",
"q",
"=",
"@channel",
".",
"queue",
"(",
"queue",
"[",
":name",
"]",
",",
"queue_options",
")",
"@queues",
"<<",
"q",
"if",
"exchange",
"x",
"=",
"@channel",
".",
"__send__",
"(",
"exchange",
"[",
":type",
"]",
",",
"exchange",
"[",
":name",
"]",
",",
"exchange_options",
")",
"binding",
"=",
"q",
".",
"bind",
"(",
"x",
",",
"options",
"[",
":key",
"]",
"?",
"{",
":key",
"=>",
"options",
"[",
":key",
"]",
"}",
":",
"{",
"}",
")",
"if",
"(",
"exchange2",
"=",
"options",
"[",
":exchange2",
"]",
")",
"q",
".",
"bind",
"(",
"@channel",
".",
"__send__",
"(",
"exchange2",
"[",
":type",
"]",
",",
"exchange2",
"[",
":name",
"]",
",",
"exchange2",
"[",
":options",
"]",
"||",
"{",
"}",
")",
")",
"end",
"q",
"=",
"binding",
"end",
"q",
".",
"subscribe",
"(",
"options",
"[",
":ack",
"]",
"?",
"{",
":ack",
"=>",
"true",
"}",
":",
"{",
"}",
")",
"do",
"|",
"header",
",",
"message",
"|",
"begin",
"if",
"(",
"pool",
"=",
"(",
"options",
"[",
":fiber_pool",
"]",
"||",
"@options",
"[",
":fiber_pool",
"]",
")",
")",
"pool",
".",
"spawn",
"{",
"receive",
"(",
"queue",
"[",
":name",
"]",
",",
"header",
",",
"message",
",",
"options",
",",
"block",
")",
"}",
"else",
"receive",
"(",
"queue",
"[",
":name",
"]",
",",
"header",
",",
"message",
",",
"options",
",",
"block",
")",
"end",
"rescue",
"StandardError",
"=>",
"e",
"header",
".",
"ack",
"if",
"options",
"[",
":ack",
"]",
"logger",
".",
"exception",
"(",
"\"Failed setting up to receive message from queue #{queue.inspect} \"",
"+",
"\"on broker #{@alias}\"",
",",
"e",
",",
":trace",
")",
"@exception_stats",
".",
"track",
"(",
"\"receive\"",
",",
"e",
")",
"update_non_delivery_stats",
"(",
"\"receive failure\"",
",",
"e",
")",
"end",
"end",
"rescue",
"StandardError",
"=>",
"e",
"logger",
".",
"exception",
"(",
"\"Failed subscribing queue #{queue.inspect}#{to_exchange} on broker #{@alias}\"",
",",
"e",
",",
":trace",
")",
"@exception_stats",
".",
"track",
"(",
"\"subscribe\"",
",",
"e",
")",
"false",
"end",
"end"
] |
Subscribe an AMQP queue to an AMQP exchange
Do not wait for confirmation from broker that subscription is complete
When a message is received, acknowledge, unserialize, and log it as specified
If the message is unserialized and it is not of the right type, it is dropped after logging an error
=== Parameters
queue(Hash):: AMQP queue being subscribed with keys :name and :options,
which are the standard AMQP ones plus
:no_declare(Boolean):: Whether to skip declaring this queue on the broker
to cause its creation; for use when caller does not have permission to create or
knows the queue already exists and wants to avoid declare overhead
exchange(Hash|nil):: AMQP exchange to subscribe to with keys :type, :name, and :options,
nil means use empty exchange by directly subscribing to queue; the :options are the
standard AMQP ones plus
:no_declare(Boolean):: Whether to skip declaring this exchange on the broker
to cause its creation; for use when caller does not have create permission or
knows the exchange already exists and wants to avoid declare overhead
options(Hash):: Subscribe options:
:ack(Boolean):: Whether caller takes responsibility for explicitly acknowledging each
message received, defaults to implicit acknowledgement in AMQP as part of message receipt
:no_unserialize(Boolean):: Do not unserialize message, this is an escape for special
situations like enrollment, also implicitly disables receive filtering and logging;
this option is implicitly invoked if initialize without a serializer
(packet class)(Array(Symbol)):: Filters to be applied in to_s when logging packet to :info,
only packet classes specified are accepted, others are not processed but are logged with error
:category(String):: Packet category description to be used in error messages
:log_data(String):: Additional data to display at end of log entry
:no_log(Boolean):: Disable receive logging unless debug level
:exchange2(Hash):: Additional exchange to which same queue is to be bound
:brokers(Array):: Identity of brokers for which to subscribe, defaults to all usable if nil or empty
:fiber_pool(FiberPool):: Pool of initialized fibers to be used for asynchronous message
processing (non-nil value will override constructor option setting)
=== Block
Required block with following parameters to be called each time exchange matches a message to the queue
identity(String):: Serialized identity of broker delivering the message
message(Packet|String):: Message received, which is unserialized unless :no_unserialize was specified
header(AMQP::Protocol::Header):: Message header (optional block parameter)
=== Raise
ArgumentError:: If a block is not supplied
=== Return
(Boolean):: true if subscribe successfully or if already subscribed, otherwise false
|
[
"Subscribe",
"an",
"AMQP",
"queue",
"to",
"an",
"AMQP",
"exchange",
"Do",
"not",
"wait",
"for",
"confirmation",
"from",
"broker",
"that",
"subscription",
"is",
"complete",
"When",
"a",
"message",
"is",
"received",
"acknowledge",
"unserialize",
"and",
"log",
"it",
"as",
"specified",
"If",
"the",
"message",
"is",
"unserialized",
"and",
"it",
"is",
"not",
"of",
"the",
"right",
"type",
"it",
"is",
"dropped",
"after",
"logging",
"an",
"error"
] |
248de38141b228bdb437757155d7fd7dd6e50733
|
https://github.com/rightscale/right_amqp/blob/248de38141b228bdb437757155d7fd7dd6e50733/lib/right_amqp/ha_client/broker_client.rb#L233-L280
|
7,394 |
rightscale/right_amqp
|
lib/right_amqp/ha_client/broker_client.rb
|
RightAMQP.BrokerClient.unsubscribe
|
def unsubscribe(queue_names, &block)
unless failed?
@queues.reject! do |q|
if queue_names.include?(q.name)
begin
logger.info("[stop] Unsubscribing queue #{q.name} on broker #{@alias}")
q.unsubscribe { block.call if block }
rescue StandardError => e
logger.exception("Failed unsubscribing queue #{q.name} on broker #{@alias}", e, :trace)
@exception_stats.track("unsubscribe", e)
block.call if block
end
true
else
false
end
end
end
true
end
|
ruby
|
def unsubscribe(queue_names, &block)
unless failed?
@queues.reject! do |q|
if queue_names.include?(q.name)
begin
logger.info("[stop] Unsubscribing queue #{q.name} on broker #{@alias}")
q.unsubscribe { block.call if block }
rescue StandardError => e
logger.exception("Failed unsubscribing queue #{q.name} on broker #{@alias}", e, :trace)
@exception_stats.track("unsubscribe", e)
block.call if block
end
true
else
false
end
end
end
true
end
|
[
"def",
"unsubscribe",
"(",
"queue_names",
",",
"&",
"block",
")",
"unless",
"failed?",
"@queues",
".",
"reject!",
"do",
"|",
"q",
"|",
"if",
"queue_names",
".",
"include?",
"(",
"q",
".",
"name",
")",
"begin",
"logger",
".",
"info",
"(",
"\"[stop] Unsubscribing queue #{q.name} on broker #{@alias}\"",
")",
"q",
".",
"unsubscribe",
"{",
"block",
".",
"call",
"if",
"block",
"}",
"rescue",
"StandardError",
"=>",
"e",
"logger",
".",
"exception",
"(",
"\"Failed unsubscribing queue #{q.name} on broker #{@alias}\"",
",",
"e",
",",
":trace",
")",
"@exception_stats",
".",
"track",
"(",
"\"unsubscribe\"",
",",
"e",
")",
"block",
".",
"call",
"if",
"block",
"end",
"true",
"else",
"false",
"end",
"end",
"end",
"true",
"end"
] |
Unsubscribe from the specified queues
Silently ignore unknown queues
=== Parameters
queue_names(Array):: Names of queues previously subscribed to
=== Block
Optional block to be called with no parameters when each unsubscribe completes
=== Return
true:: Always return true
|
[
"Unsubscribe",
"from",
"the",
"specified",
"queues",
"Silently",
"ignore",
"unknown",
"queues"
] |
248de38141b228bdb437757155d7fd7dd6e50733
|
https://github.com/rightscale/right_amqp/blob/248de38141b228bdb437757155d7fd7dd6e50733/lib/right_amqp/ha_client/broker_client.rb#L293-L312
|
7,395 |
rightscale/right_amqp
|
lib/right_amqp/ha_client/broker_client.rb
|
RightAMQP.BrokerClient.queue_status
|
def queue_status(queue_names, &block)
return false unless connected?
@queues.each do |q|
if queue_names.include?(q.name)
begin
q.status { |messages, consumers| block.call(q.name, messages, consumers) if block }
rescue StandardError => e
logger.exception("Failed checking status of queue #{q.name} on broker #{@alias}", e, :trace)
@exception_stats.track("queue_status", e)
block.call(q.name, nil, nil) if block
end
end
end
true
end
|
ruby
|
def queue_status(queue_names, &block)
return false unless connected?
@queues.each do |q|
if queue_names.include?(q.name)
begin
q.status { |messages, consumers| block.call(q.name, messages, consumers) if block }
rescue StandardError => e
logger.exception("Failed checking status of queue #{q.name} on broker #{@alias}", e, :trace)
@exception_stats.track("queue_status", e)
block.call(q.name, nil, nil) if block
end
end
end
true
end
|
[
"def",
"queue_status",
"(",
"queue_names",
",",
"&",
"block",
")",
"return",
"false",
"unless",
"connected?",
"@queues",
".",
"each",
"do",
"|",
"q",
"|",
"if",
"queue_names",
".",
"include?",
"(",
"q",
".",
"name",
")",
"begin",
"q",
".",
"status",
"{",
"|",
"messages",
",",
"consumers",
"|",
"block",
".",
"call",
"(",
"q",
".",
"name",
",",
"messages",
",",
"consumers",
")",
"if",
"block",
"}",
"rescue",
"StandardError",
"=>",
"e",
"logger",
".",
"exception",
"(",
"\"Failed checking status of queue #{q.name} on broker #{@alias}\"",
",",
"e",
",",
":trace",
")",
"@exception_stats",
".",
"track",
"(",
"\"queue_status\"",
",",
"e",
")",
"block",
".",
"call",
"(",
"q",
".",
"name",
",",
"nil",
",",
"nil",
")",
"if",
"block",
"end",
"end",
"end",
"true",
"end"
] |
Check status of specified queues
Silently ignore unknown queues
If a queue whose status is being checked does not exist in the broker,
this broker connection will fail and become unusable
=== Parameters
queue_names(Array):: Names of queues previously subscribed to
=== Block
Optional block to be called each time that status for a queue is retrieved with
parameters queue name, message count, and consumer count; the counts are nil
if there was a failure while trying to retrieve them; the block is not called
for queues to which this client is not currently subscribed
=== Return
(Boolean):: true if connected, otherwise false, in which case block never gets called
|
[
"Check",
"status",
"of",
"specified",
"queues",
"Silently",
"ignore",
"unknown",
"queues",
"If",
"a",
"queue",
"whose",
"status",
"is",
"being",
"checked",
"does",
"not",
"exist",
"in",
"the",
"broker",
"this",
"broker",
"connection",
"will",
"fail",
"and",
"become",
"unusable"
] |
248de38141b228bdb437757155d7fd7dd6e50733
|
https://github.com/rightscale/right_amqp/blob/248de38141b228bdb437757155d7fd7dd6e50733/lib/right_amqp/ha_client/broker_client.rb#L353-L367
|
7,396 |
rightscale/right_amqp
|
lib/right_amqp/ha_client/broker_client.rb
|
RightAMQP.BrokerClient.publish
|
def publish(exchange, packet, message, options = {})
return false unless connected?
begin
exchange_options = exchange[:options] || {}
unless options[:no_serialize]
log_data = ""
unless options[:no_log] && logger.level != :debug
re = "RE-" if packet.respond_to?(:tries) && !packet.tries.empty?
log_filter = options[:log_filter] unless logger.level == :debug
log_data = "#{re}SEND #{@alias} #{packet.to_s(log_filter, :send_version)}"
if logger.level == :debug
log_data += ", publish options #{options.inspect}, exchange #{exchange[:name]}, " +
"type #{exchange[:type]}, options #{exchange[:options].inspect}"
end
log_data += ", #{options[:log_data]}" if options[:log_data]
logger.info(log_data) unless log_data.empty?
end
end
delete_amqp_resources(exchange[:type], exchange[:name]) if exchange_options[:declare]
@channel.__send__(exchange[:type], exchange[:name], exchange_options).publish(message, options)
true
rescue StandardError => e
logger.exception("Failed publishing to exchange #{exchange.inspect} on broker #{@alias}", e, :trace)
@exception_stats.track("publish", e)
update_non_delivery_stats("publish failure", e)
false
end
end
|
ruby
|
def publish(exchange, packet, message, options = {})
return false unless connected?
begin
exchange_options = exchange[:options] || {}
unless options[:no_serialize]
log_data = ""
unless options[:no_log] && logger.level != :debug
re = "RE-" if packet.respond_to?(:tries) && !packet.tries.empty?
log_filter = options[:log_filter] unless logger.level == :debug
log_data = "#{re}SEND #{@alias} #{packet.to_s(log_filter, :send_version)}"
if logger.level == :debug
log_data += ", publish options #{options.inspect}, exchange #{exchange[:name]}, " +
"type #{exchange[:type]}, options #{exchange[:options].inspect}"
end
log_data += ", #{options[:log_data]}" if options[:log_data]
logger.info(log_data) unless log_data.empty?
end
end
delete_amqp_resources(exchange[:type], exchange[:name]) if exchange_options[:declare]
@channel.__send__(exchange[:type], exchange[:name], exchange_options).publish(message, options)
true
rescue StandardError => e
logger.exception("Failed publishing to exchange #{exchange.inspect} on broker #{@alias}", e, :trace)
@exception_stats.track("publish", e)
update_non_delivery_stats("publish failure", e)
false
end
end
|
[
"def",
"publish",
"(",
"exchange",
",",
"packet",
",",
"message",
",",
"options",
"=",
"{",
"}",
")",
"return",
"false",
"unless",
"connected?",
"begin",
"exchange_options",
"=",
"exchange",
"[",
":options",
"]",
"||",
"{",
"}",
"unless",
"options",
"[",
":no_serialize",
"]",
"log_data",
"=",
"\"\"",
"unless",
"options",
"[",
":no_log",
"]",
"&&",
"logger",
".",
"level",
"!=",
":debug",
"re",
"=",
"\"RE-\"",
"if",
"packet",
".",
"respond_to?",
"(",
":tries",
")",
"&&",
"!",
"packet",
".",
"tries",
".",
"empty?",
"log_filter",
"=",
"options",
"[",
":log_filter",
"]",
"unless",
"logger",
".",
"level",
"==",
":debug",
"log_data",
"=",
"\"#{re}SEND #{@alias} #{packet.to_s(log_filter, :send_version)}\"",
"if",
"logger",
".",
"level",
"==",
":debug",
"log_data",
"+=",
"\", publish options #{options.inspect}, exchange #{exchange[:name]}, \"",
"+",
"\"type #{exchange[:type]}, options #{exchange[:options].inspect}\"",
"end",
"log_data",
"+=",
"\", #{options[:log_data]}\"",
"if",
"options",
"[",
":log_data",
"]",
"logger",
".",
"info",
"(",
"log_data",
")",
"unless",
"log_data",
".",
"empty?",
"end",
"end",
"delete_amqp_resources",
"(",
"exchange",
"[",
":type",
"]",
",",
"exchange",
"[",
":name",
"]",
")",
"if",
"exchange_options",
"[",
":declare",
"]",
"@channel",
".",
"__send__",
"(",
"exchange",
"[",
":type",
"]",
",",
"exchange",
"[",
":name",
"]",
",",
"exchange_options",
")",
".",
"publish",
"(",
"message",
",",
"options",
")",
"true",
"rescue",
"StandardError",
"=>",
"e",
"logger",
".",
"exception",
"(",
"\"Failed publishing to exchange #{exchange.inspect} on broker #{@alias}\"",
",",
"e",
",",
":trace",
")",
"@exception_stats",
".",
"track",
"(",
"\"publish\"",
",",
"e",
")",
"update_non_delivery_stats",
"(",
"\"publish failure\"",
",",
"e",
")",
"false",
"end",
"end"
] |
Publish message to AMQP exchange
=== Parameters
exchange(Hash):: AMQP exchange to subscribe to with keys :type, :name, and :options,
which are the standard AMQP ones plus
:no_declare(Boolean):: Whether to skip declaring this exchange or queue on the broker
to cause its creation; for use when caller does not have create permission or
knows the object already exists and wants to avoid declare overhead
:declare(Boolean):: Whether to delete this exchange or queue from the AMQP cache
to force it to be declared on the broker and thus be created if it does not exist
packet(Packet):: Message to serialize and publish (must respond to :to_s(log_filter,
protocol_version) unless :no_serialize specified; if responds to :type, :from, :token,
and/or :one_way, these value are used if this message is returned as non-deliverable)
message(String):: Serialized message to be published
options(Hash):: Publish options -- standard AMQP ones plus
:no_serialize(Boolean):: Do not serialize packet because it is already serialized
:log_filter(Array(Symbol)):: Filters to be applied in to_s when logging packet to :info
:log_data(String):: Additional data to display at end of log entry
:no_log(Boolean):: Disable publish logging unless debug level
=== Return
(Boolean):: true if publish successfully, otherwise false
|
[
"Publish",
"message",
"to",
"AMQP",
"exchange"
] |
248de38141b228bdb437757155d7fd7dd6e50733
|
https://github.com/rightscale/right_amqp/blob/248de38141b228bdb437757155d7fd7dd6e50733/lib/right_amqp/ha_client/broker_client.rb#L391-L418
|
7,397 |
rightscale/right_amqp
|
lib/right_amqp/ha_client/broker_client.rb
|
RightAMQP.BrokerClient.close
|
def close(propagate = true, normal = true, log = true, &block)
final_status = normal ? :closed : :failed
if ![:closed, :failed].include?(@status)
begin
logger.info("[stop] Closed connection to broker #{@alias}") if log
update_status(final_status) if propagate
@connection.close do
@status = final_status
yield if block_given?
end
rescue StandardError => e
logger.exception("Failed to close broker #{@alias}", e, :trace)
@exception_stats.track("close", e)
@status = final_status
yield if block_given?
end
else
@status = final_status
yield if block_given?
end
true
end
|
ruby
|
def close(propagate = true, normal = true, log = true, &block)
final_status = normal ? :closed : :failed
if ![:closed, :failed].include?(@status)
begin
logger.info("[stop] Closed connection to broker #{@alias}") if log
update_status(final_status) if propagate
@connection.close do
@status = final_status
yield if block_given?
end
rescue StandardError => e
logger.exception("Failed to close broker #{@alias}", e, :trace)
@exception_stats.track("close", e)
@status = final_status
yield if block_given?
end
else
@status = final_status
yield if block_given?
end
true
end
|
[
"def",
"close",
"(",
"propagate",
"=",
"true",
",",
"normal",
"=",
"true",
",",
"log",
"=",
"true",
",",
"&",
"block",
")",
"final_status",
"=",
"normal",
"?",
":closed",
":",
":failed",
"if",
"!",
"[",
":closed",
",",
":failed",
"]",
".",
"include?",
"(",
"@status",
")",
"begin",
"logger",
".",
"info",
"(",
"\"[stop] Closed connection to broker #{@alias}\"",
")",
"if",
"log",
"update_status",
"(",
"final_status",
")",
"if",
"propagate",
"@connection",
".",
"close",
"do",
"@status",
"=",
"final_status",
"yield",
"if",
"block_given?",
"end",
"rescue",
"StandardError",
"=>",
"e",
"logger",
".",
"exception",
"(",
"\"Failed to close broker #{@alias}\"",
",",
"e",
",",
":trace",
")",
"@exception_stats",
".",
"track",
"(",
"\"close\"",
",",
"e",
")",
"@status",
"=",
"final_status",
"yield",
"if",
"block_given?",
"end",
"else",
"@status",
"=",
"final_status",
"yield",
"if",
"block_given?",
"end",
"true",
"end"
] |
Close broker connection
=== Parameters
propagate(Boolean):: Whether to propagate connection status updates, defaults to true
normal(Boolean):: Whether this is a normal close vs. a failed connection, defaults to true
log(Boolean):: Whether to log that closing, defaults to true
=== Block
Optional block with no parameters to be called after connection closed
=== Return
true:: Always return true
|
[
"Close",
"broker",
"connection"
] |
248de38141b228bdb437757155d7fd7dd6e50733
|
https://github.com/rightscale/right_amqp/blob/248de38141b228bdb437757155d7fd7dd6e50733/lib/right_amqp/ha_client/broker_client.rb#L477-L498
|
7,398 |
rightscale/right_amqp
|
lib/right_amqp/ha_client/broker_client.rb
|
RightAMQP.BrokerClient.connect
|
def connect(address, reconnect_interval)
begin
logger.info("[setup] Connecting to broker #{@identity}, alias #{@alias}")
@status = :connecting
@connection = AMQP.connect(:user => @options[:user],
:pass => @options[:pass],
:vhost => @options[:vhost],
:host => address[:host],
:port => address[:port],
:ssl => @options[:ssl],
:identity => @identity,
:insist => @options[:insist] || false,
:heartbeat => @options[:heartbeat],
:reconnect_delay => lambda { rand(reconnect_interval) },
:reconnect_interval => reconnect_interval)
@channel = MQ.new(@connection)
@channel.__send__(:connection).connection_status { |status| update_status(status) }
@channel.prefetch(@options[:prefetch]) if @options[:prefetch]
@channel.return_message { |header, message| handle_return(header, message) }
rescue StandardError => e
@status = :failed
@failure_stats.update
logger.exception("Failed connecting to broker #{@alias}", e, :trace)
@exception_stats.track("connect", e)
@connection.close if @connection
end
end
|
ruby
|
def connect(address, reconnect_interval)
begin
logger.info("[setup] Connecting to broker #{@identity}, alias #{@alias}")
@status = :connecting
@connection = AMQP.connect(:user => @options[:user],
:pass => @options[:pass],
:vhost => @options[:vhost],
:host => address[:host],
:port => address[:port],
:ssl => @options[:ssl],
:identity => @identity,
:insist => @options[:insist] || false,
:heartbeat => @options[:heartbeat],
:reconnect_delay => lambda { rand(reconnect_interval) },
:reconnect_interval => reconnect_interval)
@channel = MQ.new(@connection)
@channel.__send__(:connection).connection_status { |status| update_status(status) }
@channel.prefetch(@options[:prefetch]) if @options[:prefetch]
@channel.return_message { |header, message| handle_return(header, message) }
rescue StandardError => e
@status = :failed
@failure_stats.update
logger.exception("Failed connecting to broker #{@alias}", e, :trace)
@exception_stats.track("connect", e)
@connection.close if @connection
end
end
|
[
"def",
"connect",
"(",
"address",
",",
"reconnect_interval",
")",
"begin",
"logger",
".",
"info",
"(",
"\"[setup] Connecting to broker #{@identity}, alias #{@alias}\"",
")",
"@status",
"=",
":connecting",
"@connection",
"=",
"AMQP",
".",
"connect",
"(",
":user",
"=>",
"@options",
"[",
":user",
"]",
",",
":pass",
"=>",
"@options",
"[",
":pass",
"]",
",",
":vhost",
"=>",
"@options",
"[",
":vhost",
"]",
",",
":host",
"=>",
"address",
"[",
":host",
"]",
",",
":port",
"=>",
"address",
"[",
":port",
"]",
",",
":ssl",
"=>",
"@options",
"[",
":ssl",
"]",
",",
":identity",
"=>",
"@identity",
",",
":insist",
"=>",
"@options",
"[",
":insist",
"]",
"||",
"false",
",",
":heartbeat",
"=>",
"@options",
"[",
":heartbeat",
"]",
",",
":reconnect_delay",
"=>",
"lambda",
"{",
"rand",
"(",
"reconnect_interval",
")",
"}",
",",
":reconnect_interval",
"=>",
"reconnect_interval",
")",
"@channel",
"=",
"MQ",
".",
"new",
"(",
"@connection",
")",
"@channel",
".",
"__send__",
"(",
":connection",
")",
".",
"connection_status",
"{",
"|",
"status",
"|",
"update_status",
"(",
"status",
")",
"}",
"@channel",
".",
"prefetch",
"(",
"@options",
"[",
":prefetch",
"]",
")",
"if",
"@options",
"[",
":prefetch",
"]",
"@channel",
".",
"return_message",
"{",
"|",
"header",
",",
"message",
"|",
"handle_return",
"(",
"header",
",",
"message",
")",
"}",
"rescue",
"StandardError",
"=>",
"e",
"@status",
"=",
":failed",
"@failure_stats",
".",
"update",
"logger",
".",
"exception",
"(",
"\"Failed connecting to broker #{@alias}\"",
",",
"e",
",",
":trace",
")",
"@exception_stats",
".",
"track",
"(",
"\"connect\"",
",",
"e",
")",
"@connection",
".",
"close",
"if",
"@connection",
"end",
"end"
] |
Connect to broker and register for status updates
Also set prefetch value if specified and setup for message returns
=== Parameters
address(Hash):: Broker address
:host(String:: IP host name or address
:port(Integer):: TCP port number for individual broker
:index(String):: Unique index for broker within given set for use in forming alias
reconnect_interval(Integer):: Number of seconds between reconnect attempts
=== Return
true:: Always return true
|
[
"Connect",
"to",
"broker",
"and",
"register",
"for",
"status",
"updates",
"Also",
"set",
"prefetch",
"value",
"if",
"specified",
"and",
"setup",
"for",
"message",
"returns"
] |
248de38141b228bdb437757155d7fd7dd6e50733
|
https://github.com/rightscale/right_amqp/blob/248de38141b228bdb437757155d7fd7dd6e50733/lib/right_amqp/ha_client/broker_client.rb#L594-L620
|
7,399 |
rightscale/right_amqp
|
lib/right_amqp/ha_client/broker_client.rb
|
RightAMQP.BrokerClient.receive
|
def receive(queue, header, message, options, &block)
begin
if options[:no_unserialize] || @serializer.nil?
execute_callback(block, @identity, message, header)
elsif message == "nil"
# This happens as part of connecting an instance agent to a broker prior to version 13
header.ack if options[:ack]
logger.debug("RECV #{@alias} nil message ignored")
elsif (packet = unserialize(queue, message, options))
execute_callback(block, @identity, packet, header)
elsif options[:ack]
# Need to ack empty packet since no callback is being made
header.ack
end
true
rescue StandardError => e
header.ack if options[:ack]
logger.exception("Failed receiving message from queue #{queue.inspect} on broker #{@alias}", e, :trace)
@exception_stats.track("receive", e)
update_non_delivery_stats("receive failure", e)
end
end
|
ruby
|
def receive(queue, header, message, options, &block)
begin
if options[:no_unserialize] || @serializer.nil?
execute_callback(block, @identity, message, header)
elsif message == "nil"
# This happens as part of connecting an instance agent to a broker prior to version 13
header.ack if options[:ack]
logger.debug("RECV #{@alias} nil message ignored")
elsif (packet = unserialize(queue, message, options))
execute_callback(block, @identity, packet, header)
elsif options[:ack]
# Need to ack empty packet since no callback is being made
header.ack
end
true
rescue StandardError => e
header.ack if options[:ack]
logger.exception("Failed receiving message from queue #{queue.inspect} on broker #{@alias}", e, :trace)
@exception_stats.track("receive", e)
update_non_delivery_stats("receive failure", e)
end
end
|
[
"def",
"receive",
"(",
"queue",
",",
"header",
",",
"message",
",",
"options",
",",
"&",
"block",
")",
"begin",
"if",
"options",
"[",
":no_unserialize",
"]",
"||",
"@serializer",
".",
"nil?",
"execute_callback",
"(",
"block",
",",
"@identity",
",",
"message",
",",
"header",
")",
"elsif",
"message",
"==",
"\"nil\"",
"# This happens as part of connecting an instance agent to a broker prior to version 13",
"header",
".",
"ack",
"if",
"options",
"[",
":ack",
"]",
"logger",
".",
"debug",
"(",
"\"RECV #{@alias} nil message ignored\"",
")",
"elsif",
"(",
"packet",
"=",
"unserialize",
"(",
"queue",
",",
"message",
",",
"options",
")",
")",
"execute_callback",
"(",
"block",
",",
"@identity",
",",
"packet",
",",
"header",
")",
"elsif",
"options",
"[",
":ack",
"]",
"# Need to ack empty packet since no callback is being made",
"header",
".",
"ack",
"end",
"true",
"rescue",
"StandardError",
"=>",
"e",
"header",
".",
"ack",
"if",
"options",
"[",
":ack",
"]",
"logger",
".",
"exception",
"(",
"\"Failed receiving message from queue #{queue.inspect} on broker #{@alias}\"",
",",
"e",
",",
":trace",
")",
"@exception_stats",
".",
"track",
"(",
"\"receive\"",
",",
"e",
")",
"update_non_delivery_stats",
"(",
"\"receive failure\"",
",",
"e",
")",
"end",
"end"
] |
Receive message by optionally unserializing it, passing it to the callback, and optionally
acknowledging it
=== Parameters
queue(String):: Name of queue
header(AMQP::Protocol::Header):: Message header
message(String):: Serialized packet
options(Hash):: Subscribe options
:ack(Boolean):: Whether caller takes responsibility for explicitly acknowledging each
message received, defaults to implicit acknowledgement in AMQP as part of message receipt
:no_unserialize(Boolean):: Do not unserialize message, this is an escape for special
situations like enrollment, also implicitly disables receive filtering and logging;
this option is implicitly invoked if initialize without a serializer
=== Block
Block with following parameters to be called with received message
identity(String):: Serialized identity of broker delivering the message
message(Packet|String):: Message received, which is unserialized unless :no_unserialize was specified
header(AMQP::Protocol::Header):: Message header (optional block parameter)
=== Return
true:: Always return true
|
[
"Receive",
"message",
"by",
"optionally",
"unserializing",
"it",
"passing",
"it",
"to",
"the",
"callback",
"and",
"optionally",
"acknowledging",
"it"
] |
248de38141b228bdb437757155d7fd7dd6e50733
|
https://github.com/rightscale/right_amqp/blob/248de38141b228bdb437757155d7fd7dd6e50733/lib/right_amqp/ha_client/broker_client.rb#L644-L665
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.