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
|
---|---|---|---|---|---|---|---|---|---|---|---|
6,400 |
barkerest/shells
|
lib/shells/shell_base/hooks.rb
|
Shells.ShellBase.run_hook
|
def run_hook(hook_name, *args)
list = self.class.all_hooks(hook_name)
shell = self
list.each do |hook|
result = hook.call(shell, *args)
return :break if result == :break
end
list.any?
end
|
ruby
|
def run_hook(hook_name, *args)
list = self.class.all_hooks(hook_name)
shell = self
list.each do |hook|
result = hook.call(shell, *args)
return :break if result == :break
end
list.any?
end
|
[
"def",
"run_hook",
"(",
"hook_name",
",",
"*",
"args",
")",
"list",
"=",
"self",
".",
"class",
".",
"all_hooks",
"(",
"hook_name",
")",
"shell",
"=",
"self",
"list",
".",
"each",
"do",
"|",
"hook",
"|",
"result",
"=",
"hook",
".",
"call",
"(",
"shell",
",",
"args",
")",
"return",
":break",
"if",
"result",
"==",
":break",
"end",
"list",
".",
"any?",
"end"
] |
Runs a hook in the current shell instance.
The hook method is passed the shell as the first argument then the arguments passed to this method.
Return false unless the hook was executed. Returns :break if one of the hook methods returns :break.
|
[
"Runs",
"a",
"hook",
"in",
"the",
"current",
"shell",
"instance",
"."
] |
674a0254f48cea01b0ae8979933f13892e398506
|
https://github.com/barkerest/shells/blob/674a0254f48cea01b0ae8979933f13892e398506/lib/shells/shell_base/hooks.rb#L66-L74
|
6,401 |
mrsimonfletcher/roroacms
|
app/controllers/roroacms/application_controller.rb
|
Roroacms.ApplicationController.add_breadcrumb
|
def add_breadcrumb(name, url = 'javascript:;', atts = {})
hash = { name: name, url: url, atts: atts }
@breadcrumbs << hash
end
|
ruby
|
def add_breadcrumb(name, url = 'javascript:;', atts = {})
hash = { name: name, url: url, atts: atts }
@breadcrumbs << hash
end
|
[
"def",
"add_breadcrumb",
"(",
"name",
",",
"url",
"=",
"'javascript:;'",
",",
"atts",
"=",
"{",
"}",
")",
"hash",
"=",
"{",
"name",
":",
"name",
",",
"url",
":",
"url",
",",
"atts",
":",
"atts",
"}",
"@breadcrumbs",
"<<",
"hash",
"end"
] |
add a breadcrumb to the breadcrumb hash
|
[
"add",
"a",
"breadcrumb",
"to",
"the",
"breadcrumb",
"hash"
] |
62654a2f2a48e3adb3105f4dafb6e315b460eaf4
|
https://github.com/mrsimonfletcher/roroacms/blob/62654a2f2a48e3adb3105f4dafb6e315b460eaf4/app/controllers/roroacms/application_controller.rb#L128-L131
|
6,402 |
mrsimonfletcher/roroacms
|
app/controllers/roroacms/application_controller.rb
|
Roroacms.ApplicationController.authorize_demo
|
def authorize_demo
if !request.xhr? && !request.get? && ( !current_user.blank? && current_user.username.downcase == 'demo' && Setting.get('demonstration_mode') == 'Y' )
redirect_to :back, flash: { error: I18n.t('generic.demo_notification') } and return
end
render :inline => 'demo' and return if params[:action] == 'save_menu' && !current_user.blank? && current_user.username.downcase == 'demo' && Setting.get('demonstration_mode') == 'Y'
end
|
ruby
|
def authorize_demo
if !request.xhr? && !request.get? && ( !current_user.blank? && current_user.username.downcase == 'demo' && Setting.get('demonstration_mode') == 'Y' )
redirect_to :back, flash: { error: I18n.t('generic.demo_notification') } and return
end
render :inline => 'demo' and return if params[:action] == 'save_menu' && !current_user.blank? && current_user.username.downcase == 'demo' && Setting.get('demonstration_mode') == 'Y'
end
|
[
"def",
"authorize_demo",
"if",
"!",
"request",
".",
"xhr?",
"&&",
"!",
"request",
".",
"get?",
"&&",
"(",
"!",
"current_user",
".",
"blank?",
"&&",
"current_user",
".",
"username",
".",
"downcase",
"==",
"'demo'",
"&&",
"Setting",
".",
"get",
"(",
"'demonstration_mode'",
")",
"==",
"'Y'",
")",
"redirect_to",
":back",
",",
"flash",
":",
"{",
"error",
":",
"I18n",
".",
"t",
"(",
"'generic.demo_notification'",
")",
"}",
"and",
"return",
"end",
"render",
":inline",
"=>",
"'demo'",
"and",
"return",
"if",
"params",
"[",
":action",
"]",
"==",
"'save_menu'",
"&&",
"!",
"current_user",
".",
"blank?",
"&&",
"current_user",
".",
"username",
".",
"downcase",
"==",
"'demo'",
"&&",
"Setting",
".",
"get",
"(",
"'demonstration_mode'",
")",
"==",
"'Y'",
"end"
] |
restricts any CRUD functions if you are logged in as the username of demo and you have demonstration mode turned on
|
[
"restricts",
"any",
"CRUD",
"functions",
"if",
"you",
"are",
"logged",
"in",
"as",
"the",
"username",
"of",
"demo",
"and",
"you",
"have",
"demonstration",
"mode",
"turned",
"on"
] |
62654a2f2a48e3adb3105f4dafb6e315b460eaf4
|
https://github.com/mrsimonfletcher/roroacms/blob/62654a2f2a48e3adb3105f4dafb6e315b460eaf4/app/controllers/roroacms/application_controller.rb#L135-L142
|
6,403 |
mrsimonfletcher/roroacms
|
app/controllers/roroacms/application_controller.rb
|
Roroacms.ApplicationController.mark_required
|
def mark_required(object, attribute)
"*" if object.class.validators_on(attribute).map(&:class).include? ActiveModel::Validations::PresenceValidator
end
|
ruby
|
def mark_required(object, attribute)
"*" if object.class.validators_on(attribute).map(&:class).include? ActiveModel::Validations::PresenceValidator
end
|
[
"def",
"mark_required",
"(",
"object",
",",
"attribute",
")",
"\"*\"",
"if",
"object",
".",
"class",
".",
"validators_on",
"(",
"attribute",
")",
".",
"map",
"(",
":class",
")",
".",
"include?",
"ActiveModel",
"::",
"Validations",
"::",
"PresenceValidator",
"end"
] |
Adds an asterix to the field if it is required.
|
[
"Adds",
"an",
"asterix",
"to",
"the",
"field",
"if",
"it",
"is",
"required",
"."
] |
62654a2f2a48e3adb3105f4dafb6e315b460eaf4
|
https://github.com/mrsimonfletcher/roroacms/blob/62654a2f2a48e3adb3105f4dafb6e315b460eaf4/app/controllers/roroacms/application_controller.rb#L146-L148
|
6,404 |
mayth/Chizuru
|
lib/chizuru/user_stream.rb
|
Chizuru.UserStream.connect
|
def connect
uri = URI.parse("https://userstream.twitter.com/2/user.json?track=#{@screen_name}")
https = Net::HTTP.new(uri.host, uri.port)
https.use_ssl = true
https.ca_file = @ca_file
https.verify_mode = OpenSSL::SSL::VERIFY_PEER
https.verify_depth = 5
https.start do |https|
request = Net::HTTP::Get.new(uri.request_uri,
"User-Agent" => @user_agent,
"Accept-Encoding" => "identity")
request.oauth!(https, @credential.consumer, @credential.access_token)
buf = ""
https.request(request) do |response|
response.read_body do |chunk|
buf << chunk
while ((line = buf[/.+?(\r\n)+/m]) != nil)
begin
buf.sub!(line, "")
line.strip!
status = Yajl::Parser.parse(line)
rescue
break
end
yield status
end
end
end
end
end
|
ruby
|
def connect
uri = URI.parse("https://userstream.twitter.com/2/user.json?track=#{@screen_name}")
https = Net::HTTP.new(uri.host, uri.port)
https.use_ssl = true
https.ca_file = @ca_file
https.verify_mode = OpenSSL::SSL::VERIFY_PEER
https.verify_depth = 5
https.start do |https|
request = Net::HTTP::Get.new(uri.request_uri,
"User-Agent" => @user_agent,
"Accept-Encoding" => "identity")
request.oauth!(https, @credential.consumer, @credential.access_token)
buf = ""
https.request(request) do |response|
response.read_body do |chunk|
buf << chunk
while ((line = buf[/.+?(\r\n)+/m]) != nil)
begin
buf.sub!(line, "")
line.strip!
status = Yajl::Parser.parse(line)
rescue
break
end
yield status
end
end
end
end
end
|
[
"def",
"connect",
"uri",
"=",
"URI",
".",
"parse",
"(",
"\"https://userstream.twitter.com/2/user.json?track=#{@screen_name}\"",
")",
"https",
"=",
"Net",
"::",
"HTTP",
".",
"new",
"(",
"uri",
".",
"host",
",",
"uri",
".",
"port",
")",
"https",
".",
"use_ssl",
"=",
"true",
"https",
".",
"ca_file",
"=",
"@ca_file",
"https",
".",
"verify_mode",
"=",
"OpenSSL",
"::",
"SSL",
"::",
"VERIFY_PEER",
"https",
".",
"verify_depth",
"=",
"5",
"https",
".",
"start",
"do",
"|",
"https",
"|",
"request",
"=",
"Net",
"::",
"HTTP",
"::",
"Get",
".",
"new",
"(",
"uri",
".",
"request_uri",
",",
"\"User-Agent\"",
"=>",
"@user_agent",
",",
"\"Accept-Encoding\"",
"=>",
"\"identity\"",
")",
"request",
".",
"oauth!",
"(",
"https",
",",
"@credential",
".",
"consumer",
",",
"@credential",
".",
"access_token",
")",
"buf",
"=",
"\"\"",
"https",
".",
"request",
"(",
"request",
")",
"do",
"|",
"response",
"|",
"response",
".",
"read_body",
"do",
"|",
"chunk",
"|",
"buf",
"<<",
"chunk",
"while",
"(",
"(",
"line",
"=",
"buf",
"[",
"/",
"\\r",
"\\n",
"/m",
"]",
")",
"!=",
"nil",
")",
"begin",
"buf",
".",
"sub!",
"(",
"line",
",",
"\"\"",
")",
"line",
".",
"strip!",
"status",
"=",
"Yajl",
"::",
"Parser",
".",
"parse",
"(",
"line",
")",
"rescue",
"break",
"end",
"yield",
"status",
"end",
"end",
"end",
"end",
"end"
] |
Connects to UserStreaming API.
The block will be given the events or statuses from Twitter API in JSON format.
|
[
"Connects",
"to",
"UserStreaming",
"API",
"."
] |
361bc595c2e4257313d134fe0f4f4cca65c88383
|
https://github.com/mayth/Chizuru/blob/361bc595c2e4257313d134fe0f4f4cca65c88383/lib/chizuru/user_stream.rb#L42-L75
|
6,405 |
rolandasb/gogcom
|
lib/gogcom/game.rb
|
Gogcom.Game.fetch
|
def fetch()
name = urlfy(@name)
page = Net::HTTP.get(URI("http://www.gog.com/game/" + name))
data = JSON.parse(page[/(?<=var gogData = )(.*)(?=;)/,1])
data
end
|
ruby
|
def fetch()
name = urlfy(@name)
page = Net::HTTP.get(URI("http://www.gog.com/game/" + name))
data = JSON.parse(page[/(?<=var gogData = )(.*)(?=;)/,1])
data
end
|
[
"def",
"fetch",
"(",
")",
"name",
"=",
"urlfy",
"(",
"@name",
")",
"page",
"=",
"Net",
"::",
"HTTP",
".",
"get",
"(",
"URI",
"(",
"\"http://www.gog.com/game/\"",
"+",
"name",
")",
")",
"data",
"=",
"JSON",
".",
"parse",
"(",
"page",
"[",
"/",
"/",
",",
"1",
"]",
")",
"data",
"end"
] |
Fetches raw data and parses as JSON object
@return [Object]
|
[
"Fetches",
"raw",
"data",
"and",
"parses",
"as",
"JSON",
"object"
] |
015de453bb214c9ccb51665ecadce1367e6d987d
|
https://github.com/rolandasb/gogcom/blob/015de453bb214c9ccb51665ecadce1367e6d987d/lib/gogcom/game.rb#L18-L23
|
6,406 |
rolandasb/gogcom
|
lib/gogcom/game.rb
|
Gogcom.Game.parse
|
def parse(data)
game = GameItem.new(get_title(data), get_genres(data),
get_download_size(data), get_release_date(data), get_description(data),
get_price(data), get_avg_rating(data), get_avg_ratings_count(data),
get_platforms(data), get_languages(data), get_developer(data),
get_publisher(data), get_modes(data), get_bonus_content(data),
get_reviews(data), get_pegi_age(data))
game
end
|
ruby
|
def parse(data)
game = GameItem.new(get_title(data), get_genres(data),
get_download_size(data), get_release_date(data), get_description(data),
get_price(data), get_avg_rating(data), get_avg_ratings_count(data),
get_platforms(data), get_languages(data), get_developer(data),
get_publisher(data), get_modes(data), get_bonus_content(data),
get_reviews(data), get_pegi_age(data))
game
end
|
[
"def",
"parse",
"(",
"data",
")",
"game",
"=",
"GameItem",
".",
"new",
"(",
"get_title",
"(",
"data",
")",
",",
"get_genres",
"(",
"data",
")",
",",
"get_download_size",
"(",
"data",
")",
",",
"get_release_date",
"(",
"data",
")",
",",
"get_description",
"(",
"data",
")",
",",
"get_price",
"(",
"data",
")",
",",
"get_avg_rating",
"(",
"data",
")",
",",
"get_avg_ratings_count",
"(",
"data",
")",
",",
"get_platforms",
"(",
"data",
")",
",",
"get_languages",
"(",
"data",
")",
",",
"get_developer",
"(",
"data",
")",
",",
"get_publisher",
"(",
"data",
")",
",",
"get_modes",
"(",
"data",
")",
",",
"get_bonus_content",
"(",
"data",
")",
",",
"get_reviews",
"(",
"data",
")",
",",
"get_pegi_age",
"(",
"data",
")",
")",
"game",
"end"
] |
Parses raw data and returns game item.
@param [Object]
@return [Struct]
|
[
"Parses",
"raw",
"data",
"and",
"returns",
"game",
"item",
"."
] |
015de453bb214c9ccb51665ecadce1367e6d987d
|
https://github.com/rolandasb/gogcom/blob/015de453bb214c9ccb51665ecadce1367e6d987d/lib/gogcom/game.rb#L29-L38
|
6,407 |
nrser/nrser.rb
|
lib/nrser/errors/nicer_error.rb
|
NRSER.NicerError.format_message_segment
|
def format_message_segment segment
return segment.to_summary if segment.respond_to?( :to_summary )
return segment if String === segment
# TODO Do better!
segment.inspect
end
|
ruby
|
def format_message_segment segment
return segment.to_summary if segment.respond_to?( :to_summary )
return segment if String === segment
# TODO Do better!
segment.inspect
end
|
[
"def",
"format_message_segment",
"segment",
"return",
"segment",
".",
"to_summary",
"if",
"segment",
".",
"respond_to?",
"(",
":to_summary",
")",
"return",
"segment",
"if",
"String",
"===",
"segment",
"# TODO Do better!",
"segment",
".",
"inspect",
"end"
] |
Construct a nicer error.
@param [Array] message
Main message segments. See {#format_message} and {#format_message_segment}
for an understanding of how they are, well, formatted.
@param [Binding?] binding
When provided any details string will be rendered using it's
{Binding#erb} method.
@param [nil | String | Proc<()=>String> | #to_s] details
Additional text details to add to the extended message. When:
1. `nil` - no details will be added.
2. `String` - the value will be used. If `binding:` is provided, it
will be rendered against it as ERB.
3. `Proc<()=>String>` - if and when an extended message is needed
the proc will be called, and the resulting string will be used
as in (2).
4. `#to_s` - catch all; if and when an extended message is needed
`#to_s` will be called on the value and the result will be used
as in (2).
@param [Hash<Symbol, VALUE>] context
Any additional names and values to dump with an extended message.
#initialize
Format a segment of the error message.
Strings are simply returned. Other things are inspected (for now).
@param [Object] segment
The segment.
@return [String]
The formatted string for the segment.
@todo
This should talk to config when that comes about to find out how to
dump things.
|
[
"Construct",
"a",
"nicer",
"error",
"."
] |
7db9a729ec65894dfac13fd50851beae8b809738
|
https://github.com/nrser/nrser.rb/blob/7db9a729ec65894dfac13fd50851beae8b809738/lib/nrser/errors/nicer_error.rb#L158-L165
|
6,408 |
nrser/nrser.rb
|
lib/nrser/errors/nicer_error.rb
|
NRSER.NicerError.to_s
|
def to_s extended: nil
# The way to get the superclass' message
message = super()
# If `extended` is explicitly `false` then just return that
return message if extended == false
# Otherwise, see if the extended message was explicitly requested,
# of if we're configured to provide it as well.
#
# Either way, don't add it it's empty.
#
if (extended || add_extended_message?) &&
!extended_message.empty?
message + "\n\n" + extended_message
else
message
end
end
|
ruby
|
def to_s extended: nil
# The way to get the superclass' message
message = super()
# If `extended` is explicitly `false` then just return that
return message if extended == false
# Otherwise, see if the extended message was explicitly requested,
# of if we're configured to provide it as well.
#
# Either way, don't add it it's empty.
#
if (extended || add_extended_message?) &&
!extended_message.empty?
message + "\n\n" + extended_message
else
message
end
end
|
[
"def",
"to_s",
"extended",
":",
"nil",
"# The way to get the superclass' message",
"message",
"=",
"super",
"(",
")",
"# If `extended` is explicitly `false` then just return that",
"return",
"message",
"if",
"extended",
"==",
"false",
"# Otherwise, see if the extended message was explicitly requested,",
"# of if we're configured to provide it as well.",
"# ",
"# Either way, don't add it it's empty.",
"# ",
"if",
"(",
"extended",
"||",
"add_extended_message?",
")",
"&&",
"!",
"extended_message",
".",
"empty?",
"message",
"+",
"\"\\n\\n\"",
"+",
"extended_message",
"else",
"message",
"end",
"end"
] |
Get the message or the extended message.
@note
This is a bit weird, having to do with what I can tell about the
built-in errors and how they handle their message - they have *no*
instance variables, and seem to rely on `#to_s` to get the message
out of C-land, however that works.
{Exception#message} just forwards here, so I overrode that with
{#message} to just get the *summary/super-message* from this method.
@param [Boolean?] extended
Flag to explicitly control summary/super or extended message:
1. `nil` - call {#add_extended_message?} to decide (default).
2. `false` - return just the *summary/super-message*.
3. `true` - always add the *extended message* (unless it's empty).
@return [String]
|
[
"Get",
"the",
"message",
"or",
"the",
"extended",
"message",
"."
] |
7db9a729ec65894dfac13fd50851beae8b809738
|
https://github.com/nrser/nrser.rb/blob/7db9a729ec65894dfac13fd50851beae8b809738/lib/nrser/errors/nicer_error.rb#L319-L337
|
6,409 |
timotheeguerin/clin
|
lib/clin/command_mixin/core.rb
|
Clin::CommandMixin::Core.ClassMethods.inherited
|
def inherited(subclass)
subclass._arguments = []
subclass._description = ''
subclass._abstract = false
subclass._skip_options = false
subclass._exe_name = @_exe_name
subclass._default_priority = @_default_priority.to_f / 2
subclass._priority = 0
super
end
|
ruby
|
def inherited(subclass)
subclass._arguments = []
subclass._description = ''
subclass._abstract = false
subclass._skip_options = false
subclass._exe_name = @_exe_name
subclass._default_priority = @_default_priority.to_f / 2
subclass._priority = 0
super
end
|
[
"def",
"inherited",
"(",
"subclass",
")",
"subclass",
".",
"_arguments",
"=",
"[",
"]",
"subclass",
".",
"_description",
"=",
"''",
"subclass",
".",
"_abstract",
"=",
"false",
"subclass",
".",
"_skip_options",
"=",
"false",
"subclass",
".",
"_exe_name",
"=",
"@_exe_name",
"subclass",
".",
"_default_priority",
"=",
"@_default_priority",
".",
"to_f",
"/",
"2",
"subclass",
".",
"_priority",
"=",
"0",
"super",
"end"
] |
Trigger when a class inherit this class
Rest class_attributes that should not be shared with subclass
@param subclass [Clin::Command]
|
[
"Trigger",
"when",
"a",
"class",
"inherit",
"this",
"class",
"Rest",
"class_attributes",
"that",
"should",
"not",
"be",
"shared",
"with",
"subclass"
] |
43d41c47f9c652065ab7ce636d48a9fe1754135e
|
https://github.com/timotheeguerin/clin/blob/43d41c47f9c652065ab7ce636d48a9fe1754135e/lib/clin/command_mixin/core.rb#L24-L33
|
6,410 |
timotheeguerin/clin
|
lib/clin/command_mixin/core.rb
|
Clin::CommandMixin::Core.ClassMethods.arguments
|
def arguments(args = nil)
return @_arguments if args.nil?
@_arguments = []
[*args].map(&:split).flatten.each do |arg|
@_arguments << Clin::Argument.new(arg)
end
end
|
ruby
|
def arguments(args = nil)
return @_arguments if args.nil?
@_arguments = []
[*args].map(&:split).flatten.each do |arg|
@_arguments << Clin::Argument.new(arg)
end
end
|
[
"def",
"arguments",
"(",
"args",
"=",
"nil",
")",
"return",
"@_arguments",
"if",
"args",
".",
"nil?",
"@_arguments",
"=",
"[",
"]",
"[",
"args",
"]",
".",
"map",
"(",
":split",
")",
".",
"flatten",
".",
"each",
"do",
"|",
"arg",
"|",
"@_arguments",
"<<",
"Clin",
"::",
"Argument",
".",
"new",
"(",
"arg",
")",
"end",
"end"
] |
Set or get the arguments for the command
@param args [Array<String>] List of arguments to set. If nil it just return the current args.
|
[
"Set",
"or",
"get",
"the",
"arguments",
"for",
"the",
"command"
] |
43d41c47f9c652065ab7ce636d48a9fe1754135e
|
https://github.com/timotheeguerin/clin/blob/43d41c47f9c652065ab7ce636d48a9fe1754135e/lib/clin/command_mixin/core.rb#L75-L81
|
6,411 |
stormbrew/rack-bridge
|
lib/bridge/tcp_server.rb
|
Bridge.TCPSocket.verify
|
def verify()
send_bridge_request()
begin
line = gets()
match = line.match(%r{^HTTP/1\.[01] ([0-9]{3,3}) (.*)$})
if (!match)
raise "HTTP BRIDGE error: bridge server sent incorrect reply to bridge request."
end
case code = match[1].to_i
when 100, 101
return true
when 401 # 401 Access Denied, key wasn't right.
raise "HTTP BRIDGE error #{code}: host key was invalid or missing, but required."
when 503, 504 # 503 Service Unavailable or 504 Gateway Timeout
raise "HTTP BRIDGE error #{code}: could not verify server can handle requests because it's overloaded."
else
raise "HTTP BRIDGE error #{code}: #{match[2]} unknown error connecting to bridge server."
end
ensure
close() # once we do this, we just assume the connection is useless.
end
end
|
ruby
|
def verify()
send_bridge_request()
begin
line = gets()
match = line.match(%r{^HTTP/1\.[01] ([0-9]{3,3}) (.*)$})
if (!match)
raise "HTTP BRIDGE error: bridge server sent incorrect reply to bridge request."
end
case code = match[1].to_i
when 100, 101
return true
when 401 # 401 Access Denied, key wasn't right.
raise "HTTP BRIDGE error #{code}: host key was invalid or missing, but required."
when 503, 504 # 503 Service Unavailable or 504 Gateway Timeout
raise "HTTP BRIDGE error #{code}: could not verify server can handle requests because it's overloaded."
else
raise "HTTP BRIDGE error #{code}: #{match[2]} unknown error connecting to bridge server."
end
ensure
close() # once we do this, we just assume the connection is useless.
end
end
|
[
"def",
"verify",
"(",
")",
"send_bridge_request",
"(",
")",
"begin",
"line",
"=",
"gets",
"(",
")",
"match",
"=",
"line",
".",
"match",
"(",
"%r{",
"\\.",
"}",
")",
"if",
"(",
"!",
"match",
")",
"raise",
"\"HTTP BRIDGE error: bridge server sent incorrect reply to bridge request.\"",
"end",
"case",
"code",
"=",
"match",
"[",
"1",
"]",
".",
"to_i",
"when",
"100",
",",
"101",
"return",
"true",
"when",
"401",
"# 401 Access Denied, key wasn't right.",
"raise",
"\"HTTP BRIDGE error #{code}: host key was invalid or missing, but required.\"",
"when",
"503",
",",
"504",
"# 503 Service Unavailable or 504 Gateway Timeout",
"raise",
"\"HTTP BRIDGE error #{code}: could not verify server can handle requests because it's overloaded.\"",
"else",
"raise",
"\"HTTP BRIDGE error #{code}: #{match[2]} unknown error connecting to bridge server.\"",
"end",
"ensure",
"close",
"(",
")",
"# once we do this, we just assume the connection is useless.",
"end",
"end"
] |
This just tries to determine if the server will honor
requests as specified above so that the TCPServer initializer
can error out early if it won't.
|
[
"This",
"just",
"tries",
"to",
"determine",
"if",
"the",
"server",
"will",
"honor",
"requests",
"as",
"specified",
"above",
"so",
"that",
"the",
"TCPServer",
"initializer",
"can",
"error",
"out",
"early",
"if",
"it",
"won",
"t",
"."
] |
96a94de9e901f73b9ee5200d2b4be55a74912c04
|
https://github.com/stormbrew/rack-bridge/blob/96a94de9e901f73b9ee5200d2b4be55a74912c04/lib/bridge/tcp_server.rb#L38-L59
|
6,412 |
stormbrew/rack-bridge
|
lib/bridge/tcp_server.rb
|
Bridge.TCPSocket.setup
|
def setup()
send_bridge_request
code = nil
name = nil
headers = []
while (line = gets())
line = line.strip
if (line == "")
case code.to_i
when 100 # 100 Continue, just a ping. Ignore.
code = name = nil
headers = []
next
when 101 # 101 Upgrade, successfuly got a connection.
write("HTTP/1.1 100 Continue\r\n\r\n") # let the server know we're still here.
return self
when 401 # 401 Access Denied, key wasn't right.
close()
raise "HTTP BRIDGE error #{code}: host key was invalid or missing, but required."
when 503, 504 # 503 Service Unavailable or 504 Gateway Timeout, just retry.
close()
sleep_time = headers.find {|header| header["Retry-After"] } || 5
raise RetryError.new("BRIDGE server timed out or is overloaded, wait #{sleep_time}s to try again.", sleep_time)
else
raise "HTTP BRIDGE error #{code}: #{name} waiting for connection."
end
end
if (!code && !name) # This is the initial response line
if (match = line.match(%r{^HTTP/1\.[01] ([0-9]{3,3}) (.*)$}))
code = match[1]
name = match[2]
next
else
raise "Parse error in BRIDGE request reply."
end
else
if (match = line.match(%r{^(.+?):\s+(.+)$}))
headers.push({match[1] => match[2]})
else
raise "Parse error in BRIDGE request reply's headers."
end
end
end
return nil
end
|
ruby
|
def setup()
send_bridge_request
code = nil
name = nil
headers = []
while (line = gets())
line = line.strip
if (line == "")
case code.to_i
when 100 # 100 Continue, just a ping. Ignore.
code = name = nil
headers = []
next
when 101 # 101 Upgrade, successfuly got a connection.
write("HTTP/1.1 100 Continue\r\n\r\n") # let the server know we're still here.
return self
when 401 # 401 Access Denied, key wasn't right.
close()
raise "HTTP BRIDGE error #{code}: host key was invalid or missing, but required."
when 503, 504 # 503 Service Unavailable or 504 Gateway Timeout, just retry.
close()
sleep_time = headers.find {|header| header["Retry-After"] } || 5
raise RetryError.new("BRIDGE server timed out or is overloaded, wait #{sleep_time}s to try again.", sleep_time)
else
raise "HTTP BRIDGE error #{code}: #{name} waiting for connection."
end
end
if (!code && !name) # This is the initial response line
if (match = line.match(%r{^HTTP/1\.[01] ([0-9]{3,3}) (.*)$}))
code = match[1]
name = match[2]
next
else
raise "Parse error in BRIDGE request reply."
end
else
if (match = line.match(%r{^(.+?):\s+(.+)$}))
headers.push({match[1] => match[2]})
else
raise "Parse error in BRIDGE request reply's headers."
end
end
end
return nil
end
|
[
"def",
"setup",
"(",
")",
"send_bridge_request",
"code",
"=",
"nil",
"name",
"=",
"nil",
"headers",
"=",
"[",
"]",
"while",
"(",
"line",
"=",
"gets",
"(",
")",
")",
"line",
"=",
"line",
".",
"strip",
"if",
"(",
"line",
"==",
"\"\"",
")",
"case",
"code",
".",
"to_i",
"when",
"100",
"# 100 Continue, just a ping. Ignore.",
"code",
"=",
"name",
"=",
"nil",
"headers",
"=",
"[",
"]",
"next",
"when",
"101",
"# 101 Upgrade, successfuly got a connection.",
"write",
"(",
"\"HTTP/1.1 100 Continue\\r\\n\\r\\n\"",
")",
"# let the server know we're still here.",
"return",
"self",
"when",
"401",
"# 401 Access Denied, key wasn't right.",
"close",
"(",
")",
"raise",
"\"HTTP BRIDGE error #{code}: host key was invalid or missing, but required.\"",
"when",
"503",
",",
"504",
"# 503 Service Unavailable or 504 Gateway Timeout, just retry.",
"close",
"(",
")",
"sleep_time",
"=",
"headers",
".",
"find",
"{",
"|",
"header",
"|",
"header",
"[",
"\"Retry-After\"",
"]",
"}",
"||",
"5",
"raise",
"RetryError",
".",
"new",
"(",
"\"BRIDGE server timed out or is overloaded, wait #{sleep_time}s to try again.\"",
",",
"sleep_time",
")",
"else",
"raise",
"\"HTTP BRIDGE error #{code}: #{name} waiting for connection.\"",
"end",
"end",
"if",
"(",
"!",
"code",
"&&",
"!",
"name",
")",
"# This is the initial response line",
"if",
"(",
"match",
"=",
"line",
".",
"match",
"(",
"%r{",
"\\.",
"}",
")",
")",
"code",
"=",
"match",
"[",
"1",
"]",
"name",
"=",
"match",
"[",
"2",
"]",
"next",
"else",
"raise",
"\"Parse error in BRIDGE request reply.\"",
"end",
"else",
"if",
"(",
"match",
"=",
"line",
".",
"match",
"(",
"%r{",
"\\s",
"}",
")",
")",
"headers",
".",
"push",
"(",
"{",
"match",
"[",
"1",
"]",
"=>",
"match",
"[",
"2",
"]",
"}",
")",
"else",
"raise",
"\"Parse error in BRIDGE request reply's headers.\"",
"end",
"end",
"end",
"return",
"nil",
"end"
] |
This does the full setup process on the request, returning only
when the connection is actually available.
|
[
"This",
"does",
"the",
"full",
"setup",
"process",
"on",
"the",
"request",
"returning",
"only",
"when",
"the",
"connection",
"is",
"actually",
"available",
"."
] |
96a94de9e901f73b9ee5200d2b4be55a74912c04
|
https://github.com/stormbrew/rack-bridge/blob/96a94de9e901f73b9ee5200d2b4be55a74912c04/lib/bridge/tcp_server.rb#L63-L108
|
6,413 |
MBO/attrtastic
|
lib/attrtastic/semantic_attributes_helper.rb
|
Attrtastic.SemanticAttributesHelper.semantic_attributes_for
|
def semantic_attributes_for(record, options = {}, &block)
options[:html] ||= {}
html_class = [ "attrtastic", record.class.to_s.underscore, options[:html][:class] ].compact.join(" ")
output = tag(:div, { :class => html_class}, true)
if block_given?
output << capture(SemanticAttributesBuilder.new(record, self), &block)
else
output << capture(SemanticAttributesBuilder.new(record, self)) do |attr|
attr.attributes
end
end
output.safe_concat("</div>")
end
|
ruby
|
def semantic_attributes_for(record, options = {}, &block)
options[:html] ||= {}
html_class = [ "attrtastic", record.class.to_s.underscore, options[:html][:class] ].compact.join(" ")
output = tag(:div, { :class => html_class}, true)
if block_given?
output << capture(SemanticAttributesBuilder.new(record, self), &block)
else
output << capture(SemanticAttributesBuilder.new(record, self)) do |attr|
attr.attributes
end
end
output.safe_concat("</div>")
end
|
[
"def",
"semantic_attributes_for",
"(",
"record",
",",
"options",
"=",
"{",
"}",
",",
"&",
"block",
")",
"options",
"[",
":html",
"]",
"||=",
"{",
"}",
"html_class",
"=",
"[",
"\"attrtastic\"",
",",
"record",
".",
"class",
".",
"to_s",
".",
"underscore",
",",
"options",
"[",
":html",
"]",
"[",
":class",
"]",
"]",
".",
"compact",
".",
"join",
"(",
"\" \"",
")",
"output",
"=",
"tag",
"(",
":div",
",",
"{",
":class",
"=>",
"html_class",
"}",
",",
"true",
")",
"if",
"block_given?",
"output",
"<<",
"capture",
"(",
"SemanticAttributesBuilder",
".",
"new",
"(",
"record",
",",
"self",
")",
",",
"block",
")",
"else",
"output",
"<<",
"capture",
"(",
"SemanticAttributesBuilder",
".",
"new",
"(",
"record",
",",
"self",
")",
")",
"do",
"|",
"attr",
"|",
"attr",
".",
"attributes",
"end",
"end",
"output",
".",
"safe_concat",
"(",
"\"</div>\"",
")",
"end"
] |
Creates attributes for given object
@param[ActiveRecord] record AR instance record for which to display attributes
@param[Hash] options Opions
@option options [Hash] :html ({}) Hash with optional :class html class name for html block
@yield [attr] Block which is yield inside of markup
@yieldparam [SemanticAttributesBuilder] builder Builder for attributes for given AR record
@example
<%= semantic_attributes_for @user do |attr| %>
<%= attr.attributes do %>
<%= attr.attribute :name %>
<%= attr.attribute :email %>
<% end %>
<% end %>
@example
<%= semantic_attributes_for @user %>
|
[
"Creates",
"attributes",
"for",
"given",
"object"
] |
c024a1c42b665eed590004236e2d067d1ca59a4e
|
https://github.com/MBO/attrtastic/blob/c024a1c42b665eed590004236e2d067d1ca59a4e/lib/attrtastic/semantic_attributes_helper.rb#L44-L58
|
6,414 |
reidmorrison/jruby-hornetq
|
lib/hornetq/client/requestor_pattern.rb
|
HornetQ::Client.RequestorPattern.wait_for_reply
|
def wait_for_reply(user_id, timeout)
# We only want the reply to the supplied message_id, so set filter on message id
filter = "#{Java::org.hornetq.api.core::FilterConstants::HORNETQ_USERID} = 'ID:#{user_id}'" if user_id
@session.consumer(:queue_name => @reply_queue, :filter=>filter) do |consumer|
consumer.receive(timeout)
end
end
|
ruby
|
def wait_for_reply(user_id, timeout)
# We only want the reply to the supplied message_id, so set filter on message id
filter = "#{Java::org.hornetq.api.core::FilterConstants::HORNETQ_USERID} = 'ID:#{user_id}'" if user_id
@session.consumer(:queue_name => @reply_queue, :filter=>filter) do |consumer|
consumer.receive(timeout)
end
end
|
[
"def",
"wait_for_reply",
"(",
"user_id",
",",
"timeout",
")",
"# We only want the reply to the supplied message_id, so set filter on message id",
"filter",
"=",
"\"#{Java::org.hornetq.api.core::FilterConstants::HORNETQ_USERID} = 'ID:#{user_id}'\"",
"if",
"user_id",
"@session",
".",
"consumer",
"(",
":queue_name",
"=>",
"@reply_queue",
",",
":filter",
"=>",
"filter",
")",
"do",
"|",
"consumer",
"|",
"consumer",
".",
"receive",
"(",
"timeout",
")",
"end",
"end"
] |
Asynchronous wait for reply
Parameters:
user_id: the user defined id to correlate a response for
Supply a nil user_id to receive any message from the queue
Returns the message received
Note: Call submit_request before calling this method
|
[
"Asynchronous",
"wait",
"for",
"reply"
] |
528245f06b18e038eadaff5d3315eb95fc4d849d
|
https://github.com/reidmorrison/jruby-hornetq/blob/528245f06b18e038eadaff5d3315eb95fc4d849d/lib/hornetq/client/requestor_pattern.rb#L98-L104
|
6,415 |
adventistmedia/worldly
|
lib/worldly/country.rb
|
Worldly.Country.build_fields
|
def build_fields
if @data.key?(:fields)
@data[:fields].each do |k,v|
v[:required] = true unless v.key?(:required)
end
else
{city: {label:'City', required: true}, region: {label: 'Province', required: false}, postcode: {label: 'Post Code', required: false} }
end
end
|
ruby
|
def build_fields
if @data.key?(:fields)
@data[:fields].each do |k,v|
v[:required] = true unless v.key?(:required)
end
else
{city: {label:'City', required: true}, region: {label: 'Province', required: false}, postcode: {label: 'Post Code', required: false} }
end
end
|
[
"def",
"build_fields",
"if",
"@data",
".",
"key?",
"(",
":fields",
")",
"@data",
"[",
":fields",
"]",
".",
"each",
"do",
"|",
"k",
",",
"v",
"|",
"v",
"[",
":required",
"]",
"=",
"true",
"unless",
"v",
".",
"key?",
"(",
":required",
")",
"end",
"else",
"{",
"city",
":",
"{",
"label",
":",
"'City'",
",",
"required",
":",
"true",
"}",
",",
"region",
":",
"{",
"label",
":",
"'Province'",
",",
"required",
":",
"false",
"}",
",",
"postcode",
":",
"{",
"label",
":",
"'Post Code'",
",",
"required",
":",
"false",
"}",
"}",
"end",
"end"
] |
all fields are required by default unless otherwise stated
|
[
"all",
"fields",
"are",
"required",
"by",
"default",
"unless",
"otherwise",
"stated"
] |
f2ce6458623a9b79248887d08a9b3383341ab217
|
https://github.com/adventistmedia/worldly/blob/f2ce6458623a9b79248887d08a9b3383341ab217/lib/worldly/country.rb#L176-L184
|
6,416 |
saclark/lite_page
|
lib/lite_page.rb
|
LitePage.ClassMethods.page_url
|
def page_url(url)
define_method(:page_url) do |query_params = {}|
uri = URI(url)
existing_params = URI.decode_www_form(uri.query || '')
new_params = query_params.to_a
unless existing_params.empty? && new_params.empty?
combined_params = existing_params.push(*new_params)
uri.query = URI.encode_www_form(combined_params)
end
uri.to_s
end
end
|
ruby
|
def page_url(url)
define_method(:page_url) do |query_params = {}|
uri = URI(url)
existing_params = URI.decode_www_form(uri.query || '')
new_params = query_params.to_a
unless existing_params.empty? && new_params.empty?
combined_params = existing_params.push(*new_params)
uri.query = URI.encode_www_form(combined_params)
end
uri.to_s
end
end
|
[
"def",
"page_url",
"(",
"url",
")",
"define_method",
"(",
":page_url",
")",
"do",
"|",
"query_params",
"=",
"{",
"}",
"|",
"uri",
"=",
"URI",
"(",
"url",
")",
"existing_params",
"=",
"URI",
".",
"decode_www_form",
"(",
"uri",
".",
"query",
"||",
"''",
")",
"new_params",
"=",
"query_params",
".",
"to_a",
"unless",
"existing_params",
".",
"empty?",
"&&",
"new_params",
".",
"empty?",
"combined_params",
"=",
"existing_params",
".",
"push",
"(",
"new_params",
")",
"uri",
".",
"query",
"=",
"URI",
".",
"encode_www_form",
"(",
"combined_params",
")",
"end",
"uri",
".",
"to_s",
"end",
"end"
] |
Defines an instance method `page_url` which returns the url passed to this
method and takes optional query parameters that will be appended to the
url if given.
@param url [String] the page url
@return [Symbol] the name of the defined method (ruby 2.1+)
|
[
"Defines",
"an",
"instance",
"method",
"page_url",
"which",
"returns",
"the",
"url",
"passed",
"to",
"this",
"method",
"and",
"takes",
"optional",
"query",
"parameters",
"that",
"will",
"be",
"appended",
"to",
"the",
"url",
"if",
"given",
"."
] |
efa3ae28a49428ee60c6ee95b51c5d79f603acec
|
https://github.com/saclark/lite_page/blob/efa3ae28a49428ee60c6ee95b51c5d79f603acec/lib/lite_page.rb#L28-L41
|
6,417 |
jinx/core
|
lib/jinx/resource/merge_visitor.rb
|
Jinx.MergeVisitor.merge
|
def merge(source, target)
# trivial case
return target if source.equal?(target)
# the domain attributes to merge
mas = @mergeable.call(source)
unless mas.empty? then
logger.debug { "Merging #{source.qp} #{mas.to_series} into #{target.qp}..." }
end
# merge the non-domain attributes
target.merge_attributes(source)
# merge the source domain attributes into the target
target.merge_attributes(source, mas, @matches, &@filter)
end
|
ruby
|
def merge(source, target)
# trivial case
return target if source.equal?(target)
# the domain attributes to merge
mas = @mergeable.call(source)
unless mas.empty? then
logger.debug { "Merging #{source.qp} #{mas.to_series} into #{target.qp}..." }
end
# merge the non-domain attributes
target.merge_attributes(source)
# merge the source domain attributes into the target
target.merge_attributes(source, mas, @matches, &@filter)
end
|
[
"def",
"merge",
"(",
"source",
",",
"target",
")",
"# trivial case",
"return",
"target",
"if",
"source",
".",
"equal?",
"(",
"target",
")",
"# the domain attributes to merge",
"mas",
"=",
"@mergeable",
".",
"call",
"(",
"source",
")",
"unless",
"mas",
".",
"empty?",
"then",
"logger",
".",
"debug",
"{",
"\"Merging #{source.qp} #{mas.to_series} into #{target.qp}...\"",
"}",
"end",
"# merge the non-domain attributes",
"target",
".",
"merge_attributes",
"(",
"source",
")",
"# merge the source domain attributes into the target",
"target",
".",
"merge_attributes",
"(",
"source",
",",
"mas",
",",
"@matches",
",",
"@filter",
")",
"end"
] |
Merges the given source object into the target object.
@param [Resource] source the domain object to merge from
@param [Resource] target the domain object to merge into
@return [Resource] the merged target
|
[
"Merges",
"the",
"given",
"source",
"object",
"into",
"the",
"target",
"object",
"."
] |
964a274cc9d7ab74613910e8375e12ed210a434d
|
https://github.com/jinx/core/blob/964a274cc9d7ab74613910e8375e12ed210a434d/lib/jinx/resource/merge_visitor.rb#L52-L64
|
6,418 |
codescrum/bebox
|
lib/bebox/node.rb
|
Bebox.Node.checkpoint_parameter_from_file
|
def checkpoint_parameter_from_file(node_type, parameter)
Bebox::Node.checkpoint_parameter_from_file(self.project_root, self.environment, self.hostname, node_type, parameter)
end
|
ruby
|
def checkpoint_parameter_from_file(node_type, parameter)
Bebox::Node.checkpoint_parameter_from_file(self.project_root, self.environment, self.hostname, node_type, parameter)
end
|
[
"def",
"checkpoint_parameter_from_file",
"(",
"node_type",
",",
"parameter",
")",
"Bebox",
"::",
"Node",
".",
"checkpoint_parameter_from_file",
"(",
"self",
".",
"project_root",
",",
"self",
".",
"environment",
",",
"self",
".",
"hostname",
",",
"node_type",
",",
"parameter",
")",
"end"
] |
Get node checkpoint parameter from the yml file
|
[
"Get",
"node",
"checkpoint",
"parameter",
"from",
"the",
"yml",
"file"
] |
0d19315847103341e599d32837ab0bd75524e5be
|
https://github.com/codescrum/bebox/blob/0d19315847103341e599d32837ab0bd75524e5be/lib/bebox/node.rb#L38-L40
|
6,419 |
codescrum/bebox
|
lib/bebox/node.rb
|
Bebox.Node.prepare
|
def prepare
started_at = DateTime.now.to_s
prepare_deploy
prepare_common_installation
puppet_installation
create_prepare_checkpoint(started_at)
end
|
ruby
|
def prepare
started_at = DateTime.now.to_s
prepare_deploy
prepare_common_installation
puppet_installation
create_prepare_checkpoint(started_at)
end
|
[
"def",
"prepare",
"started_at",
"=",
"DateTime",
".",
"now",
".",
"to_s",
"prepare_deploy",
"prepare_common_installation",
"puppet_installation",
"create_prepare_checkpoint",
"(",
"started_at",
")",
"end"
] |
Prepare the configured nodes
|
[
"Prepare",
"the",
"configured",
"nodes"
] |
0d19315847103341e599d32837ab0bd75524e5be
|
https://github.com/codescrum/bebox/blob/0d19315847103341e599d32837ab0bd75524e5be/lib/bebox/node.rb#L49-L55
|
6,420 |
codescrum/bebox
|
lib/bebox/node.rb
|
Bebox.Node.create_hiera_template
|
def create_hiera_template
options = {ssh_key: Bebox::Project.public_ssh_key_from_file(project_root, environment), project_name: Bebox::Project.shortname_from_file(project_root)}
Bebox::Provision.generate_hiera_for_steps(self.project_root, "node.yaml.erb", self.hostname, options)
end
|
ruby
|
def create_hiera_template
options = {ssh_key: Bebox::Project.public_ssh_key_from_file(project_root, environment), project_name: Bebox::Project.shortname_from_file(project_root)}
Bebox::Provision.generate_hiera_for_steps(self.project_root, "node.yaml.erb", self.hostname, options)
end
|
[
"def",
"create_hiera_template",
"options",
"=",
"{",
"ssh_key",
":",
"Bebox",
"::",
"Project",
".",
"public_ssh_key_from_file",
"(",
"project_root",
",",
"environment",
")",
",",
"project_name",
":",
"Bebox",
"::",
"Project",
".",
"shortname_from_file",
"(",
"project_root",
")",
"}",
"Bebox",
"::",
"Provision",
".",
"generate_hiera_for_steps",
"(",
"self",
".",
"project_root",
",",
"\"node.yaml.erb\"",
",",
"self",
".",
"hostname",
",",
"options",
")",
"end"
] |
Create the puppet hiera template file
|
[
"Create",
"the",
"puppet",
"hiera",
"template",
"file"
] |
0d19315847103341e599d32837ab0bd75524e5be
|
https://github.com/codescrum/bebox/blob/0d19315847103341e599d32837ab0bd75524e5be/lib/bebox/node.rb#L82-L85
|
6,421 |
codescrum/bebox
|
lib/bebox/node.rb
|
Bebox.Node.create_node_checkpoint
|
def create_node_checkpoint
# Set the creation time for the node
self.created_at = DateTime.now.to_s
# Create the checkpoint file from template
Bebox::Environment.create_checkpoint_directories(project_root, environment)
generate_file_from_template("#{Bebox::FilesHelper::templates_path}/node/node.yml.erb", "#{project_root}/.checkpoints/environments/#{environment}/nodes/#{hostname}.yml", {node: self})
end
|
ruby
|
def create_node_checkpoint
# Set the creation time for the node
self.created_at = DateTime.now.to_s
# Create the checkpoint file from template
Bebox::Environment.create_checkpoint_directories(project_root, environment)
generate_file_from_template("#{Bebox::FilesHelper::templates_path}/node/node.yml.erb", "#{project_root}/.checkpoints/environments/#{environment}/nodes/#{hostname}.yml", {node: self})
end
|
[
"def",
"create_node_checkpoint",
"# Set the creation time for the node",
"self",
".",
"created_at",
"=",
"DateTime",
".",
"now",
".",
"to_s",
"# Create the checkpoint file from template",
"Bebox",
"::",
"Environment",
".",
"create_checkpoint_directories",
"(",
"project_root",
",",
"environment",
")",
"generate_file_from_template",
"(",
"\"#{Bebox::FilesHelper::templates_path}/node/node.yml.erb\"",
",",
"\"#{project_root}/.checkpoints/environments/#{environment}/nodes/#{hostname}.yml\"",
",",
"{",
"node",
":",
"self",
"}",
")",
"end"
] |
Create checkpoint for node
|
[
"Create",
"checkpoint",
"for",
"node"
] |
0d19315847103341e599d32837ab0bd75524e5be
|
https://github.com/codescrum/bebox/blob/0d19315847103341e599d32837ab0bd75524e5be/lib/bebox/node.rb#L105-L111
|
6,422 |
jphenow/m2m_fast_insert
|
lib/m2m_fast_insert/has_and_belongs_to_many_override.rb
|
M2MFastInsert.HasAndBelongsToManyOverride.define_fast_methods_for_model
|
def define_fast_methods_for_model(name, options)
join_table = options[:join_table]
join_column_name = name.to_s.downcase.singularize
define_method "fast_#{join_column_name}_ids_insert" do |*args|
table_name = self.class.table_name.singularize
insert = M2MFastInsert::Base.new id, join_column_name, table_name, join_table, *args
insert.fast_insert
end
end
|
ruby
|
def define_fast_methods_for_model(name, options)
join_table = options[:join_table]
join_column_name = name.to_s.downcase.singularize
define_method "fast_#{join_column_name}_ids_insert" do |*args|
table_name = self.class.table_name.singularize
insert = M2MFastInsert::Base.new id, join_column_name, table_name, join_table, *args
insert.fast_insert
end
end
|
[
"def",
"define_fast_methods_for_model",
"(",
"name",
",",
"options",
")",
"join_table",
"=",
"options",
"[",
":join_table",
"]",
"join_column_name",
"=",
"name",
".",
"to_s",
".",
"downcase",
".",
"singularize",
"define_method",
"\"fast_#{join_column_name}_ids_insert\"",
"do",
"|",
"*",
"args",
"|",
"table_name",
"=",
"self",
".",
"class",
".",
"table_name",
".",
"singularize",
"insert",
"=",
"M2MFastInsert",
"::",
"Base",
".",
"new",
"id",
",",
"join_column_name",
",",
"table_name",
",",
"join_table",
",",
"args",
"insert",
".",
"fast_insert",
"end",
"end"
] |
Get necessary table and column information so we can define
fast insertion methods
name - Plural name of the model we're associating with
options - see ActiveRecord docs
|
[
"Get",
"necessary",
"table",
"and",
"column",
"information",
"so",
"we",
"can",
"define",
"fast",
"insertion",
"methods"
] |
df5be1e6ac38327b6461911cbee3d547d9715cb6
|
https://github.com/jphenow/m2m_fast_insert/blob/df5be1e6ac38327b6461911cbee3d547d9715cb6/lib/m2m_fast_insert/has_and_belongs_to_many_override.rb#L27-L35
|
6,423 |
blambeau/yargi
|
lib/yargi/random.rb
|
Yargi.Random.execute
|
def execute
graph = Digraph.new{|g|
vertex_count.times do |i|
vertex = g.add_vertex
vertex_builder.call(vertex,i) if vertex_builder
end
edge_count.times do |i|
source = g.ith_vertex(Kernel.rand(vertex_count))
target = g.ith_vertex(Kernel.rand(vertex_count))
edge = g.connect(source, target)
edge_builder.call(edge,i) if edge_builder
end
}
strip ? _strip(graph) : graph
end
|
ruby
|
def execute
graph = Digraph.new{|g|
vertex_count.times do |i|
vertex = g.add_vertex
vertex_builder.call(vertex,i) if vertex_builder
end
edge_count.times do |i|
source = g.ith_vertex(Kernel.rand(vertex_count))
target = g.ith_vertex(Kernel.rand(vertex_count))
edge = g.connect(source, target)
edge_builder.call(edge,i) if edge_builder
end
}
strip ? _strip(graph) : graph
end
|
[
"def",
"execute",
"graph",
"=",
"Digraph",
".",
"new",
"{",
"|",
"g",
"|",
"vertex_count",
".",
"times",
"do",
"|",
"i",
"|",
"vertex",
"=",
"g",
".",
"add_vertex",
"vertex_builder",
".",
"call",
"(",
"vertex",
",",
"i",
")",
"if",
"vertex_builder",
"end",
"edge_count",
".",
"times",
"do",
"|",
"i",
"|",
"source",
"=",
"g",
".",
"ith_vertex",
"(",
"Kernel",
".",
"rand",
"(",
"vertex_count",
")",
")",
"target",
"=",
"g",
".",
"ith_vertex",
"(",
"Kernel",
".",
"rand",
"(",
"vertex_count",
")",
")",
"edge",
"=",
"g",
".",
"connect",
"(",
"source",
",",
"target",
")",
"edge_builder",
".",
"call",
"(",
"edge",
",",
"i",
")",
"if",
"edge_builder",
"end",
"}",
"strip",
"?",
"_strip",
"(",
"graph",
")",
":",
"graph",
"end"
] |
Creates an algorithm instance
Executes the random generation
|
[
"Creates",
"an",
"algorithm",
"instance",
"Executes",
"the",
"random",
"generation"
] |
100141e96d245a0a8211cd4f7590909be149bc3c
|
https://github.com/blambeau/yargi/blob/100141e96d245a0a8211cd4f7590909be149bc3c/lib/yargi/random.rb#L35-L49
|
6,424 |
Raybeam/myreplicator
|
app/models/myreplicator/log.rb
|
Myreplicator.Log.kill
|
def kill
return false unless hostname == Socket.gethostname
begin
Process.kill('KILL', pid)
self.state = "killed"
self.save!
rescue Errno::ESRCH
puts "pid #{pid} does not exist!"
mark_dead
end
end
|
ruby
|
def kill
return false unless hostname == Socket.gethostname
begin
Process.kill('KILL', pid)
self.state = "killed"
self.save!
rescue Errno::ESRCH
puts "pid #{pid} does not exist!"
mark_dead
end
end
|
[
"def",
"kill",
"return",
"false",
"unless",
"hostname",
"==",
"Socket",
".",
"gethostname",
"begin",
"Process",
".",
"kill",
"(",
"'KILL'",
",",
"pid",
")",
"self",
".",
"state",
"=",
"\"killed\"",
"self",
".",
"save!",
"rescue",
"Errno",
"::",
"ESRCH",
"puts",
"\"pid #{pid} does not exist!\"",
"mark_dead",
"end",
"end"
] |
Kills the job if running
Using PID
|
[
"Kills",
"the",
"job",
"if",
"running",
"Using",
"PID"
] |
470938e70f46886b525c65a4a464b4cf8383d00d
|
https://github.com/Raybeam/myreplicator/blob/470938e70f46886b525c65a4a464b4cf8383d00d/app/models/myreplicator/log.rb#L69-L79
|
6,425 |
Raybeam/myreplicator
|
app/models/myreplicator/log.rb
|
Myreplicator.Log.running?
|
def running?
logs = Log.where(:file => file,
:job_type => job_type,
:state => "running",
:export_id => export_id,
:hostname => hostname)
if logs.count > 0
logs.each do |log|
begin
Process.getpgid(log.pid)
puts "still running #{log.file}"
return true
rescue Errno::ESRCH
log.mark_dead
end
end
end
return false
end
|
ruby
|
def running?
logs = Log.where(:file => file,
:job_type => job_type,
:state => "running",
:export_id => export_id,
:hostname => hostname)
if logs.count > 0
logs.each do |log|
begin
Process.getpgid(log.pid)
puts "still running #{log.file}"
return true
rescue Errno::ESRCH
log.mark_dead
end
end
end
return false
end
|
[
"def",
"running?",
"logs",
"=",
"Log",
".",
"where",
"(",
":file",
"=>",
"file",
",",
":job_type",
"=>",
"job_type",
",",
":state",
"=>",
"\"running\"",
",",
":export_id",
"=>",
"export_id",
",",
":hostname",
"=>",
"hostname",
")",
"if",
"logs",
".",
"count",
">",
"0",
"logs",
".",
"each",
"do",
"|",
"log",
"|",
"begin",
"Process",
".",
"getpgid",
"(",
"log",
".",
"pid",
")",
"puts",
"\"still running #{log.file}\"",
"return",
"true",
"rescue",
"Errno",
"::",
"ESRCH",
"log",
".",
"mark_dead",
"end",
"end",
"end",
"return",
"false",
"end"
] |
Checks to see if the PID of the log is active or not
|
[
"Checks",
"to",
"see",
"if",
"the",
"PID",
"of",
"the",
"log",
"is",
"active",
"or",
"not"
] |
470938e70f46886b525c65a4a464b4cf8383d00d
|
https://github.com/Raybeam/myreplicator/blob/470938e70f46886b525c65a4a464b4cf8383d00d/app/models/myreplicator/log.rb#L84-L104
|
6,426 |
feduxorg/the_array_comparator
|
lib/the_array_comparator/strategy_dispatcher.rb
|
TheArrayComparator.StrategyDispatcher.register
|
def register(name, klass)
if valid_strategy? klass
available_strategies[name.to_sym] = klass
else
fail exception_to_raise_for_invalid_strategy, "Registering #{klass} failed. It does not support \"#{class_must_have_methods.join('-, ')}\"-method"
end
end
|
ruby
|
def register(name, klass)
if valid_strategy? klass
available_strategies[name.to_sym] = klass
else
fail exception_to_raise_for_invalid_strategy, "Registering #{klass} failed. It does not support \"#{class_must_have_methods.join('-, ')}\"-method"
end
end
|
[
"def",
"register",
"(",
"name",
",",
"klass",
")",
"if",
"valid_strategy?",
"klass",
"available_strategies",
"[",
"name",
".",
"to_sym",
"]",
"=",
"klass",
"else",
"fail",
"exception_to_raise_for_invalid_strategy",
",",
"\"Registering #{klass} failed. It does not support \\\"#{class_must_have_methods.join('-, ')}\\\"-method\"",
"end",
"end"
] |
Register a new comparator strategy
@param [String,Symbol] name
The name which can be used to refer to the registered strategy
@param [Comparator] klass
The strategy class which should be registered
@raise user defined exception
Raise exception if an incompatible strategy class is given. Please
see #exception_to_raise_for_invalid_strategy for more information
|
[
"Register",
"a",
"new",
"comparator",
"strategy"
] |
66cdaf953909a34366cbee2b519dfcf306bc03c7
|
https://github.com/feduxorg/the_array_comparator/blob/66cdaf953909a34366cbee2b519dfcf306bc03c7/lib/the_array_comparator/strategy_dispatcher.rb#L52-L58
|
6,427 |
chef-workflow/furnish-ip
|
lib/furnish/range_set.rb
|
Furnish.RangeSet.assign_group_items
|
def assign_group_items(name, items, raise_if_exists=false)
group = group_items(name)
if items.kind_of?(Array)
items = Set[*items]
elsif !items.kind_of?(Set)
items = Set[items]
end
c_allocated = allocated.count
c_group = group.count
items.each do |item|
utf8_item = item.encode("UTF-8")
allocated.add(utf8_item)
group.add(utf8_item)
end
if raise_if_exists
raise unless group.count == c_group + items.count && allocated.count == c_allocated + items.count
end
replace_group(name, group)
return items
end
|
ruby
|
def assign_group_items(name, items, raise_if_exists=false)
group = group_items(name)
if items.kind_of?(Array)
items = Set[*items]
elsif !items.kind_of?(Set)
items = Set[items]
end
c_allocated = allocated.count
c_group = group.count
items.each do |item|
utf8_item = item.encode("UTF-8")
allocated.add(utf8_item)
group.add(utf8_item)
end
if raise_if_exists
raise unless group.count == c_group + items.count && allocated.count == c_allocated + items.count
end
replace_group(name, group)
return items
end
|
[
"def",
"assign_group_items",
"(",
"name",
",",
"items",
",",
"raise_if_exists",
"=",
"false",
")",
"group",
"=",
"group_items",
"(",
"name",
")",
"if",
"items",
".",
"kind_of?",
"(",
"Array",
")",
"items",
"=",
"Set",
"[",
"items",
"]",
"elsif",
"!",
"items",
".",
"kind_of?",
"(",
"Set",
")",
"items",
"=",
"Set",
"[",
"items",
"]",
"end",
"c_allocated",
"=",
"allocated",
".",
"count",
"c_group",
"=",
"group",
".",
"count",
"items",
".",
"each",
"do",
"|",
"item",
"|",
"utf8_item",
"=",
"item",
".",
"encode",
"(",
"\"UTF-8\"",
")",
"allocated",
".",
"add",
"(",
"utf8_item",
")",
"group",
".",
"add",
"(",
"utf8_item",
")",
"end",
"if",
"raise_if_exists",
"raise",
"unless",
"group",
".",
"count",
"==",
"c_group",
"+",
"items",
".",
"count",
"&&",
"allocated",
".",
"count",
"==",
"c_allocated",
"+",
"items",
".",
"count",
"end",
"replace_group",
"(",
"name",
",",
"group",
")",
"return",
"items",
"end"
] |
Assign one or more items to a group. This method is additive, so multitemle
calls will grow the group, not replace it.
|
[
"Assign",
"one",
"or",
"more",
"items",
"to",
"a",
"group",
".",
"This",
"method",
"is",
"additive",
"so",
"multitemle",
"calls",
"will",
"grow",
"the",
"group",
"not",
"replace",
"it",
"."
] |
52c356d62d96ede988d915ebb48bd9e77269a52a
|
https://github.com/chef-workflow/furnish-ip/blob/52c356d62d96ede988d915ebb48bd9e77269a52a/lib/furnish/range_set.rb#L110-L135
|
6,428 |
chef-workflow/furnish-ip
|
lib/furnish/range_set.rb
|
Furnish.RangeSet.remove_from_group
|
def remove_from_group(name, items)
group = group_items(name)
items.each do |item|
utf8_item = item.encode("UTF-8")
deallocate(utf8_item)
group.delete(utf8_item)
end
replace_group(name, group)
return items
end
|
ruby
|
def remove_from_group(name, items)
group = group_items(name)
items.each do |item|
utf8_item = item.encode("UTF-8")
deallocate(utf8_item)
group.delete(utf8_item)
end
replace_group(name, group)
return items
end
|
[
"def",
"remove_from_group",
"(",
"name",
",",
"items",
")",
"group",
"=",
"group_items",
"(",
"name",
")",
"items",
".",
"each",
"do",
"|",
"item",
"|",
"utf8_item",
"=",
"item",
".",
"encode",
"(",
"\"UTF-8\"",
")",
"deallocate",
"(",
"utf8_item",
")",
"group",
".",
"delete",
"(",
"utf8_item",
")",
"end",
"replace_group",
"(",
"name",
",",
"group",
")",
"return",
"items",
"end"
] |
Remove the items from the group provided by name, also deallocates them.
|
[
"Remove",
"the",
"items",
"from",
"the",
"group",
"provided",
"by",
"name",
"also",
"deallocates",
"them",
"."
] |
52c356d62d96ede988d915ebb48bd9e77269a52a
|
https://github.com/chef-workflow/furnish-ip/blob/52c356d62d96ede988d915ebb48bd9e77269a52a/lib/furnish/range_set.rb#L140-L152
|
6,429 |
chef-workflow/furnish-ip
|
lib/furnish/range_set.rb
|
Furnish.RangeSet.decommission_group
|
def decommission_group(name)
group = group_items(name)
group.each do |item|
deallocate(item)
end
groups.delete(name)
return name
end
|
ruby
|
def decommission_group(name)
group = group_items(name)
group.each do |item|
deallocate(item)
end
groups.delete(name)
return name
end
|
[
"def",
"decommission_group",
"(",
"name",
")",
"group",
"=",
"group_items",
"(",
"name",
")",
"group",
".",
"each",
"do",
"|",
"item",
"|",
"deallocate",
"(",
"item",
")",
"end",
"groups",
".",
"delete",
"(",
"name",
")",
"return",
"name",
"end"
] |
Remove a group and free its allocated item addresses.
|
[
"Remove",
"a",
"group",
"and",
"free",
"its",
"allocated",
"item",
"addresses",
"."
] |
52c356d62d96ede988d915ebb48bd9e77269a52a
|
https://github.com/chef-workflow/furnish-ip/blob/52c356d62d96ede988d915ebb48bd9e77269a52a/lib/furnish/range_set.rb#L157-L167
|
6,430 |
roberthoner/encrypted_store
|
lib/encrypted_store/instance.rb
|
EncryptedStore.Instance.preload_keys
|
def preload_keys(amount = 12)
keys = EncryptedStore::ActiveRecord.preload_keys(amount)
keys.each { |k| (@_decrypted_keys ||= {})[k.id] = k.decrypted_key }
end
|
ruby
|
def preload_keys(amount = 12)
keys = EncryptedStore::ActiveRecord.preload_keys(amount)
keys.each { |k| (@_decrypted_keys ||= {})[k.id] = k.decrypted_key }
end
|
[
"def",
"preload_keys",
"(",
"amount",
"=",
"12",
")",
"keys",
"=",
"EncryptedStore",
"::",
"ActiveRecord",
".",
"preload_keys",
"(",
"amount",
")",
"keys",
".",
"each",
"{",
"|",
"k",
"|",
"(",
"@_decrypted_keys",
"||=",
"{",
"}",
")",
"[",
"k",
".",
"id",
"]",
"=",
"k",
".",
"decrypted_key",
"}",
"end"
] |
Preloads the most recent `amount` keys.
|
[
"Preloads",
"the",
"most",
"recent",
"amount",
"keys",
"."
] |
89e78eb19e0cb710b08b71209e42eda085dcaa8a
|
https://github.com/roberthoner/encrypted_store/blob/89e78eb19e0cb710b08b71209e42eda085dcaa8a/lib/encrypted_store/instance.rb#L17-L20
|
6,431 |
raygao/rforce-raygao
|
lib/rforce/binding.rb
|
RForce.Binding.login
|
def login(user, password)
@user = user
@password = password
response = call_remote(:login, [:username, user, :password, password])
raise "Incorrect user name / password [#{response.fault}]" unless response.loginResponse
result = response[:loginResponse][:result]
@session_id = result[:sessionId]
init_server(result[:serverUrl])
response
end
|
ruby
|
def login(user, password)
@user = user
@password = password
response = call_remote(:login, [:username, user, :password, password])
raise "Incorrect user name / password [#{response.fault}]" unless response.loginResponse
result = response[:loginResponse][:result]
@session_id = result[:sessionId]
init_server(result[:serverUrl])
response
end
|
[
"def",
"login",
"(",
"user",
",",
"password",
")",
"@user",
"=",
"user",
"@password",
"=",
"password",
"response",
"=",
"call_remote",
"(",
":login",
",",
"[",
":username",
",",
"user",
",",
":password",
",",
"password",
"]",
")",
"raise",
"\"Incorrect user name / password [#{response.fault}]\"",
"unless",
"response",
".",
"loginResponse",
"result",
"=",
"response",
"[",
":loginResponse",
"]",
"[",
":result",
"]",
"@session_id",
"=",
"result",
"[",
":sessionId",
"]",
"init_server",
"(",
"result",
"[",
":serverUrl",
"]",
")",
"response",
"end"
] |
Log in to the server with a user name and password, remembering
the session ID returned to us by SalesForce.
|
[
"Log",
"in",
"to",
"the",
"server",
"with",
"a",
"user",
"name",
"and",
"password",
"remembering",
"the",
"session",
"ID",
"returned",
"to",
"us",
"by",
"SalesForce",
"."
] |
21bf35db2844f3e43b1cf8d290bfc0f413384fbf
|
https://github.com/raygao/rforce-raygao/blob/21bf35db2844f3e43b1cf8d290bfc0f413384fbf/lib/rforce/binding.rb#L98-L112
|
6,432 |
raygao/rforce-raygao
|
lib/rforce/binding.rb
|
RForce.Binding.login_with_oauth
|
def login_with_oauth
result = @server.post @oauth[:login_url], '', {}
case result
when Net::HTTPSuccess
doc = REXML::Document.new result.body
@session_id = doc.elements['*/sessionId'].text
server_url = doc.elements['*/serverUrl'].text
init_server server_url
return {:sessionId => @sessionId, :serverUrl => server_url}
when Net::HTTPUnauthorized
raise 'Invalid OAuth tokens'
else
raise 'Unexpected error: #{response.inspect}'
end
end
|
ruby
|
def login_with_oauth
result = @server.post @oauth[:login_url], '', {}
case result
when Net::HTTPSuccess
doc = REXML::Document.new result.body
@session_id = doc.elements['*/sessionId'].text
server_url = doc.elements['*/serverUrl'].text
init_server server_url
return {:sessionId => @sessionId, :serverUrl => server_url}
when Net::HTTPUnauthorized
raise 'Invalid OAuth tokens'
else
raise 'Unexpected error: #{response.inspect}'
end
end
|
[
"def",
"login_with_oauth",
"result",
"=",
"@server",
".",
"post",
"@oauth",
"[",
":login_url",
"]",
",",
"''",
",",
"{",
"}",
"case",
"result",
"when",
"Net",
"::",
"HTTPSuccess",
"doc",
"=",
"REXML",
"::",
"Document",
".",
"new",
"result",
".",
"body",
"@session_id",
"=",
"doc",
".",
"elements",
"[",
"'*/sessionId'",
"]",
".",
"text",
"server_url",
"=",
"doc",
".",
"elements",
"[",
"'*/serverUrl'",
"]",
".",
"text",
"init_server",
"server_url",
"return",
"{",
":sessionId",
"=>",
"@sessionId",
",",
":serverUrl",
"=>",
"server_url",
"}",
"when",
"Net",
"::",
"HTTPUnauthorized",
"raise",
"'Invalid OAuth tokens'",
"else",
"raise",
"'Unexpected error: #{response.inspect}'",
"end",
"end"
] |
Log in to the server with OAuth, remembering
the session ID returned to us by SalesForce.
|
[
"Log",
"in",
"to",
"the",
"server",
"with",
"OAuth",
"remembering",
"the",
"session",
"ID",
"returned",
"to",
"us",
"by",
"SalesForce",
"."
] |
21bf35db2844f3e43b1cf8d290bfc0f413384fbf
|
https://github.com/raygao/rforce-raygao/blob/21bf35db2844f3e43b1cf8d290bfc0f413384fbf/lib/rforce/binding.rb#L116-L132
|
6,433 |
raygao/rforce-raygao
|
lib/rforce/binding.rb
|
RForce.Binding.method_missing
|
def method_missing(method, *args)
unless args.size == 1 && [Hash, Array].include?(args[0].class)
raise 'Expected 1 Hash or Array argument'
end
call_remote method, args[0]
end
|
ruby
|
def method_missing(method, *args)
unless args.size == 1 && [Hash, Array].include?(args[0].class)
raise 'Expected 1 Hash or Array argument'
end
call_remote method, args[0]
end
|
[
"def",
"method_missing",
"(",
"method",
",",
"*",
"args",
")",
"unless",
"args",
".",
"size",
"==",
"1",
"&&",
"[",
"Hash",
",",
"Array",
"]",
".",
"include?",
"(",
"args",
"[",
"0",
"]",
".",
"class",
")",
"raise",
"'Expected 1 Hash or Array argument'",
"end",
"call_remote",
"method",
",",
"args",
"[",
"0",
"]",
"end"
] |
Turns method calls on this object into remote SOAP calls.
|
[
"Turns",
"method",
"calls",
"on",
"this",
"object",
"into",
"remote",
"SOAP",
"calls",
"."
] |
21bf35db2844f3e43b1cf8d290bfc0f413384fbf
|
https://github.com/raygao/rforce-raygao/blob/21bf35db2844f3e43b1cf8d290bfc0f413384fbf/lib/rforce/binding.rb#L247-L253
|
6,434 |
barkerest/shells
|
lib/shells/shell_base/interface.rb
|
Shells.ShellBase.teardown
|
def teardown #:doc:
unless options[:quit].to_s.strip == ''
self.ignore_io_error = true
exec_ignore_code options[:quit], command_timeout: 1, timeout_error: false
end
end
|
ruby
|
def teardown #:doc:
unless options[:quit].to_s.strip == ''
self.ignore_io_error = true
exec_ignore_code options[:quit], command_timeout: 1, timeout_error: false
end
end
|
[
"def",
"teardown",
"#:doc:\r",
"unless",
"options",
"[",
":quit",
"]",
".",
"to_s",
".",
"strip",
"==",
"''",
"self",
".",
"ignore_io_error",
"=",
"true",
"exec_ignore_code",
"options",
"[",
":quit",
"]",
",",
"command_timeout",
":",
"1",
",",
"timeout_error",
":",
"false",
"end",
"end"
] |
Tears down the shell session.
This method is called after the session block is run before disconnecting the shell.
The default implementation simply sends the quit command to the shell and waits up to 1 second for a result.
This method will be called even if an exception is raised during the session.
|
[
"Tears",
"down",
"the",
"shell",
"session",
"."
] |
674a0254f48cea01b0ae8979933f13892e398506
|
https://github.com/barkerest/shells/blob/674a0254f48cea01b0ae8979933f13892e398506/lib/shells/shell_base/interface.rb#L37-L42
|
6,435 |
richard-viney/lightstreamer
|
lib/lightstreamer/post_request.rb
|
Lightstreamer.PostRequest.execute_multiple
|
def execute_multiple(url, bodies)
response = Excon.post url, body: bodies.join("\r\n"), expects: 200, connect_timeout: 15
response_lines = response.body.split("\n").map(&:strip)
errors = []
errors << parse_error(response_lines) until response_lines.empty?
raise LightstreamerError if errors.size != bodies.size
errors
rescue Excon::Error => error
raise Errors::ConnectionError, error.message
end
|
ruby
|
def execute_multiple(url, bodies)
response = Excon.post url, body: bodies.join("\r\n"), expects: 200, connect_timeout: 15
response_lines = response.body.split("\n").map(&:strip)
errors = []
errors << parse_error(response_lines) until response_lines.empty?
raise LightstreamerError if errors.size != bodies.size
errors
rescue Excon::Error => error
raise Errors::ConnectionError, error.message
end
|
[
"def",
"execute_multiple",
"(",
"url",
",",
"bodies",
")",
"response",
"=",
"Excon",
".",
"post",
"url",
",",
"body",
":",
"bodies",
".",
"join",
"(",
"\"\\r\\n\"",
")",
",",
"expects",
":",
"200",
",",
"connect_timeout",
":",
"15",
"response_lines",
"=",
"response",
".",
"body",
".",
"split",
"(",
"\"\\n\"",
")",
".",
"map",
"(",
":strip",
")",
"errors",
"=",
"[",
"]",
"errors",
"<<",
"parse_error",
"(",
"response_lines",
")",
"until",
"response_lines",
".",
"empty?",
"raise",
"LightstreamerError",
"if",
"errors",
".",
"size",
"!=",
"bodies",
".",
"size",
"errors",
"rescue",
"Excon",
"::",
"Error",
"=>",
"error",
"raise",
"Errors",
"::",
"ConnectionError",
",",
"error",
".",
"message",
"end"
] |
Sends a POST request to the specified Lightstreamer URL that concatenates multiple individual POST request bodies
into one to avoid sending lots of individual requests. The return value is an array with one entry per body and
indicates the error state returned by the server for that body's request, or `nil` if no error occurred.
@param [String] url The URL to send the POST request to.
@param [Array<String>] bodies The individual POST request bodies that are to be sent together in one request.
These should be created with {#request_body}.
@return [Array<LightstreamerError, nil>] The execution result of each of the passed bodies. If an entry is `nil`
then no error occurred when executing that body.
|
[
"Sends",
"a",
"POST",
"request",
"to",
"the",
"specified",
"Lightstreamer",
"URL",
"that",
"concatenates",
"multiple",
"individual",
"POST",
"request",
"bodies",
"into",
"one",
"to",
"avoid",
"sending",
"lots",
"of",
"individual",
"requests",
".",
"The",
"return",
"value",
"is",
"an",
"array",
"with",
"one",
"entry",
"per",
"body",
"and",
"indicates",
"the",
"error",
"state",
"returned",
"by",
"the",
"server",
"for",
"that",
"body",
"s",
"request",
"or",
"nil",
"if",
"no",
"error",
"occurred",
"."
] |
7be6350bd861495a52ca35a8640a1e6df34cf9d1
|
https://github.com/richard-viney/lightstreamer/blob/7be6350bd861495a52ca35a8640a1e6df34cf9d1/lib/lightstreamer/post_request.rb#L29-L42
|
6,436 |
richard-viney/lightstreamer
|
lib/lightstreamer/post_request.rb
|
Lightstreamer.PostRequest.request_body
|
def request_body(query)
params = {}
query.each do |key, value|
next if value.nil?
value = value.map(&:to_s).join(' ') if value.is_a? Array
params[key] = value
end
URI.encode_www_form params
end
|
ruby
|
def request_body(query)
params = {}
query.each do |key, value|
next if value.nil?
value = value.map(&:to_s).join(' ') if value.is_a? Array
params[key] = value
end
URI.encode_www_form params
end
|
[
"def",
"request_body",
"(",
"query",
")",
"params",
"=",
"{",
"}",
"query",
".",
"each",
"do",
"|",
"key",
",",
"value",
"|",
"next",
"if",
"value",
".",
"nil?",
"value",
"=",
"value",
".",
"map",
"(",
":to_s",
")",
".",
"join",
"(",
"' '",
")",
"if",
"value",
".",
"is_a?",
"Array",
"params",
"[",
"key",
"]",
"=",
"value",
"end",
"URI",
".",
"encode_www_form",
"params",
"end"
] |
Returns the request body to send for a POST request with the given options.
@param [Hash] query The POST request's query params.
@return [String] The request body for the given query params.
|
[
"Returns",
"the",
"request",
"body",
"to",
"send",
"for",
"a",
"POST",
"request",
"with",
"the",
"given",
"options",
"."
] |
7be6350bd861495a52ca35a8640a1e6df34cf9d1
|
https://github.com/richard-viney/lightstreamer/blob/7be6350bd861495a52ca35a8640a1e6df34cf9d1/lib/lightstreamer/post_request.rb#L49-L59
|
6,437 |
richard-viney/lightstreamer
|
lib/lightstreamer/post_request.rb
|
Lightstreamer.PostRequest.parse_error
|
def parse_error(response_lines)
first_line = response_lines.shift
return nil if first_line == 'OK'
return Errors::SyncError.new if first_line == 'SYNC ERROR'
if first_line == 'ERROR'
error_code = response_lines.shift
LightstreamerError.build response_lines.shift, error_code
else
LightstreamerError.new first_line
end
end
|
ruby
|
def parse_error(response_lines)
first_line = response_lines.shift
return nil if first_line == 'OK'
return Errors::SyncError.new if first_line == 'SYNC ERROR'
if first_line == 'ERROR'
error_code = response_lines.shift
LightstreamerError.build response_lines.shift, error_code
else
LightstreamerError.new first_line
end
end
|
[
"def",
"parse_error",
"(",
"response_lines",
")",
"first_line",
"=",
"response_lines",
".",
"shift",
"return",
"nil",
"if",
"first_line",
"==",
"'OK'",
"return",
"Errors",
"::",
"SyncError",
".",
"new",
"if",
"first_line",
"==",
"'SYNC ERROR'",
"if",
"first_line",
"==",
"'ERROR'",
"error_code",
"=",
"response_lines",
".",
"shift",
"LightstreamerError",
".",
"build",
"response_lines",
".",
"shift",
",",
"error_code",
"else",
"LightstreamerError",
".",
"new",
"first_line",
"end",
"end"
] |
Parses the next error from the given lines that were returned by a POST request. The consumed lines are removed
from the passed array.
@param [Array<String>] response_lines
@return [LightstreamerError, nil]
|
[
"Parses",
"the",
"next",
"error",
"from",
"the",
"given",
"lines",
"that",
"were",
"returned",
"by",
"a",
"POST",
"request",
".",
"The",
"consumed",
"lines",
"are",
"removed",
"from",
"the",
"passed",
"array",
"."
] |
7be6350bd861495a52ca35a8640a1e6df34cf9d1
|
https://github.com/richard-viney/lightstreamer/blob/7be6350bd861495a52ca35a8640a1e6df34cf9d1/lib/lightstreamer/post_request.rb#L67-L79
|
6,438 |
Sacristan/ga_collector_pusher
|
lib/ga_collector_pusher/instance.rb
|
GACollectorPusher.Instance.add_exception
|
def add_exception description: nil, is_fatal: false
is_fatal_int = is_fatal ? 1 : 0
@params = {
t: "exception",
exd: description,
exf: is_fatal_int
}
send_to_ga
end
|
ruby
|
def add_exception description: nil, is_fatal: false
is_fatal_int = is_fatal ? 1 : 0
@params = {
t: "exception",
exd: description,
exf: is_fatal_int
}
send_to_ga
end
|
[
"def",
"add_exception",
"description",
":",
"nil",
",",
"is_fatal",
":",
"false",
"is_fatal_int",
"=",
"is_fatal",
"?",
"1",
":",
"0",
"@params",
"=",
"{",
"t",
":",
"\"exception\"",
",",
"exd",
":",
"description",
",",
"exf",
":",
"is_fatal_int",
"}",
"send_to_ga",
"end"
] |
convert bool to integer
|
[
"convert",
"bool",
"to",
"integer"
] |
851132d88b3b4259f10e0deb5a1cc787538d51ab
|
https://github.com/Sacristan/ga_collector_pusher/blob/851132d88b3b4259f10e0deb5a1cc787538d51ab/lib/ga_collector_pusher/instance.rb#L74-L84
|
6,439 |
lulibrary/aspire
|
lib/aspire/util.rb
|
Aspire.Util.child_url?
|
def child_url?(url1, url2, api = nil, strict: false)
parent_url?(url2, url1, api, strict: strict)
end
|
ruby
|
def child_url?(url1, url2, api = nil, strict: false)
parent_url?(url2, url1, api, strict: strict)
end
|
[
"def",
"child_url?",
"(",
"url1",
",",
"url2",
",",
"api",
"=",
"nil",
",",
"strict",
":",
"false",
")",
"parent_url?",
"(",
"url2",
",",
"url1",
",",
"api",
",",
"strict",
":",
"strict",
")",
"end"
] |
Returns true if the first URL is the child of the second URL
@param url1 [Aspire::Caching::CacheEntry, String] the first URL
@param url2 [Aspire::Caching::CacheEntry, String] the second URL
@param api [Aspire::API::LinkedData] the API for generating canonical URLs
@param strict [Boolean] if true, the URL must be a parent of this entry,
otherwise the URL must be a parent or the same as this entry
@return [Boolean] true if the URL is a child of the cache entry, false
otherwise
|
[
"Returns",
"true",
"if",
"the",
"first",
"URL",
"is",
"the",
"child",
"of",
"the",
"second",
"URL"
] |
623f481a2e79b9cb0b5feb923da438eb1ed2abfe
|
https://github.com/lulibrary/aspire/blob/623f481a2e79b9cb0b5feb923da438eb1ed2abfe/lib/aspire/util.rb#L23-L25
|
6,440 |
lulibrary/aspire
|
lib/aspire/util.rb
|
Aspire.Util.linked_data
|
def linked_data(uri, ld)
uri = linked_data_path(uri)
return nil unless uri && ld
# The URI used to retrieve the data may be the canonical URI or a
# tenancy aliases. We ignore the host part of the URIs and match just
# the path
ld.each { |u, data| return data if uri == linked_data_path(u) }
# No match was found
nil
end
|
ruby
|
def linked_data(uri, ld)
uri = linked_data_path(uri)
return nil unless uri && ld
# The URI used to retrieve the data may be the canonical URI or a
# tenancy aliases. We ignore the host part of the URIs and match just
# the path
ld.each { |u, data| return data if uri == linked_data_path(u) }
# No match was found
nil
end
|
[
"def",
"linked_data",
"(",
"uri",
",",
"ld",
")",
"uri",
"=",
"linked_data_path",
"(",
"uri",
")",
"return",
"nil",
"unless",
"uri",
"&&",
"ld",
"# The URI used to retrieve the data may be the canonical URI or a",
"# tenancy aliases. We ignore the host part of the URIs and match just",
"# the path",
"ld",
".",
"each",
"{",
"|",
"u",
",",
"data",
"|",
"return",
"data",
"if",
"uri",
"==",
"linked_data_path",
"(",
"u",
")",
"}",
"# No match was found",
"nil",
"end"
] |
Returns the data for a URI from a parsed linked data API response
which may contain multiple objects
@param uri [String] the URI of the object
@param ld [Hash] the parsed JSON data from the Aspire linked data API
@return [Hash] the parsed JSON data for the URI
|
[
"Returns",
"the",
"data",
"for",
"a",
"URI",
"from",
"a",
"parsed",
"linked",
"data",
"API",
"response",
"which",
"may",
"contain",
"multiple",
"objects"
] |
623f481a2e79b9cb0b5feb923da438eb1ed2abfe
|
https://github.com/lulibrary/aspire/blob/623f481a2e79b9cb0b5feb923da438eb1ed2abfe/lib/aspire/util.rb#L56-L65
|
6,441 |
lulibrary/aspire
|
lib/aspire/util.rb
|
Aspire.Util.linked_data_path
|
def linked_data_path(uri)
URI.parse(uri).path
rescue URI::InvalidComponentError, URI::InvalidURIError
nil
end
|
ruby
|
def linked_data_path(uri)
URI.parse(uri).path
rescue URI::InvalidComponentError, URI::InvalidURIError
nil
end
|
[
"def",
"linked_data_path",
"(",
"uri",
")",
"URI",
".",
"parse",
"(",
"uri",
")",
".",
"path",
"rescue",
"URI",
"::",
"InvalidComponentError",
",",
"URI",
"::",
"InvalidURIError",
"nil",
"end"
] |
Returns the path of a URI
@param uri [String] the URI
@return [String, nil] the URI path or nil if invalid
|
[
"Returns",
"the",
"path",
"of",
"a",
"URI"
] |
623f481a2e79b9cb0b5feb923da438eb1ed2abfe
|
https://github.com/lulibrary/aspire/blob/623f481a2e79b9cb0b5feb923da438eb1ed2abfe/lib/aspire/util.rb#L70-L74
|
6,442 |
lulibrary/aspire
|
lib/aspire/util.rb
|
Aspire.Util.list_url?
|
def list_url?(u = nil, parsed: nil)
return false if (u.nil? || u.empty?) && parsed.nil?
parsed ||= parse_url(u)
child_type = parsed[:child_type]
parsed[:type] == 'lists' && (child_type.nil? || child_type.empty?)
end
|
ruby
|
def list_url?(u = nil, parsed: nil)
return false if (u.nil? || u.empty?) && parsed.nil?
parsed ||= parse_url(u)
child_type = parsed[:child_type]
parsed[:type] == 'lists' && (child_type.nil? || child_type.empty?)
end
|
[
"def",
"list_url?",
"(",
"u",
"=",
"nil",
",",
"parsed",
":",
"nil",
")",
"return",
"false",
"if",
"(",
"u",
".",
"nil?",
"||",
"u",
".",
"empty?",
")",
"&&",
"parsed",
".",
"nil?",
"parsed",
"||=",
"parse_url",
"(",
"u",
")",
"child_type",
"=",
"parsed",
"[",
":child_type",
"]",
"parsed",
"[",
":type",
"]",
"==",
"'lists'",
"&&",
"(",
"child_type",
".",
"nil?",
"||",
"child_type",
".",
"empty?",
")",
"end"
] |
Returns true if a URL is a list URL, false otherwise
@param u [String] the URL of the API object
@return [Boolean] true if the URL is a list URL, false otherwise
|
[
"Returns",
"true",
"if",
"a",
"URL",
"is",
"a",
"list",
"URL",
"false",
"otherwise"
] |
623f481a2e79b9cb0b5feb923da438eb1ed2abfe
|
https://github.com/lulibrary/aspire/blob/623f481a2e79b9cb0b5feb923da438eb1ed2abfe/lib/aspire/util.rb#L86-L91
|
6,443 |
lulibrary/aspire
|
lib/aspire/util.rb
|
Aspire.Util.parent_url?
|
def parent_url?(url1, url2, api = nil, strict: false)
u1 = url_for_comparison(url1, api, parsed: true)
u2 = url_for_comparison(url2, api, parsed: true)
# Both URLs must have the same parent
return false unless u1[:type] == u2[:type] && u1[:id] == u2[:id]
# Non-strict comparison requires only the same parent object
return true unless strict
# Strict comparison requires that this entry is a child of the URL
u1[:child_type].nil? && !u2[:child_type].nil? ? true : false
end
|
ruby
|
def parent_url?(url1, url2, api = nil, strict: false)
u1 = url_for_comparison(url1, api, parsed: true)
u2 = url_for_comparison(url2, api, parsed: true)
# Both URLs must have the same parent
return false unless u1[:type] == u2[:type] && u1[:id] == u2[:id]
# Non-strict comparison requires only the same parent object
return true unless strict
# Strict comparison requires that this entry is a child of the URL
u1[:child_type].nil? && !u2[:child_type].nil? ? true : false
end
|
[
"def",
"parent_url?",
"(",
"url1",
",",
"url2",
",",
"api",
"=",
"nil",
",",
"strict",
":",
"false",
")",
"u1",
"=",
"url_for_comparison",
"(",
"url1",
",",
"api",
",",
"parsed",
":",
"true",
")",
"u2",
"=",
"url_for_comparison",
"(",
"url2",
",",
"api",
",",
"parsed",
":",
"true",
")",
"# Both URLs must have the same parent",
"return",
"false",
"unless",
"u1",
"[",
":type",
"]",
"==",
"u2",
"[",
":type",
"]",
"&&",
"u1",
"[",
":id",
"]",
"==",
"u2",
"[",
":id",
"]",
"# Non-strict comparison requires only the same parent object",
"return",
"true",
"unless",
"strict",
"# Strict comparison requires that this entry is a child of the URL",
"u1",
"[",
":child_type",
"]",
".",
"nil?",
"&&",
"!",
"u2",
"[",
":child_type",
"]",
".",
"nil?",
"?",
"true",
":",
"false",
"end"
] |
Returns true if the first URL is the parent of the second URL
@param url1 [Aspire::Caching::CacheEntry, String] the first URL
@param url2 [Aspire::Caching::CacheEntry, String] the second URL
@param api [Aspire::API::LinkedData] the API for generating canonical URLs
@param strict [Boolean] if true, the first URL must be a parent of the
second URL, otherwise the first URL must be a parent or the same as the
second.
@return [Boolean] true if the URL has the same parent as this entry
|
[
"Returns",
"true",
"if",
"the",
"first",
"URL",
"is",
"the",
"parent",
"of",
"the",
"second",
"URL"
] |
623f481a2e79b9cb0b5feb923da438eb1ed2abfe
|
https://github.com/lulibrary/aspire/blob/623f481a2e79b9cb0b5feb923da438eb1ed2abfe/lib/aspire/util.rb#L108-L117
|
6,444 |
lulibrary/aspire
|
lib/aspire/util.rb
|
Aspire.Util.url_for_comparison
|
def url_for_comparison(url, api = nil, parsed: false)
if url.is_a?(MatchData) && parsed
url
elsif parsed && url.respond_to?(:parsed_url)
url.parsed_url
elsif !parsed && url.respond_to?(url)
url.url
else
result = api.nil? ? url.to_s : api.canonical_url(url.to_s)
parsed ? parse_url(result) : result
end
end
|
ruby
|
def url_for_comparison(url, api = nil, parsed: false)
if url.is_a?(MatchData) && parsed
url
elsif parsed && url.respond_to?(:parsed_url)
url.parsed_url
elsif !parsed && url.respond_to?(url)
url.url
else
result = api.nil? ? url.to_s : api.canonical_url(url.to_s)
parsed ? parse_url(result) : result
end
end
|
[
"def",
"url_for_comparison",
"(",
"url",
",",
"api",
"=",
"nil",
",",
"parsed",
":",
"false",
")",
"if",
"url",
".",
"is_a?",
"(",
"MatchData",
")",
"&&",
"parsed",
"url",
"elsif",
"parsed",
"&&",
"url",
".",
"respond_to?",
"(",
":parsed_url",
")",
"url",
".",
"parsed_url",
"elsif",
"!",
"parsed",
"&&",
"url",
".",
"respond_to?",
"(",
"url",
")",
"url",
".",
"url",
"else",
"result",
"=",
"api",
".",
"nil?",
"?",
"url",
".",
"to_s",
":",
"api",
".",
"canonical_url",
"(",
"url",
".",
"to_s",
")",
"parsed",
"?",
"parse_url",
"(",
"result",
")",
":",
"result",
"end",
"end"
] |
Returns a parsed or unparsed URL for comparison
@param url [Aspire::Caching::CacheEntry, String] the URL
@param api [Aspire::API::LinkedData] the API for generating canonical URLs
@param parsed [Boolean] if true, return a parsed URL, otherwise return
an unparsed URL string
@return [Aspire::Caching::CacheEntry, String] the URL for comparison
|
[
"Returns",
"a",
"parsed",
"or",
"unparsed",
"URL",
"for",
"comparison"
] |
623f481a2e79b9cb0b5feb923da438eb1ed2abfe
|
https://github.com/lulibrary/aspire/blob/623f481a2e79b9cb0b5feb923da438eb1ed2abfe/lib/aspire/util.rb#L153-L164
|
6,445 |
lulibrary/aspire
|
lib/aspire/util.rb
|
Aspire.Util.url_path
|
def url_path
# Get the path component of the URL as a relative path
filename = URI.parse(url).path
filename.slice!(0) # Remove the leading /
# Return the path with '.json' extension if not already present
filename.end_with?('.json') ? filename : "#{filename}.json"
rescue URI::InvalidComponentError, URI::InvalidURIError
# Return nil if the URL is invalid
nil
end
|
ruby
|
def url_path
# Get the path component of the URL as a relative path
filename = URI.parse(url).path
filename.slice!(0) # Remove the leading /
# Return the path with '.json' extension if not already present
filename.end_with?('.json') ? filename : "#{filename}.json"
rescue URI::InvalidComponentError, URI::InvalidURIError
# Return nil if the URL is invalid
nil
end
|
[
"def",
"url_path",
"# Get the path component of the URL as a relative path",
"filename",
"=",
"URI",
".",
"parse",
"(",
"url",
")",
".",
"path",
"filename",
".",
"slice!",
"(",
"0",
")",
"# Remove the leading /",
"# Return the path with '.json' extension if not already present",
"filename",
".",
"end_with?",
"(",
"'.json'",
")",
"?",
"filename",
":",
"\"#{filename}.json\"",
"rescue",
"URI",
"::",
"InvalidComponentError",
",",
"URI",
"::",
"InvalidURIError",
"# Return nil if the URL is invalid",
"nil",
"end"
] |
Returns the path from the URL as a relative filename
|
[
"Returns",
"the",
"path",
"from",
"the",
"URL",
"as",
"a",
"relative",
"filename"
] |
623f481a2e79b9cb0b5feb923da438eb1ed2abfe
|
https://github.com/lulibrary/aspire/blob/623f481a2e79b9cb0b5feb923da438eb1ed2abfe/lib/aspire/util.rb#L167-L176
|
6,446 |
Dev-Crea/swagger-docs-generator
|
lib/swagger_docs_generator/generator.rb
|
SwaggerDocsGenerator.Generator.import_documentations
|
def import_documentations
require SwaggerDocsGenerator.file_base
SwaggerDocsGenerator.file_docs.each { |rb| require rb }
end
|
ruby
|
def import_documentations
require SwaggerDocsGenerator.file_base
SwaggerDocsGenerator.file_docs.each { |rb| require rb }
end
|
[
"def",
"import_documentations",
"require",
"SwaggerDocsGenerator",
".",
"file_base",
"SwaggerDocsGenerator",
".",
"file_docs",
".",
"each",
"{",
"|",
"rb",
"|",
"require",
"rb",
"}",
"end"
] |
Import documentation file
|
[
"Import",
"documentation",
"file"
] |
5d3de176aa1119cb38100b451bee028d66c0809d
|
https://github.com/Dev-Crea/swagger-docs-generator/blob/5d3de176aa1119cb38100b451bee028d66c0809d/lib/swagger_docs_generator/generator.rb#L20-L23
|
6,447 |
Dev-Crea/swagger-docs-generator
|
lib/swagger_docs_generator/generator.rb
|
SwaggerDocsGenerator.Generator.generate_swagger_file
|
def generate_swagger_file
delete_file_before
File.open(@swagger_file, 'a+') do |file|
file.write(if SwaggerDocsGenerator.configure.compress
write_in_swagger_file.to_json
else
JSON.pretty_generate write_in_swagger_file
end)
end
end
|
ruby
|
def generate_swagger_file
delete_file_before
File.open(@swagger_file, 'a+') do |file|
file.write(if SwaggerDocsGenerator.configure.compress
write_in_swagger_file.to_json
else
JSON.pretty_generate write_in_swagger_file
end)
end
end
|
[
"def",
"generate_swagger_file",
"delete_file_before",
"File",
".",
"open",
"(",
"@swagger_file",
",",
"'a+'",
")",
"do",
"|",
"file",
"|",
"file",
".",
"write",
"(",
"if",
"SwaggerDocsGenerator",
".",
"configure",
".",
"compress",
"write_in_swagger_file",
".",
"to_json",
"else",
"JSON",
".",
"pretty_generate",
"write_in_swagger_file",
"end",
")",
"end",
"end"
] |
Open or create a swagger.json file
|
[
"Open",
"or",
"create",
"a",
"swagger",
".",
"json",
"file"
] |
5d3de176aa1119cb38100b451bee028d66c0809d
|
https://github.com/Dev-Crea/swagger-docs-generator/blob/5d3de176aa1119cb38100b451bee028d66c0809d/lib/swagger_docs_generator/generator.rb#L26-L35
|
6,448 |
mharris717/ascension
|
lib/ascension/parse/card.rb
|
Parse.Card.mod_for_phrases
|
def mod_for_phrases(raw_cell, method_name_or_ability_class, card_to_setup)
return unless raw_cell
#puts [raw,cat,card_class,name].inspect
raw_cell.split(/[,;]/).each do |raw_cell_part|
p = make_parsed_phrase_obj(raw_cell_part,method_name_or_ability_class)
p.mod_card(card_to_setup) if p
end
end
|
ruby
|
def mod_for_phrases(raw_cell, method_name_or_ability_class, card_to_setup)
return unless raw_cell
#puts [raw,cat,card_class,name].inspect
raw_cell.split(/[,;]/).each do |raw_cell_part|
p = make_parsed_phrase_obj(raw_cell_part,method_name_or_ability_class)
p.mod_card(card_to_setup) if p
end
end
|
[
"def",
"mod_for_phrases",
"(",
"raw_cell",
",",
"method_name_or_ability_class",
",",
"card_to_setup",
")",
"return",
"unless",
"raw_cell",
"#puts [raw,cat,card_class,name].inspect",
"raw_cell",
".",
"split",
"(",
"/",
"/",
")",
".",
"each",
"do",
"|",
"raw_cell_part",
"|",
"p",
"=",
"make_parsed_phrase_obj",
"(",
"raw_cell_part",
",",
"method_name_or_ability_class",
")",
"p",
".",
"mod_card",
"(",
"card_to_setup",
")",
"if",
"p",
"end",
"end"
] |
Raw Cell is the text from the csv file for this column
method_name_or_ability_class is one of two things:
1. the symbol for the method to call for this column
2. The Class that represents this ability
|
[
"Raw",
"Cell",
"is",
"the",
"text",
"from",
"the",
"csv",
"file",
"for",
"this",
"column"
] |
d4f4b9a603524d53b03436c370adf4756e5ca616
|
https://github.com/mharris717/ascension/blob/d4f4b9a603524d53b03436c370adf4756e5ca616/lib/ascension/parse/card.rb#L25-L32
|
6,449 |
lyjia/zog
|
lib/zog/heart.rb
|
Zog.Heart.method_missing
|
def method_missing(meth, *args, &block)
if @categories.include?(meth)
if block_given?
args[0] = yield block
end
self::msg(meth, args[0])
else
super
end
end
|
ruby
|
def method_missing(meth, *args, &block)
if @categories.include?(meth)
if block_given?
args[0] = yield block
end
self::msg(meth, args[0])
else
super
end
end
|
[
"def",
"method_missing",
"(",
"meth",
",",
"*",
"args",
",",
"&",
"block",
")",
"if",
"@categories",
".",
"include?",
"(",
"meth",
")",
"if",
"block_given?",
"args",
"[",
"0",
"]",
"=",
"yield",
"block",
"end",
"self",
"::",
"msg",
"(",
"meth",
",",
"args",
"[",
"0",
"]",
")",
"else",
"super",
"end",
"end"
] |
This is what responds to Zog.info, Zog.error, etc
|
[
"This",
"is",
"what",
"responds",
"to",
"Zog",
".",
"info",
"Zog",
".",
"error",
"etc"
] |
c7db39ee324f925e19ed8ed7b96b51ec734f6992
|
https://github.com/lyjia/zog/blob/c7db39ee324f925e19ed8ed7b96b51ec734f6992/lib/zog/heart.rb#L100-L114
|
6,450 |
phildionne/associates
|
lib/associates.rb
|
Associates.ClassMethods.associate
|
def associate(model, options = {})
options[:only] = Array(options[:only])
options[:except] = Array(options[:except])
options[:depends_on] = Array(options[:depends_on])
options = {
delegate: true
}.merge(options)
associate = build_associate(model, options)
self.associates << associate
define_associate_delegation(associate) if options[:delegate]
define_associate_instance_setter_method(associate)
define_associate_instance_getter_method(associate)
end
|
ruby
|
def associate(model, options = {})
options[:only] = Array(options[:only])
options[:except] = Array(options[:except])
options[:depends_on] = Array(options[:depends_on])
options = {
delegate: true
}.merge(options)
associate = build_associate(model, options)
self.associates << associate
define_associate_delegation(associate) if options[:delegate]
define_associate_instance_setter_method(associate)
define_associate_instance_getter_method(associate)
end
|
[
"def",
"associate",
"(",
"model",
",",
"options",
"=",
"{",
"}",
")",
"options",
"[",
":only",
"]",
"=",
"Array",
"(",
"options",
"[",
":only",
"]",
")",
"options",
"[",
":except",
"]",
"=",
"Array",
"(",
"options",
"[",
":except",
"]",
")",
"options",
"[",
":depends_on",
"]",
"=",
"Array",
"(",
"options",
"[",
":depends_on",
"]",
")",
"options",
"=",
"{",
"delegate",
":",
"true",
"}",
".",
"merge",
"(",
"options",
")",
"associate",
"=",
"build_associate",
"(",
"model",
",",
"options",
")",
"self",
".",
"associates",
"<<",
"associate",
"define_associate_delegation",
"(",
"associate",
")",
"if",
"options",
"[",
":delegate",
"]",
"define_associate_instance_setter_method",
"(",
"associate",
")",
"define_associate_instance_getter_method",
"(",
"associate",
")",
"end"
] |
Defines an associated model
@example
class User
include Associates
associate :user, only: :username
end
@param model [Symbol, Class]
@param [Hash] options
@option options [Symbol, Array] :only Only generate methods for the given attributes
@option options [Symbol, Array] :except Generate all the model's methods except
for the given attributes
@option options [Symbol] :depends_on Specify one or more associate name on
which the current associate model depends to be valid. Allow to automatically
setup `belongs_to` associations between models
@option options [String, Class] :class_name Specify the class name of the associate.
Use it only if that name can’t be inferred from the associate's name
@option options [Boolean] :delegate (true) Wether or not to delegate the associate's
attributes getter and setters methods to the associate instance
|
[
"Defines",
"an",
"associated",
"model"
] |
630edcc47340a73ad787feaf2cdf326b4487bb9f
|
https://github.com/phildionne/associates/blob/630edcc47340a73ad787feaf2cdf326b4487bb9f/lib/associates.rb#L64-L79
|
6,451 |
phildionne/associates
|
lib/associates.rb
|
Associates.ClassMethods.build_associate
|
def build_associate(model, options = {})
model_name = model.to_s.underscore
model_klass = (options[:class_name] || model).to_s.classify.constantize
dependent_associate_names = options[:depends_on].map(&:to_s)
attribute_names = extract_attribute_names(model_klass, options)
ensure_name_uniqueness(associates.map(&:name), model_name)
ensure_attribute_uniqueness(associates.map(&:attribute_names), attribute_names) if options[:delegate]
ensure_dependent_names_existence(associates.map(&:name), dependent_associate_names)
Item.new(model_name, model_klass, attribute_names, dependent_associate_names, options)
end
|
ruby
|
def build_associate(model, options = {})
model_name = model.to_s.underscore
model_klass = (options[:class_name] || model).to_s.classify.constantize
dependent_associate_names = options[:depends_on].map(&:to_s)
attribute_names = extract_attribute_names(model_klass, options)
ensure_name_uniqueness(associates.map(&:name), model_name)
ensure_attribute_uniqueness(associates.map(&:attribute_names), attribute_names) if options[:delegate]
ensure_dependent_names_existence(associates.map(&:name), dependent_associate_names)
Item.new(model_name, model_klass, attribute_names, dependent_associate_names, options)
end
|
[
"def",
"build_associate",
"(",
"model",
",",
"options",
"=",
"{",
"}",
")",
"model_name",
"=",
"model",
".",
"to_s",
".",
"underscore",
"model_klass",
"=",
"(",
"options",
"[",
":class_name",
"]",
"||",
"model",
")",
".",
"to_s",
".",
"classify",
".",
"constantize",
"dependent_associate_names",
"=",
"options",
"[",
":depends_on",
"]",
".",
"map",
"(",
":to_s",
")",
"attribute_names",
"=",
"extract_attribute_names",
"(",
"model_klass",
",",
"options",
")",
"ensure_name_uniqueness",
"(",
"associates",
".",
"map",
"(",
":name",
")",
",",
"model_name",
")",
"ensure_attribute_uniqueness",
"(",
"associates",
".",
"map",
"(",
":attribute_names",
")",
",",
"attribute_names",
")",
"if",
"options",
"[",
":delegate",
"]",
"ensure_dependent_names_existence",
"(",
"associates",
".",
"map",
"(",
":name",
")",
",",
"dependent_associate_names",
")",
"Item",
".",
"new",
"(",
"model_name",
",",
"model_klass",
",",
"attribute_names",
",",
"dependent_associate_names",
",",
"options",
")",
"end"
] |
Builds an associate
@param model [Symbol, Class]
@param options [Hash]
@return [Item]
|
[
"Builds",
"an",
"associate"
] |
630edcc47340a73ad787feaf2cdf326b4487bb9f
|
https://github.com/phildionne/associates/blob/630edcc47340a73ad787feaf2cdf326b4487bb9f/lib/associates.rb#L89-L100
|
6,452 |
phildionne/associates
|
lib/associates.rb
|
Associates.ClassMethods.ensure_attribute_uniqueness
|
def ensure_attribute_uniqueness(associates_attribute_names, attribute_names)
attribute_names.each do |attribute_name|
if associates_attribute_names.include?(attribute_name)
raise NameError, "already defined attribute name '#{attribute_name}' for #{name}(#{object_id})"
end
end
end
|
ruby
|
def ensure_attribute_uniqueness(associates_attribute_names, attribute_names)
attribute_names.each do |attribute_name|
if associates_attribute_names.include?(attribute_name)
raise NameError, "already defined attribute name '#{attribute_name}' for #{name}(#{object_id})"
end
end
end
|
[
"def",
"ensure_attribute_uniqueness",
"(",
"associates_attribute_names",
",",
"attribute_names",
")",
"attribute_names",
".",
"each",
"do",
"|",
"attribute_name",
"|",
"if",
"associates_attribute_names",
".",
"include?",
"(",
"attribute_name",
")",
"raise",
"NameError",
",",
"\"already defined attribute name '#{attribute_name}' for #{name}(#{object_id})\"",
"end",
"end",
"end"
] |
Ensure associate attribute names don't clash with already declared ones
@param associates_attribute_names [Array]
@param attribute_names [Array]
|
[
"Ensure",
"associate",
"attribute",
"names",
"don",
"t",
"clash",
"with",
"already",
"declared",
"ones"
] |
630edcc47340a73ad787feaf2cdf326b4487bb9f
|
https://github.com/phildionne/associates/blob/630edcc47340a73ad787feaf2cdf326b4487bb9f/lib/associates.rb#L116-L122
|
6,453 |
phildionne/associates
|
lib/associates.rb
|
Associates.ClassMethods.ensure_dependent_names_existence
|
def ensure_dependent_names_existence(associates_names, dependent_associate_names)
dependent_associate_names.each do |dependent_name|
unless associates_names.include?(dependent_name)
raise NameError, "undefined associated model '#{dependent_name}' for #{name}(#{object_id})"
end
end
end
|
ruby
|
def ensure_dependent_names_existence(associates_names, dependent_associate_names)
dependent_associate_names.each do |dependent_name|
unless associates_names.include?(dependent_name)
raise NameError, "undefined associated model '#{dependent_name}' for #{name}(#{object_id})"
end
end
end
|
[
"def",
"ensure_dependent_names_existence",
"(",
"associates_names",
",",
"dependent_associate_names",
")",
"dependent_associate_names",
".",
"each",
"do",
"|",
"dependent_name",
"|",
"unless",
"associates_names",
".",
"include?",
"(",
"dependent_name",
")",
"raise",
"NameError",
",",
"\"undefined associated model '#{dependent_name}' for #{name}(#{object_id})\"",
"end",
"end",
"end"
] |
Ensure associate dependent names exists
@param associates_names [Array]
@param dependent_associate_names [Array]
|
[
"Ensure",
"associate",
"dependent",
"names",
"exists"
] |
630edcc47340a73ad787feaf2cdf326b4487bb9f
|
https://github.com/phildionne/associates/blob/630edcc47340a73ad787feaf2cdf326b4487bb9f/lib/associates.rb#L128-L134
|
6,454 |
phildionne/associates
|
lib/associates.rb
|
Associates.ClassMethods.define_associate_delegation
|
def define_associate_delegation(associate)
methods = [associate.attribute_names, associate.attribute_names.map { |attr| "#{attr}=" }].flatten
send(:delegate, *methods, to: associate.name)
end
|
ruby
|
def define_associate_delegation(associate)
methods = [associate.attribute_names, associate.attribute_names.map { |attr| "#{attr}=" }].flatten
send(:delegate, *methods, to: associate.name)
end
|
[
"def",
"define_associate_delegation",
"(",
"associate",
")",
"methods",
"=",
"[",
"associate",
".",
"attribute_names",
",",
"associate",
".",
"attribute_names",
".",
"map",
"{",
"|",
"attr",
"|",
"\"#{attr}=\"",
"}",
"]",
".",
"flatten",
"send",
"(",
":delegate",
",",
"methods",
",",
"to",
":",
"associate",
".",
"name",
")",
"end"
] |
Define associated model attribute methods delegation
@param associate [Item]
|
[
"Define",
"associated",
"model",
"attribute",
"methods",
"delegation"
] |
630edcc47340a73ad787feaf2cdf326b4487bb9f
|
https://github.com/phildionne/associates/blob/630edcc47340a73ad787feaf2cdf326b4487bb9f/lib/associates.rb#L156-L159
|
6,455 |
phildionne/associates
|
lib/associates.rb
|
Associates.ClassMethods.define_associate_instance_setter_method
|
def define_associate_instance_setter_method(associate)
define_method "#{associate.name}=" do |object|
unless object.is_a?(associate.klass)
raise ArgumentError, "#{associate.klass}(##{associate.klass.object_id}) expected, got #{object.class}(##{object.class.object_id})"
end
instance = instance_variable_set("@#{associate.name}", object)
depending = associates.select { |_associate| _associate.dependent_names.include?(associate.name) }
depending.each do |_associate|
send(_associate.name).send("#{associate.name}=", instance)
end
instance
end
end
|
ruby
|
def define_associate_instance_setter_method(associate)
define_method "#{associate.name}=" do |object|
unless object.is_a?(associate.klass)
raise ArgumentError, "#{associate.klass}(##{associate.klass.object_id}) expected, got #{object.class}(##{object.class.object_id})"
end
instance = instance_variable_set("@#{associate.name}", object)
depending = associates.select { |_associate| _associate.dependent_names.include?(associate.name) }
depending.each do |_associate|
send(_associate.name).send("#{associate.name}=", instance)
end
instance
end
end
|
[
"def",
"define_associate_instance_setter_method",
"(",
"associate",
")",
"define_method",
"\"#{associate.name}=\"",
"do",
"|",
"object",
"|",
"unless",
"object",
".",
"is_a?",
"(",
"associate",
".",
"klass",
")",
"raise",
"ArgumentError",
",",
"\"#{associate.klass}(##{associate.klass.object_id}) expected, got #{object.class}(##{object.class.object_id})\"",
"end",
"instance",
"=",
"instance_variable_set",
"(",
"\"@#{associate.name}\"",
",",
"object",
")",
"depending",
"=",
"associates",
".",
"select",
"{",
"|",
"_associate",
"|",
"_associate",
".",
"dependent_names",
".",
"include?",
"(",
"associate",
".",
"name",
")",
"}",
"depending",
".",
"each",
"do",
"|",
"_associate",
"|",
"send",
"(",
"_associate",
".",
"name",
")",
".",
"send",
"(",
"\"#{associate.name}=\"",
",",
"instance",
")",
"end",
"instance",
"end",
"end"
] |
Define associated model instance setter method
@example
@association.user = User.new
@param associate [Item]
|
[
"Define",
"associated",
"model",
"instance",
"setter",
"method"
] |
630edcc47340a73ad787feaf2cdf326b4487bb9f
|
https://github.com/phildionne/associates/blob/630edcc47340a73ad787feaf2cdf326b4487bb9f/lib/associates.rb#L168-L183
|
6,456 |
phildionne/associates
|
lib/associates.rb
|
Associates.ClassMethods.define_associate_instance_getter_method
|
def define_associate_instance_getter_method(associate)
define_method associate.name do
instance = instance_variable_get("@#{associate.name}") || instance_variable_set("@#{associate.name}", associate.klass.new)
depending = associates.select { |_associate| _associate.dependent_names.include?(associate.name) }
depending.each do |_associate|
existing = send(_associate.name).send(associate.name)
send(_associate.name).send("#{associate.name}=", instance) unless existing
end
instance
end
end
|
ruby
|
def define_associate_instance_getter_method(associate)
define_method associate.name do
instance = instance_variable_get("@#{associate.name}") || instance_variable_set("@#{associate.name}", associate.klass.new)
depending = associates.select { |_associate| _associate.dependent_names.include?(associate.name) }
depending.each do |_associate|
existing = send(_associate.name).send(associate.name)
send(_associate.name).send("#{associate.name}=", instance) unless existing
end
instance
end
end
|
[
"def",
"define_associate_instance_getter_method",
"(",
"associate",
")",
"define_method",
"associate",
".",
"name",
"do",
"instance",
"=",
"instance_variable_get",
"(",
"\"@#{associate.name}\"",
")",
"||",
"instance_variable_set",
"(",
"\"@#{associate.name}\"",
",",
"associate",
".",
"klass",
".",
"new",
")",
"depending",
"=",
"associates",
".",
"select",
"{",
"|",
"_associate",
"|",
"_associate",
".",
"dependent_names",
".",
"include?",
"(",
"associate",
".",
"name",
")",
"}",
"depending",
".",
"each",
"do",
"|",
"_associate",
"|",
"existing",
"=",
"send",
"(",
"_associate",
".",
"name",
")",
".",
"send",
"(",
"associate",
".",
"name",
")",
"send",
"(",
"_associate",
".",
"name",
")",
".",
"send",
"(",
"\"#{associate.name}=\"",
",",
"instance",
")",
"unless",
"existing",
"end",
"instance",
"end",
"end"
] |
Define associated model instance getter method
@example
@association.user
@param associate [Item]
|
[
"Define",
"associated",
"model",
"instance",
"getter",
"method"
] |
630edcc47340a73ad787feaf2cdf326b4487bb9f
|
https://github.com/phildionne/associates/blob/630edcc47340a73ad787feaf2cdf326b4487bb9f/lib/associates.rb#L192-L204
|
6,457 |
barkerest/incline
|
app/mailers/incline/user_mailer.rb
|
Incline.UserMailer.account_activation
|
def account_activation(data = {})
@data = {
user: nil,
client_ip: '0.0.0.0'
}.merge(data || {})
raise unless data[:user]
mail to: data[:user].email, subject: 'Account activation'
end
|
ruby
|
def account_activation(data = {})
@data = {
user: nil,
client_ip: '0.0.0.0'
}.merge(data || {})
raise unless data[:user]
mail to: data[:user].email, subject: 'Account activation'
end
|
[
"def",
"account_activation",
"(",
"data",
"=",
"{",
"}",
")",
"@data",
"=",
"{",
"user",
":",
"nil",
",",
"client_ip",
":",
"'0.0.0.0'",
"}",
".",
"merge",
"(",
"data",
"||",
"{",
"}",
")",
"raise",
"unless",
"data",
"[",
":user",
"]",
"mail",
"to",
":",
"data",
"[",
":user",
"]",
".",
"email",
",",
"subject",
":",
"'Account activation'",
"end"
] |
Sends the activation email to a new user.
|
[
"Sends",
"the",
"activation",
"email",
"to",
"a",
"new",
"user",
"."
] |
1ff08db7aa8ab7f86b223268b700bc67d15bb8aa
|
https://github.com/barkerest/incline/blob/1ff08db7aa8ab7f86b223268b700bc67d15bb8aa/app/mailers/incline/user_mailer.rb#L11-L18
|
6,458 |
barkerest/incline
|
app/mailers/incline/user_mailer.rb
|
Incline.UserMailer.invalid_password_reset
|
def invalid_password_reset(data = {})
@data = {
email: nil,
message: 'This email address is not associated with an existing account.',
client_ip: '0.0.0.0'
}.merge(data || {})
raise unless data[:email]
mail to: data[:email], subject: 'Password reset request'
end
|
ruby
|
def invalid_password_reset(data = {})
@data = {
email: nil,
message: 'This email address is not associated with an existing account.',
client_ip: '0.0.0.0'
}.merge(data || {})
raise unless data[:email]
mail to: data[:email], subject: 'Password reset request'
end
|
[
"def",
"invalid_password_reset",
"(",
"data",
"=",
"{",
"}",
")",
"@data",
"=",
"{",
"email",
":",
"nil",
",",
"message",
":",
"'This email address is not associated with an existing account.'",
",",
"client_ip",
":",
"'0.0.0.0'",
"}",
".",
"merge",
"(",
"data",
"||",
"{",
"}",
")",
"raise",
"unless",
"data",
"[",
":email",
"]",
"mail",
"to",
":",
"data",
"[",
":email",
"]",
",",
"subject",
":",
"'Password reset request'",
"end"
] |
Sends an invalid password reset attempt message to a user whether they exist or not.
|
[
"Sends",
"an",
"invalid",
"password",
"reset",
"attempt",
"message",
"to",
"a",
"user",
"whether",
"they",
"exist",
"or",
"not",
"."
] |
1ff08db7aa8ab7f86b223268b700bc67d15bb8aa
|
https://github.com/barkerest/incline/blob/1ff08db7aa8ab7f86b223268b700bc67d15bb8aa/app/mailers/incline/user_mailer.rb#L33-L41
|
6,459 |
siefca/configuration-blocks
|
lib/configuration-blocks/core.rb
|
ConfigurationBlocks.ClassMethods.configuration_module
|
def configuration_module(base = self)
Module.new.tap do |cm|
delegators = get_configuration_methods
base = send(base) if base.is_a?(Symbol)
cm.extend Module.new {
delegators.each do |method|
module_eval do
define_method(method) do |*args|
base.send(method, *args)
end
end
end
}
end
end
|
ruby
|
def configuration_module(base = self)
Module.new.tap do |cm|
delegators = get_configuration_methods
base = send(base) if base.is_a?(Symbol)
cm.extend Module.new {
delegators.each do |method|
module_eval do
define_method(method) do |*args|
base.send(method, *args)
end
end
end
}
end
end
|
[
"def",
"configuration_module",
"(",
"base",
"=",
"self",
")",
"Module",
".",
"new",
".",
"tap",
"do",
"|",
"cm",
"|",
"delegators",
"=",
"get_configuration_methods",
"base",
"=",
"send",
"(",
"base",
")",
"if",
"base",
".",
"is_a?",
"(",
"Symbol",
")",
"cm",
".",
"extend",
"Module",
".",
"new",
"{",
"delegators",
".",
"each",
"do",
"|",
"method",
"|",
"module_eval",
"do",
"define_method",
"(",
"method",
")",
"do",
"|",
"*",
"args",
"|",
"base",
".",
"send",
"(",
"method",
",",
"args",
")",
"end",
"end",
"end",
"}",
"end",
"end"
] |
Creates and returns anonymous module containing
delegators that point to methods from a class this module is included in
or the given +base+.
@param base [Object,Symbol] base object which delegators will point to (defaults to object on which
this method has been called). If symbol is given, then it should contain the name of a method that
will be called on current object.
@return [Module] anonymous module with proxy module methods delegating actions to +base+ object
|
[
"Creates",
"and",
"returns",
"anonymous",
"module",
"containing",
"delegators",
"that",
"point",
"to",
"methods",
"from",
"a",
"class",
"this",
"module",
"is",
"included",
"in",
"or",
"the",
"given",
"+",
"base",
"+",
"."
] |
1b04f5f3e97639b455a473c5f9c2200cf9f18c26
|
https://github.com/siefca/configuration-blocks/blob/1b04f5f3e97639b455a473c5f9c2200cf9f18c26/lib/configuration-blocks/core.rb#L84-L98
|
6,460 |
siefca/configuration-blocks
|
lib/configuration-blocks/core.rb
|
ConfigurationBlocks.ClassMethods.get_configuration_methods
|
def get_configuration_methods(local_only = false)
all_delegators = singleton_class.send(:cf_block_delegators) + cf_block_delegators
return all_delegators if local_only
ancestors.each_with_object(all_delegators) do |ancestor, all|
all.merge(ancestor.send(__method__, true)) if ancestor.respond_to?(__method__)
end
end
|
ruby
|
def get_configuration_methods(local_only = false)
all_delegators = singleton_class.send(:cf_block_delegators) + cf_block_delegators
return all_delegators if local_only
ancestors.each_with_object(all_delegators) do |ancestor, all|
all.merge(ancestor.send(__method__, true)) if ancestor.respond_to?(__method__)
end
end
|
[
"def",
"get_configuration_methods",
"(",
"local_only",
"=",
"false",
")",
"all_delegators",
"=",
"singleton_class",
".",
"send",
"(",
":cf_block_delegators",
")",
"+",
"cf_block_delegators",
"return",
"all_delegators",
"if",
"local_only",
"ancestors",
".",
"each_with_object",
"(",
"all_delegators",
")",
"do",
"|",
"ancestor",
",",
"all",
"|",
"all",
".",
"merge",
"(",
"ancestor",
".",
"send",
"(",
"__method__",
",",
"true",
")",
")",
"if",
"ancestor",
".",
"respond_to?",
"(",
"__method__",
")",
"end",
"end"
] |
Gets all method names known to configuration engine.
@param local_only [Boolean] optional flag that if set, causes only methods added
by current class or module to be listed.
@return [Array<Symbol>] delegated method names
|
[
"Gets",
"all",
"method",
"names",
"known",
"to",
"configuration",
"engine",
"."
] |
1b04f5f3e97639b455a473c5f9c2200cf9f18c26
|
https://github.com/siefca/configuration-blocks/blob/1b04f5f3e97639b455a473c5f9c2200cf9f18c26/lib/configuration-blocks/core.rb#L106-L112
|
6,461 |
siefca/configuration-blocks
|
lib/configuration-blocks/core.rb
|
ConfigurationBlocks.ClassMethods.configuration_block_delegate
|
def configuration_block_delegate(*methods)
methods.flatten.each { |m| cf_block_delegators.add(m.to_sym) }
@cb_conf_module = nil if @cb_conf_module
nil
end
|
ruby
|
def configuration_block_delegate(*methods)
methods.flatten.each { |m| cf_block_delegators.add(m.to_sym) }
@cb_conf_module = nil if @cb_conf_module
nil
end
|
[
"def",
"configuration_block_delegate",
"(",
"*",
"methods",
")",
"methods",
".",
"flatten",
".",
"each",
"{",
"|",
"m",
"|",
"cf_block_delegators",
".",
"add",
"(",
"m",
".",
"to_sym",
")",
"}",
"@cb_conf_module",
"=",
"nil",
"if",
"@cb_conf_module",
"nil",
"end"
] |
This DSL method is intended to be used in a class or module to indicate which methods
should be delegated.
@param methods [Array<Symbol,String>] list of method names
@return [nil]
|
[
"This",
"DSL",
"method",
"is",
"intended",
"to",
"be",
"used",
"in",
"a",
"class",
"or",
"module",
"to",
"indicate",
"which",
"methods",
"should",
"be",
"delegated",
"."
] |
1b04f5f3e97639b455a473c5f9c2200cf9f18c26
|
https://github.com/siefca/configuration-blocks/blob/1b04f5f3e97639b455a473c5f9c2200cf9f18c26/lib/configuration-blocks/core.rb#L119-L123
|
6,462 |
siefca/configuration-blocks
|
lib/configuration-blocks/core.rb
|
ConfigurationBlocks.ClassMethods.configuration_block_core
|
def configuration_block_core(conf_module, &block)
return conf_module unless block_given?
return conf_module.tap(&block) unless block.arity == 0
conf_module.module_eval(&block)
conf_module
end
|
ruby
|
def configuration_block_core(conf_module, &block)
return conf_module unless block_given?
return conf_module.tap(&block) unless block.arity == 0
conf_module.module_eval(&block)
conf_module
end
|
[
"def",
"configuration_block_core",
"(",
"conf_module",
",",
"&",
"block",
")",
"return",
"conf_module",
"unless",
"block_given?",
"return",
"conf_module",
".",
"tap",
"(",
"block",
")",
"unless",
"block",
".",
"arity",
"==",
"0",
"conf_module",
".",
"module_eval",
"(",
"block",
")",
"conf_module",
"end"
] |
Evaluates configuration block within a context of the given module.
|
[
"Evaluates",
"configuration",
"block",
"within",
"a",
"context",
"of",
"the",
"given",
"module",
"."
] |
1b04f5f3e97639b455a473c5f9c2200cf9f18c26
|
https://github.com/siefca/configuration-blocks/blob/1b04f5f3e97639b455a473c5f9c2200cf9f18c26/lib/configuration-blocks/core.rb#L136-L141
|
6,463 |
barkerest/barkest_core
|
app/helpers/barkest_core/status_helper.rb
|
BarkestCore.StatusHelper.show_system_status
|
def show_system_status(options = {})
options = {
url_on_completion: nil,
completion_button: 'Continue',
main_status: 'System is busy'
}.merge(options || {})
if block_given?
clear_system_status
Spawnling.new do
status = BarkestCore::GlobalStatus.new
if status.acquire_lock
status.set_message options[:main_status]
begin
yield status
ensure
status.release_lock
end
else
yield false
end
end
end
session[:status_comp_url] = options[:url_on_completion]
session[:status_comp_lbl] = options[:completion_button]
redirect_to status_current_url
end
|
ruby
|
def show_system_status(options = {})
options = {
url_on_completion: nil,
completion_button: 'Continue',
main_status: 'System is busy'
}.merge(options || {})
if block_given?
clear_system_status
Spawnling.new do
status = BarkestCore::GlobalStatus.new
if status.acquire_lock
status.set_message options[:main_status]
begin
yield status
ensure
status.release_lock
end
else
yield false
end
end
end
session[:status_comp_url] = options[:url_on_completion]
session[:status_comp_lbl] = options[:completion_button]
redirect_to status_current_url
end
|
[
"def",
"show_system_status",
"(",
"options",
"=",
"{",
"}",
")",
"options",
"=",
"{",
"url_on_completion",
":",
"nil",
",",
"completion_button",
":",
"'Continue'",
",",
"main_status",
":",
"'System is busy'",
"}",
".",
"merge",
"(",
"options",
"||",
"{",
"}",
")",
"if",
"block_given?",
"clear_system_status",
"Spawnling",
".",
"new",
"do",
"status",
"=",
"BarkestCore",
"::",
"GlobalStatus",
".",
"new",
"if",
"status",
".",
"acquire_lock",
"status",
".",
"set_message",
"options",
"[",
":main_status",
"]",
"begin",
"yield",
"status",
"ensure",
"status",
".",
"release_lock",
"end",
"else",
"yield",
"false",
"end",
"end",
"end",
"session",
"[",
":status_comp_url",
"]",
"=",
"options",
"[",
":url_on_completion",
"]",
"session",
"[",
":status_comp_lbl",
"]",
"=",
"options",
"[",
":completion_button",
"]",
"redirect_to",
"status_current_url",
"end"
] |
Shows the system status while optionally performing a long running code block.
Accepted options:
url_on_completion::
This is the URL you want to redirect to when the long running code completes.
If not set, then the completion button will have an empty HREF which means it will simply reload the status page.
It is therefore highly recommended that you provide this value when using this method.
completion_button::
This is the label for the button that becomes visible when the long running code completes.
Defaults to 'Continue'.
main_status::
This is the initial status to report for the system when a long running code block is provided.
If a code block is provided, this will reset the system status and spawn a thread to run the code block.
Before running the code block, it will acquire a GlobalStatus lock and set the initial status.
When the code block exits, either through error or normal behavior, the GlobalStatus lock will be released.
It will yield the +status+ object to the code block on a successful lock, or it will yield false to the code
block to let it know that a lock could not be acquired. You should check for this in your code block and
handle the error as appropriate.
Example 1:
def my_action
Spawling.new do
GlobalStatus.lock_for do |status|
if status
clear_system_status # reset the log file.
# Do something that takes a long time.
...
end
end
end
show_system_status(:url_on_completion => my_target_url)
end
Example 2:
def my_action
show_system_status(:url_on_completion => my_target_url) do |status|
if status
# Do something that takes a long time.
...
end
end
end
The benefits of Example 2 is that it handles the thread spawning and status locking for you.
|
[
"Shows",
"the",
"system",
"status",
"while",
"optionally",
"performing",
"a",
"long",
"running",
"code",
"block",
"."
] |
3eeb025ec870888cacbc9bae252a39ebf9295f61
|
https://github.com/barkerest/barkest_core/blob/3eeb025ec870888cacbc9bae252a39ebf9295f61/app/helpers/barkest_core/status_helper.rb#L60-L88
|
6,464 |
barkerest/barkest_core
|
app/helpers/barkest_core/status_helper.rb
|
BarkestCore.StatusHelper.clear_system_status
|
def clear_system_status
unless BarkestCore::GlobalStatus.locked?
# open, truncate, and close.
File.open(BarkestCore::WorkPath.system_status_file,'w').close
end
end
|
ruby
|
def clear_system_status
unless BarkestCore::GlobalStatus.locked?
# open, truncate, and close.
File.open(BarkestCore::WorkPath.system_status_file,'w').close
end
end
|
[
"def",
"clear_system_status",
"unless",
"BarkestCore",
"::",
"GlobalStatus",
".",
"locked?",
"# open, truncate, and close.",
"File",
".",
"open",
"(",
"BarkestCore",
"::",
"WorkPath",
".",
"system_status_file",
",",
"'w'",
")",
".",
"close",
"end",
"end"
] |
Clears the system status log file.
If the file does not exist, it is created as a zero byte file.
This is important for the status checking, since if there is no log file it will report an error.
|
[
"Clears",
"the",
"system",
"status",
"log",
"file",
"."
] |
3eeb025ec870888cacbc9bae252a39ebf9295f61
|
https://github.com/barkerest/barkest_core/blob/3eeb025ec870888cacbc9bae252a39ebf9295f61/app/helpers/barkest_core/status_helper.rb#L96-L101
|
6,465 |
bblack16/bblib-ruby
|
lib/bblib/core/mixins/numeric_enhancements.rb
|
BBLib.NumericEnhancements.to_delimited_s
|
def to_delimited_s(delim = ',')
split = self.to_s.split('.')
split[0] = split.first.reverse.gsub(/(\d{3})/, "\\1#{delim}").reverse
split.join('.').uncapsulate(',')
end
|
ruby
|
def to_delimited_s(delim = ',')
split = self.to_s.split('.')
split[0] = split.first.reverse.gsub(/(\d{3})/, "\\1#{delim}").reverse
split.join('.').uncapsulate(',')
end
|
[
"def",
"to_delimited_s",
"(",
"delim",
"=",
"','",
")",
"split",
"=",
"self",
".",
"to_s",
".",
"split",
"(",
"'.'",
")",
"split",
"[",
"0",
"]",
"=",
"split",
".",
"first",
".",
"reverse",
".",
"gsub",
"(",
"/",
"\\d",
"/",
",",
"\"\\\\1#{delim}\"",
")",
".",
"reverse",
"split",
".",
"join",
"(",
"'.'",
")",
".",
"uncapsulate",
"(",
"','",
")",
"end"
] |
Convert this integer into a string with every three digits separated by a delimiter
on the left side of the decimal
|
[
"Convert",
"this",
"integer",
"into",
"a",
"string",
"with",
"every",
"three",
"digits",
"separated",
"by",
"a",
"delimiter",
"on",
"the",
"left",
"side",
"of",
"the",
"decimal"
] |
274eedeb583cc56243884fd041645488d5bd08a9
|
https://github.com/bblack16/bblib-ruby/blob/274eedeb583cc56243884fd041645488d5bd08a9/lib/bblib/core/mixins/numeric_enhancements.rb#L24-L28
|
6,466 |
barkerest/incline
|
lib/incline/json_log_formatter.rb
|
Incline.JsonLogFormatter.call
|
def call(sev, time, _, msg) #:nodoc:
level = ({
Logger::DEBUG => 'DEBUG',
Logger::INFO => 'INFO',
Logger::WARN => 'WARN',
Logger::ERROR => 'ERROR',
Logger::FATAL => 'FATAL',
}[sev] || sev.to_s).upcase
if msg.present? && AUTO_DEBUG_PATTERNS.find{|pattern| msg =~ pattern}
return '' if debug_skip?
level = 'DEBUG'
end
if msg.present?
# And we'll expand exceptions so we get as much info as possible.
# If you just want the message, make sure you just pass the message.
if msg.is_a?(::Exception)
msg = "#{msg.message} (#{msg.class})\n#{(msg.backtrace || []).join("\n")}"
elsif !msg.is_a?(::String)
msg = msg.inspect
end
msg = rm_fmt msg
{
level: level,
time: time.strftime('%Y-%m-%d %H:%M:%S'),
message: msg,
app_name: app_name,
app_version: app_version,
process_id: Process.pid,
}.to_json + "\r\n"
else
''
end
end
|
ruby
|
def call(sev, time, _, msg) #:nodoc:
level = ({
Logger::DEBUG => 'DEBUG',
Logger::INFO => 'INFO',
Logger::WARN => 'WARN',
Logger::ERROR => 'ERROR',
Logger::FATAL => 'FATAL',
}[sev] || sev.to_s).upcase
if msg.present? && AUTO_DEBUG_PATTERNS.find{|pattern| msg =~ pattern}
return '' if debug_skip?
level = 'DEBUG'
end
if msg.present?
# And we'll expand exceptions so we get as much info as possible.
# If you just want the message, make sure you just pass the message.
if msg.is_a?(::Exception)
msg = "#{msg.message} (#{msg.class})\n#{(msg.backtrace || []).join("\n")}"
elsif !msg.is_a?(::String)
msg = msg.inspect
end
msg = rm_fmt msg
{
level: level,
time: time.strftime('%Y-%m-%d %H:%M:%S'),
message: msg,
app_name: app_name,
app_version: app_version,
process_id: Process.pid,
}.to_json + "\r\n"
else
''
end
end
|
[
"def",
"call",
"(",
"sev",
",",
"time",
",",
"_",
",",
"msg",
")",
"#:nodoc:",
"level",
"=",
"(",
"{",
"Logger",
"::",
"DEBUG",
"=>",
"'DEBUG'",
",",
"Logger",
"::",
"INFO",
"=>",
"'INFO'",
",",
"Logger",
"::",
"WARN",
"=>",
"'WARN'",
",",
"Logger",
"::",
"ERROR",
"=>",
"'ERROR'",
",",
"Logger",
"::",
"FATAL",
"=>",
"'FATAL'",
",",
"}",
"[",
"sev",
"]",
"||",
"sev",
".",
"to_s",
")",
".",
"upcase",
"if",
"msg",
".",
"present?",
"&&",
"AUTO_DEBUG_PATTERNS",
".",
"find",
"{",
"|",
"pattern",
"|",
"msg",
"=~",
"pattern",
"}",
"return",
"''",
"if",
"debug_skip?",
"level",
"=",
"'DEBUG'",
"end",
"if",
"msg",
".",
"present?",
"# And we'll expand exceptions so we get as much info as possible.",
"# If you just want the message, make sure you just pass the message.",
"if",
"msg",
".",
"is_a?",
"(",
"::",
"Exception",
")",
"msg",
"=",
"\"#{msg.message} (#{msg.class})\\n#{(msg.backtrace || []).join(\"\\n\")}\"",
"elsif",
"!",
"msg",
".",
"is_a?",
"(",
"::",
"String",
")",
"msg",
"=",
"msg",
".",
"inspect",
"end",
"msg",
"=",
"rm_fmt",
"msg",
"{",
"level",
":",
"level",
",",
"time",
":",
"time",
".",
"strftime",
"(",
"'%Y-%m-%d %H:%M:%S'",
")",
",",
"message",
":",
"msg",
",",
"app_name",
":",
"app_name",
",",
"app_version",
":",
"app_version",
",",
"process_id",
":",
"Process",
".",
"pid",
",",
"}",
".",
"to_json",
"+",
"\"\\r\\n\"",
"else",
"''",
"end",
"end"
] |
Overrides the default formatter behavior to log a JSON line.
|
[
"Overrides",
"the",
"default",
"formatter",
"behavior",
"to",
"log",
"a",
"JSON",
"line",
"."
] |
1ff08db7aa8ab7f86b223268b700bc67d15bb8aa
|
https://github.com/barkerest/incline/blob/1ff08db7aa8ab7f86b223268b700bc67d15bb8aa/lib/incline/json_log_formatter.rb#L17-L53
|
6,467 |
ffmike/shoehorn
|
lib/shoehorn/business_cards.rb
|
Shoehorn.BusinessCards.estimate_pdf_business_card_report
|
def estimate_pdf_business_card_report
xml = Builder::XmlMarkup.new
xml.instruct!
xml.Request(:xmlns => "urn:sbx:apis:SbxBaseComponents") do |xml|
connection.requester_credentials_block(xml)
xml.EstimatePdfBusinessCardReport
end
response = connection.post_xml(xml)
document = REXML::Document.new(response)
number_of_cards = document.elements["EstimatePdfBusinessCardReportCallResponse"].elements["NumberOfBusinessCards"].text.to_i rescue 0
number_of_pages = document.elements["EstimatePdfBusinessCardReportCallResponse"].elements["NumberOfPages"].text.to_i rescue 0
return number_of_cards, number_of_pages
end
|
ruby
|
def estimate_pdf_business_card_report
xml = Builder::XmlMarkup.new
xml.instruct!
xml.Request(:xmlns => "urn:sbx:apis:SbxBaseComponents") do |xml|
connection.requester_credentials_block(xml)
xml.EstimatePdfBusinessCardReport
end
response = connection.post_xml(xml)
document = REXML::Document.new(response)
number_of_cards = document.elements["EstimatePdfBusinessCardReportCallResponse"].elements["NumberOfBusinessCards"].text.to_i rescue 0
number_of_pages = document.elements["EstimatePdfBusinessCardReportCallResponse"].elements["NumberOfPages"].text.to_i rescue 0
return number_of_cards, number_of_pages
end
|
[
"def",
"estimate_pdf_business_card_report",
"xml",
"=",
"Builder",
"::",
"XmlMarkup",
".",
"new",
"xml",
".",
"instruct!",
"xml",
".",
"Request",
"(",
":xmlns",
"=>",
"\"urn:sbx:apis:SbxBaseComponents\"",
")",
"do",
"|",
"xml",
"|",
"connection",
".",
"requester_credentials_block",
"(",
"xml",
")",
"xml",
".",
"EstimatePdfBusinessCardReport",
"end",
"response",
"=",
"connection",
".",
"post_xml",
"(",
"xml",
")",
"document",
"=",
"REXML",
"::",
"Document",
".",
"new",
"(",
"response",
")",
"number_of_cards",
"=",
"document",
".",
"elements",
"[",
"\"EstimatePdfBusinessCardReportCallResponse\"",
"]",
".",
"elements",
"[",
"\"NumberOfBusinessCards\"",
"]",
".",
"text",
".",
"to_i",
"rescue",
"0",
"number_of_pages",
"=",
"document",
".",
"elements",
"[",
"\"EstimatePdfBusinessCardReportCallResponse\"",
"]",
".",
"elements",
"[",
"\"NumberOfPages\"",
"]",
".",
"text",
".",
"to_i",
"rescue",
"0",
"return",
"number_of_cards",
",",
"number_of_pages",
"end"
] |
Returns the estimated number of cards and number of pages for exporting Business Cards as PDF
|
[
"Returns",
"the",
"estimated",
"number",
"of",
"cards",
"and",
"number",
"of",
"pages",
"for",
"exporting",
"Business",
"Cards",
"as",
"PDF"
] |
b3da6d2bc4bd49652ac76197d01077b14bafb70a
|
https://github.com/ffmike/shoehorn/blob/b3da6d2bc4bd49652ac76197d01077b14bafb70a/lib/shoehorn/business_cards.rb#L56-L68
|
6,468 |
ffmike/shoehorn
|
lib/shoehorn/business_cards.rb
|
Shoehorn.BusinessCards.generate_pdf_business_card_report
|
def generate_pdf_business_card_report
xml = Builder::XmlMarkup.new
xml.instruct!
xml.Request(:xmlns => "urn:sbx:apis:SbxBaseComponents") do |xml|
connection.requester_credentials_block(xml)
xml.GeneratePdfBusinessCardReport
end
response = connection.post_xml(xml)
document = REXML::Document.new(response)
document.elements["GeneratePdfBusinessCardReportCallResponse"].elements["URL"].text
end
|
ruby
|
def generate_pdf_business_card_report
xml = Builder::XmlMarkup.new
xml.instruct!
xml.Request(:xmlns => "urn:sbx:apis:SbxBaseComponents") do |xml|
connection.requester_credentials_block(xml)
xml.GeneratePdfBusinessCardReport
end
response = connection.post_xml(xml)
document = REXML::Document.new(response)
document.elements["GeneratePdfBusinessCardReportCallResponse"].elements["URL"].text
end
|
[
"def",
"generate_pdf_business_card_report",
"xml",
"=",
"Builder",
"::",
"XmlMarkup",
".",
"new",
"xml",
".",
"instruct!",
"xml",
".",
"Request",
"(",
":xmlns",
"=>",
"\"urn:sbx:apis:SbxBaseComponents\"",
")",
"do",
"|",
"xml",
"|",
"connection",
".",
"requester_credentials_block",
"(",
"xml",
")",
"xml",
".",
"GeneratePdfBusinessCardReport",
"end",
"response",
"=",
"connection",
".",
"post_xml",
"(",
"xml",
")",
"document",
"=",
"REXML",
"::",
"Document",
".",
"new",
"(",
"response",
")",
"document",
".",
"elements",
"[",
"\"GeneratePdfBusinessCardReportCallResponse\"",
"]",
".",
"elements",
"[",
"\"URL\"",
"]",
".",
"text",
"end"
] |
Returns a URL for one-time download of Business Cards as PDF
|
[
"Returns",
"a",
"URL",
"for",
"one",
"-",
"time",
"download",
"of",
"Business",
"Cards",
"as",
"PDF"
] |
b3da6d2bc4bd49652ac76197d01077b14bafb70a
|
https://github.com/ffmike/shoehorn/blob/b3da6d2bc4bd49652ac76197d01077b14bafb70a/lib/shoehorn/business_cards.rb#L71-L81
|
6,469 |
ffmike/shoehorn
|
lib/shoehorn/business_cards.rb
|
Shoehorn.BusinessCards.notify_preference
|
def notify_preference
xml = Builder::XmlMarkup.new
xml.instruct!
xml.Request(:xmlns => "urn:sbx:apis:SbxBaseComponents") do |xml|
connection.requester_credentials_block(xml)
xml.GetBusinessCardNotifyPreferenceCall
end
response = connection.post_xml(xml)
document = REXML::Document.new(response)
document.elements["GetBusinessCardNotifyPreferenceCallResponse"].elements["BusinessCardNotifyPreference"].text == "1"
end
|
ruby
|
def notify_preference
xml = Builder::XmlMarkup.new
xml.instruct!
xml.Request(:xmlns => "urn:sbx:apis:SbxBaseComponents") do |xml|
connection.requester_credentials_block(xml)
xml.GetBusinessCardNotifyPreferenceCall
end
response = connection.post_xml(xml)
document = REXML::Document.new(response)
document.elements["GetBusinessCardNotifyPreferenceCallResponse"].elements["BusinessCardNotifyPreference"].text == "1"
end
|
[
"def",
"notify_preference",
"xml",
"=",
"Builder",
"::",
"XmlMarkup",
".",
"new",
"xml",
".",
"instruct!",
"xml",
".",
"Request",
"(",
":xmlns",
"=>",
"\"urn:sbx:apis:SbxBaseComponents\"",
")",
"do",
"|",
"xml",
"|",
"connection",
".",
"requester_credentials_block",
"(",
"xml",
")",
"xml",
".",
"GetBusinessCardNotifyPreferenceCall",
"end",
"response",
"=",
"connection",
".",
"post_xml",
"(",
"xml",
")",
"document",
"=",
"REXML",
"::",
"Document",
".",
"new",
"(",
"response",
")",
"document",
".",
"elements",
"[",
"\"GetBusinessCardNotifyPreferenceCallResponse\"",
"]",
".",
"elements",
"[",
"\"BusinessCardNotifyPreference\"",
"]",
".",
"text",
"==",
"\"1\"",
"end"
] |
Does the user have business card auto-share mode turned on?
|
[
"Does",
"the",
"user",
"have",
"business",
"card",
"auto",
"-",
"share",
"mode",
"turned",
"on?"
] |
b3da6d2bc4bd49652ac76197d01077b14bafb70a
|
https://github.com/ffmike/shoehorn/blob/b3da6d2bc4bd49652ac76197d01077b14bafb70a/lib/shoehorn/business_cards.rb#L106-L116
|
6,470 |
ffmike/shoehorn
|
lib/shoehorn/business_cards.rb
|
Shoehorn.BusinessCards.notify_preference=
|
def notify_preference=(value)
if value
translated_value = "1"
else
translated_value = "0"
end
xml = Builder::XmlMarkup.new
xml.instruct!
xml.Request(:xmlns => "urn:sbx:apis:SbxBaseComponents") do |xml|
connection.requester_credentials_block(xml)
xml.SetBusinessCardNotifyPreferenceCall do |xml|
xml.BusinessCardNotifyPreference(translated_value)
end
end
response = connection.post_xml(xml)
# TODO: Retrieve the new value to make sure it worked?
value
end
|
ruby
|
def notify_preference=(value)
if value
translated_value = "1"
else
translated_value = "0"
end
xml = Builder::XmlMarkup.new
xml.instruct!
xml.Request(:xmlns => "urn:sbx:apis:SbxBaseComponents") do |xml|
connection.requester_credentials_block(xml)
xml.SetBusinessCardNotifyPreferenceCall do |xml|
xml.BusinessCardNotifyPreference(translated_value)
end
end
response = connection.post_xml(xml)
# TODO: Retrieve the new value to make sure it worked?
value
end
|
[
"def",
"notify_preference",
"=",
"(",
"value",
")",
"if",
"value",
"translated_value",
"=",
"\"1\"",
"else",
"translated_value",
"=",
"\"0\"",
"end",
"xml",
"=",
"Builder",
"::",
"XmlMarkup",
".",
"new",
"xml",
".",
"instruct!",
"xml",
".",
"Request",
"(",
":xmlns",
"=>",
"\"urn:sbx:apis:SbxBaseComponents\"",
")",
"do",
"|",
"xml",
"|",
"connection",
".",
"requester_credentials_block",
"(",
"xml",
")",
"xml",
".",
"SetBusinessCardNotifyPreferenceCall",
"do",
"|",
"xml",
"|",
"xml",
".",
"BusinessCardNotifyPreference",
"(",
"translated_value",
")",
"end",
"end",
"response",
"=",
"connection",
".",
"post_xml",
"(",
"xml",
")",
"# TODO: Retrieve the new value to make sure it worked?",
"value",
"end"
] |
Turn auto-share mode on or off
|
[
"Turn",
"auto",
"-",
"share",
"mode",
"on",
"or",
"off"
] |
b3da6d2bc4bd49652ac76197d01077b14bafb70a
|
https://github.com/ffmike/shoehorn/blob/b3da6d2bc4bd49652ac76197d01077b14bafb70a/lib/shoehorn/business_cards.rb#L119-L136
|
6,471 |
ffmike/shoehorn
|
lib/shoehorn/business_cards.rb
|
Shoehorn.BusinessCards.auto_share_contact_details
|
def auto_share_contact_details
xml = Builder::XmlMarkup.new
xml.instruct!
xml.Request(:xmlns => "urn:sbx:apis:SbxBaseComponents") do |xml|
connection.requester_credentials_block(xml)
xml.GetAutoShareContactDetailsCall
end
response = connection.post_xml(xml)
details = Hash.new
document = REXML::Document.new(response)
details_element = document.elements["GetAutoShareContactDetailsCallResponse"]
details[:first_name] = details_element.elements["FirstName"].text
details[:last_name] = details_element.elements["LastName"].text
details[:email] = details_element.elements["Email"].text
details[:additional_contact_info] = details_element.elements["AdditionalContactInfo"].text
details
end
|
ruby
|
def auto_share_contact_details
xml = Builder::XmlMarkup.new
xml.instruct!
xml.Request(:xmlns => "urn:sbx:apis:SbxBaseComponents") do |xml|
connection.requester_credentials_block(xml)
xml.GetAutoShareContactDetailsCall
end
response = connection.post_xml(xml)
details = Hash.new
document = REXML::Document.new(response)
details_element = document.elements["GetAutoShareContactDetailsCallResponse"]
details[:first_name] = details_element.elements["FirstName"].text
details[:last_name] = details_element.elements["LastName"].text
details[:email] = details_element.elements["Email"].text
details[:additional_contact_info] = details_element.elements["AdditionalContactInfo"].text
details
end
|
[
"def",
"auto_share_contact_details",
"xml",
"=",
"Builder",
"::",
"XmlMarkup",
".",
"new",
"xml",
".",
"instruct!",
"xml",
".",
"Request",
"(",
":xmlns",
"=>",
"\"urn:sbx:apis:SbxBaseComponents\"",
")",
"do",
"|",
"xml",
"|",
"connection",
".",
"requester_credentials_block",
"(",
"xml",
")",
"xml",
".",
"GetAutoShareContactDetailsCall",
"end",
"response",
"=",
"connection",
".",
"post_xml",
"(",
"xml",
")",
"details",
"=",
"Hash",
".",
"new",
"document",
"=",
"REXML",
"::",
"Document",
".",
"new",
"(",
"response",
")",
"details_element",
"=",
"document",
".",
"elements",
"[",
"\"GetAutoShareContactDetailsCallResponse\"",
"]",
"details",
"[",
":first_name",
"]",
"=",
"details_element",
".",
"elements",
"[",
"\"FirstName\"",
"]",
".",
"text",
"details",
"[",
":last_name",
"]",
"=",
"details_element",
".",
"elements",
"[",
"\"LastName\"",
"]",
".",
"text",
"details",
"[",
":email",
"]",
"=",
"details_element",
".",
"elements",
"[",
"\"Email\"",
"]",
".",
"text",
"details",
"[",
":additional_contact_info",
"]",
"=",
"details_element",
".",
"elements",
"[",
"\"AdditionalContactInfo\"",
"]",
".",
"text",
"details",
"end"
] |
Get user's contact information that is sent out with business cards
|
[
"Get",
"user",
"s",
"contact",
"information",
"that",
"is",
"sent",
"out",
"with",
"business",
"cards"
] |
b3da6d2bc4bd49652ac76197d01077b14bafb70a
|
https://github.com/ffmike/shoehorn/blob/b3da6d2bc4bd49652ac76197d01077b14bafb70a/lib/shoehorn/business_cards.rb#L151-L167
|
6,472 |
devnull-tools/yummi
|
lib/yummi/colorizers.rb
|
Yummi.Colorizer.color_for
|
def color_for (arg)
arg = Yummi::Context::new(arg) unless arg.is_a? Context
call(arg)
end
|
ruby
|
def color_for (arg)
arg = Yummi::Context::new(arg) unless arg.is_a? Context
call(arg)
end
|
[
"def",
"color_for",
"(",
"arg",
")",
"arg",
"=",
"Yummi",
"::",
"Context",
"::",
"new",
"(",
"arg",
")",
"unless",
"arg",
".",
"is_a?",
"Context",
"call",
"(",
"arg",
")",
"end"
] |
Returns the color for the given value
=== Args
A context or a value.
|
[
"Returns",
"the",
"color",
"for",
"the",
"given",
"value"
] |
b31cc1ef9a9f4ca1c22e0b77a84a1995bde5c2df
|
https://github.com/devnull-tools/yummi/blob/b31cc1ef9a9f4ca1c22e0b77a84a1995bde5c2df/lib/yummi/colorizers.rb#L53-L56
|
6,473 |
inside-track/remi
|
lib/remi/data_subjects/csv_file.rb
|
Remi.Parser::CsvFile.parse
|
def parse(data)
# Assumes that each file has exactly the same structure
result_df = nil
Array(data).each_with_index do |filename, idx|
filename = filename.to_s
logger.info "Converting #{filename} to a dataframe"
processed_filename = preprocess(filename)
csv_df = Daru::DataFrame.from_csv processed_filename, @csv_options
# Daru 0.1.4 doesn't add vectors if it's a headers-only file
if csv_df.vectors.size == 0
headers_df = Daru::DataFrame.from_csv processed_filename, @csv_options.merge(return_headers: true)
csv_df = Daru::DataFrame.new([], order: headers_df.vectors.to_a)
end
csv_df[@filename_field] = Daru::Vector.new([filename] * csv_df.size, index: csv_df.index) if @filename_field
if idx == 0
result_df = csv_df
else
result_df = result_df.concat csv_df
end
end
Remi::DataFrame.create(:daru, result_df)
end
|
ruby
|
def parse(data)
# Assumes that each file has exactly the same structure
result_df = nil
Array(data).each_with_index do |filename, idx|
filename = filename.to_s
logger.info "Converting #{filename} to a dataframe"
processed_filename = preprocess(filename)
csv_df = Daru::DataFrame.from_csv processed_filename, @csv_options
# Daru 0.1.4 doesn't add vectors if it's a headers-only file
if csv_df.vectors.size == 0
headers_df = Daru::DataFrame.from_csv processed_filename, @csv_options.merge(return_headers: true)
csv_df = Daru::DataFrame.new([], order: headers_df.vectors.to_a)
end
csv_df[@filename_field] = Daru::Vector.new([filename] * csv_df.size, index: csv_df.index) if @filename_field
if idx == 0
result_df = csv_df
else
result_df = result_df.concat csv_df
end
end
Remi::DataFrame.create(:daru, result_df)
end
|
[
"def",
"parse",
"(",
"data",
")",
"# Assumes that each file has exactly the same structure",
"result_df",
"=",
"nil",
"Array",
"(",
"data",
")",
".",
"each_with_index",
"do",
"|",
"filename",
",",
"idx",
"|",
"filename",
"=",
"filename",
".",
"to_s",
"logger",
".",
"info",
"\"Converting #{filename} to a dataframe\"",
"processed_filename",
"=",
"preprocess",
"(",
"filename",
")",
"csv_df",
"=",
"Daru",
"::",
"DataFrame",
".",
"from_csv",
"processed_filename",
",",
"@csv_options",
"# Daru 0.1.4 doesn't add vectors if it's a headers-only file",
"if",
"csv_df",
".",
"vectors",
".",
"size",
"==",
"0",
"headers_df",
"=",
"Daru",
"::",
"DataFrame",
".",
"from_csv",
"processed_filename",
",",
"@csv_options",
".",
"merge",
"(",
"return_headers",
":",
"true",
")",
"csv_df",
"=",
"Daru",
"::",
"DataFrame",
".",
"new",
"(",
"[",
"]",
",",
"order",
":",
"headers_df",
".",
"vectors",
".",
"to_a",
")",
"end",
"csv_df",
"[",
"@filename_field",
"]",
"=",
"Daru",
"::",
"Vector",
".",
"new",
"(",
"[",
"filename",
"]",
"*",
"csv_df",
".",
"size",
",",
"index",
":",
"csv_df",
".",
"index",
")",
"if",
"@filename_field",
"if",
"idx",
"==",
"0",
"result_df",
"=",
"csv_df",
"else",
"result_df",
"=",
"result_df",
".",
"concat",
"csv_df",
"end",
"end",
"Remi",
"::",
"DataFrame",
".",
"create",
"(",
":daru",
",",
"result_df",
")",
"end"
] |
Converts a list of filenames into a dataframe after parsing them
according ot the csv options that were set
@param data [Object] Extracted data that needs to be parsed
@return [Remi::DataFrame] The data converted into a dataframe
|
[
"Converts",
"a",
"list",
"of",
"filenames",
"into",
"a",
"dataframe",
"after",
"parsing",
"them",
"according",
"ot",
"the",
"csv",
"options",
"that",
"were",
"set"
] |
f7e5f28f08f8c0403e04cd82d6fc14b6b2c362a7
|
https://github.com/inside-track/remi/blob/f7e5f28f08f8c0403e04cd82d6fc14b6b2c362a7/lib/remi/data_subjects/csv_file.rb#L71-L96
|
6,474 |
inside-track/remi
|
lib/remi/data_subjects/csv_file.rb
|
Remi.Encoder::CsvFile.encode
|
def encode(dataframe)
logger.info "Writing CSV file to temporary location #{@working_file}"
label_columns = self.fields.reduce({}) { |h, (k, v)|
if v[:label]
h[k] = v[:label].to_sym
end
h
}
dataframe.rename_vectors label_columns
dataframe.write_csv @working_file, @csv_options
@working_file
end
|
ruby
|
def encode(dataframe)
logger.info "Writing CSV file to temporary location #{@working_file}"
label_columns = self.fields.reduce({}) { |h, (k, v)|
if v[:label]
h[k] = v[:label].to_sym
end
h
}
dataframe.rename_vectors label_columns
dataframe.write_csv @working_file, @csv_options
@working_file
end
|
[
"def",
"encode",
"(",
"dataframe",
")",
"logger",
".",
"info",
"\"Writing CSV file to temporary location #{@working_file}\"",
"label_columns",
"=",
"self",
".",
"fields",
".",
"reduce",
"(",
"{",
"}",
")",
"{",
"|",
"h",
",",
"(",
"k",
",",
"v",
")",
"|",
"if",
"v",
"[",
":label",
"]",
"h",
"[",
"k",
"]",
"=",
"v",
"[",
":label",
"]",
".",
"to_sym",
"end",
"h",
"}",
"dataframe",
".",
"rename_vectors",
"label_columns",
"dataframe",
".",
"write_csv",
"@working_file",
",",
"@csv_options",
"@working_file",
"end"
] |
Converts the dataframe to a CSV file stored in the local work directory.
If labels are present write the CSV file with those headers but maintain
the structure of the original dataframe
@param dataframe [Remi::DataFrame] The dataframe to be encoded
@return [Object] The path to the file
|
[
"Converts",
"the",
"dataframe",
"to",
"a",
"CSV",
"file",
"stored",
"in",
"the",
"local",
"work",
"directory",
".",
"If",
"labels",
"are",
"present",
"write",
"the",
"CSV",
"file",
"with",
"those",
"headers",
"but",
"maintain",
"the",
"structure",
"of",
"the",
"original",
"dataframe"
] |
f7e5f28f08f8c0403e04cd82d6fc14b6b2c362a7
|
https://github.com/inside-track/remi/blob/f7e5f28f08f8c0403e04cd82d6fc14b6b2c362a7/lib/remi/data_subjects/csv_file.rb#L167-L179
|
6,475 |
riddopic/garcun
|
lib/garcon/task/immediate_executor.rb
|
Garcon.ImmediateExecutor.post
|
def post(*args, &task)
raise ArgumentError, 'no block given' unless block_given?
return false unless running?
task.call(*args)
true
end
|
ruby
|
def post(*args, &task)
raise ArgumentError, 'no block given' unless block_given?
return false unless running?
task.call(*args)
true
end
|
[
"def",
"post",
"(",
"*",
"args",
",",
"&",
"task",
")",
"raise",
"ArgumentError",
",",
"'no block given'",
"unless",
"block_given?",
"return",
"false",
"unless",
"running?",
"task",
".",
"call",
"(",
"args",
")",
"true",
"end"
] |
Creates a new executor
@!macro executor_method_post
|
[
"Creates",
"a",
"new",
"executor"
] |
c2409bd8cf9c14b967a719810dab5269d69b42de
|
https://github.com/riddopic/garcun/blob/c2409bd8cf9c14b967a719810dab5269d69b42de/lib/garcon/task/immediate_executor.rb#L44-L49
|
6,476 |
DigitPaint/html_mockup
|
lib/html_mockup/template.rb
|
HtmlMockup.Template.target_extension
|
def target_extension
return @target_extension if @target_extension
if type = MIME::Types[self.target_mime_type].first
# Dirty little hack to enforce the use of .html instead of .htm
if type.sub_type == "html"
@target_extension = "html"
else
@target_extension = type.extensions.first
end
else
@target_extension = File.extname(self.source_path.to_s).sub(/^\./, "")
end
end
|
ruby
|
def target_extension
return @target_extension if @target_extension
if type = MIME::Types[self.target_mime_type].first
# Dirty little hack to enforce the use of .html instead of .htm
if type.sub_type == "html"
@target_extension = "html"
else
@target_extension = type.extensions.first
end
else
@target_extension = File.extname(self.source_path.to_s).sub(/^\./, "")
end
end
|
[
"def",
"target_extension",
"return",
"@target_extension",
"if",
"@target_extension",
"if",
"type",
"=",
"MIME",
"::",
"Types",
"[",
"self",
".",
"target_mime_type",
"]",
".",
"first",
"# Dirty little hack to enforce the use of .html instead of .htm",
"if",
"type",
".",
"sub_type",
"==",
"\"html\"",
"@target_extension",
"=",
"\"html\"",
"else",
"@target_extension",
"=",
"type",
".",
"extensions",
".",
"first",
"end",
"else",
"@target_extension",
"=",
"File",
".",
"extname",
"(",
"self",
".",
"source_path",
".",
"to_s",
")",
".",
"sub",
"(",
"/",
"\\.",
"/",
",",
"\"\"",
")",
"end",
"end"
] |
Try to infer the final extension of the output file.
|
[
"Try",
"to",
"infer",
"the",
"final",
"extension",
"of",
"the",
"output",
"file",
"."
] |
976edadc01216b82a8cea177f53fb32559eaf41e
|
https://github.com/DigitPaint/html_mockup/blob/976edadc01216b82a8cea177f53fb32559eaf41e/lib/html_mockup/template.rb#L79-L92
|
6,477 |
meloncargo/dragonfly-azure_data_store
|
lib/dragonfly/azure_data_store.rb
|
Dragonfly.AzureDataStore.update_metadata
|
def update_metadata(uid)
return false unless store_meta
path = full_path(uid)
meta = storage(:get_blob, container_name, path)[0].metadata
return false if meta.present?
meta = meta_from_file(path)
return false if meta.blank?
storage(:set_blob_metadata, container_name, path, meta)
storage(:delete_blob, container_name, meta_path(path))
true
rescue Azure::Core::Http::HTTPError
nil
end
|
ruby
|
def update_metadata(uid)
return false unless store_meta
path = full_path(uid)
meta = storage(:get_blob, container_name, path)[0].metadata
return false if meta.present?
meta = meta_from_file(path)
return false if meta.blank?
storage(:set_blob_metadata, container_name, path, meta)
storage(:delete_blob, container_name, meta_path(path))
true
rescue Azure::Core::Http::HTTPError
nil
end
|
[
"def",
"update_metadata",
"(",
"uid",
")",
"return",
"false",
"unless",
"store_meta",
"path",
"=",
"full_path",
"(",
"uid",
")",
"meta",
"=",
"storage",
"(",
":get_blob",
",",
"container_name",
",",
"path",
")",
"[",
"0",
"]",
".",
"metadata",
"return",
"false",
"if",
"meta",
".",
"present?",
"meta",
"=",
"meta_from_file",
"(",
"path",
")",
"return",
"false",
"if",
"meta",
".",
"blank?",
"storage",
"(",
":set_blob_metadata",
",",
"container_name",
",",
"path",
",",
"meta",
")",
"storage",
"(",
":delete_blob",
",",
"container_name",
",",
"meta_path",
"(",
"path",
")",
")",
"true",
"rescue",
"Azure",
"::",
"Core",
"::",
"Http",
"::",
"HTTPError",
"nil",
"end"
] |
Updates metadata of file and deletes old meta file from legacy mode.
|
[
"Updates",
"metadata",
"of",
"file",
"and",
"deletes",
"old",
"meta",
"file",
"from",
"legacy",
"mode",
"."
] |
fd7d1e7507660fc2f5bc7dae8d9dbb2bfc634dc4
|
https://github.com/meloncargo/dragonfly-azure_data_store/blob/fd7d1e7507660fc2f5bc7dae8d9dbb2bfc634dc4/lib/dragonfly/azure_data_store.rb#L46-L58
|
6,478 |
Thermatix/ruta
|
lib/ruta/router.rb
|
Ruta.Router.map
|
def map ref,route, options={}
context = Context.collection[get_context]
context.routes[ref]= Route.new(route, context,options)
end
|
ruby
|
def map ref,route, options={}
context = Context.collection[get_context]
context.routes[ref]= Route.new(route, context,options)
end
|
[
"def",
"map",
"ref",
",",
"route",
",",
"options",
"=",
"{",
"}",
"context",
"=",
"Context",
".",
"collection",
"[",
"get_context",
"]",
"context",
".",
"routes",
"[",
"ref",
"]",
"=",
"Route",
".",
"new",
"(",
"route",
",",
"context",
",",
"options",
")",
"end"
] |
map a route
@param [Symbol] ref to map route to for easy future reference
|
[
"map",
"a",
"route"
] |
b4a6e3bc7c0c4b66c804023d638b173e3f61e157
|
https://github.com/Thermatix/ruta/blob/b4a6e3bc7c0c4b66c804023d638b173e3f61e157/lib/ruta/router.rb#L32-L35
|
6,479 |
Thermatix/ruta
|
lib/ruta/router.rb
|
Ruta.Router.root_to
|
def root_to reference
Router.set_root_to reference
context = Context.collection[reference]
context.routes[:root]= Route.new('/', context,{ context: reference})
end
|
ruby
|
def root_to reference
Router.set_root_to reference
context = Context.collection[reference]
context.routes[:root]= Route.new('/', context,{ context: reference})
end
|
[
"def",
"root_to",
"reference",
"Router",
".",
"set_root_to",
"reference",
"context",
"=",
"Context",
".",
"collection",
"[",
"reference",
"]",
"context",
".",
"routes",
"[",
":root",
"]",
"=",
"Route",
".",
"new",
"(",
"'/'",
",",
"context",
",",
"{",
"context",
":",
"reference",
"}",
")",
"end"
] |
set the root context, this is the initial context that will be renered by the router
@note there is only ever one root, calling this multiple times will over right the original root
@param [Symbol] reference to context
|
[
"set",
"the",
"root",
"context",
"this",
"is",
"the",
"initial",
"context",
"that",
"will",
"be",
"renered",
"by",
"the",
"router"
] |
b4a6e3bc7c0c4b66c804023d638b173e3f61e157
|
https://github.com/Thermatix/ruta/blob/b4a6e3bc7c0c4b66c804023d638b173e3f61e157/lib/ruta/router.rb#L41-L45
|
6,480 |
maynard/kenna
|
lib/kenna.rb
|
Kenna.Api.fakeUser
|
def fakeUser
@roles = ['administrator', 'normal user', 'Linux Test Environment']
@role = @roles[rand(0..2)]
@fake_user = {
"user":
{
"firstname": Faker::Name.first_name,
"lastname": Faker::Name.last_name,
"email": Faker::Internet.email,
"role": @role
}
}
end
|
ruby
|
def fakeUser
@roles = ['administrator', 'normal user', 'Linux Test Environment']
@role = @roles[rand(0..2)]
@fake_user = {
"user":
{
"firstname": Faker::Name.first_name,
"lastname": Faker::Name.last_name,
"email": Faker::Internet.email,
"role": @role
}
}
end
|
[
"def",
"fakeUser",
"@roles",
"=",
"[",
"'administrator'",
",",
"'normal user'",
",",
"'Linux Test Environment'",
"]",
"@role",
"=",
"@roles",
"[",
"rand",
"(",
"0",
"..",
"2",
")",
"]",
"@fake_user",
"=",
"{",
"\"user\"",
":",
"{",
"\"firstname\"",
":",
"Faker",
"::",
"Name",
".",
"first_name",
",",
"\"lastname\"",
":",
"Faker",
"::",
"Name",
".",
"last_name",
",",
"\"email\"",
":",
"Faker",
"::",
"Internet",
".",
"email",
",",
"\"role\"",
":",
"@role",
"}",
"}",
"end"
] |
Generate a unique fake user for testing
|
[
"Generate",
"a",
"unique",
"fake",
"user",
"for",
"testing"
] |
71eebceccf37ac571d1bd161c4cfaa0a276fe513
|
https://github.com/maynard/kenna/blob/71eebceccf37ac571d1bd161c4cfaa0a276fe513/lib/kenna.rb#L106-L118
|
6,481 |
chrisjones-tripletri/action_command
|
lib/action_command/log_parser.rb
|
ActionCommand.LogMessage.populate
|
def populate(line, msg)
@line = line
@sequence = msg['sequence']
@depth = msg['depth']
@cmd = msg['cmd']
@kind = msg['kind']
@msg = msg['msg']
@key = msg['key']
end
|
ruby
|
def populate(line, msg)
@line = line
@sequence = msg['sequence']
@depth = msg['depth']
@cmd = msg['cmd']
@kind = msg['kind']
@msg = msg['msg']
@key = msg['key']
end
|
[
"def",
"populate",
"(",
"line",
",",
"msg",
")",
"@line",
"=",
"line",
"@sequence",
"=",
"msg",
"[",
"'sequence'",
"]",
"@depth",
"=",
"msg",
"[",
"'depth'",
"]",
"@cmd",
"=",
"msg",
"[",
"'cmd'",
"]",
"@kind",
"=",
"msg",
"[",
"'kind'",
"]",
"@msg",
"=",
"msg",
"[",
"'msg'",
"]",
"@key",
"=",
"msg",
"[",
"'key'",
"]",
"end"
] |
Create a new log message
|
[
"Create",
"a",
"new",
"log",
"message"
] |
9b9a8ba30e407ca6d88a62a164d1dc22ba149874
|
https://github.com/chrisjones-tripletri/action_command/blob/9b9a8ba30e407ca6d88a62a164d1dc22ba149874/lib/action_command/log_parser.rb#L11-L19
|
6,482 |
chrisjones-tripletri/action_command
|
lib/action_command/log_parser.rb
|
ActionCommand.LogParser.next
|
def next(msg)
# be tolerant of the fact that there might be other
# stuff in the log file.
next_line do |input, line|
if input.key?('sequence')
msg.populate(line, input) unless @sequence && @sequence != input['sequence']
return true
end
end
return false
end
|
ruby
|
def next(msg)
# be tolerant of the fact that there might be other
# stuff in the log file.
next_line do |input, line|
if input.key?('sequence')
msg.populate(line, input) unless @sequence && @sequence != input['sequence']
return true
end
end
return false
end
|
[
"def",
"next",
"(",
"msg",
")",
"# be tolerant of the fact that there might be other ",
"# stuff in the log file.",
"next_line",
"do",
"|",
"input",
",",
"line",
"|",
"if",
"input",
".",
"key?",
"(",
"'sequence'",
")",
"msg",
".",
"populate",
"(",
"line",
",",
"input",
")",
"unless",
"@sequence",
"&&",
"@sequence",
"!=",
"input",
"[",
"'sequence'",
"]",
"return",
"true",
"end",
"end",
"return",
"false",
"end"
] |
Populates a message from the next line in the
|
[
"Populates",
"a",
"message",
"from",
"the",
"next",
"line",
"in",
"the"
] |
9b9a8ba30e407ca6d88a62a164d1dc22ba149874
|
https://github.com/chrisjones-tripletri/action_command/blob/9b9a8ba30e407ca6d88a62a164d1dc22ba149874/lib/action_command/log_parser.rb#L80-L90
|
6,483 |
codescrum/bebox
|
lib/bebox/project.rb
|
Bebox.Project.generate_ruby_version
|
def generate_ruby_version
ruby_version = (RUBY_PATCHLEVEL == 0) ? RUBY_VERSION : "#{RUBY_VERSION}-p#{RUBY_PATCHLEVEL}"
File.open("#{self.path}/.ruby-version", 'w') do |f|
f.write ruby_version
end
end
|
ruby
|
def generate_ruby_version
ruby_version = (RUBY_PATCHLEVEL == 0) ? RUBY_VERSION : "#{RUBY_VERSION}-p#{RUBY_PATCHLEVEL}"
File.open("#{self.path}/.ruby-version", 'w') do |f|
f.write ruby_version
end
end
|
[
"def",
"generate_ruby_version",
"ruby_version",
"=",
"(",
"RUBY_PATCHLEVEL",
"==",
"0",
")",
"?",
"RUBY_VERSION",
":",
"\"#{RUBY_VERSION}-p#{RUBY_PATCHLEVEL}\"",
"File",
".",
"open",
"(",
"\"#{self.path}/.ruby-version\"",
",",
"'w'",
")",
"do",
"|",
"f",
"|",
"f",
".",
"write",
"ruby_version",
"end",
"end"
] |
Create rbenv local
|
[
"Create",
"rbenv",
"local"
] |
0d19315847103341e599d32837ab0bd75524e5be
|
https://github.com/codescrum/bebox/blob/0d19315847103341e599d32837ab0bd75524e5be/lib/bebox/project.rb#L84-L89
|
6,484 |
codescrum/bebox
|
lib/bebox/project.rb
|
Bebox.Project.generate_steps_templates
|
def generate_steps_templates
Bebox::PROVISION_STEPS.each do |step|
ssh_key = ''
step_dir = Bebox::Provision.step_name(step)
templates_path = Bebox::Project::templates_path
# Generate site.pp template
generate_file_from_template("#{templates_path}/puppet/#{step}/manifests/site.pp.erb", "#{self.path}/puppet/steps/#{step_dir}/manifests/site.pp", {nodes: []})
# Generate hiera.yaml template
generate_file_from_template("#{templates_path}/puppet/#{step}/hiera/hiera.yaml.erb", "#{self.path}/puppet/steps/#{step_dir}/hiera/hiera.yaml", {step_dir: step_dir})
# Generate common.yaml template
generate_file_from_template("#{templates_path}/puppet/#{step}/hiera/data/common.yaml.erb", "#{self.path}/puppet/steps/#{step_dir}/hiera/data/common.yaml", {step_dir: step_dir, ssh_key: ssh_key, project_name: self.shortname})
end
end
|
ruby
|
def generate_steps_templates
Bebox::PROVISION_STEPS.each do |step|
ssh_key = ''
step_dir = Bebox::Provision.step_name(step)
templates_path = Bebox::Project::templates_path
# Generate site.pp template
generate_file_from_template("#{templates_path}/puppet/#{step}/manifests/site.pp.erb", "#{self.path}/puppet/steps/#{step_dir}/manifests/site.pp", {nodes: []})
# Generate hiera.yaml template
generate_file_from_template("#{templates_path}/puppet/#{step}/hiera/hiera.yaml.erb", "#{self.path}/puppet/steps/#{step_dir}/hiera/hiera.yaml", {step_dir: step_dir})
# Generate common.yaml template
generate_file_from_template("#{templates_path}/puppet/#{step}/hiera/data/common.yaml.erb", "#{self.path}/puppet/steps/#{step_dir}/hiera/data/common.yaml", {step_dir: step_dir, ssh_key: ssh_key, project_name: self.shortname})
end
end
|
[
"def",
"generate_steps_templates",
"Bebox",
"::",
"PROVISION_STEPS",
".",
"each",
"do",
"|",
"step",
"|",
"ssh_key",
"=",
"''",
"step_dir",
"=",
"Bebox",
"::",
"Provision",
".",
"step_name",
"(",
"step",
")",
"templates_path",
"=",
"Bebox",
"::",
"Project",
"::",
"templates_path",
"# Generate site.pp template",
"generate_file_from_template",
"(",
"\"#{templates_path}/puppet/#{step}/manifests/site.pp.erb\"",
",",
"\"#{self.path}/puppet/steps/#{step_dir}/manifests/site.pp\"",
",",
"{",
"nodes",
":",
"[",
"]",
"}",
")",
"# Generate hiera.yaml template",
"generate_file_from_template",
"(",
"\"#{templates_path}/puppet/#{step}/hiera/hiera.yaml.erb\"",
",",
"\"#{self.path}/puppet/steps/#{step_dir}/hiera/hiera.yaml\"",
",",
"{",
"step_dir",
":",
"step_dir",
"}",
")",
"# Generate common.yaml template",
"generate_file_from_template",
"(",
"\"#{templates_path}/puppet/#{step}/hiera/data/common.yaml.erb\"",
",",
"\"#{self.path}/puppet/steps/#{step_dir}/hiera/data/common.yaml\"",
",",
"{",
"step_dir",
":",
"step_dir",
",",
"ssh_key",
":",
"ssh_key",
",",
"project_name",
":",
"self",
".",
"shortname",
"}",
")",
"end",
"end"
] |
Generate steps templates for hiera and manifests files
|
[
"Generate",
"steps",
"templates",
"for",
"hiera",
"and",
"manifests",
"files"
] |
0d19315847103341e599d32837ab0bd75524e5be
|
https://github.com/codescrum/bebox/blob/0d19315847103341e599d32837ab0bd75524e5be/lib/bebox/project.rb#L165-L177
|
6,485 |
codescrum/bebox
|
lib/bebox/wizards/provision_wizard.rb
|
Bebox.ProvisionWizard.apply_step
|
def apply_step(project_root, environment, step)
# Check if environment has configured the ssh keys
(return warn _('wizard.provision.ssh_key_advice')%{environment: environment}) unless Bebox::Environment.check_environment_access(project_root, environment)
nodes_to_step = Bebox::Node.nodes_in_environment(project_root, environment, previous_checkpoint(step))
# Check if there are nodes for provisioning step-N
(return warn _('wizard.provision.no_provision_nodes')%{step: step}) unless nodes_to_step.count > 0
nodes_for_provisioning(nodes_to_step, step)
# Apply the nodes provisioning for step-N
in_step_nodes = Bebox::Node.list(project_root, environment, "steps/#{step}")
outputs = []
nodes_to_step.each do |node|
next unless check_node_to_step(node, in_step_nodes, step)
outputs << provision_step_in_node(project_root, environment, step, in_step_nodes, node)
end
return outputs
end
|
ruby
|
def apply_step(project_root, environment, step)
# Check if environment has configured the ssh keys
(return warn _('wizard.provision.ssh_key_advice')%{environment: environment}) unless Bebox::Environment.check_environment_access(project_root, environment)
nodes_to_step = Bebox::Node.nodes_in_environment(project_root, environment, previous_checkpoint(step))
# Check if there are nodes for provisioning step-N
(return warn _('wizard.provision.no_provision_nodes')%{step: step}) unless nodes_to_step.count > 0
nodes_for_provisioning(nodes_to_step, step)
# Apply the nodes provisioning for step-N
in_step_nodes = Bebox::Node.list(project_root, environment, "steps/#{step}")
outputs = []
nodes_to_step.each do |node|
next unless check_node_to_step(node, in_step_nodes, step)
outputs << provision_step_in_node(project_root, environment, step, in_step_nodes, node)
end
return outputs
end
|
[
"def",
"apply_step",
"(",
"project_root",
",",
"environment",
",",
"step",
")",
"# Check if environment has configured the ssh keys",
"(",
"return",
"warn",
"_",
"(",
"'wizard.provision.ssh_key_advice'",
")",
"%",
"{",
"environment",
":",
"environment",
"}",
")",
"unless",
"Bebox",
"::",
"Environment",
".",
"check_environment_access",
"(",
"project_root",
",",
"environment",
")",
"nodes_to_step",
"=",
"Bebox",
"::",
"Node",
".",
"nodes_in_environment",
"(",
"project_root",
",",
"environment",
",",
"previous_checkpoint",
"(",
"step",
")",
")",
"# Check if there are nodes for provisioning step-N",
"(",
"return",
"warn",
"_",
"(",
"'wizard.provision.no_provision_nodes'",
")",
"%",
"{",
"step",
":",
"step",
"}",
")",
"unless",
"nodes_to_step",
".",
"count",
">",
"0",
"nodes_for_provisioning",
"(",
"nodes_to_step",
",",
"step",
")",
"# Apply the nodes provisioning for step-N",
"in_step_nodes",
"=",
"Bebox",
"::",
"Node",
".",
"list",
"(",
"project_root",
",",
"environment",
",",
"\"steps/#{step}\"",
")",
"outputs",
"=",
"[",
"]",
"nodes_to_step",
".",
"each",
"do",
"|",
"node",
"|",
"next",
"unless",
"check_node_to_step",
"(",
"node",
",",
"in_step_nodes",
",",
"step",
")",
"outputs",
"<<",
"provision_step_in_node",
"(",
"project_root",
",",
"environment",
",",
"step",
",",
"in_step_nodes",
",",
"node",
")",
"end",
"return",
"outputs",
"end"
] |
Apply a step for the nodes in a environment
|
[
"Apply",
"a",
"step",
"for",
"the",
"nodes",
"in",
"a",
"environment"
] |
0d19315847103341e599d32837ab0bd75524e5be
|
https://github.com/codescrum/bebox/blob/0d19315847103341e599d32837ab0bd75524e5be/lib/bebox/wizards/provision_wizard.rb#L7-L22
|
6,486 |
GemHQ/coin-op
|
lib/coin-op/bit/fee.rb
|
CoinOp::Bit.Fee.estimate
|
def estimate(unspents, payees, network:, tx_size: nil, fee_per_kb: nil)
# https://en.bitcoin.it/wiki/Transaction_fees
# dupe because we'll need to add a change output
payees = payees.dup
unspent_total = unspents.inject(0) { |sum, output| sum += output.value }
payee_total = payees.inject(0) { |sum, payee| sum += payee.value }
nominal_change = unspent_total - payee_total
payees << Output.new(value: nominal_change, network: network) if nominal_change > 0
tx_size ||= estimate_tx_size(unspents, payees)
# conditions for 0-fee transactions
small = tx_size < 1000
min_payee = payees.min_by { |payee| payee.value }
big_outputs = min_payee.value > 1_000_000
high_priority = priority(
size: tx_size,
unspents: unspents.map { |output| { value: output.value, age: output.confirmations } }
) > PRIORITY_THRESHOLD
# 0-fee requirements met
return 0 if small && big_outputs && high_priority
# Otherwise, calculate the fee by size
fee_for_bytes(tx_size, network: network, fee_per_kb: fee_per_kb)
end
|
ruby
|
def estimate(unspents, payees, network:, tx_size: nil, fee_per_kb: nil)
# https://en.bitcoin.it/wiki/Transaction_fees
# dupe because we'll need to add a change output
payees = payees.dup
unspent_total = unspents.inject(0) { |sum, output| sum += output.value }
payee_total = payees.inject(0) { |sum, payee| sum += payee.value }
nominal_change = unspent_total - payee_total
payees << Output.new(value: nominal_change, network: network) if nominal_change > 0
tx_size ||= estimate_tx_size(unspents, payees)
# conditions for 0-fee transactions
small = tx_size < 1000
min_payee = payees.min_by { |payee| payee.value }
big_outputs = min_payee.value > 1_000_000
high_priority = priority(
size: tx_size,
unspents: unspents.map { |output| { value: output.value, age: output.confirmations } }
) > PRIORITY_THRESHOLD
# 0-fee requirements met
return 0 if small && big_outputs && high_priority
# Otherwise, calculate the fee by size
fee_for_bytes(tx_size, network: network, fee_per_kb: fee_per_kb)
end
|
[
"def",
"estimate",
"(",
"unspents",
",",
"payees",
",",
"network",
":",
",",
"tx_size",
":",
"nil",
",",
"fee_per_kb",
":",
"nil",
")",
"# https://en.bitcoin.it/wiki/Transaction_fees",
"# dupe because we'll need to add a change output",
"payees",
"=",
"payees",
".",
"dup",
"unspent_total",
"=",
"unspents",
".",
"inject",
"(",
"0",
")",
"{",
"|",
"sum",
",",
"output",
"|",
"sum",
"+=",
"output",
".",
"value",
"}",
"payee_total",
"=",
"payees",
".",
"inject",
"(",
"0",
")",
"{",
"|",
"sum",
",",
"payee",
"|",
"sum",
"+=",
"payee",
".",
"value",
"}",
"nominal_change",
"=",
"unspent_total",
"-",
"payee_total",
"payees",
"<<",
"Output",
".",
"new",
"(",
"value",
":",
"nominal_change",
",",
"network",
":",
"network",
")",
"if",
"nominal_change",
">",
"0",
"tx_size",
"||=",
"estimate_tx_size",
"(",
"unspents",
",",
"payees",
")",
"# conditions for 0-fee transactions",
"small",
"=",
"tx_size",
"<",
"1000",
"min_payee",
"=",
"payees",
".",
"min_by",
"{",
"|",
"payee",
"|",
"payee",
".",
"value",
"}",
"big_outputs",
"=",
"min_payee",
".",
"value",
">",
"1_000_000",
"high_priority",
"=",
"priority",
"(",
"size",
":",
"tx_size",
",",
"unspents",
":",
"unspents",
".",
"map",
"{",
"|",
"output",
"|",
"{",
"value",
":",
"output",
".",
"value",
",",
"age",
":",
"output",
".",
"confirmations",
"}",
"}",
")",
">",
"PRIORITY_THRESHOLD",
"# 0-fee requirements met",
"return",
"0",
"if",
"small",
"&&",
"big_outputs",
"&&",
"high_priority",
"# Otherwise, calculate the fee by size",
"fee_for_bytes",
"(",
"tx_size",
",",
"network",
":",
"network",
",",
"fee_per_kb",
":",
"fee_per_kb",
")",
"end"
] |
Given an array of unspent Outputs and an array of Outputs for a
Transaction, estimate the fee required for the transaction to be
included in a block.
Optionally takes an Integer tx_size specifying the transaction size in bytes
This is useful if you have the scriptSigs for the unspents, because
you can get a more accurate size than the estimate which is generated
here by default
Optionally takes an Integer fee_per_kb specifying the chosen cost per 1000
bytes to use
Returns the estimated fee in satoshis.
|
[
"Given",
"an",
"array",
"of",
"unspent",
"Outputs",
"and",
"an",
"array",
"of",
"Outputs",
"for",
"a",
"Transaction",
"estimate",
"the",
"fee",
"required",
"for",
"the",
"transaction",
"to",
"be",
"included",
"in",
"a",
"block",
"."
] |
0b704b52d9826405cffb1606e914bf21b8dcc681
|
https://github.com/GemHQ/coin-op/blob/0b704b52d9826405cffb1606e914bf21b8dcc681/lib/coin-op/bit/fee.rb#L28-L57
|
6,487 |
Thoughtwright-LLC/httpmagic
|
lib/http_magic/api.rb
|
HttpMagic.Api.post
|
def post(data = {})
request = Request.new(@uri,
headers: @headers,
data: data,
)
request.post
end
|
ruby
|
def post(data = {})
request = Request.new(@uri,
headers: @headers,
data: data,
)
request.post
end
|
[
"def",
"post",
"(",
"data",
"=",
"{",
"}",
")",
"request",
"=",
"Request",
".",
"new",
"(",
"@uri",
",",
"headers",
":",
"@headers",
",",
"data",
":",
"data",
",",
")",
"request",
".",
"post",
"end"
] |
POST's a resource from the URI and returns the result based on its content
type. JSON content will be parsed and returned as equivalent Ruby objects.
All other content types will be returned as text.
Assuming an api where each resource is namespaced with 'api/v1' and where
the url http://www.example.com/api/v1/foo/create responds with the
following when a 'name' is sent with the request.
Header:
Content-Type: application/json
Body:
{
"name": "New Foo"
}
== Example
class ExampleApi < HttpMagic::Api
url 'www.example.com'
namespace 'api/v1'
end
ExampleApi.foo.create.post(name: 'New Foo')
=> { "name" => "New Foo" }
|
[
"POST",
"s",
"a",
"resource",
"from",
"the",
"URI",
"and",
"returns",
"the",
"result",
"based",
"on",
"its",
"content",
"type",
".",
"JSON",
"content",
"will",
"be",
"parsed",
"and",
"returned",
"as",
"equivalent",
"Ruby",
"objects",
".",
"All",
"other",
"content",
"types",
"will",
"be",
"returned",
"as",
"text",
"."
] |
e37dba9965eae7252a6f9e5c5a6641683a275a75
|
https://github.com/Thoughtwright-LLC/httpmagic/blob/e37dba9965eae7252a6f9e5c5a6641683a275a75/lib/http_magic/api.rb#L220-L226
|
6,488 |
Thoughtwright-LLC/httpmagic
|
lib/http_magic/api.rb
|
HttpMagic.Api.put
|
def put(data = {})
request = Request.new(@uri,
headers: @headers,
data: data,
)
request.put
end
|
ruby
|
def put(data = {})
request = Request.new(@uri,
headers: @headers,
data: data,
)
request.put
end
|
[
"def",
"put",
"(",
"data",
"=",
"{",
"}",
")",
"request",
"=",
"Request",
".",
"new",
"(",
"@uri",
",",
"headers",
":",
"@headers",
",",
"data",
":",
"data",
",",
")",
"request",
".",
"put",
"end"
] |
PUT's a resource to the URI and returns the result based on its content
type. JSON content will be parsed and returned as equivalent Ruby objects.
All other content types will be returned as text.
Assuming an api where each resource is namespaced with 'api/v1' and where
a GET to the url http://www.example.com/api/v1/foo/99 responds with the
following.
Header:
Content-Type: application/json
Body:
{
"name": "Foo"
}
== Example
class ExampleApi < HttpMagic::Api
url 'www.example.com'
namespace 'api/v1'
end
ExampleApi.foo[99].put(name: 'Changed Foo')
=> { "name" => "Changed Foo" }
|
[
"PUT",
"s",
"a",
"resource",
"to",
"the",
"URI",
"and",
"returns",
"the",
"result",
"based",
"on",
"its",
"content",
"type",
".",
"JSON",
"content",
"will",
"be",
"parsed",
"and",
"returned",
"as",
"equivalent",
"Ruby",
"objects",
".",
"All",
"other",
"content",
"types",
"will",
"be",
"returned",
"as",
"text",
"."
] |
e37dba9965eae7252a6f9e5c5a6641683a275a75
|
https://github.com/Thoughtwright-LLC/httpmagic/blob/e37dba9965eae7252a6f9e5c5a6641683a275a75/lib/http_magic/api.rb#L255-L261
|
6,489 |
mayth/Chizuru
|
lib/chizuru/bot.rb
|
Chizuru.Bot.consumer
|
def consumer(cons, *init_args, &block)
if cons.instance_of? Class
cons = cons.new(*init_args)
end
ch = ConsumerHelper.new(cons, credential)
ch.instance_eval &block
provider.add_consumer(ch.consumer)
end
|
ruby
|
def consumer(cons, *init_args, &block)
if cons.instance_of? Class
cons = cons.new(*init_args)
end
ch = ConsumerHelper.new(cons, credential)
ch.instance_eval &block
provider.add_consumer(ch.consumer)
end
|
[
"def",
"consumer",
"(",
"cons",
",",
"*",
"init_args",
",",
"&",
"block",
")",
"if",
"cons",
".",
"instance_of?",
"Class",
"cons",
"=",
"cons",
".",
"new",
"(",
"init_args",
")",
"end",
"ch",
"=",
"ConsumerHelper",
".",
"new",
"(",
"cons",
",",
"credential",
")",
"ch",
".",
"instance_eval",
"block",
"provider",
".",
"add_consumer",
"(",
"ch",
".",
"consumer",
")",
"end"
] |
Adds a consumer.
* If an instance of Consumer or its subclasses is given, it is used.
* If Class is given, initialize its instance, and use it. In this case, the rest arguments are passed to the constructor of the given class.
|
[
"Adds",
"a",
"consumer",
"."
] |
361bc595c2e4257313d134fe0f4f4cca65c88383
|
https://github.com/mayth/Chizuru/blob/361bc595c2e4257313d134fe0f4f4cca65c88383/lib/chizuru/bot.rb#L46-L53
|
6,490 |
RISCfuture/has_metadata_column
|
lib/has_metadata_column.rb
|
HasMetadataColumn.Extensions.attribute
|
def attribute(attr)
return super unless self.class.metadata_column_fields.include?(attr.to_sym)
options = self.class.metadata_column_fields[attr.to_sym] || {}
default = options.include?(:default) ? options[:default] : nil
_metadata_hash.include?(attr) ? HasMetadataColumn.metadata_typecast(_metadata_hash[attr], options[:type]) : default
end
|
ruby
|
def attribute(attr)
return super unless self.class.metadata_column_fields.include?(attr.to_sym)
options = self.class.metadata_column_fields[attr.to_sym] || {}
default = options.include?(:default) ? options[:default] : nil
_metadata_hash.include?(attr) ? HasMetadataColumn.metadata_typecast(_metadata_hash[attr], options[:type]) : default
end
|
[
"def",
"attribute",
"(",
"attr",
")",
"return",
"super",
"unless",
"self",
".",
"class",
".",
"metadata_column_fields",
".",
"include?",
"(",
"attr",
".",
"to_sym",
")",
"options",
"=",
"self",
".",
"class",
".",
"metadata_column_fields",
"[",
"attr",
".",
"to_sym",
"]",
"||",
"{",
"}",
"default",
"=",
"options",
".",
"include?",
"(",
":default",
")",
"?",
"options",
"[",
":default",
"]",
":",
"nil",
"_metadata_hash",
".",
"include?",
"(",
"attr",
")",
"?",
"HasMetadataColumn",
".",
"metadata_typecast",
"(",
"_metadata_hash",
"[",
"attr",
"]",
",",
"options",
"[",
":type",
"]",
")",
":",
"default",
"end"
] |
ATTRIBUTE MATCHER METHODS
|
[
"ATTRIBUTE",
"MATCHER",
"METHODS"
] |
cd9793dfd137fac0c8d5168f83623347157c6f98
|
https://github.com/RISCfuture/has_metadata_column/blob/cd9793dfd137fac0c8d5168f83623347157c6f98/lib/has_metadata_column.rb#L251-L257
|
6,491 |
riddopic/hoodie
|
lib/hoodie/utils/ansi.rb
|
Hoodie.ANSI.build_ansi_methods
|
def build_ansi_methods(hash)
hash.each do |key, value|
define_method(key) do |string=nil, &block|
result = Array.new
result << %(\e[#{value}m)
if block_given?
result << block.call
elsif string.respond_to?(:to_str)
result << string.to_str
elsif respond_to?(:to_str)
result << to_str
else
return result
end
result << %(\e[0m)
result.join
end
end
true
end
|
ruby
|
def build_ansi_methods(hash)
hash.each do |key, value|
define_method(key) do |string=nil, &block|
result = Array.new
result << %(\e[#{value}m)
if block_given?
result << block.call
elsif string.respond_to?(:to_str)
result << string.to_str
elsif respond_to?(:to_str)
result << to_str
else
return result
end
result << %(\e[0m)
result.join
end
end
true
end
|
[
"def",
"build_ansi_methods",
"(",
"hash",
")",
"hash",
".",
"each",
"do",
"|",
"key",
",",
"value",
"|",
"define_method",
"(",
"key",
")",
"do",
"|",
"string",
"=",
"nil",
",",
"&",
"block",
"|",
"result",
"=",
"Array",
".",
"new",
"result",
"<<",
"%(\\e[#{value}m)",
"if",
"block_given?",
"result",
"<<",
"block",
".",
"call",
"elsif",
"string",
".",
"respond_to?",
"(",
":to_str",
")",
"result",
"<<",
"string",
".",
"to_str",
"elsif",
"respond_to?",
"(",
":to_str",
")",
"result",
"<<",
"to_str",
"else",
"return",
"result",
"end",
"result",
"<<",
"%(\\e[0m)",
"result",
".",
"join",
"end",
"end",
"true",
"end"
] |
Dynamicly constructs ANSI methods for the color methods based on the ANSI
code hash passed in.
@param [Hash] hash
A hash where the keys represent the method names and the values are the
ANSI codes.
@return [Boolean]
True if successful.
|
[
"Dynamicly",
"constructs",
"ANSI",
"methods",
"for",
"the",
"color",
"methods",
"based",
"on",
"the",
"ANSI",
"code",
"hash",
"passed",
"in",
"."
] |
921601dd4849845d3f5d3765dafcf00178b2aa66
|
https://github.com/riddopic/hoodie/blob/921601dd4849845d3f5d3765dafcf00178b2aa66/lib/hoodie/utils/ansi.rb#L127-L150
|
6,492 |
riddopic/hoodie
|
lib/hoodie/utils/ansi.rb
|
Hoodie.ANSI.uncolor
|
def uncolor(string = nil, &block)
if block_given?
block.call.to_str.gsub(ANSI_REGEX, '')
elsif string.respond_to?(:to_str)
string.to_str.gsub(ANSI_REGEX, '')
elsif respond_to?(:to_str)
to_str.gsub(ANSI_REGEX, '')
else
''
end
end
|
ruby
|
def uncolor(string = nil, &block)
if block_given?
block.call.to_str.gsub(ANSI_REGEX, '')
elsif string.respond_to?(:to_str)
string.to_str.gsub(ANSI_REGEX, '')
elsif respond_to?(:to_str)
to_str.gsub(ANSI_REGEX, '')
else
''
end
end
|
[
"def",
"uncolor",
"(",
"string",
"=",
"nil",
",",
"&",
"block",
")",
"if",
"block_given?",
"block",
".",
"call",
".",
"to_str",
".",
"gsub",
"(",
"ANSI_REGEX",
",",
"''",
")",
"elsif",
"string",
".",
"respond_to?",
"(",
":to_str",
")",
"string",
".",
"to_str",
".",
"gsub",
"(",
"ANSI_REGEX",
",",
"''",
")",
"elsif",
"respond_to?",
"(",
":to_str",
")",
"to_str",
".",
"gsub",
"(",
"ANSI_REGEX",
",",
"''",
")",
"else",
"''",
"end",
"end"
] |
Removes ANSI code sequences from a string.
@param [String] string
The string to operate on.
@yieldreturn [String]
The string to operate on.
@return [String]
The supplied string stripped of ANSI codes.
|
[
"Removes",
"ANSI",
"code",
"sequences",
"from",
"a",
"string",
"."
] |
921601dd4849845d3f5d3765dafcf00178b2aa66
|
https://github.com/riddopic/hoodie/blob/921601dd4849845d3f5d3765dafcf00178b2aa66/lib/hoodie/utils/ansi.rb#L163-L173
|
6,493 |
barkerest/incline
|
lib/incline/validators/recaptcha_validator.rb
|
Incline.RecaptchaValidator.validate_each
|
def validate_each(record, attribute, value)
# Do NOT raise an error if nil.
return if value.blank?
# Make sure the response only gets processed once.
return if value == :verified
# Automatically skip validation if paused.
return if Incline::Recaptcha::paused?
# If the user form includes the recaptcha field, then something will come in
# and then we want to check it.
remote_ip, _, response = value.partition('|')
if remote_ip.blank? || response.blank?
record.errors[:base] << (options[:message] || 'Requires reCAPTCHA challenge to be completed')
else
if Incline::Recaptcha::verify(response: response, remote_ip: remote_ip)
record.send "#{attribute}=", :verified
else
record.errors[:base] << (options[:message] || 'Invalid response from reCAPTCHA challenge')
end
end
end
|
ruby
|
def validate_each(record, attribute, value)
# Do NOT raise an error if nil.
return if value.blank?
# Make sure the response only gets processed once.
return if value == :verified
# Automatically skip validation if paused.
return if Incline::Recaptcha::paused?
# If the user form includes the recaptcha field, then something will come in
# and then we want to check it.
remote_ip, _, response = value.partition('|')
if remote_ip.blank? || response.blank?
record.errors[:base] << (options[:message] || 'Requires reCAPTCHA challenge to be completed')
else
if Incline::Recaptcha::verify(response: response, remote_ip: remote_ip)
record.send "#{attribute}=", :verified
else
record.errors[:base] << (options[:message] || 'Invalid response from reCAPTCHA challenge')
end
end
end
|
[
"def",
"validate_each",
"(",
"record",
",",
"attribute",
",",
"value",
")",
"# Do NOT raise an error if nil.",
"return",
"if",
"value",
".",
"blank?",
"# Make sure the response only gets processed once.",
"return",
"if",
"value",
"==",
":verified",
"# Automatically skip validation if paused.",
"return",
"if",
"Incline",
"::",
"Recaptcha",
"::",
"paused?",
"# If the user form includes the recaptcha field, then something will come in",
"# and then we want to check it.",
"remote_ip",
",",
"_",
",",
"response",
"=",
"value",
".",
"partition",
"(",
"'|'",
")",
"if",
"remote_ip",
".",
"blank?",
"||",
"response",
".",
"blank?",
"record",
".",
"errors",
"[",
":base",
"]",
"<<",
"(",
"options",
"[",
":message",
"]",
"||",
"'Requires reCAPTCHA challenge to be completed'",
")",
"else",
"if",
"Incline",
"::",
"Recaptcha",
"::",
"verify",
"(",
"response",
":",
"response",
",",
"remote_ip",
":",
"remote_ip",
")",
"record",
".",
"send",
"\"#{attribute}=\"",
",",
":verified",
"else",
"record",
".",
"errors",
"[",
":base",
"]",
"<<",
"(",
"options",
"[",
":message",
"]",
"||",
"'Invalid response from reCAPTCHA challenge'",
")",
"end",
"end",
"end"
] |
Validates a reCAPTCHA attribute.
The value of the attribute should be a hash with two keys: :response, :remote_ip
|
[
"Validates",
"a",
"reCAPTCHA",
"attribute",
"."
] |
1ff08db7aa8ab7f86b223268b700bc67d15bb8aa
|
https://github.com/barkerest/incline/blob/1ff08db7aa8ab7f86b223268b700bc67d15bb8aa/lib/incline/validators/recaptcha_validator.rb#L11-L34
|
6,494 |
djspinmonkey/classy
|
lib/classy/aliasable.rb
|
Aliasable.ControllingClassMethods.included
|
def included( klass )
klass.extend AliasingClassMethods
klass.extend UniversalClassMethods
# Hoo boy. We need to set the @@classy_aliases class variable in the
# including class to point to the same actual hash object that the
# @@classy_aliases variable on the controlling module points to. When
# everything is class based, this is done automatically, since
# sub-classes share class variables.
#
klass.send(:class_variable_set, :@@classy_aliases, self.send(:class_variable_get, :@@classy_aliases))
super
end
|
ruby
|
def included( klass )
klass.extend AliasingClassMethods
klass.extend UniversalClassMethods
# Hoo boy. We need to set the @@classy_aliases class variable in the
# including class to point to the same actual hash object that the
# @@classy_aliases variable on the controlling module points to. When
# everything is class based, this is done automatically, since
# sub-classes share class variables.
#
klass.send(:class_variable_set, :@@classy_aliases, self.send(:class_variable_get, :@@classy_aliases))
super
end
|
[
"def",
"included",
"(",
"klass",
")",
"klass",
".",
"extend",
"AliasingClassMethods",
"klass",
".",
"extend",
"UniversalClassMethods",
"# Hoo boy. We need to set the @@classy_aliases class variable in the",
"# including class to point to the same actual hash object that the",
"# @@classy_aliases variable on the controlling module points to. When",
"# everything is class based, this is done automatically, since",
"# sub-classes share class variables.",
"#",
"klass",
".",
"send",
"(",
":class_variable_set",
",",
":@@classy_aliases",
",",
"self",
".",
"send",
"(",
":class_variable_get",
",",
":@@classy_aliases",
")",
")",
"super",
"end"
] |
Handle a class including a module that has included Aliasable. Since the
contolling module has extended this module, this method ends up being
called when the controlling module is included.
As a minor side effect, an instance method named #included ends up on any
class that directly includes Aliasable. If you know an elegant way to
avoid this, I welcome pull requests. :-)
:nodoc:
|
[
"Handle",
"a",
"class",
"including",
"a",
"module",
"that",
"has",
"included",
"Aliasable",
".",
"Since",
"the",
"contolling",
"module",
"has",
"extended",
"this",
"module",
"this",
"method",
"ends",
"up",
"being",
"called",
"when",
"the",
"controlling",
"module",
"is",
"included",
"."
] |
1589e2ae33c7fb7fc7ec88b0c24d7df18e2594b3
|
https://github.com/djspinmonkey/classy/blob/1589e2ae33c7fb7fc7ec88b0c24d7df18e2594b3/lib/classy/aliasable.rb#L73-L86
|
6,495 |
rayko/da_face
|
lib/da_face/utilities.rb
|
DaFace.Utilities.symbolize_keys
|
def symbolize_keys keys, hash
new_hash = {}
keys.each do |key|
if hash[key].kind_of? Hash
new_hash[key.to_sym] = symbolize_keys(hash[key].keys, hash[key])
elsif hash[key].kind_of? Array
new_hash[key.to_sym] = []
hash[key].each do |item|
if item.kind_of? Hash
new_hash[key.to_sym] << symbolize_keys(item.keys, item)
else
new_hash[key.to_sym] << item
end
end
else
new_hash[key.to_sym] = hash[key]
end
end
return new_hash
end
|
ruby
|
def symbolize_keys keys, hash
new_hash = {}
keys.each do |key|
if hash[key].kind_of? Hash
new_hash[key.to_sym] = symbolize_keys(hash[key].keys, hash[key])
elsif hash[key].kind_of? Array
new_hash[key.to_sym] = []
hash[key].each do |item|
if item.kind_of? Hash
new_hash[key.to_sym] << symbolize_keys(item.keys, item)
else
new_hash[key.to_sym] << item
end
end
else
new_hash[key.to_sym] = hash[key]
end
end
return new_hash
end
|
[
"def",
"symbolize_keys",
"keys",
",",
"hash",
"new_hash",
"=",
"{",
"}",
"keys",
".",
"each",
"do",
"|",
"key",
"|",
"if",
"hash",
"[",
"key",
"]",
".",
"kind_of?",
"Hash",
"new_hash",
"[",
"key",
".",
"to_sym",
"]",
"=",
"symbolize_keys",
"(",
"hash",
"[",
"key",
"]",
".",
"keys",
",",
"hash",
"[",
"key",
"]",
")",
"elsif",
"hash",
"[",
"key",
"]",
".",
"kind_of?",
"Array",
"new_hash",
"[",
"key",
".",
"to_sym",
"]",
"=",
"[",
"]",
"hash",
"[",
"key",
"]",
".",
"each",
"do",
"|",
"item",
"|",
"if",
"item",
".",
"kind_of?",
"Hash",
"new_hash",
"[",
"key",
".",
"to_sym",
"]",
"<<",
"symbolize_keys",
"(",
"item",
".",
"keys",
",",
"item",
")",
"else",
"new_hash",
"[",
"key",
".",
"to_sym",
"]",
"<<",
"item",
"end",
"end",
"else",
"new_hash",
"[",
"key",
".",
"to_sym",
"]",
"=",
"hash",
"[",
"key",
"]",
"end",
"end",
"return",
"new_hash",
"end"
] |
Creates a new hash with all keys as symbols, can be
any level of depth
|
[
"Creates",
"a",
"new",
"hash",
"with",
"all",
"keys",
"as",
"symbols",
"can",
"be",
"any",
"level",
"of",
"depth"
] |
6260f4dc420fcc59a6985be0df248cb4773c4bf2
|
https://github.com/rayko/da_face/blob/6260f4dc420fcc59a6985be0df248cb4773c4bf2/lib/da_face/utilities.rb#L6-L26
|
6,496 |
wedesoft/multiarray
|
lib/multiarray/shortcuts.rb
|
Hornetseye.MultiArrayConstructor.constructor_shortcut
|
def constructor_shortcut( target )
define_method target.to_s.downcase do |*args|
new target, *args
end
end
|
ruby
|
def constructor_shortcut( target )
define_method target.to_s.downcase do |*args|
new target, *args
end
end
|
[
"def",
"constructor_shortcut",
"(",
"target",
")",
"define_method",
"target",
".",
"to_s",
".",
"downcase",
"do",
"|",
"*",
"args",
"|",
"new",
"target",
",",
"args",
"end",
"end"
] |
Meta-programming method for creating constructor shortcut methods
@param [Class] target Element-type to create constructor shortcut for.
@return [Proc] The new method.
@private
|
[
"Meta",
"-",
"programming",
"method",
"for",
"creating",
"constructor",
"shortcut",
"methods"
] |
1ae1d98bacb4b941d6f406e44ccb184de12f83d9
|
https://github.com/wedesoft/multiarray/blob/1ae1d98bacb4b941d6f406e44ccb184de12f83d9/lib/multiarray/shortcuts.rb#L30-L34
|
6,497 |
anga/BetterRailsDebugger
|
lib/better_rails_debugger/analyzer.rb
|
BetterRailsDebugger.Analyzer.collect_information
|
def collect_information(identifier, group_id)
group = ::BetterRailsDebugger::AnalysisGroup.find group_id
if not group.present?
Rails.logger.error "[BetterRailsDebugger] Group '#{recorded[:group_id]}' not found. Skiping..."
return
end
# Load Mongo db if required
if not Mongoid::Config.configured?
Mongoid.load!(BetterRailsDebugger::Configuration.instance.mongoid_config_file, Rails.env.to_sym)
Mongoid.logger.level = Logger::FATAL
end
instance = ::BetterRailsDebugger::GroupInstance.create identifier: identifier, analysis_group_id: group_id, caller_file: caller[3][/[^:]+/], status: 'pending'
collect_memory_information(instance)
collect_trace_point_history(instance)
# Now, it's time to analyze all collected data and generate a report
::BetterRailsDebugger::AnalysisRecorderJob.perform_later({ instance_id: instance.id.to_s })
end
|
ruby
|
def collect_information(identifier, group_id)
group = ::BetterRailsDebugger::AnalysisGroup.find group_id
if not group.present?
Rails.logger.error "[BetterRailsDebugger] Group '#{recorded[:group_id]}' not found. Skiping..."
return
end
# Load Mongo db if required
if not Mongoid::Config.configured?
Mongoid.load!(BetterRailsDebugger::Configuration.instance.mongoid_config_file, Rails.env.to_sym)
Mongoid.logger.level = Logger::FATAL
end
instance = ::BetterRailsDebugger::GroupInstance.create identifier: identifier, analysis_group_id: group_id, caller_file: caller[3][/[^:]+/], status: 'pending'
collect_memory_information(instance)
collect_trace_point_history(instance)
# Now, it's time to analyze all collected data and generate a report
::BetterRailsDebugger::AnalysisRecorderJob.perform_later({ instance_id: instance.id.to_s })
end
|
[
"def",
"collect_information",
"(",
"identifier",
",",
"group_id",
")",
"group",
"=",
"::",
"BetterRailsDebugger",
"::",
"AnalysisGroup",
".",
"find",
"group_id",
"if",
"not",
"group",
".",
"present?",
"Rails",
".",
"logger",
".",
"error",
"\"[BetterRailsDebugger] Group '#{recorded[:group_id]}' not found. Skiping...\"",
"return",
"end",
"# Load Mongo db if required",
"if",
"not",
"Mongoid",
"::",
"Config",
".",
"configured?",
"Mongoid",
".",
"load!",
"(",
"BetterRailsDebugger",
"::",
"Configuration",
".",
"instance",
".",
"mongoid_config_file",
",",
"Rails",
".",
"env",
".",
"to_sym",
")",
"Mongoid",
".",
"logger",
".",
"level",
"=",
"Logger",
"::",
"FATAL",
"end",
"instance",
"=",
"::",
"BetterRailsDebugger",
"::",
"GroupInstance",
".",
"create",
"identifier",
":",
"identifier",
",",
"analysis_group_id",
":",
"group_id",
",",
"caller_file",
":",
"caller",
"[",
"3",
"]",
"[",
"/",
"/",
"]",
",",
"status",
":",
"'pending'",
"collect_memory_information",
"(",
"instance",
")",
"collect_trace_point_history",
"(",
"instance",
")",
"# Now, it's time to analyze all collected data and generate a report",
"::",
"BetterRailsDebugger",
"::",
"AnalysisRecorderJob",
".",
"perform_later",
"(",
"{",
"instance_id",
":",
"instance",
".",
"id",
".",
"to_s",
"}",
")",
"end"
] |
Record into db, information about object creation
|
[
"Record",
"into",
"db",
"information",
"about",
"object",
"creation"
] |
2ac7af13b8ee12483bd9a92680d8f43042f1f1d5
|
https://github.com/anga/BetterRailsDebugger/blob/2ac7af13b8ee12483bd9a92680d8f43042f1f1d5/lib/better_rails_debugger/analyzer.rb#L63-L83
|
6,498 |
tclaus/keytechkit.gem
|
lib/keytechKit/elements/element_files/element_file_handler.rb
|
KeytechKit.ElementFileHandler.masterfile?
|
def masterfile?(element_key)
if Tools.class_type(element_key) == 'DO' # Only DO Types can have a file
file_list = load(element_key)
unless file_list.nil?
file_list.each do |file|
return true if file.fileStorageType.casecmp('master').zero?
end
end
end
false
end
|
ruby
|
def masterfile?(element_key)
if Tools.class_type(element_key) == 'DO' # Only DO Types can have a file
file_list = load(element_key)
unless file_list.nil?
file_list.each do |file|
return true if file.fileStorageType.casecmp('master').zero?
end
end
end
false
end
|
[
"def",
"masterfile?",
"(",
"element_key",
")",
"if",
"Tools",
".",
"class_type",
"(",
"element_key",
")",
"==",
"'DO'",
"# Only DO Types can have a file",
"file_list",
"=",
"load",
"(",
"element_key",
")",
"unless",
"file_list",
".",
"nil?",
"file_list",
".",
"each",
"do",
"|",
"file",
"|",
"return",
"true",
"if",
"file",
".",
"fileStorageType",
".",
"casecmp",
"(",
"'master'",
")",
".",
"zero?",
"end",
"end",
"end",
"false",
"end"
] |
Returns true or false if a masterfile exist
|
[
"Returns",
"true",
"or",
"false",
"if",
"a",
"masterfile",
"exist"
] |
caa7a6bee32b75ec18a4004179ae10cb69d148c2
|
https://github.com/tclaus/keytechkit.gem/blob/caa7a6bee32b75ec18a4004179ae10cb69d148c2/lib/keytechKit/elements/element_files/element_file_handler.rb#L17-L27
|
6,499 |
tclaus/keytechkit.gem
|
lib/keytechKit/elements/element_files/element_file_handler.rb
|
KeytechKit.ElementFileHandler.masterfile_name
|
def masterfile_name(element_key)
file_list = load(element_key)
unless file_list.nil?
file_list.each do |file|
return file.fileName if file.fileStorageType.downcase! == 'master'
end
end
''
end
|
ruby
|
def masterfile_name(element_key)
file_list = load(element_key)
unless file_list.nil?
file_list.each do |file|
return file.fileName if file.fileStorageType.downcase! == 'master'
end
end
''
end
|
[
"def",
"masterfile_name",
"(",
"element_key",
")",
"file_list",
"=",
"load",
"(",
"element_key",
")",
"unless",
"file_list",
".",
"nil?",
"file_list",
".",
"each",
"do",
"|",
"file",
"|",
"return",
"file",
".",
"fileName",
"if",
"file",
".",
"fileStorageType",
".",
"downcase!",
"==",
"'master'",
"end",
"end",
"''",
"end"
] |
Returns the name of a masterfile if present
|
[
"Returns",
"the",
"name",
"of",
"a",
"masterfile",
"if",
"present"
] |
caa7a6bee32b75ec18a4004179ae10cb69d148c2
|
https://github.com/tclaus/keytechkit.gem/blob/caa7a6bee32b75ec18a4004179ae10cb69d148c2/lib/keytechKit/elements/element_files/element_file_handler.rb#L43-L51
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.