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
16,900
TwP/logging
lib/logging/color_scheme.rb
Logging.ColorScheme.[]=
def []=( color_tag, constants ) @scheme[to_key(color_tag)] = constants.respond_to?(:map) ? constants.map { |c| to_constant(c) }.join : to_constant(constants) end
ruby
def []=( color_tag, constants ) @scheme[to_key(color_tag)] = constants.respond_to?(:map) ? constants.map { |c| to_constant(c) }.join : to_constant(constants) end
[ "def", "[]=", "(", "color_tag", ",", "constants", ")", "@scheme", "[", "to_key", "(", "color_tag", ")", "]", "=", "constants", ".", "respond_to?", "(", ":map", ")", "?", "constants", ".", "map", "{", "|", "c", "|", "to_constant", "(", "c", ")", "}", ".", "join", ":", "to_constant", "(", "constants", ")", "end" ]
Allow the scheme to be set like a Hash.
[ "Allow", "the", "scheme", "to", "be", "set", "like", "a", "Hash", "." ]
aa9a5b840479f4176504e4c53ce29d8d01315ccc
https://github.com/TwP/logging/blob/aa9a5b840479f4176504e4c53ce29d8d01315ccc/lib/logging/color_scheme.rb#L172-L175
16,901
TwP/logging
lib/logging/color_scheme.rb
Logging.ColorScheme.to_constant
def to_constant( v ) v = v.to_s.upcase ColorScheme.const_get(v) if (ColorScheme.const_defined?(v, false) rescue ColorScheme.const_defined?(v)) end
ruby
def to_constant( v ) v = v.to_s.upcase ColorScheme.const_get(v) if (ColorScheme.const_defined?(v, false) rescue ColorScheme.const_defined?(v)) end
[ "def", "to_constant", "(", "v", ")", "v", "=", "v", ".", "to_s", ".", "upcase", "ColorScheme", ".", "const_get", "(", "v", ")", "if", "(", "ColorScheme", ".", "const_defined?", "(", "v", ",", "false", ")", "rescue", "ColorScheme", ".", "const_defined?", "(", "v", ")", ")", "end" ]
Return a normalized representation of a color setting.
[ "Return", "a", "normalized", "representation", "of", "a", "color", "setting", "." ]
aa9a5b840479f4176504e4c53ce29d8d01315ccc
https://github.com/TwP/logging/blob/aa9a5b840479f4176504e4c53ce29d8d01315ccc/lib/logging/color_scheme.rb#L206-L209
16,902
TwP/logging
lib/logging/appender.rb
Logging.Appender.encoding=
def encoding=( value ) if value.nil? @encoding = nil else @encoding = Object.const_defined?(:Encoding) ? Encoding.find(value.to_s) : nil end end
ruby
def encoding=( value ) if value.nil? @encoding = nil else @encoding = Object.const_defined?(:Encoding) ? Encoding.find(value.to_s) : nil end end
[ "def", "encoding", "=", "(", "value", ")", "if", "value", ".", "nil?", "@encoding", "=", "nil", "else", "@encoding", "=", "Object", ".", "const_defined?", "(", ":Encoding", ")", "?", "Encoding", ".", "find", "(", "value", ".", "to_s", ")", ":", "nil", "end", "end" ]
Set the appender encoding to the given value. The value can either be an Encoding instance or a String or Symbol referring to a valid encoding. This method only applies to Ruby 1.9 or later. The encoding will always be nil for older Rubies. value - The encoding as a String, Symbol, or Encoding instance. Raises ArgumentError if the value is not a valid encoding.
[ "Set", "the", "appender", "encoding", "to", "the", "given", "value", ".", "The", "value", "can", "either", "be", "an", "Encoding", "instance", "or", "a", "String", "or", "Symbol", "referring", "to", "a", "valid", "encoding", "." ]
aa9a5b840479f4176504e4c53ce29d8d01315ccc
https://github.com/TwP/logging/blob/aa9a5b840479f4176504e4c53ce29d8d01315ccc/lib/logging/appender.rb#L283-L289
16,903
TwP/logging
lib/logging/appender.rb
Logging.Appender.allow
def allow( event ) return nil if @level > event.level @filters.each do |filter| break unless event = filter.allow(event) end event end
ruby
def allow( event ) return nil if @level > event.level @filters.each do |filter| break unless event = filter.allow(event) end event end
[ "def", "allow", "(", "event", ")", "return", "nil", "if", "@level", ">", "event", ".", "level", "@filters", ".", "each", "do", "|", "filter", "|", "break", "unless", "event", "=", "filter", ".", "allow", "(", "event", ")", "end", "event", "end" ]
Check to see if the event should be processed by the appender. An event will be rejected if the event level is lower than the configured level for the appender. Or it will be rejected if one of the filters rejects the event. event - The LogEvent to check Returns the event if it is allowed; returns `nil` if it is not allowed.
[ "Check", "to", "see", "if", "the", "event", "should", "be", "processed", "by", "the", "appender", ".", "An", "event", "will", "be", "rejected", "if", "the", "event", "level", "is", "lower", "than", "the", "configured", "level", "for", "the", "appender", ".", "Or", "it", "will", "be", "rejected", "if", "one", "of", "the", "filters", "rejects", "the", "event", "." ]
aa9a5b840479f4176504e4c53ce29d8d01315ccc
https://github.com/TwP/logging/blob/aa9a5b840479f4176504e4c53ce29d8d01315ccc/lib/logging/appender.rb#L298-L304
16,904
TwP/logging
lib/logging/diagnostic_context.rb
Logging.MappedDiagnosticContext.context
def context c = Thread.current.thread_variable_get(NAME) if c.nil? c = if Thread.current.thread_variable_get(STACK_NAME) flatten(stack) else Hash.new end Thread.current.thread_variable_set(NAME, c) end return c end
ruby
def context c = Thread.current.thread_variable_get(NAME) if c.nil? c = if Thread.current.thread_variable_get(STACK_NAME) flatten(stack) else Hash.new end Thread.current.thread_variable_set(NAME, c) end return c end
[ "def", "context", "c", "=", "Thread", ".", "current", ".", "thread_variable_get", "(", "NAME", ")", "if", "c", ".", "nil?", "c", "=", "if", "Thread", ".", "current", ".", "thread_variable_get", "(", "STACK_NAME", ")", "flatten", "(", "stack", ")", "else", "Hash", ".", "new", "end", "Thread", ".", "current", ".", "thread_variable_set", "(", "NAME", ",", "c", ")", "end", "return", "c", "end" ]
Returns the Hash acting as the storage for this MappedDiagnosticContext. A new storage Hash is created for each Thread running in the application.
[ "Returns", "the", "Hash", "acting", "as", "the", "storage", "for", "this", "MappedDiagnosticContext", ".", "A", "new", "storage", "Hash", "is", "created", "for", "each", "Thread", "running", "in", "the", "application", "." ]
aa9a5b840479f4176504e4c53ce29d8d01315ccc
https://github.com/TwP/logging/blob/aa9a5b840479f4176504e4c53ce29d8d01315ccc/lib/logging/diagnostic_context.rb#L160-L173
16,905
TwP/logging
lib/logging/diagnostic_context.rb
Logging.MappedDiagnosticContext.stack
def stack s = Thread.current.thread_variable_get(STACK_NAME) if s.nil? s = [{}] Thread.current.thread_variable_set(STACK_NAME, s) end return s end
ruby
def stack s = Thread.current.thread_variable_get(STACK_NAME) if s.nil? s = [{}] Thread.current.thread_variable_set(STACK_NAME, s) end return s end
[ "def", "stack", "s", "=", "Thread", ".", "current", ".", "thread_variable_get", "(", "STACK_NAME", ")", "if", "s", ".", "nil?", "s", "=", "[", "{", "}", "]", "Thread", ".", "current", ".", "thread_variable_set", "(", "STACK_NAME", ",", "s", ")", "end", "return", "s", "end" ]
Returns the stack of Hash objects that are storing the diagnostic context information. This stack is guarnteed to always contain at least one Hash.
[ "Returns", "the", "stack", "of", "Hash", "objects", "that", "are", "storing", "the", "diagnostic", "context", "information", ".", "This", "stack", "is", "guarnteed", "to", "always", "contain", "at", "least", "one", "Hash", "." ]
aa9a5b840479f4176504e4c53ce29d8d01315ccc
https://github.com/TwP/logging/blob/aa9a5b840479f4176504e4c53ce29d8d01315ccc/lib/logging/diagnostic_context.rb#L179-L186
16,906
TwP/logging
lib/logging/diagnostic_context.rb
Logging.MappedDiagnosticContext.sanitize
def sanitize( hash, target = {} ) unless hash.is_a?(Hash) raise ArgumentError, "Expecting a Hash but received a #{hash.class.name}" end hash.each { |k,v| target[k.to_s] = v } return target end
ruby
def sanitize( hash, target = {} ) unless hash.is_a?(Hash) raise ArgumentError, "Expecting a Hash but received a #{hash.class.name}" end hash.each { |k,v| target[k.to_s] = v } return target end
[ "def", "sanitize", "(", "hash", ",", "target", "=", "{", "}", ")", "unless", "hash", ".", "is_a?", "(", "Hash", ")", "raise", "ArgumentError", ",", "\"Expecting a Hash but received a #{hash.class.name}\"", "end", "hash", ".", "each", "{", "|", "k", ",", "v", "|", "target", "[", "k", ".", "to_s", "]", "=", "v", "}", "return", "target", "end" ]
Given a Hash convert all keys into Strings. The values are not altered in any way. The converted keys and their values are stored in the target Hash if provided. Otherwise a new Hash is created and returned. hash - The Hash of values to push onto the context stack. target - The target Hash to store the key value pairs. Returns a new Hash with all keys converted to Strings. Raises an ArgumentError if hash is not a Hash.
[ "Given", "a", "Hash", "convert", "all", "keys", "into", "Strings", ".", "The", "values", "are", "not", "altered", "in", "any", "way", ".", "The", "converted", "keys", "and", "their", "values", "are", "stored", "in", "the", "target", "Hash", "if", "provided", ".", "Otherwise", "a", "new", "Hash", "is", "created", "and", "returned", "." ]
aa9a5b840479f4176504e4c53ce29d8d01315ccc
https://github.com/TwP/logging/blob/aa9a5b840479f4176504e4c53ce29d8d01315ccc/lib/logging/diagnostic_context.rb#L211-L218
16,907
TwP/logging
lib/logging/diagnostic_context.rb
Logging.NestedDiagnosticContext.context
def context c = Thread.current.thread_variable_get(NAME) if c.nil? c = Array.new Thread.current.thread_variable_set(NAME, c) end return c end
ruby
def context c = Thread.current.thread_variable_get(NAME) if c.nil? c = Array.new Thread.current.thread_variable_set(NAME, c) end return c end
[ "def", "context", "c", "=", "Thread", ".", "current", ".", "thread_variable_get", "(", "NAME", ")", "if", "c", ".", "nil?", "c", "=", "Array", ".", "new", "Thread", ".", "current", ".", "thread_variable_set", "(", "NAME", ",", "c", ")", "end", "return", "c", "end" ]
Returns the Array acting as the storage stack for this NestedDiagnosticContext. A new storage Array is created for each Thread running in the application.
[ "Returns", "the", "Array", "acting", "as", "the", "storage", "stack", "for", "this", "NestedDiagnosticContext", ".", "A", "new", "storage", "Array", "is", "created", "for", "each", "Thread", "running", "in", "the", "application", "." ]
aa9a5b840479f4176504e4c53ce29d8d01315ccc
https://github.com/TwP/logging/blob/aa9a5b840479f4176504e4c53ce29d8d01315ccc/lib/logging/diagnostic_context.rb#L363-L370
16,908
TwP/logging
lib/logging/layouts/parseable.rb
Logging::Layouts.Parseable.iso8601_format
def iso8601_format( time ) value = apply_utc_offset(time) str = value.strftime('%Y-%m-%dT%H:%M:%S') str << ('.%06d' % value.usec) offset = value.gmt_offset.abs return str << 'Z' if offset == 0 offset = sprintf('%02d:%02d', offset / 3600, offset % 3600 / 60) return str << (value.gmt_offset < 0 ? '-' : '+') << offset end
ruby
def iso8601_format( time ) value = apply_utc_offset(time) str = value.strftime('%Y-%m-%dT%H:%M:%S') str << ('.%06d' % value.usec) offset = value.gmt_offset.abs return str << 'Z' if offset == 0 offset = sprintf('%02d:%02d', offset / 3600, offset % 3600 / 60) return str << (value.gmt_offset < 0 ? '-' : '+') << offset end
[ "def", "iso8601_format", "(", "time", ")", "value", "=", "apply_utc_offset", "(", "time", ")", "str", "=", "value", ".", "strftime", "(", "'%Y-%m-%dT%H:%M:%S'", ")", "str", "<<", "(", "'.%06d'", "%", "value", ".", "usec", ")", "offset", "=", "value", ".", "gmt_offset", ".", "abs", "return", "str", "<<", "'Z'", "if", "offset", "==", "0", "offset", "=", "sprintf", "(", "'%02d:%02d'", ",", "offset", "/", "3600", ",", "offset", "%", "3600", "/", "60", ")", "return", "str", "<<", "(", "value", ".", "gmt_offset", "<", "0", "?", "'-'", ":", "'+'", ")", "<<", "offset", "end" ]
Convert the given `time` into an ISO8601 formatted time string.
[ "Convert", "the", "given", "time", "into", "an", "ISO8601", "formatted", "time", "string", "." ]
aa9a5b840479f4176504e4c53ce29d8d01315ccc
https://github.com/TwP/logging/blob/aa9a5b840479f4176504e4c53ce29d8d01315ccc/lib/logging/layouts/parseable.rb#L283-L294
16,909
cfndsl/cfndsl
lib/cfndsl/jsonable.rb
CfnDsl.JSONable.as_json
def as_json(_options = {}) hash = {} instance_variables.each do |var| name = var[1..-1] if name =~ /^__/ # if a variable starts with double underscore, strip one off name = name[1..-1] elsif name =~ /^_/ # Hide variables that start with single underscore name = nil end hash[name] = instance_variable_get(var) if name end hash end
ruby
def as_json(_options = {}) hash = {} instance_variables.each do |var| name = var[1..-1] if name =~ /^__/ # if a variable starts with double underscore, strip one off name = name[1..-1] elsif name =~ /^_/ # Hide variables that start with single underscore name = nil end hash[name] = instance_variable_get(var) if name end hash end
[ "def", "as_json", "(", "_options", "=", "{", "}", ")", "hash", "=", "{", "}", "instance_variables", ".", "each", "do", "|", "var", "|", "name", "=", "var", "[", "1", "..", "-", "1", "]", "if", "name", "=~", "/", "/", "# if a variable starts with double underscore, strip one off", "name", "=", "name", "[", "1", "..", "-", "1", "]", "elsif", "name", "=~", "/", "/", "# Hide variables that start with single underscore", "name", "=", "nil", "end", "hash", "[", "name", "]", "=", "instance_variable_get", "(", "var", ")", "if", "name", "end", "hash", "end" ]
Use instance variables to build a json object. Instance variables that begin with a single underscore are elided. Instance variables that begin with two underscores have one of them removed.
[ "Use", "instance", "variables", "to", "build", "a", "json", "object", ".", "Instance", "variables", "that", "begin", "with", "a", "single", "underscore", "are", "elided", ".", "Instance", "variables", "that", "begin", "with", "two", "underscores", "have", "one", "of", "them", "removed", "." ]
785fb272728e0c44f0ddb10393dd56dd84f018af
https://github.com/cfndsl/cfndsl/blob/785fb272728e0c44f0ddb10393dd56dd84f018af/lib/cfndsl/jsonable.rb#L177-L193
16,910
opentok/OpenTok-Ruby-SDK
lib/opentok/broadcasts.rb
OpenTok.Broadcasts.find
def find(broadcast_id) raise ArgumentError, "broadcast_id not provided" if broadcast_id.to_s.empty? broadcast_json = @client.get_broadcast(broadcast_id.to_s) Broadcast.new self, broadcast_json end
ruby
def find(broadcast_id) raise ArgumentError, "broadcast_id not provided" if broadcast_id.to_s.empty? broadcast_json = @client.get_broadcast(broadcast_id.to_s) Broadcast.new self, broadcast_json end
[ "def", "find", "(", "broadcast_id", ")", "raise", "ArgumentError", ",", "\"broadcast_id not provided\"", "if", "broadcast_id", ".", "to_s", ".", "empty?", "broadcast_json", "=", "@client", ".", "get_broadcast", "(", "broadcast_id", ".", "to_s", ")", "Broadcast", ".", "new", "self", ",", "broadcast_json", "end" ]
Gets a Broadcast object for the given broadcast ID. @param [String] broadcast_id The broadcast ID. @return [Broadcast] The broadcast object, which includes properties defining the broadcast. @raise [OpenTokBroadcastError] No matching broadcast found. @raise [OpenTokAuthenticationError] Authentication failed. Invalid API key. @raise [OpenTokError] OpenTok server error.
[ "Gets", "a", "Broadcast", "object", "for", "the", "given", "broadcast", "ID", "." ]
dfa22dc77d93e4493f48e4ef4c6ea62e58ea8cfd
https://github.com/opentok/OpenTok-Ruby-SDK/blob/dfa22dc77d93e4493f48e4ef4c6ea62e58ea8cfd/lib/opentok/broadcasts.rb#L75-L79
16,911
opentok/OpenTok-Ruby-SDK
lib/opentok/broadcasts.rb
OpenTok.Broadcasts.stop
def stop(broadcast_id) raise ArgumentError, "broadcast_id not provided" if broadcast_id.to_s.empty? broadcast_json = @client.stop_broadcast(broadcast_id) Broadcast.new self, broadcast_json end
ruby
def stop(broadcast_id) raise ArgumentError, "broadcast_id not provided" if broadcast_id.to_s.empty? broadcast_json = @client.stop_broadcast(broadcast_id) Broadcast.new self, broadcast_json end
[ "def", "stop", "(", "broadcast_id", ")", "raise", "ArgumentError", ",", "\"broadcast_id not provided\"", "if", "broadcast_id", ".", "to_s", ".", "empty?", "broadcast_json", "=", "@client", ".", "stop_broadcast", "(", "broadcast_id", ")", "Broadcast", ".", "new", "self", ",", "broadcast_json", "end" ]
Stops an OpenTok broadcast Note that broadcasts automatically stop after 120 minute @param [String] broadcast_id The broadcast ID. @return [Broadcast] The broadcast object, which includes properties defining the broadcast. @raise [OpenTokBroadcastError] The broadcast could not be stopped. The request was invalid. @raise [OpenTokAuthenticationError] Authentication failed. Invalid API key. @raise [OpenTokError] OpenTok server error.
[ "Stops", "an", "OpenTok", "broadcast" ]
dfa22dc77d93e4493f48e4ef4c6ea62e58ea8cfd
https://github.com/opentok/OpenTok-Ruby-SDK/blob/dfa22dc77d93e4493f48e4ef4c6ea62e58ea8cfd/lib/opentok/broadcasts.rb#L94-L98
16,912
opentok/OpenTok-Ruby-SDK
lib/opentok/opentok.rb
OpenTok.OpenTok.create_session
def create_session(opts={}) # normalize opts so all keys are symbols and only include valid_opts valid_opts = [ :media_mode, :location, :archive_mode ] opts = opts.inject({}) do |m,(k,v)| if valid_opts.include? k.to_sym m[k.to_sym] = v end m end # keep opts around for Session constructor, build REST params params = opts.clone # anything other than :relayed sets the REST param to "disabled", in which case we force # opts to be :routed. if we were more strict we could raise an error when the value isn't # either :relayed or :routed if params.delete(:media_mode) == :routed params["p2p.preference"] = "disabled" else params["p2p.preference"] = "enabled" opts[:media_mode] = :relayed end # location is optional, but it has to be an IP address if specified at all unless params[:location].nil? raise "location must be an IPv4 address" unless params[:location] =~ Resolv::IPv4::Regex end # archive mode is optional, but it has to be one of the valid values if present unless params[:archive_mode].nil? raise "archive mode must be either always or manual" unless ARCHIVE_MODES.include? params[:archive_mode].to_sym end raise "A session with always archive mode must also have the routed media mode." if (params[:archive_mode] == :always && params[:media_mode] == :relayed) response = client.create_session(params) Session.new api_key, api_secret, response['sessions']['Session']['session_id'], opts end
ruby
def create_session(opts={}) # normalize opts so all keys are symbols and only include valid_opts valid_opts = [ :media_mode, :location, :archive_mode ] opts = opts.inject({}) do |m,(k,v)| if valid_opts.include? k.to_sym m[k.to_sym] = v end m end # keep opts around for Session constructor, build REST params params = opts.clone # anything other than :relayed sets the REST param to "disabled", in which case we force # opts to be :routed. if we were more strict we could raise an error when the value isn't # either :relayed or :routed if params.delete(:media_mode) == :routed params["p2p.preference"] = "disabled" else params["p2p.preference"] = "enabled" opts[:media_mode] = :relayed end # location is optional, but it has to be an IP address if specified at all unless params[:location].nil? raise "location must be an IPv4 address" unless params[:location] =~ Resolv::IPv4::Regex end # archive mode is optional, but it has to be one of the valid values if present unless params[:archive_mode].nil? raise "archive mode must be either always or manual" unless ARCHIVE_MODES.include? params[:archive_mode].to_sym end raise "A session with always archive mode must also have the routed media mode." if (params[:archive_mode] == :always && params[:media_mode] == :relayed) response = client.create_session(params) Session.new api_key, api_secret, response['sessions']['Session']['session_id'], opts end
[ "def", "create_session", "(", "opts", "=", "{", "}", ")", "# normalize opts so all keys are symbols and only include valid_opts", "valid_opts", "=", "[", ":media_mode", ",", ":location", ",", ":archive_mode", "]", "opts", "=", "opts", ".", "inject", "(", "{", "}", ")", "do", "|", "m", ",", "(", "k", ",", "v", ")", "|", "if", "valid_opts", ".", "include?", "k", ".", "to_sym", "m", "[", "k", ".", "to_sym", "]", "=", "v", "end", "m", "end", "# keep opts around for Session constructor, build REST params", "params", "=", "opts", ".", "clone", "# anything other than :relayed sets the REST param to \"disabled\", in which case we force", "# opts to be :routed. if we were more strict we could raise an error when the value isn't", "# either :relayed or :routed", "if", "params", ".", "delete", "(", ":media_mode", ")", "==", ":routed", "params", "[", "\"p2p.preference\"", "]", "=", "\"disabled\"", "else", "params", "[", "\"p2p.preference\"", "]", "=", "\"enabled\"", "opts", "[", ":media_mode", "]", "=", ":relayed", "end", "# location is optional, but it has to be an IP address if specified at all", "unless", "params", "[", ":location", "]", ".", "nil?", "raise", "\"location must be an IPv4 address\"", "unless", "params", "[", ":location", "]", "=~", "Resolv", "::", "IPv4", "::", "Regex", "end", "# archive mode is optional, but it has to be one of the valid values if present", "unless", "params", "[", ":archive_mode", "]", ".", "nil?", "raise", "\"archive mode must be either always or manual\"", "unless", "ARCHIVE_MODES", ".", "include?", "params", "[", ":archive_mode", "]", ".", "to_sym", "end", "raise", "\"A session with always archive mode must also have the routed media mode.\"", "if", "(", "params", "[", ":archive_mode", "]", "==", ":always", "&&", "params", "[", ":media_mode", "]", "==", ":relayed", ")", "response", "=", "client", ".", "create_session", "(", "params", ")", "Session", ".", "new", "api_key", ",", "api_secret", ",", "response", "[", "'sessions'", "]", "[", "'Session'", "]", "[", "'session_id'", "]", ",", "opts", "end" ]
Create a new OpenTok object. @param [String] api_key The OpenTok API key for your {https://tokbox.com/account OpenTok project}. @param [String] api_secret Your OpenTok API key. @option opts [Symbol] :api_url Do not set this parameter. It is for internal use by TokBox. @option opts [Symbol] :ua_addendum Do not set this parameter. It is for internal use by TokBox. Creates a new OpenTok session and returns the session ID, which uniquely identifies the session. For example, when using the OpenTok JavaScript library, use the session ID when calling the OT.initSession()</a> method (to initialize an OpenTok session). OpenTok sessions do not expire. However, authentication tokens do expire (see the generateToken() method). Also note that sessions cannot explicitly be destroyed. A session ID string can be up to 255 characters long. Calling this method results in an OpenTokException in the event of an error. Check the error message for details. You can also create a session using the OpenTok REST API (see http://www.tokbox.com/opentok/api/#session_id_production) or at your {https://tokbox.com/account OpenTok account page}. @param [Hash] opts (Optional) This hash defines options for the session. @option opts [Symbol] :media_mode Determines whether the session will transmit streams the using OpenTok Media Router (<code>:routed</code>) or not (<code>:relayed</code>). By default, this property is set to <code>:relayed</code>. With the <code>media_mode</code> property set to <code>:relayed</code>, the session will attempt to transmit streams directly between clients. If clients cannot connect due to firewall restrictions, the session uses the OpenTok TURN server to relay audio-video streams. With the <code>media_mode</code> property set to <code>:routed</code>, the session will use the {https://tokbox.com/opentok/tutorials/create-session/#media-mode OpenTok Media Router}. The OpenTok Media Router provides the following benefits: * The OpenTok Media Router can decrease bandwidth usage in multiparty sessions. (When the <code>media_mode</code> property is set to <code>:relayed</code>, each client must send a separate audio-video stream to each client subscribing to it.) * The OpenTok Media Router can improve the quality of the user experience through {https://tokbox.com/platform/fallback audio fallback and video recovery}. With these features, if a client's connectivity degrades to a degree that it does not support video for a stream it's subscribing to, the video is dropped on that client (without affecting other clients), and the client receives audio only. If the client's connectivity improves, the video returns. * The OpenTok Media Router supports the {https://tokbox.com/opentok/tutorials/archiving archiving} feature, which lets you record, save, and retrieve OpenTok sessions. @option opts [String] :location An IP address that the OpenTok servers will use to situate the session in its global network. If you do not set a location hint, the OpenTok servers will be based on the first client connecting to the session. @option opts [Symbol] :archive_mode Determines whether the session will be archived automatically (<code>:always</code>) or not (<code>:manual</code>). When using automatic archiving, the session must use the <code>:routed</code> media mode. @return [Session] The Session object. The session_id property of the object is the session ID.
[ "Create", "a", "new", "OpenTok", "object", "." ]
dfa22dc77d93e4493f48e4ef4c6ea62e58ea8cfd
https://github.com/opentok/OpenTok-Ruby-SDK/blob/dfa22dc77d93e4493f48e4ef4c6ea62e58ea8cfd/lib/opentok/opentok.rb#L145-L181
16,913
opentok/OpenTok-Ruby-SDK
lib/opentok/streams.rb
OpenTok.Streams.all
def all(session_id) raise ArgumentError, 'session_id not provided' if session_id.to_s.empty? response_json = @client.info_stream(session_id, '') StreamList.new response_json end
ruby
def all(session_id) raise ArgumentError, 'session_id not provided' if session_id.to_s.empty? response_json = @client.info_stream(session_id, '') StreamList.new response_json end
[ "def", "all", "(", "session_id", ")", "raise", "ArgumentError", ",", "'session_id not provided'", "if", "session_id", ".", "to_s", ".", "empty?", "response_json", "=", "@client", ".", "info_stream", "(", "session_id", ",", "''", ")", "StreamList", ".", "new", "response_json", "end" ]
Use this method to get information on all OpenTok streams in a session. For example, you can call this method to get information about layout classes used by OpenTok streams. The layout classes define how the stream is displayed in the layout of a live streaming broadcast or a composed archive. For more information, see {https://tokbox.com/developer/guides/broadcast/live-streaming/#assign-layout-classes-to-streams Assigning layout classes to streams in live streaming broadcasts} and {https://tokbox.com/developer/guides/archiving/layout-control.html Customizing the video layout for composed archives}. @param [String] session_id The session ID of the OpenTok session. @return [StreamList] The StreamList of Stream objects. @raise [ArgumentError] The stream_id or session_id is invalid. @raise [OpenTokAuthenticationError] You are not authorized to fetch the stream information. Check your authentication credentials. @raise [OpenTokError] An OpenTok server error.
[ "Use", "this", "method", "to", "get", "information", "on", "all", "OpenTok", "streams", "in", "a", "session", "." ]
dfa22dc77d93e4493f48e4ef4c6ea62e58ea8cfd
https://github.com/opentok/OpenTok-Ruby-SDK/blob/dfa22dc77d93e4493f48e4ef4c6ea62e58ea8cfd/lib/opentok/streams.rb#L49-L53
16,914
opentok/OpenTok-Ruby-SDK
lib/opentok/archives.rb
OpenTok.Archives.find
def find(archive_id) raise ArgumentError, "archive_id not provided" if archive_id.to_s.empty? archive_json = @client.get_archive(archive_id.to_s) Archive.new self, archive_json end
ruby
def find(archive_id) raise ArgumentError, "archive_id not provided" if archive_id.to_s.empty? archive_json = @client.get_archive(archive_id.to_s) Archive.new self, archive_json end
[ "def", "find", "(", "archive_id", ")", "raise", "ArgumentError", ",", "\"archive_id not provided\"", "if", "archive_id", ".", "to_s", ".", "empty?", "archive_json", "=", "@client", ".", "get_archive", "(", "archive_id", ".", "to_s", ")", "Archive", ".", "new", "self", ",", "archive_json", "end" ]
Gets an Archive object for the given archive ID. @param [String] archive_id The archive ID. @return [Archive] The Archive object. @raise [OpenTokArchiveError] The archive could not be retrieved. The archive ID is invalid. @raise [OpenTokAuthenticationError] Authentication failed while retrieving the archive. Invalid API key. @raise [OpenTokArchiveError] The archive could not be retrieved.
[ "Gets", "an", "Archive", "object", "for", "the", "given", "archive", "ID", "." ]
dfa22dc77d93e4493f48e4ef4c6ea62e58ea8cfd
https://github.com/opentok/OpenTok-Ruby-SDK/blob/dfa22dc77d93e4493f48e4ef4c6ea62e58ea8cfd/lib/opentok/archives.rb#L90-L94
16,915
opentok/OpenTok-Ruby-SDK
lib/opentok/archives.rb
OpenTok.Archives.all
def all(options = {}) raise ArgumentError, "Limit is invalid" unless options[:count].nil? or (0..1000).include? options[:count] archive_list_json = @client.list_archives(options[:offset], options[:count], options[:sessionId]) ArchiveList.new self, archive_list_json end
ruby
def all(options = {}) raise ArgumentError, "Limit is invalid" unless options[:count].nil? or (0..1000).include? options[:count] archive_list_json = @client.list_archives(options[:offset], options[:count], options[:sessionId]) ArchiveList.new self, archive_list_json end
[ "def", "all", "(", "options", "=", "{", "}", ")", "raise", "ArgumentError", ",", "\"Limit is invalid\"", "unless", "options", "[", ":count", "]", ".", "nil?", "or", "(", "0", "..", "1000", ")", ".", "include?", "options", "[", ":count", "]", "archive_list_json", "=", "@client", ".", "list_archives", "(", "options", "[", ":offset", "]", ",", "options", "[", ":count", "]", ",", "options", "[", ":sessionId", "]", ")", "ArchiveList", ".", "new", "self", ",", "archive_list_json", "end" ]
Returns an ArchiveList, which is an array of archives that are completed and in-progress, for your API key. @param [Hash] options A hash with keys defining which range of archives to retrieve. @option options [integer] :offset Optional. The index offset of the first archive. 0 is offset of the most recently started archive. 1 is the offset of the archive that started prior to the most recent archive. If you do not specify an offset, 0 is used. @option options [integer] :count Optional. The number of archives to be returned. The maximum number of archives returned is 1000. @option options [String] :session_id Optional. The session ID that archives belong to. This is useful when listing multiple archives for an {https://tokbox.com/developer/guides/archiving/#automatic-archives automatically archived session}. @return [ArchiveList] An ArchiveList object, which is an array of Archive objects.
[ "Returns", "an", "ArchiveList", "which", "is", "an", "array", "of", "archives", "that", "are", "completed", "and", "in", "-", "progress", "for", "your", "API", "key", "." ]
dfa22dc77d93e4493f48e4ef4c6ea62e58ea8cfd
https://github.com/opentok/OpenTok-Ruby-SDK/blob/dfa22dc77d93e4493f48e4ef4c6ea62e58ea8cfd/lib/opentok/archives.rb#L109-L113
16,916
opentok/OpenTok-Ruby-SDK
lib/opentok/archives.rb
OpenTok.Archives.stop_by_id
def stop_by_id(archive_id) raise ArgumentError, "archive_id not provided" if archive_id.to_s.empty? archive_json = @client.stop_archive(archive_id) Archive.new self, archive_json end
ruby
def stop_by_id(archive_id) raise ArgumentError, "archive_id not provided" if archive_id.to_s.empty? archive_json = @client.stop_archive(archive_id) Archive.new self, archive_json end
[ "def", "stop_by_id", "(", "archive_id", ")", "raise", "ArgumentError", ",", "\"archive_id not provided\"", "if", "archive_id", ".", "to_s", ".", "empty?", "archive_json", "=", "@client", ".", "stop_archive", "(", "archive_id", ")", "Archive", ".", "new", "self", ",", "archive_json", "end" ]
Stops an OpenTok archive that is being recorded. Archives automatically stop recording after 120 minutes or when all clients have disconnected from the session being archived. @param [String] archive_id The archive ID of the archive you want to stop recording. @return [Archive] The Archive object corresponding to the archive being stopped. @raise [OpenTokArchiveError] The archive could not be stopped. The request was invalid. @raise [OpenTokAuthenticationError] Authentication failed while stopping an archive. @raise [OpenTokArchiveError] The archive could not be stopped. The archive ID does not exist. @raise [OpenTokArchiveError] The archive could not be stopped. The archive is not currently recording. @raise [OpenTokArchiveError] The archive could not be started.
[ "Stops", "an", "OpenTok", "archive", "that", "is", "being", "recorded", "." ]
dfa22dc77d93e4493f48e4ef4c6ea62e58ea8cfd
https://github.com/opentok/OpenTok-Ruby-SDK/blob/dfa22dc77d93e4493f48e4ef4c6ea62e58ea8cfd/lib/opentok/archives.rb#L130-L134
16,917
opentok/OpenTok-Ruby-SDK
lib/opentok/archives.rb
OpenTok.Archives.delete_by_id
def delete_by_id(archive_id) raise ArgumentError, "archive_id not provided" if archive_id.to_s.empty? response = @client.delete_archive(archive_id) (200..300).include? response.code end
ruby
def delete_by_id(archive_id) raise ArgumentError, "archive_id not provided" if archive_id.to_s.empty? response = @client.delete_archive(archive_id) (200..300).include? response.code end
[ "def", "delete_by_id", "(", "archive_id", ")", "raise", "ArgumentError", ",", "\"archive_id not provided\"", "if", "archive_id", ".", "to_s", ".", "empty?", "response", "=", "@client", ".", "delete_archive", "(", "archive_id", ")", "(", "200", "..", "300", ")", ".", "include?", "response", ".", "code", "end" ]
Deletes an OpenTok archive. You can only delete an archive which has a status of "available", "uploaded", or "deleted". Deleting an archive removes its record from the list of archives. For an "available" archive, it also removes the archive file, making it unavailable for download. For a "deleted" archive, the archive remains deleted. @param [String] archive_id The archive ID of the archive you want to delete. @raise [OpenTokAuthenticationError] Authentication failed or an invalid archive ID was given. @raise [OpenTokArchiveError] The archive could not be deleted. The status must be 'available', 'deleted', or 'uploaded'. @raise [OpenTokArchiveError] The archive could not be deleted.
[ "Deletes", "an", "OpenTok", "archive", "." ]
dfa22dc77d93e4493f48e4ef4c6ea62e58ea8cfd
https://github.com/opentok/OpenTok-Ruby-SDK/blob/dfa22dc77d93e4493f48e4ef4c6ea62e58ea8cfd/lib/opentok/archives.rb#L149-L153
16,918
email-spec/email-spec
lib/email_spec/helpers.rb
EmailSpec.Helpers.find_email
def find_email(address, opts={}) address = convert_address(address) if opts[:with_subject] expected_subject = (opts[:with_subject].is_a?(String) ? Regexp.escape(opts[:with_subject]) : opts[:with_subject]) mailbox_for(address).find { |m| m.subject =~ Regexp.new(expected_subject) } elsif opts[:with_text] expected_text = (opts[:with_text].is_a?(String) ? Regexp.escape(opts[:with_text]) : opts[:with_text]) mailbox_for(address).find { |m| m.default_part_body =~ Regexp.new(expected_text) } elsif opts[:from] mailbox_for(address).find { |m| m.from.include? opts[:from] } else mailbox_for(address).first end end
ruby
def find_email(address, opts={}) address = convert_address(address) if opts[:with_subject] expected_subject = (opts[:with_subject].is_a?(String) ? Regexp.escape(opts[:with_subject]) : opts[:with_subject]) mailbox_for(address).find { |m| m.subject =~ Regexp.new(expected_subject) } elsif opts[:with_text] expected_text = (opts[:with_text].is_a?(String) ? Regexp.escape(opts[:with_text]) : opts[:with_text]) mailbox_for(address).find { |m| m.default_part_body =~ Regexp.new(expected_text) } elsif opts[:from] mailbox_for(address).find { |m| m.from.include? opts[:from] } else mailbox_for(address).first end end
[ "def", "find_email", "(", "address", ",", "opts", "=", "{", "}", ")", "address", "=", "convert_address", "(", "address", ")", "if", "opts", "[", ":with_subject", "]", "expected_subject", "=", "(", "opts", "[", ":with_subject", "]", ".", "is_a?", "(", "String", ")", "?", "Regexp", ".", "escape", "(", "opts", "[", ":with_subject", "]", ")", ":", "opts", "[", ":with_subject", "]", ")", "mailbox_for", "(", "address", ")", ".", "find", "{", "|", "m", "|", "m", ".", "subject", "=~", "Regexp", ".", "new", "(", "expected_subject", ")", "}", "elsif", "opts", "[", ":with_text", "]", "expected_text", "=", "(", "opts", "[", ":with_text", "]", ".", "is_a?", "(", "String", ")", "?", "Regexp", ".", "escape", "(", "opts", "[", ":with_text", "]", ")", ":", "opts", "[", ":with_text", "]", ")", "mailbox_for", "(", "address", ")", ".", "find", "{", "|", "m", "|", "m", ".", "default_part_body", "=~", "Regexp", ".", "new", "(", "expected_text", ")", "}", "elsif", "opts", "[", ":from", "]", "mailbox_for", "(", "address", ")", ".", "find", "{", "|", "m", "|", "m", ".", "from", ".", "include?", "opts", "[", ":from", "]", "}", "else", "mailbox_for", "(", "address", ")", ".", "first", "end", "end" ]
Should be able to accept String or Regexp options.
[ "Should", "be", "able", "to", "accept", "String", "or", "Regexp", "options", "." ]
107bd6fc5189bab0b1a82b7a21e80f6a7e1c6596
https://github.com/email-spec/email-spec/blob/107bd6fc5189bab0b1a82b7a21e80f6a7e1c6596/lib/email_spec/helpers.rb#L72-L85
16,919
easydatawarehousing/opal-ferro
opal/opal-ferro/ferro_router.js.rb
Ferro.Router.path_to_parts
def path_to_parts(path) path. downcase. split('/'). map { |part| part.empty? ? nil : part.strip }. compact end
ruby
def path_to_parts(path) path. downcase. split('/'). map { |part| part.empty? ? nil : part.strip }. compact end
[ "def", "path_to_parts", "(", "path", ")", "path", ".", "downcase", ".", "split", "(", "'/'", ")", ".", "map", "{", "|", "part", "|", "part", ".", "empty?", "?", "nil", ":", "part", ".", "strip", "}", ".", "compact", "end" ]
Internal method to split a path into components
[ "Internal", "method", "to", "split", "a", "path", "into", "components" ]
0cc0c19a956cbc2d9ce99c1539cb774a02cb9ca7
https://github.com/easydatawarehousing/opal-ferro/blob/0cc0c19a956cbc2d9ce99c1539cb774a02cb9ca7/opal/opal-ferro/ferro_router.js.rb#L80-L86
16,920
easydatawarehousing/opal-ferro
opal/opal-ferro/ferro_router.js.rb
Ferro.Router.navigated
def navigated url = get_location @params = [] idx = match(path_to_parts(decode(url.pathname)), decode(url.search)) if idx @routes[idx][:callback].call(@params) else @page404.call(url.pathname) end end
ruby
def navigated url = get_location @params = [] idx = match(path_to_parts(decode(url.pathname)), decode(url.search)) if idx @routes[idx][:callback].call(@params) else @page404.call(url.pathname) end end
[ "def", "navigated", "url", "=", "get_location", "@params", "=", "[", "]", "idx", "=", "match", "(", "path_to_parts", "(", "decode", "(", "url", ".", "pathname", ")", ")", ",", "decode", "(", "url", ".", "search", ")", ")", "if", "idx", "@routes", "[", "idx", "]", "[", ":callback", "]", ".", "call", "(", "@params", ")", "else", "@page404", ".", "call", "(", "url", ".", "pathname", ")", "end", "end" ]
Internal method called when the web browser navigates
[ "Internal", "method", "called", "when", "the", "web", "browser", "navigates" ]
0cc0c19a956cbc2d9ce99c1539cb774a02cb9ca7
https://github.com/easydatawarehousing/opal-ferro/blob/0cc0c19a956cbc2d9ce99c1539cb774a02cb9ca7/opal/opal-ferro/ferro_router.js.rb#L96-L107
16,921
easydatawarehousing/opal-ferro
opal/opal-ferro/ferro_router.js.rb
Ferro.Router.match
def match(path, search) matches = get_matches(path) if matches.length > 0 match = matches.sort { |m| m[1] }.first @params = match[2] add_search_to_params(search) match[0] else nil end end
ruby
def match(path, search) matches = get_matches(path) if matches.length > 0 match = matches.sort { |m| m[1] }.first @params = match[2] add_search_to_params(search) match[0] else nil end end
[ "def", "match", "(", "path", ",", "search", ")", "matches", "=", "get_matches", "(", "path", ")", "if", "matches", ".", "length", ">", "0", "match", "=", "matches", ".", "sort", "{", "|", "m", "|", "m", "[", "1", "]", "}", ".", "first", "@params", "=", "match", "[", "2", "]", "add_search_to_params", "(", "search", ")", "match", "[", "0", "]", "else", "nil", "end", "end" ]
Internal method to match a path to the most likely route @param [String] path Url to match @param [String] search Url search parameters
[ "Internal", "method", "to", "match", "a", "path", "to", "the", "most", "likely", "route" ]
0cc0c19a956cbc2d9ce99c1539cb774a02cb9ca7
https://github.com/easydatawarehousing/opal-ferro/blob/0cc0c19a956cbc2d9ce99c1539cb774a02cb9ca7/opal/opal-ferro/ferro_router.js.rb#L113-L126
16,922
easydatawarehousing/opal-ferro
opal/opal-ferro/ferro_router.js.rb
Ferro.Router.get_matches
def get_matches(path) matches = [] @routes.each_with_index do |route, i| score, pars = score_route(route[:parts], path) matches << [i, score, pars] if score > 0 end matches end
ruby
def get_matches(path) matches = [] @routes.each_with_index do |route, i| score, pars = score_route(route[:parts], path) matches << [i, score, pars] if score > 0 end matches end
[ "def", "get_matches", "(", "path", ")", "matches", "=", "[", "]", "@routes", ".", "each_with_index", "do", "|", "route", ",", "i", "|", "score", ",", "pars", "=", "score_route", "(", "route", "[", ":parts", "]", ",", "path", ")", "matches", "<<", "[", "i", ",", "score", ",", "pars", "]", "if", "score", ">", "0", "end", "matches", "end" ]
Internal method to match a path to possible routes @param [String] path Url to match
[ "Internal", "method", "to", "match", "a", "path", "to", "possible", "routes" ]
0cc0c19a956cbc2d9ce99c1539cb774a02cb9ca7
https://github.com/easydatawarehousing/opal-ferro/blob/0cc0c19a956cbc2d9ce99c1539cb774a02cb9ca7/opal/opal-ferro/ferro_router.js.rb#L131-L140
16,923
easydatawarehousing/opal-ferro
opal/opal-ferro/ferro_router.js.rb
Ferro.Router.score_route
def score_route(parts, path) score = 0 pars = {} if parts.length == path.length parts.each_with_index do |part, i| if part[0] == ':' score += 1 pars["#{part[1..-1]}"] = path[i] elsif part == path[i].downcase score += 2 end end end return score, pars end
ruby
def score_route(parts, path) score = 0 pars = {} if parts.length == path.length parts.each_with_index do |part, i| if part[0] == ':' score += 1 pars["#{part[1..-1]}"] = path[i] elsif part == path[i].downcase score += 2 end end end return score, pars end
[ "def", "score_route", "(", "parts", ",", "path", ")", "score", "=", "0", "pars", "=", "{", "}", "if", "parts", ".", "length", "==", "path", ".", "length", "parts", ".", "each_with_index", "do", "|", "part", ",", "i", "|", "if", "part", "[", "0", "]", "==", "':'", "score", "+=", "1", "pars", "[", "\"#{part[1..-1]}\"", "]", "=", "path", "[", "i", "]", "elsif", "part", "==", "path", "[", "i", "]", ".", "downcase", "score", "+=", "2", "end", "end", "end", "return", "score", ",", "pars", "end" ]
Internal method to add a match score @param [String] parts Parts of a route @param [String] path Url to match
[ "Internal", "method", "to", "add", "a", "match", "score" ]
0cc0c19a956cbc2d9ce99c1539cb774a02cb9ca7
https://github.com/easydatawarehousing/opal-ferro/blob/0cc0c19a956cbc2d9ce99c1539cb774a02cb9ca7/opal/opal-ferro/ferro_router.js.rb#L146-L162
16,924
easydatawarehousing/opal-ferro
opal/opal-ferro/ferro_router.js.rb
Ferro.Router.add_search_to_params
def add_search_to_params(search) if !search.empty? pars = search[1..-1].split('&') pars.each do |par| pair = par.split('=') @params[ pair[0] ] = pair[1] if pair.length == 2 end end end
ruby
def add_search_to_params(search) if !search.empty? pars = search[1..-1].split('&') pars.each do |par| pair = par.split('=') @params[ pair[0] ] = pair[1] if pair.length == 2 end end end
[ "def", "add_search_to_params", "(", "search", ")", "if", "!", "search", ".", "empty?", "pars", "=", "search", "[", "1", "..", "-", "1", "]", ".", "split", "(", "'&'", ")", "pars", ".", "each", "do", "|", "par", "|", "pair", "=", "par", ".", "split", "(", "'='", ")", "@params", "[", "pair", "[", "0", "]", "]", "=", "pair", "[", "1", "]", "if", "pair", ".", "length", "==", "2", "end", "end", "end" ]
Internal method to split search parameters @param [String] search Url search parameters
[ "Internal", "method", "to", "split", "search", "parameters" ]
0cc0c19a956cbc2d9ce99c1539cb774a02cb9ca7
https://github.com/easydatawarehousing/opal-ferro/blob/0cc0c19a956cbc2d9ce99c1539cb774a02cb9ca7/opal/opal-ferro/ferro_router.js.rb#L167-L176
16,925
easydatawarehousing/opal-ferro
opal/opal-ferro/ferro_factory.js.rb
Ferro.Factory.dasherize
def dasherize(class_name) return class_name if class_name !~ /[A-Z:_]/ c = class_name.to_s.gsub('::', '') (c[0] + c[1..-1].gsub(/[A-Z]/){ |c| "-#{c}" }). downcase. gsub('_', '-') end
ruby
def dasherize(class_name) return class_name if class_name !~ /[A-Z:_]/ c = class_name.to_s.gsub('::', '') (c[0] + c[1..-1].gsub(/[A-Z]/){ |c| "-#{c}" }). downcase. gsub('_', '-') end
[ "def", "dasherize", "(", "class_name", ")", "return", "class_name", "if", "class_name", "!~", "/", "/", "c", "=", "class_name", ".", "to_s", ".", "gsub", "(", "'::'", ",", "''", ")", "(", "c", "[", "0", "]", "+", "c", "[", "1", "..", "-", "1", "]", ".", "gsub", "(", "/", "/", ")", "{", "|", "c", "|", "\"-#{c}\"", "}", ")", ".", "downcase", ".", "gsub", "(", "'_'", ",", "'-'", ")", "end" ]
Convert a Ruby classname to a dasherized name for use with CSS. @param [String] class_name The Ruby class name @return [String] CSS class name
[ "Convert", "a", "Ruby", "classname", "to", "a", "dasherized", "name", "for", "use", "with", "CSS", "." ]
0cc0c19a956cbc2d9ce99c1539cb774a02cb9ca7
https://github.com/easydatawarehousing/opal-ferro/blob/0cc0c19a956cbc2d9ce99c1539cb774a02cb9ca7/opal/opal-ferro/ferro_factory.js.rb#L75-L82
16,926
easydatawarehousing/opal-ferro
opal/opal-ferro/ferro_factory.js.rb
Ferro.Factory.composite_state
def composite_state(class_name, state) if @compositor list = @compositor.css_classes_for("#{class_name}::#{state}") return list if !list.empty? end [ dasherize(state) ] end
ruby
def composite_state(class_name, state) if @compositor list = @compositor.css_classes_for("#{class_name}::#{state}") return list if !list.empty? end [ dasherize(state) ] end
[ "def", "composite_state", "(", "class_name", ",", "state", ")", "if", "@compositor", "list", "=", "@compositor", ".", "css_classes_for", "(", "\"#{class_name}::#{state}\"", ")", "return", "list", "if", "!", "list", ".", "empty?", "end", "[", "dasherize", "(", "state", ")", "]", "end" ]
Convert a state-name to a list of CSS class names. @param [String] class_name Ruby class name @param [String] state State name @return [String] A list of CSS class names
[ "Convert", "a", "state", "-", "name", "to", "a", "list", "of", "CSS", "class", "names", "." ]
0cc0c19a956cbc2d9ce99c1539cb774a02cb9ca7
https://github.com/easydatawarehousing/opal-ferro/blob/0cc0c19a956cbc2d9ce99c1539cb774a02cb9ca7/opal/opal-ferro/ferro_factory.js.rb#L98-L105
16,927
easydatawarehousing/opal-ferro
opal/opal-ferro/ferro_factory.js.rb
Ferro.Factory.composite_classes
def composite_classes(target, element, add_superclass) if @compositor composite_for(target.class.name, element) if add_superclass composite_for(target.class.superclass.name, element) end end end
ruby
def composite_classes(target, element, add_superclass) if @compositor composite_for(target.class.name, element) if add_superclass composite_for(target.class.superclass.name, element) end end end
[ "def", "composite_classes", "(", "target", ",", "element", ",", "add_superclass", ")", "if", "@compositor", "composite_for", "(", "target", ".", "class", ".", "name", ",", "element", ")", "if", "add_superclass", "composite_for", "(", "target", ".", "class", ".", "superclass", ".", "name", ",", "element", ")", "end", "end", "end" ]
Internal method Composite CSS classes from Ruby class name
[ "Internal", "method", "Composite", "CSS", "classes", "from", "Ruby", "class", "name" ]
0cc0c19a956cbc2d9ce99c1539cb774a02cb9ca7
https://github.com/easydatawarehousing/opal-ferro/blob/0cc0c19a956cbc2d9ce99c1539cb774a02cb9ca7/opal/opal-ferro/ferro_factory.js.rb#L109-L117
16,928
easydatawarehousing/opal-ferro
opal/opal-ferro/ferro_compositor.js.rb
Ferro.Compositor.css_classes_for_map
def css_classes_for_map(classname, mapping) css = mapping[classname] css.class == String ? css_classes_for_map(css, mapping) : (css || []) end
ruby
def css_classes_for_map(classname, mapping) css = mapping[classname] css.class == String ? css_classes_for_map(css, mapping) : (css || []) end
[ "def", "css_classes_for_map", "(", "classname", ",", "mapping", ")", "css", "=", "mapping", "[", "classname", "]", "css", ".", "class", "==", "String", "?", "css_classes_for_map", "(", "css", ",", "mapping", ")", ":", "(", "css", "||", "[", "]", ")", "end" ]
Internal method to get mapping from selected map.
[ "Internal", "method", "to", "get", "mapping", "from", "selected", "map", "." ]
0cc0c19a956cbc2d9ce99c1539cb774a02cb9ca7
https://github.com/easydatawarehousing/opal-ferro/blob/0cc0c19a956cbc2d9ce99c1539cb774a02cb9ca7/opal/opal-ferro/ferro_compositor.js.rb#L38-L41
16,929
easydatawarehousing/opal-ferro
opal/opal-ferro/ferro_compositor.js.rb
Ferro.Compositor.switch_theme
def switch_theme(root_element, theme) old_map = @mapping new_map = map(theme) root_element.each_child do |e| old_classes = css_classes_for_map e.class.name, old_map new_classes = css_classes_for_map e.class.name, new_map update_element_css_classes(e, old_classes, new_classes) old_classes = css_classes_for_map e.class.superclass.name, old_map new_classes = css_classes_for_map e.class.superclass.name, new_map update_element_css_classes(e, old_classes, new_classes) end @mapping = new_map end
ruby
def switch_theme(root_element, theme) old_map = @mapping new_map = map(theme) root_element.each_child do |e| old_classes = css_classes_for_map e.class.name, old_map new_classes = css_classes_for_map e.class.name, new_map update_element_css_classes(e, old_classes, new_classes) old_classes = css_classes_for_map e.class.superclass.name, old_map new_classes = css_classes_for_map e.class.superclass.name, new_map update_element_css_classes(e, old_classes, new_classes) end @mapping = new_map end
[ "def", "switch_theme", "(", "root_element", ",", "theme", ")", "old_map", "=", "@mapping", "new_map", "=", "map", "(", "theme", ")", "root_element", ".", "each_child", "do", "|", "e", "|", "old_classes", "=", "css_classes_for_map", "e", ".", "class", ".", "name", ",", "old_map", "new_classes", "=", "css_classes_for_map", "e", ".", "class", ".", "name", ",", "new_map", "update_element_css_classes", "(", "e", ",", "old_classes", ",", "new_classes", ")", "old_classes", "=", "css_classes_for_map", "e", ".", "class", ".", "superclass", ".", "name", ",", "old_map", "new_classes", "=", "css_classes_for_map", "e", ".", "class", ".", "superclass", ".", "name", ",", "new_map", "update_element_css_classes", "(", "e", ",", "old_classes", ",", "new_classes", ")", "end", "@mapping", "=", "new_map", "end" ]
Internal method to switch to a new theme.
[ "Internal", "method", "to", "switch", "to", "a", "new", "theme", "." ]
0cc0c19a956cbc2d9ce99c1539cb774a02cb9ca7
https://github.com/easydatawarehousing/opal-ferro/blob/0cc0c19a956cbc2d9ce99c1539cb774a02cb9ca7/opal/opal-ferro/ferro_compositor.js.rb#L44-L59
16,930
easydatawarehousing/opal-ferro
opal/opal-ferro/ferro_elementary.js.rb
Ferro.Elementary._stylize
def _stylize styles = style if styles.class == Hash set_attribute( 'style', styles.map { |k, v| "#{k}:#{v};" }.join ) end end
ruby
def _stylize styles = style if styles.class == Hash set_attribute( 'style', styles.map { |k, v| "#{k}:#{v};" }.join ) end end
[ "def", "_stylize", "styles", "=", "style", "if", "styles", ".", "class", "==", "Hash", "set_attribute", "(", "'style'", ",", "styles", ".", "map", "{", "|", "k", ",", "v", "|", "\"#{k}:#{v};\"", "}", ".", "join", ")", "end", "end" ]
Internal method.
[ "Internal", "method", "." ]
0cc0c19a956cbc2d9ce99c1539cb774a02cb9ca7
https://github.com/easydatawarehousing/opal-ferro/blob/0cc0c19a956cbc2d9ce99c1539cb774a02cb9ca7/opal/opal-ferro/ferro_elementary.js.rb#L52-L61
16,931
easydatawarehousing/opal-ferro
opal/opal-ferro/ferro_elementary.js.rb
Ferro.Elementary.add_child
def add_child(name, element_class, options = {}) sym = symbolize(name) raise "Child '#{sym}' already defined" if @children.has_key?(sym) raise "Illegal name (#{sym})" if RESERVED_NAMES.include?(sym) @children[sym] = element_class.new(self, sym, options) end
ruby
def add_child(name, element_class, options = {}) sym = symbolize(name) raise "Child '#{sym}' already defined" if @children.has_key?(sym) raise "Illegal name (#{sym})" if RESERVED_NAMES.include?(sym) @children[sym] = element_class.new(self, sym, options) end
[ "def", "add_child", "(", "name", ",", "element_class", ",", "options", "=", "{", "}", ")", "sym", "=", "symbolize", "(", "name", ")", "raise", "\"Child '#{sym}' already defined\"", "if", "@children", ".", "has_key?", "(", "sym", ")", "raise", "\"Illegal name (#{sym})\"", "if", "RESERVED_NAMES", ".", "include?", "(", "sym", ")", "@children", "[", "sym", "]", "=", "element_class", ".", "new", "(", "self", ",", "sym", ",", "options", ")", "end" ]
Add a child element. @param [String] name A unique name for the element that is not in RESERVED_NAMES @param [String] element_class Ruby class name for the new element @param [Hash] options Options to pass to the element. Any option key that is not recognized is set as an attribute on the DOM element. Recognized keys are: prepend Prepend the new element before this DOM element content Add the value of content as a textnode to the DOM element
[ "Add", "a", "child", "element", "." ]
0cc0c19a956cbc2d9ce99c1539cb774a02cb9ca7
https://github.com/easydatawarehousing/opal-ferro/blob/0cc0c19a956cbc2d9ce99c1539cb774a02cb9ca7/opal/opal-ferro/ferro_elementary.js.rb#L76-L81
16,932
easydatawarehousing/opal-ferro
opal/opal-ferro/ferro_elementary.js.rb
Ferro.Elementary.each_child
def each_child(&block) if block_given? block.call self @children.each do |_, child| child.each_child(&block) end end end
ruby
def each_child(&block) if block_given? block.call self @children.each do |_, child| child.each_child(&block) end end end
[ "def", "each_child", "(", "&", "block", ")", "if", "block_given?", "block", ".", "call", "self", "@children", ".", "each", "do", "|", "_", ",", "child", "|", "child", ".", "each_child", "(", "block", ")", "end", "end", "end" ]
Recursively iterate all child elements param [Block] block A block to execute for every child element and the element itself
[ "Recursively", "iterate", "all", "child", "elements" ]
0cc0c19a956cbc2d9ce99c1539cb774a02cb9ca7
https://github.com/easydatawarehousing/opal-ferro/blob/0cc0c19a956cbc2d9ce99c1539cb774a02cb9ca7/opal/opal-ferro/ferro_elementary.js.rb#L104-L112
16,933
easydatawarehousing/opal-ferro
opal/opal-ferro/ferro_i18n.js.rb
Ferro.I18n._replace_options
def _replace_options(string, options) # Unescape the string so we can use the returned string # to set an elements inner html. s = string.gsub('&lt;', '<').gsub('&gt;', '>') if options # But escape option values to prevent code injection s.gsub(/%\{(\w+)\}/) do |m| key = ($1 || m.tr("%{}", "")) if options.key?(key) options[key].to_s.gsub('<', '&lt;').gsub('>', '&gt;') else key end end else s end end
ruby
def _replace_options(string, options) # Unescape the string so we can use the returned string # to set an elements inner html. s = string.gsub('&lt;', '<').gsub('&gt;', '>') if options # But escape option values to prevent code injection s.gsub(/%\{(\w+)\}/) do |m| key = ($1 || m.tr("%{}", "")) if options.key?(key) options[key].to_s.gsub('<', '&lt;').gsub('>', '&gt;') else key end end else s end end
[ "def", "_replace_options", "(", "string", ",", "options", ")", "# Unescape the string so we can use the returned string", "# to set an elements inner html.", "s", "=", "string", ".", "gsub", "(", "'&lt;'", ",", "'<'", ")", ".", "gsub", "(", "'&gt;'", ",", "'>'", ")", "if", "options", "# But escape option values to prevent code injection", "s", ".", "gsub", "(", "/", "\\{", "\\w", "\\}", "/", ")", "do", "|", "m", "|", "key", "=", "(", "$1", "||", "m", ".", "tr", "(", "\"%{}\"", ",", "\"\"", ")", ")", "if", "options", ".", "key?", "(", "key", ")", "options", "[", "key", "]", ".", "to_s", ".", "gsub", "(", "'<'", ",", "'&lt;'", ")", ".", "gsub", "(", "'>'", ",", "'&gt;'", ")", "else", "key", "end", "end", "else", "s", "end", "end" ]
Internal method to substitute placeholders with a value.
[ "Internal", "method", "to", "substitute", "placeholders", "with", "a", "value", "." ]
0cc0c19a956cbc2d9ce99c1539cb774a02cb9ca7
https://github.com/easydatawarehousing/opal-ferro/blob/0cc0c19a956cbc2d9ce99c1539cb774a02cb9ca7/opal/opal-ferro/ferro_i18n.js.rb#L116-L135
16,934
easydatawarehousing/opal-ferro
opal/opal-ferro/ferro_base_element.js.rb
Ferro.BaseElement.option_replace
def option_replace(key, default = nil) value = @options[key] || default @options.delete(key) if @options.has_key?(key) value end
ruby
def option_replace(key, default = nil) value = @options[key] || default @options.delete(key) if @options.has_key?(key) value end
[ "def", "option_replace", "(", "key", ",", "default", "=", "nil", ")", "value", "=", "@options", "[", "key", "]", "||", "default", "@options", ".", "delete", "(", "key", ")", "if", "@options", ".", "has_key?", "(", "key", ")", "value", "end" ]
Delete a key from the elements options hash. Will be renamed to option_delete. @param [key] key Key of the option hash to be removed @param [value] default Optional value to use if option value is nil @return [value] Return the current option value or value of default parameter
[ "Delete", "a", "key", "from", "the", "elements", "options", "hash", ".", "Will", "be", "renamed", "to", "option_delete", "." ]
0cc0c19a956cbc2d9ce99c1539cb774a02cb9ca7
https://github.com/easydatawarehousing/opal-ferro/blob/0cc0c19a956cbc2d9ce99c1539cb774a02cb9ca7/opal/opal-ferro/ferro_base_element.js.rb#L62-L66
16,935
easydatawarehousing/opal-ferro
opal/opal-ferro/ferro_base_element.js.rb
Ferro.BaseElement.update_state
def update_state(state, active) if !active.nil? @states.each do |s, v| v[1] = active if s == state classify_state v end end end
ruby
def update_state(state, active) if !active.nil? @states.each do |s, v| v[1] = active if s == state classify_state v end end end
[ "def", "update_state", "(", "state", ",", "active", ")", "if", "!", "active", ".", "nil?", "@states", ".", "each", "do", "|", "s", ",", "v", "|", "v", "[", "1", "]", "=", "active", "if", "s", "==", "state", "classify_state", "v", "end", "end", "end" ]
Update the value of the state. @param [String] state The state name @param [Boolean] active The new value of the state. Pass true to enable and set the CSS class false to disable and remove the CSS class nil to skip altering state and the CSS class
[ "Update", "the", "value", "of", "the", "state", "." ]
0cc0c19a956cbc2d9ce99c1539cb774a02cb9ca7
https://github.com/easydatawarehousing/opal-ferro/blob/0cc0c19a956cbc2d9ce99c1539cb774a02cb9ca7/opal/opal-ferro/ferro_base_element.js.rb#L104-L111
16,936
easydatawarehousing/opal-ferro
opal/opal-ferro/ferro_base_element.js.rb
Ferro.BaseElement.toggle_state
def toggle_state(state) @states.select { |s, _| s == state }.each do |s, v| v[1] = !v[1] classify_state v end end
ruby
def toggle_state(state) @states.select { |s, _| s == state }.each do |s, v| v[1] = !v[1] classify_state v end end
[ "def", "toggle_state", "(", "state", ")", "@states", ".", "select", "{", "|", "s", ",", "_", "|", "s", "==", "state", "}", ".", "each", "do", "|", "s", ",", "v", "|", "v", "[", "1", "]", "=", "!", "v", "[", "1", "]", "classify_state", "v", "end", "end" ]
Toggle the boolean value of the state @param [String] state The state name
[ "Toggle", "the", "boolean", "value", "of", "the", "state" ]
0cc0c19a956cbc2d9ce99c1539cb774a02cb9ca7
https://github.com/easydatawarehousing/opal-ferro/blob/0cc0c19a956cbc2d9ce99c1539cb774a02cb9ca7/opal/opal-ferro/ferro_base_element.js.rb#L116-L121
16,937
mailman/mailman
lib/mailman/router.rb
Mailman.Router.route
def route(message) @params.clear @message = message result = nil if @bounce_block and message.respond_to?(:bounced?) and message.bounced? return instance_exec(&@bounce_block) end routes.each do |route| break if result = route.match!(message) end if result @params.merge!(result[:params]) if !result[:klass].nil? if result[:klass].is_a?(Class) # no instance method specified result[:klass].new.send(:receive, @message, @params) elsif result[:klass].kind_of?(String) # instance method specified klass, method = result[:klass].split('#') klass.camelize.constantize.new.send(method.to_sym, @message, @params) end elsif result[:block].arity > 0 instance_exec(*result[:args], &result[:block]) else instance_exec(&result[:block]) end elsif @default_block instance_exec(&@default_block) end end
ruby
def route(message) @params.clear @message = message result = nil if @bounce_block and message.respond_to?(:bounced?) and message.bounced? return instance_exec(&@bounce_block) end routes.each do |route| break if result = route.match!(message) end if result @params.merge!(result[:params]) if !result[:klass].nil? if result[:klass].is_a?(Class) # no instance method specified result[:klass].new.send(:receive, @message, @params) elsif result[:klass].kind_of?(String) # instance method specified klass, method = result[:klass].split('#') klass.camelize.constantize.new.send(method.to_sym, @message, @params) end elsif result[:block].arity > 0 instance_exec(*result[:args], &result[:block]) else instance_exec(&result[:block]) end elsif @default_block instance_exec(&@default_block) end end
[ "def", "route", "(", "message", ")", "@params", ".", "clear", "@message", "=", "message", "result", "=", "nil", "if", "@bounce_block", "and", "message", ".", "respond_to?", "(", ":bounced?", ")", "and", "message", ".", "bounced?", "return", "instance_exec", "(", "@bounce_block", ")", "end", "routes", ".", "each", "do", "|", "route", "|", "break", "if", "result", "=", "route", ".", "match!", "(", "message", ")", "end", "if", "result", "@params", ".", "merge!", "(", "result", "[", ":params", "]", ")", "if", "!", "result", "[", ":klass", "]", ".", "nil?", "if", "result", "[", ":klass", "]", ".", "is_a?", "(", "Class", ")", "# no instance method specified", "result", "[", ":klass", "]", ".", "new", ".", "send", "(", ":receive", ",", "@message", ",", "@params", ")", "elsif", "result", "[", ":klass", "]", ".", "kind_of?", "(", "String", ")", "# instance method specified", "klass", ",", "method", "=", "result", "[", ":klass", "]", ".", "split", "(", "'#'", ")", "klass", ".", "camelize", ".", "constantize", ".", "new", ".", "send", "(", "method", ".", "to_sym", ",", "@message", ",", "@params", ")", "end", "elsif", "result", "[", ":block", "]", ".", "arity", ">", "0", "instance_exec", "(", "result", "[", ":args", "]", ",", "result", "[", ":block", "]", ")", "else", "instance_exec", "(", "result", "[", ":block", "]", ")", "end", "elsif", "@default_block", "instance_exec", "(", "@default_block", ")", "end", "end" ]
Route a message. If the route block accepts arguments, it passes any captured params. Named params are available from the +params+ helper. The message is available from the +message+ helper. @param [Mail::Message] the message to route.
[ "Route", "a", "message", ".", "If", "the", "route", "block", "accepts", "arguments", "it", "passes", "any", "captured", "params", ".", "Named", "params", "are", "available", "from", "the", "+", "params", "+", "helper", ".", "The", "message", "is", "available", "from", "the", "+", "message", "+", "helper", "." ]
b955154c5d73b85cdc76687222288b1cf5a2ea91
https://github.com/mailman/mailman/blob/b955154c5d73b85cdc76687222288b1cf5a2ea91/lib/mailman/router.rb#L38-L68
16,938
mailman/mailman
lib/mailman/route.rb
Mailman.Route.match!
def match!(message) params = {} args = [] @conditions.each do |condition| if result = condition.match(message) params.merge!(result[0]) args += result[1] else return nil end end { :block => @block, :klass => @klass, :params => params, :args => args } end
ruby
def match!(message) params = {} args = [] @conditions.each do |condition| if result = condition.match(message) params.merge!(result[0]) args += result[1] else return nil end end { :block => @block, :klass => @klass, :params => params, :args => args } end
[ "def", "match!", "(", "message", ")", "params", "=", "{", "}", "args", "=", "[", "]", "@conditions", ".", "each", "do", "|", "condition", "|", "if", "result", "=", "condition", ".", "match", "(", "message", ")", "params", ".", "merge!", "(", "result", "[", "0", "]", ")", "args", "+=", "result", "[", "1", "]", "else", "return", "nil", "end", "end", "{", ":block", "=>", "@block", ",", ":klass", "=>", "@klass", ",", ":params", "=>", "params", ",", ":args", "=>", "args", "}", "end" ]
Checks whether a message matches the route. @param [Mail::Message] message the message to match against @return [Hash] the +:block+ and +:klass+ associated with the route, the +:params+ hash, and the block +:args+ array.
[ "Checks", "whether", "a", "message", "matches", "the", "route", "." ]
b955154c5d73b85cdc76687222288b1cf5a2ea91
https://github.com/mailman/mailman/blob/b955154c5d73b85cdc76687222288b1cf5a2ea91/lib/mailman/route.rb#L25-L37
16,939
mailman/mailman
lib/mailman/application.rb
Mailman.Application.run
def run Mailman.logger.info "Mailman v#{Mailman::VERSION} started" if config.rails_root rails_env = File.join(config.rails_root, 'config', 'environment.rb') if File.exist?(rails_env) && !(defined?(::Rails) && ::Rails.env) Mailman.logger.info "Rails root found in #{config.rails_root}, requiring environment..." require rails_env end end if config.graceful_death # When user presses CTRL-C, finish processing current message before exiting Signal.trap("INT") { @polling_interrupt = true } end # STDIN if !IS_WINDOWS && !config.ignore_stdin && $stdin.fcntl(Fcntl::F_GETFL, 0) == 0 Mailman.logger.debug "Processing message from STDIN." @processor.process($stdin.read) # IMAP elsif config.imap options = {:processor => @processor}.merge(config.imap) Mailman.logger.info "IMAP receiver enabled (#{options[:username]}@#{options[:server]})." polling_loop Receiver::IMAP.new(options) # POP3 elsif config.pop3 options = {:processor => @processor}.merge(config.pop3) Mailman.logger.info "POP3 receiver enabled (#{options[:username]}@#{options[:server]})." polling_loop Receiver::POP3.new(options) # HTTP elsif config.http options = {:processor => @processor}.merge(config.http) Mailman.logger.info "HTTP server started" Receiver::HTTP.new(options).start_and_block # Maildir elsif config.maildir Mailman.logger.info "Maildir receiver enabled (#{config.maildir})." Mailman.logger.debug "Processing new message queue..." @maildir.list(:new).each do |message| @processor.process_maildir_message(message) end if config.watch_maildir require 'listen' Mailman.logger.debug "Monitoring the Maildir for new messages..." base = Pathname.new(@maildir.path) callback = Proc.new do |modified, added, removed| added.each do |new_file| message = Maildir::Message.new(@maildir, Pathname.new(new_file).relative_path_from(base).to_s) @processor.process_maildir_message(message) end end @listener = Listen::Listener.new(File.join(@maildir.path, 'new'), &callback) @listener.start sleep end end end
ruby
def run Mailman.logger.info "Mailman v#{Mailman::VERSION} started" if config.rails_root rails_env = File.join(config.rails_root, 'config', 'environment.rb') if File.exist?(rails_env) && !(defined?(::Rails) && ::Rails.env) Mailman.logger.info "Rails root found in #{config.rails_root}, requiring environment..." require rails_env end end if config.graceful_death # When user presses CTRL-C, finish processing current message before exiting Signal.trap("INT") { @polling_interrupt = true } end # STDIN if !IS_WINDOWS && !config.ignore_stdin && $stdin.fcntl(Fcntl::F_GETFL, 0) == 0 Mailman.logger.debug "Processing message from STDIN." @processor.process($stdin.read) # IMAP elsif config.imap options = {:processor => @processor}.merge(config.imap) Mailman.logger.info "IMAP receiver enabled (#{options[:username]}@#{options[:server]})." polling_loop Receiver::IMAP.new(options) # POP3 elsif config.pop3 options = {:processor => @processor}.merge(config.pop3) Mailman.logger.info "POP3 receiver enabled (#{options[:username]}@#{options[:server]})." polling_loop Receiver::POP3.new(options) # HTTP elsif config.http options = {:processor => @processor}.merge(config.http) Mailman.logger.info "HTTP server started" Receiver::HTTP.new(options).start_and_block # Maildir elsif config.maildir Mailman.logger.info "Maildir receiver enabled (#{config.maildir})." Mailman.logger.debug "Processing new message queue..." @maildir.list(:new).each do |message| @processor.process_maildir_message(message) end if config.watch_maildir require 'listen' Mailman.logger.debug "Monitoring the Maildir for new messages..." base = Pathname.new(@maildir.path) callback = Proc.new do |modified, added, removed| added.each do |new_file| message = Maildir::Message.new(@maildir, Pathname.new(new_file).relative_path_from(base).to_s) @processor.process_maildir_message(message) end end @listener = Listen::Listener.new(File.join(@maildir.path, 'new'), &callback) @listener.start sleep end end end
[ "def", "run", "Mailman", ".", "logger", ".", "info", "\"Mailman v#{Mailman::VERSION} started\"", "if", "config", ".", "rails_root", "rails_env", "=", "File", ".", "join", "(", "config", ".", "rails_root", ",", "'config'", ",", "'environment.rb'", ")", "if", "File", ".", "exist?", "(", "rails_env", ")", "&&", "!", "(", "defined?", "(", "::", "Rails", ")", "&&", "::", "Rails", ".", "env", ")", "Mailman", ".", "logger", ".", "info", "\"Rails root found in #{config.rails_root}, requiring environment...\"", "require", "rails_env", "end", "end", "if", "config", ".", "graceful_death", "# When user presses CTRL-C, finish processing current message before exiting", "Signal", ".", "trap", "(", "\"INT\"", ")", "{", "@polling_interrupt", "=", "true", "}", "end", "# STDIN", "if", "!", "IS_WINDOWS", "&&", "!", "config", ".", "ignore_stdin", "&&", "$stdin", ".", "fcntl", "(", "Fcntl", "::", "F_GETFL", ",", "0", ")", "==", "0", "Mailman", ".", "logger", ".", "debug", "\"Processing message from STDIN.\"", "@processor", ".", "process", "(", "$stdin", ".", "read", ")", "# IMAP", "elsif", "config", ".", "imap", "options", "=", "{", ":processor", "=>", "@processor", "}", ".", "merge", "(", "config", ".", "imap", ")", "Mailman", ".", "logger", ".", "info", "\"IMAP receiver enabled (#{options[:username]}@#{options[:server]}).\"", "polling_loop", "Receiver", "::", "IMAP", ".", "new", "(", "options", ")", "# POP3", "elsif", "config", ".", "pop3", "options", "=", "{", ":processor", "=>", "@processor", "}", ".", "merge", "(", "config", ".", "pop3", ")", "Mailman", ".", "logger", ".", "info", "\"POP3 receiver enabled (#{options[:username]}@#{options[:server]}).\"", "polling_loop", "Receiver", "::", "POP3", ".", "new", "(", "options", ")", "# HTTP", "elsif", "config", ".", "http", "options", "=", "{", ":processor", "=>", "@processor", "}", ".", "merge", "(", "config", ".", "http", ")", "Mailman", ".", "logger", ".", "info", "\"HTTP server started\"", "Receiver", "::", "HTTP", ".", "new", "(", "options", ")", ".", "start_and_block", "# Maildir", "elsif", "config", ".", "maildir", "Mailman", ".", "logger", ".", "info", "\"Maildir receiver enabled (#{config.maildir}).\"", "Mailman", ".", "logger", ".", "debug", "\"Processing new message queue...\"", "@maildir", ".", "list", "(", ":new", ")", ".", "each", "do", "|", "message", "|", "@processor", ".", "process_maildir_message", "(", "message", ")", "end", "if", "config", ".", "watch_maildir", "require", "'listen'", "Mailman", ".", "logger", ".", "debug", "\"Monitoring the Maildir for new messages...\"", "base", "=", "Pathname", ".", "new", "(", "@maildir", ".", "path", ")", "callback", "=", "Proc", ".", "new", "do", "|", "modified", ",", "added", ",", "removed", "|", "added", ".", "each", "do", "|", "new_file", "|", "message", "=", "Maildir", "::", "Message", ".", "new", "(", "@maildir", ",", "Pathname", ".", "new", "(", "new_file", ")", ".", "relative_path_from", "(", "base", ")", ".", "to_s", ")", "@processor", ".", "process_maildir_message", "(", "message", ")", "end", "end", "@listener", "=", "Listen", "::", "Listener", ".", "new", "(", "File", ".", "join", "(", "@maildir", ".", "path", ",", "'new'", ")", ",", "callback", ")", "@listener", ".", "start", "sleep", "end", "end", "end" ]
Runs the application.
[ "Runs", "the", "application", "." ]
b955154c5d73b85cdc76687222288b1cf5a2ea91
https://github.com/mailman/mailman/blob/b955154c5d73b85cdc76687222288b1cf5a2ea91/lib/mailman/application.rb#L56-L122
16,940
mailman/mailman
lib/mailman/application.rb
Mailman.Application.polling_loop
def polling_loop(connection) if polling? polling_msg = "Polling enabled. Checking every #{config.poll_interval} seconds." else polling_msg = "Polling disabled. Checking for messages once." end Mailman.logger.info(polling_msg) tries ||= 5 loop do begin connection.connect connection.get_messages rescue SystemCallError, EOFError => e Mailman.logger.error e.message unless (tries -= 1).zero? Mailman.logger.error "Retrying..." begin connection.disconnect rescue # don't crash in the crash handler end retry end ensure connection.started? && connection.disconnect end break unless polling? sleep config.poll_interval end end
ruby
def polling_loop(connection) if polling? polling_msg = "Polling enabled. Checking every #{config.poll_interval} seconds." else polling_msg = "Polling disabled. Checking for messages once." end Mailman.logger.info(polling_msg) tries ||= 5 loop do begin connection.connect connection.get_messages rescue SystemCallError, EOFError => e Mailman.logger.error e.message unless (tries -= 1).zero? Mailman.logger.error "Retrying..." begin connection.disconnect rescue # don't crash in the crash handler end retry end ensure connection.started? && connection.disconnect end break unless polling? sleep config.poll_interval end end
[ "def", "polling_loop", "(", "connection", ")", "if", "polling?", "polling_msg", "=", "\"Polling enabled. Checking every #{config.poll_interval} seconds.\"", "else", "polling_msg", "=", "\"Polling disabled. Checking for messages once.\"", "end", "Mailman", ".", "logger", ".", "info", "(", "polling_msg", ")", "tries", "||=", "5", "loop", "do", "begin", "connection", ".", "connect", "connection", ".", "get_messages", "rescue", "SystemCallError", ",", "EOFError", "=>", "e", "Mailman", ".", "logger", ".", "error", "e", ".", "message", "unless", "(", "tries", "-=", "1", ")", ".", "zero?", "Mailman", ".", "logger", ".", "error", "\"Retrying...\"", "begin", "connection", ".", "disconnect", "rescue", "# don't crash in the crash handler", "end", "retry", "end", "ensure", "connection", ".", "started?", "&&", "connection", ".", "disconnect", "end", "break", "unless", "polling?", "sleep", "config", ".", "poll_interval", "end", "end" ]
Run the polling loop for the email inbox connection
[ "Run", "the", "polling", "loop", "for", "the", "email", "inbox", "connection" ]
b955154c5d73b85cdc76687222288b1cf5a2ea91
https://github.com/mailman/mailman/blob/b955154c5d73b85cdc76687222288b1cf5a2ea91/lib/mailman/application.rb#L134-L164
16,941
airbnb/hypernova-ruby
lib/hypernova/controller_helpers.rb
Hypernova.ControllerHelpers.hypernova_batch_render
def hypernova_batch_render(job) if @hypernova_batch.nil? raise NilBatchError.new('called hypernova_batch_render without calling '\ 'hypernova_batch_before. Check your around_filter for :hypernova_render_support') end batch_token = @hypernova_batch.render(job) template_safe_token = Hypernova.render_token(batch_token) @hypernova_batch_mapping[template_safe_token] = batch_token template_safe_token end
ruby
def hypernova_batch_render(job) if @hypernova_batch.nil? raise NilBatchError.new('called hypernova_batch_render without calling '\ 'hypernova_batch_before. Check your around_filter for :hypernova_render_support') end batch_token = @hypernova_batch.render(job) template_safe_token = Hypernova.render_token(batch_token) @hypernova_batch_mapping[template_safe_token] = batch_token template_safe_token end
[ "def", "hypernova_batch_render", "(", "job", ")", "if", "@hypernova_batch", ".", "nil?", "raise", "NilBatchError", ".", "new", "(", "'called hypernova_batch_render without calling '", "'hypernova_batch_before. Check your around_filter for :hypernova_render_support'", ")", "end", "batch_token", "=", "@hypernova_batch", ".", "render", "(", "job", ")", "template_safe_token", "=", "Hypernova", ".", "render_token", "(", "batch_token", ")", "@hypernova_batch_mapping", "[", "template_safe_token", "]", "=", "batch_token", "template_safe_token", "end" ]
enqueue a render into the current request's hypernova batch
[ "enqueue", "a", "render", "into", "the", "current", "request", "s", "hypernova", "batch" ]
ce2497003566bf2837a30ee6bffac700538ffbdc
https://github.com/airbnb/hypernova-ruby/blob/ce2497003566bf2837a30ee6bffac700538ffbdc/lib/hypernova/controller_helpers.rb#L22-L31
16,942
airbnb/hypernova-ruby
lib/hypernova/controller_helpers.rb
Hypernova.ControllerHelpers.render_react_component
def render_react_component(component, data = {}) begin new_data = get_view_data(component, data) rescue StandardError => e on_error(e) new_data = data end job = { :data => new_data, :name => component, } hypernova_batch_render(job) end
ruby
def render_react_component(component, data = {}) begin new_data = get_view_data(component, data) rescue StandardError => e on_error(e) new_data = data end job = { :data => new_data, :name => component, } hypernova_batch_render(job) end
[ "def", "render_react_component", "(", "component", ",", "data", "=", "{", "}", ")", "begin", "new_data", "=", "get_view_data", "(", "component", ",", "data", ")", "rescue", "StandardError", "=>", "e", "on_error", "(", "e", ")", "new_data", "=", "data", "end", "job", "=", "{", ":data", "=>", "new_data", ",", ":name", "=>", "component", ",", "}", "hypernova_batch_render", "(", "job", ")", "end" ]
shortcut method to render a react component @param [String] name the hypernova bundle name, like 'packages/p3/foo.bundle.js' (for now) @param [Hash] props the props to be passed to the component :^)k|8 <-- this is a chill peep riding a skateboard
[ "shortcut", "method", "to", "render", "a", "react", "component" ]
ce2497003566bf2837a30ee6bffac700538ffbdc
https://github.com/airbnb/hypernova-ruby/blob/ce2497003566bf2837a30ee6bffac700538ffbdc/lib/hypernova/controller_helpers.rb#L38-L51
16,943
airbnb/hypernova-ruby
lib/hypernova/controller_helpers.rb
Hypernova.ControllerHelpers.hypernova_batch_after
def hypernova_batch_after if @hypernova_batch.nil? raise NilBatchError.new('called hypernova_batch_after without calling '\ 'hypernova_batch_before. Check your around_filter for :hypernova_render_support') end return if @hypernova_batch.empty? jobs = @hypernova_batch.jobs hash = jobs.each_with_object({}) do |job, h| h[job[:name]] = job end hash = prepare_request(hash, hash) if send_request?(hash) begin will_send_request(hash) result = @hypernova_batch.submit! on_success(result, hash) rescue StandardError => e on_error(e, nil, hash) result = @hypernova_batch.submit_fallback! end else result = @hypernova_batch.submit_fallback! end new_body = Hypernova.replace_tokens_with_result( response.body, @hypernova_batch_mapping, result ) response.body = new_body end
ruby
def hypernova_batch_after if @hypernova_batch.nil? raise NilBatchError.new('called hypernova_batch_after without calling '\ 'hypernova_batch_before. Check your around_filter for :hypernova_render_support') end return if @hypernova_batch.empty? jobs = @hypernova_batch.jobs hash = jobs.each_with_object({}) do |job, h| h[job[:name]] = job end hash = prepare_request(hash, hash) if send_request?(hash) begin will_send_request(hash) result = @hypernova_batch.submit! on_success(result, hash) rescue StandardError => e on_error(e, nil, hash) result = @hypernova_batch.submit_fallback! end else result = @hypernova_batch.submit_fallback! end new_body = Hypernova.replace_tokens_with_result( response.body, @hypernova_batch_mapping, result ) response.body = new_body end
[ "def", "hypernova_batch_after", "if", "@hypernova_batch", ".", "nil?", "raise", "NilBatchError", ".", "new", "(", "'called hypernova_batch_after without calling '", "'hypernova_batch_before. Check your around_filter for :hypernova_render_support'", ")", "end", "return", "if", "@hypernova_batch", ".", "empty?", "jobs", "=", "@hypernova_batch", ".", "jobs", "hash", "=", "jobs", ".", "each_with_object", "(", "{", "}", ")", "do", "|", "job", ",", "h", "|", "h", "[", "job", "[", ":name", "]", "]", "=", "job", "end", "hash", "=", "prepare_request", "(", "hash", ",", "hash", ")", "if", "send_request?", "(", "hash", ")", "begin", "will_send_request", "(", "hash", ")", "result", "=", "@hypernova_batch", ".", "submit!", "on_success", "(", "result", ",", "hash", ")", "rescue", "StandardError", "=>", "e", "on_error", "(", "e", ",", "nil", ",", "hash", ")", "result", "=", "@hypernova_batch", ".", "submit_fallback!", "end", "else", "result", "=", "@hypernova_batch", ".", "submit_fallback!", "end", "new_body", "=", "Hypernova", ".", "replace_tokens_with_result", "(", "response", ".", "body", ",", "@hypernova_batch_mapping", ",", "result", ")", "response", ".", "body", "=", "new_body", "end" ]
Modifies response.body to have all batched hypernova render results
[ "Modifies", "response", ".", "body", "to", "have", "all", "batched", "hypernova", "render", "results" ]
ce2497003566bf2837a30ee6bffac700538ffbdc
https://github.com/airbnb/hypernova-ruby/blob/ce2497003566bf2837a30ee6bffac700538ffbdc/lib/hypernova/controller_helpers.rb#L73-L104
16,944
airbnb/hypernova-ruby
lib/hypernova/batch.rb
Hypernova.Batch.jobs_hash
def jobs_hash hash = {} jobs.each_with_index { |job, idx| hash[idx.to_s] = job } hash end
ruby
def jobs_hash hash = {} jobs.each_with_index { |job, idx| hash[idx.to_s] = job } hash end
[ "def", "jobs_hash", "hash", "=", "{", "}", "jobs", ".", "each_with_index", "{", "|", "job", ",", "idx", "|", "hash", "[", "idx", ".", "to_s", "]", "=", "job", "}", "hash", "end" ]
creates a hash with each index mapped to the value at that index
[ "creates", "a", "hash", "with", "each", "index", "mapped", "to", "the", "value", "at", "that", "index" ]
ce2497003566bf2837a30ee6bffac700538ffbdc
https://github.com/airbnb/hypernova-ruby/blob/ce2497003566bf2837a30ee6bffac700538ffbdc/lib/hypernova/batch.rb#L43-L47
16,945
rspec/rspec-its
lib/rspec/its.rb
RSpec.Its.its
def its(attribute, *options, &block) its_caller = caller.select {|file_line| file_line !~ %r(/lib/rspec/its) } describe(attribute.to_s, :caller => its_caller) do let(:__its_subject) do if Array === attribute if Hash === subject attribute.inject(subject) {|inner, attr| inner[attr] } else subject[*attribute] end else attribute_chain = attribute.to_s.split('.') attribute_chain.inject(subject) do |inner_subject, attr| inner_subject.send(attr) end end end def is_expected expect(__its_subject) end alias_method :are_expected, :is_expected def will(matcher=nil, message=nil) unless matcher.supports_block_expectations? raise ArgumentError, "`will` only supports block expectations" end expect { __its_subject }.to matcher, message end def will_not(matcher=nil, message=nil) unless matcher.supports_block_expectations? raise ArgumentError, "`will_not` only supports block expectations" end expect { __its_subject }.to_not matcher, message end def should(matcher=nil, message=nil) RSpec::Expectations::PositiveExpectationHandler.handle_matcher(__its_subject, matcher, message) end def should_not(matcher=nil, message=nil) RSpec::Expectations::NegativeExpectationHandler.handle_matcher(__its_subject, matcher, message) end options << {} unless options.last.kind_of?(Hash) options.last.merge!(:caller => its_caller) example(nil, *options, &block) end end
ruby
def its(attribute, *options, &block) its_caller = caller.select {|file_line| file_line !~ %r(/lib/rspec/its) } describe(attribute.to_s, :caller => its_caller) do let(:__its_subject) do if Array === attribute if Hash === subject attribute.inject(subject) {|inner, attr| inner[attr] } else subject[*attribute] end else attribute_chain = attribute.to_s.split('.') attribute_chain.inject(subject) do |inner_subject, attr| inner_subject.send(attr) end end end def is_expected expect(__its_subject) end alias_method :are_expected, :is_expected def will(matcher=nil, message=nil) unless matcher.supports_block_expectations? raise ArgumentError, "`will` only supports block expectations" end expect { __its_subject }.to matcher, message end def will_not(matcher=nil, message=nil) unless matcher.supports_block_expectations? raise ArgumentError, "`will_not` only supports block expectations" end expect { __its_subject }.to_not matcher, message end def should(matcher=nil, message=nil) RSpec::Expectations::PositiveExpectationHandler.handle_matcher(__its_subject, matcher, message) end def should_not(matcher=nil, message=nil) RSpec::Expectations::NegativeExpectationHandler.handle_matcher(__its_subject, matcher, message) end options << {} unless options.last.kind_of?(Hash) options.last.merge!(:caller => its_caller) example(nil, *options, &block) end end
[ "def", "its", "(", "attribute", ",", "*", "options", ",", "&", "block", ")", "its_caller", "=", "caller", ".", "select", "{", "|", "file_line", "|", "file_line", "!~", "%r(", ")", "}", "describe", "(", "attribute", ".", "to_s", ",", ":caller", "=>", "its_caller", ")", "do", "let", "(", ":__its_subject", ")", "do", "if", "Array", "===", "attribute", "if", "Hash", "===", "subject", "attribute", ".", "inject", "(", "subject", ")", "{", "|", "inner", ",", "attr", "|", "inner", "[", "attr", "]", "}", "else", "subject", "[", "attribute", "]", "end", "else", "attribute_chain", "=", "attribute", ".", "to_s", ".", "split", "(", "'.'", ")", "attribute_chain", ".", "inject", "(", "subject", ")", "do", "|", "inner_subject", ",", "attr", "|", "inner_subject", ".", "send", "(", "attr", ")", "end", "end", "end", "def", "is_expected", "expect", "(", "__its_subject", ")", "end", "alias_method", ":are_expected", ",", ":is_expected", "def", "will", "(", "matcher", "=", "nil", ",", "message", "=", "nil", ")", "unless", "matcher", ".", "supports_block_expectations?", "raise", "ArgumentError", ",", "\"`will` only supports block expectations\"", "end", "expect", "{", "__its_subject", "}", ".", "to", "matcher", ",", "message", "end", "def", "will_not", "(", "matcher", "=", "nil", ",", "message", "=", "nil", ")", "unless", "matcher", ".", "supports_block_expectations?", "raise", "ArgumentError", ",", "\"`will_not` only supports block expectations\"", "end", "expect", "{", "__its_subject", "}", ".", "to_not", "matcher", ",", "message", "end", "def", "should", "(", "matcher", "=", "nil", ",", "message", "=", "nil", ")", "RSpec", "::", "Expectations", "::", "PositiveExpectationHandler", ".", "handle_matcher", "(", "__its_subject", ",", "matcher", ",", "message", ")", "end", "def", "should_not", "(", "matcher", "=", "nil", ",", "message", "=", "nil", ")", "RSpec", "::", "Expectations", "::", "NegativeExpectationHandler", ".", "handle_matcher", "(", "__its_subject", ",", "matcher", ",", "message", ")", "end", "options", "<<", "{", "}", "unless", "options", ".", "last", ".", "kind_of?", "(", "Hash", ")", "options", ".", "last", ".", "merge!", "(", ":caller", "=>", "its_caller", ")", "example", "(", "nil", ",", "options", ",", "block", ")", "end", "end" ]
Creates a nested example group named by the submitted `attribute`, and then generates an example using the submitted block. @example # This ... describe Array do its(:size) { should eq(0) } end # ... generates the same runtime structure as this: describe Array do describe "size" do it "should eq(0)" do subject.size.should eq(0) end end end The attribute can be a `Symbol` or a `String`. Given a `String` with dots, the result is as though you concatenated that `String` onto the subject in an expression. @example describe Person do subject do Person.new.tap do |person| person.phone_numbers << "555-1212" end end its("phone_numbers.first") { should eq("555-1212") } end When the subject is a `Hash`, you can refer to the Hash keys by specifying a `Symbol` or `String` in an array. @example describe "a configuration Hash" do subject do { :max_users => 3, 'admin' => :all_permissions. 'john_doe' => {:permissions => [:read, :write]}} end its([:max_users]) { should eq(3) } its(['admin']) { should eq(:all_permissions) } its(['john_doe', :permissions]) { should eq([:read, :write]) } # You can still access its regular methods this way: its(:keys) { should include(:max_users) } its(:count) { should eq(2) } end With an implicit subject, `is_expected` can be used as an alternative to `should` (e.g. for one-liner use). An `are_expected` alias is also supplied. @example describe Array do its(:size) { is_expected.to eq(0) } end With an implicit subject, `will` can be used as an alternative to `expect { subject.attribute }.to matcher` (e.g. for one-liner use). @example describe Array do its(:foo) { will raise_error(NoMethodError) } end With an implicit subject, `will_not` can be used as an alternative to `expect { subject.attribute }.to_not matcher` (e.g. for one-liner use). @example describe Array do its(:size) { will_not raise_error } end You can pass more than one argument on the `its` block to add some metadata to the generated example @example # This ... describe Array do its(:size, :focus) { should eq(0) } end # ... generates the same runtime structure as this: describe Array do describe "size" do it "should eq(0)", :focus do subject.size.should eq(0) end end end Note that this method does not modify `subject` in any way, so if you refer to `subject` in `let` or `before` blocks, you're still referring to the outer subject. @example describe Person do subject { Person.new } before { subject.age = 25 } its(:age) { should eq(25) } end
[ "Creates", "a", "nested", "example", "group", "named", "by", "the", "submitted", "attribute", "and", "then", "generates", "an", "example", "using", "the", "submitted", "block", "." ]
f80aa97fe87b4da9f991b8556d41905e27a4ffbb
https://github.com/rspec/rspec-its/blob/f80aa97fe87b4da9f991b8556d41905e27a4ffbb/lib/rspec/its.rb#L121-L172
16,946
soffes/hue
lib/hue/light.rb
Hue.Light.refresh
def refresh json = JSON(Net::HTTP.get(URI.parse(base_url))) unpack(json) end
ruby
def refresh json = JSON(Net::HTTP.get(URI.parse(base_url))) unpack(json) end
[ "def", "refresh", "json", "=", "JSON", "(", "Net", "::", "HTTP", ".", "get", "(", "URI", ".", "parse", "(", "base_url", ")", ")", ")", "unpack", "(", "json", ")", "end" ]
Refresh the state of the lamp
[ "Refresh", "the", "state", "of", "the", "lamp" ]
2e9db44148d7d964e586af9268ac4dc1efb379d6
https://github.com/soffes/hue/blob/2e9db44148d7d964e586af9268ac4dc1efb379d6/lib/hue/light.rb#L138-L141
16,947
Netflix/spectator-rb
lib/spectator/timer.rb
Spectator.Timer.record
def record(nanos) return if nanos < 0 @count.add_and_get(1) @total_time.add_and_get(nanos) @total_sq.add_and_get(nanos * nanos) @max.max(nanos) end
ruby
def record(nanos) return if nanos < 0 @count.add_and_get(1) @total_time.add_and_get(nanos) @total_sq.add_and_get(nanos * nanos) @max.max(nanos) end
[ "def", "record", "(", "nanos", ")", "return", "if", "nanos", "<", "0", "@count", ".", "add_and_get", "(", "1", ")", "@total_time", ".", "add_and_get", "(", "nanos", ")", "@total_sq", ".", "add_and_get", "(", "nanos", "*", "nanos", ")", "@max", ".", "max", "(", "nanos", ")", "end" ]
Update the statistics kept by this timer. If the amount of nanoseconds passed is negative, the value will be ignored.
[ "Update", "the", "statistics", "kept", "by", "this", "timer", ".", "If", "the", "amount", "of", "nanoseconds", "passed", "is", "negative", "the", "value", "will", "be", "ignored", "." ]
0022320f729ea716ca0d12123caf07668e137e0f
https://github.com/Netflix/spectator-rb/blob/0022320f729ea716ca0d12123caf07668e137e0f/lib/spectator/timer.rb#L22-L28
16,948
Netflix/spectator-rb
lib/spectator/meter_id.rb
Spectator.MeterId.with_tag
def with_tag(key, value) new_tags = @tags.dup new_tags[key] = value MeterId.new(@name, new_tags) end
ruby
def with_tag(key, value) new_tags = @tags.dup new_tags[key] = value MeterId.new(@name, new_tags) end
[ "def", "with_tag", "(", "key", ",", "value", ")", "new_tags", "=", "@tags", ".", "dup", "new_tags", "[", "key", "]", "=", "value", "MeterId", ".", "new", "(", "@name", ",", "new_tags", ")", "end" ]
Create a new MeterId with a given key and value
[ "Create", "a", "new", "MeterId", "with", "a", "given", "key", "and", "value" ]
0022320f729ea716ca0d12123caf07668e137e0f
https://github.com/Netflix/spectator-rb/blob/0022320f729ea716ca0d12123caf07668e137e0f/lib/spectator/meter_id.rb#L15-L19
16,949
Netflix/spectator-rb
lib/spectator/meter_id.rb
Spectator.MeterId.key
def key if @key.nil? hash_key = @name.to_s @key = hash_key keys = @tags.keys keys.sort keys.each do |k| v = tags[k] hash_key += "|#{k}|#{v}" end @key = hash_key end @key end
ruby
def key if @key.nil? hash_key = @name.to_s @key = hash_key keys = @tags.keys keys.sort keys.each do |k| v = tags[k] hash_key += "|#{k}|#{v}" end @key = hash_key end @key end
[ "def", "key", "if", "@key", ".", "nil?", "hash_key", "=", "@name", ".", "to_s", "@key", "=", "hash_key", "keys", "=", "@tags", ".", "keys", "keys", ".", "sort", "keys", ".", "each", "do", "|", "k", "|", "v", "=", "tags", "[", "k", "]", "hash_key", "+=", "\"|#{k}|#{v}\"", "end", "@key", "=", "hash_key", "end", "@key", "end" ]
lazyily compute a key to be used in hashes for efficiency
[ "lazyily", "compute", "a", "key", "to", "be", "used", "in", "hashes", "for", "efficiency" ]
0022320f729ea716ca0d12123caf07668e137e0f
https://github.com/Netflix/spectator-rb/blob/0022320f729ea716ca0d12123caf07668e137e0f/lib/spectator/meter_id.rb#L27-L40
16,950
Netflix/spectator-rb
lib/spectator/distribution_summary.rb
Spectator.DistributionSummary.record
def record(amount) return if amount < 0 @count.add_and_get(1) @total_amount.add_and_get(amount) @total_sq.add_and_get(amount * amount) @max.max(amount) end
ruby
def record(amount) return if amount < 0 @count.add_and_get(1) @total_amount.add_and_get(amount) @total_sq.add_and_get(amount * amount) @max.max(amount) end
[ "def", "record", "(", "amount", ")", "return", "if", "amount", "<", "0", "@count", ".", "add_and_get", "(", "1", ")", "@total_amount", ".", "add_and_get", "(", "amount", ")", "@total_sq", ".", "add_and_get", "(", "amount", "*", "amount", ")", "@max", ".", "max", "(", "amount", ")", "end" ]
Initialize a new DistributionSummary instance with a given id Update the statistics kept by the summary with the specified amount.
[ "Initialize", "a", "new", "DistributionSummary", "instance", "with", "a", "given", "id", "Update", "the", "statistics", "kept", "by", "the", "summary", "with", "the", "specified", "amount", "." ]
0022320f729ea716ca0d12123caf07668e137e0f
https://github.com/Netflix/spectator-rb/blob/0022320f729ea716ca0d12123caf07668e137e0f/lib/spectator/distribution_summary.rb#L21-L27
16,951
Netflix/spectator-rb
lib/spectator/distribution_summary.rb
Spectator.DistributionSummary.measure
def measure cnt = Measure.new(@id.with_stat('count'), @count.get_and_set(0)) tot = Measure.new(@id.with_stat('totalAmount'), @total_amount.get_and_set(0)) tot_sq = Measure.new(@id.with_stat('totalOfSquares'), @total_sq.get_and_set(0)) mx = Measure.new(@id.with_stat('max'), @max.get_and_set(Float::NAN)) [cnt, tot, tot_sq, mx] end
ruby
def measure cnt = Measure.new(@id.with_stat('count'), @count.get_and_set(0)) tot = Measure.new(@id.with_stat('totalAmount'), @total_amount.get_and_set(0)) tot_sq = Measure.new(@id.with_stat('totalOfSquares'), @total_sq.get_and_set(0)) mx = Measure.new(@id.with_stat('max'), @max.get_and_set(Float::NAN)) [cnt, tot, tot_sq, mx] end
[ "def", "measure", "cnt", "=", "Measure", ".", "new", "(", "@id", ".", "with_stat", "(", "'count'", ")", ",", "@count", ".", "get_and_set", "(", "0", ")", ")", "tot", "=", "Measure", ".", "new", "(", "@id", ".", "with_stat", "(", "'totalAmount'", ")", ",", "@total_amount", ".", "get_and_set", "(", "0", ")", ")", "tot_sq", "=", "Measure", ".", "new", "(", "@id", ".", "with_stat", "(", "'totalOfSquares'", ")", ",", "@total_sq", ".", "get_and_set", "(", "0", ")", ")", "mx", "=", "Measure", ".", "new", "(", "@id", ".", "with_stat", "(", "'max'", ")", ",", "@max", ".", "get_and_set", "(", "Float", "::", "NAN", ")", ")", "[", "cnt", ",", "tot", ",", "tot_sq", ",", "mx", "]", "end" ]
Get a list of measurements, and reset the stats The stats returned are the current count, the total amount, the sum of the square of the amounts recorded, and the max value
[ "Get", "a", "list", "of", "measurements", "and", "reset", "the", "stats", "The", "stats", "returned", "are", "the", "current", "count", "the", "total", "amount", "the", "sum", "of", "the", "square", "of", "the", "amounts", "recorded", "and", "the", "max", "value" ]
0022320f729ea716ca0d12123caf07668e137e0f
https://github.com/Netflix/spectator-rb/blob/0022320f729ea716ca0d12123caf07668e137e0f/lib/spectator/distribution_summary.rb#L42-L51
16,952
Netflix/spectator-rb
lib/spectator/http.rb
Spectator.Http.post_json
def post_json(endpoint, payload) s = payload.to_json uri = URI(endpoint) http = Net::HTTP.new(uri.host, uri.port) req = Net::HTTP::Post.new(uri.path, 'Content-Type' => 'application/json') req.body = s begin res = http.request(req) rescue StandardError => e Spectator.logger.info("Cause #{e.cause} - msg=#{e.message}") return 400 end res.value end
ruby
def post_json(endpoint, payload) s = payload.to_json uri = URI(endpoint) http = Net::HTTP.new(uri.host, uri.port) req = Net::HTTP::Post.new(uri.path, 'Content-Type' => 'application/json') req.body = s begin res = http.request(req) rescue StandardError => e Spectator.logger.info("Cause #{e.cause} - msg=#{e.message}") return 400 end res.value end
[ "def", "post_json", "(", "endpoint", ",", "payload", ")", "s", "=", "payload", ".", "to_json", "uri", "=", "URI", "(", "endpoint", ")", "http", "=", "Net", "::", "HTTP", ".", "new", "(", "uri", ".", "host", ",", "uri", ".", "port", ")", "req", "=", "Net", "::", "HTTP", "::", "Post", ".", "new", "(", "uri", ".", "path", ",", "'Content-Type'", "=>", "'application/json'", ")", "req", ".", "body", "=", "s", "begin", "res", "=", "http", ".", "request", "(", "req", ")", "rescue", "StandardError", "=>", "e", "Spectator", ".", "logger", ".", "info", "(", "\"Cause #{e.cause} - msg=#{e.message}\"", ")", "return", "400", "end", "res", ".", "value", "end" ]
Create a new instance using the given registry to record stats for the requests performed Send a JSON payload to a given endpoing
[ "Create", "a", "new", "instance", "using", "the", "given", "registry", "to", "record", "stats", "for", "the", "requests", "performed", "Send", "a", "JSON", "payload", "to", "a", "given", "endpoing" ]
0022320f729ea716ca0d12123caf07668e137e0f
https://github.com/Netflix/spectator-rb/blob/0022320f729ea716ca0d12123caf07668e137e0f/lib/spectator/http.rb#L14-L28
16,953
Netflix/spectator-rb
lib/spectator/registry.rb
Spectator.Publisher.stop
def stop unless @started Spectator.logger.info('Attemping to stop Spectator ' \ 'without a previous call to start') return end @should_stop = true Spectator.logger.info('Stopping spectator') @publish_thread.kill if @publish_thread @started = false Spectator.logger.info('Sending last batch of metrics before exiting') send_metrics_now end
ruby
def stop unless @started Spectator.logger.info('Attemping to stop Spectator ' \ 'without a previous call to start') return end @should_stop = true Spectator.logger.info('Stopping spectator') @publish_thread.kill if @publish_thread @started = false Spectator.logger.info('Sending last batch of metrics before exiting') send_metrics_now end
[ "def", "stop", "unless", "@started", "Spectator", ".", "logger", ".", "info", "(", "'Attemping to stop Spectator '", "'without a previous call to start'", ")", "return", "end", "@should_stop", "=", "true", "Spectator", ".", "logger", ".", "info", "(", "'Stopping spectator'", ")", "@publish_thread", ".", "kill", "if", "@publish_thread", "@started", "=", "false", "Spectator", ".", "logger", ".", "info", "(", "'Sending last batch of metrics before exiting'", ")", "send_metrics_now", "end" ]
Stop publishing measurements
[ "Stop", "publishing", "measurements" ]
0022320f729ea716ca0d12123caf07668e137e0f
https://github.com/Netflix/spectator-rb/blob/0022320f729ea716ca0d12123caf07668e137e0f/lib/spectator/registry.rb#L157-L171
16,954
Netflix/spectator-rb
lib/spectator/registry.rb
Spectator.Publisher.op_for_measurement
def op_for_measurement(measure) stat = measure.id.tags.fetch(:statistic, :unknown) OPS.fetch(stat, UNKNOWN_OP) end
ruby
def op_for_measurement(measure) stat = measure.id.tags.fetch(:statistic, :unknown) OPS.fetch(stat, UNKNOWN_OP) end
[ "def", "op_for_measurement", "(", "measure", ")", "stat", "=", "measure", ".", "id", ".", "tags", ".", "fetch", "(", ":statistic", ",", ":unknown", ")", "OPS", ".", "fetch", "(", "stat", ",", "UNKNOWN_OP", ")", "end" ]
Get the operation to be used for the given Measure Gauges are aggregated using MAX_OP, counters with ADD_OP
[ "Get", "the", "operation", "to", "be", "used", "for", "the", "given", "Measure", "Gauges", "are", "aggregated", "using", "MAX_OP", "counters", "with", "ADD_OP" ]
0022320f729ea716ca0d12123caf07668e137e0f
https://github.com/Netflix/spectator-rb/blob/0022320f729ea716ca0d12123caf07668e137e0f/lib/spectator/registry.rb#L187-L190
16,955
Netflix/spectator-rb
lib/spectator/registry.rb
Spectator.Publisher.should_send
def should_send(measure) op = op_for_measurement(measure) return measure.value > 0 if op == ADD_OP return !measure.value.nan? if op == MAX_OP false end
ruby
def should_send(measure) op = op_for_measurement(measure) return measure.value > 0 if op == ADD_OP return !measure.value.nan? if op == MAX_OP false end
[ "def", "should_send", "(", "measure", ")", "op", "=", "op_for_measurement", "(", "measure", ")", "return", "measure", ".", "value", ">", "0", "if", "op", "==", "ADD_OP", "return", "!", "measure", ".", "value", ".", "nan?", "if", "op", "==", "MAX_OP", "false", "end" ]
Gauges are sent if they have a value Counters if they have a number of increments greater than 0
[ "Gauges", "are", "sent", "if", "they", "have", "a", "value", "Counters", "if", "they", "have", "a", "number", "of", "increments", "greater", "than", "0" ]
0022320f729ea716ca0d12123caf07668e137e0f
https://github.com/Netflix/spectator-rb/blob/0022320f729ea716ca0d12123caf07668e137e0f/lib/spectator/registry.rb#L194-L200
16,956
Netflix/spectator-rb
lib/spectator/registry.rb
Spectator.Publisher.build_string_table
def build_string_table(measurements) common_tags = @registry.common_tags table = {} common_tags.each do |k, v| table[k] = 0 table[v] = 0 end table[:name] = 0 measurements.each do |m| table[m.id.name] = 0 m.id.tags.each do |k, v| table[k] = 0 table[v] = 0 end end keys = table.keys.sort keys.each_with_index do |str, index| table[str] = index end table end
ruby
def build_string_table(measurements) common_tags = @registry.common_tags table = {} common_tags.each do |k, v| table[k] = 0 table[v] = 0 end table[:name] = 0 measurements.each do |m| table[m.id.name] = 0 m.id.tags.each do |k, v| table[k] = 0 table[v] = 0 end end keys = table.keys.sort keys.each_with_index do |str, index| table[str] = index end table end
[ "def", "build_string_table", "(", "measurements", ")", "common_tags", "=", "@registry", ".", "common_tags", "table", "=", "{", "}", "common_tags", ".", "each", "do", "|", "k", ",", "v", "|", "table", "[", "k", "]", "=", "0", "table", "[", "v", "]", "=", "0", "end", "table", "[", ":name", "]", "=", "0", "measurements", ".", "each", "do", "|", "m", "|", "table", "[", "m", ".", "id", ".", "name", "]", "=", "0", "m", ".", "id", ".", "tags", ".", "each", "do", "|", "k", ",", "v", "|", "table", "[", "k", "]", "=", "0", "table", "[", "v", "]", "=", "0", "end", "end", "keys", "=", "table", ".", "keys", ".", "sort", "keys", ".", "each_with_index", "do", "|", "str", ",", "index", "|", "table", "[", "str", "]", "=", "index", "end", "table", "end" ]
Build a string table from the list of measurements Unique words are identified, and assigned a number starting from 0 based on their lexicographical order
[ "Build", "a", "string", "table", "from", "the", "list", "of", "measurements", "Unique", "words", "are", "identified", "and", "assigned", "a", "number", "starting", "from", "0", "based", "on", "their", "lexicographical", "order" ]
0022320f729ea716ca0d12123caf07668e137e0f
https://github.com/Netflix/spectator-rb/blob/0022320f729ea716ca0d12123caf07668e137e0f/lib/spectator/registry.rb#L205-L225
16,957
Netflix/spectator-rb
lib/spectator/registry.rb
Spectator.Publisher.payload_for_measurements
def payload_for_measurements(measurements) table = build_string_table(measurements) payload = [] payload.push(table.length) strings = table.keys.sort payload.concat(strings) measurements.each { |m| append_measurement(payload, table, m) } payload end
ruby
def payload_for_measurements(measurements) table = build_string_table(measurements) payload = [] payload.push(table.length) strings = table.keys.sort payload.concat(strings) measurements.each { |m| append_measurement(payload, table, m) } payload end
[ "def", "payload_for_measurements", "(", "measurements", ")", "table", "=", "build_string_table", "(", "measurements", ")", "payload", "=", "[", "]", "payload", ".", "push", "(", "table", ".", "length", ")", "strings", "=", "table", ".", "keys", ".", "sort", "payload", ".", "concat", "(", "strings", ")", "measurements", ".", "each", "{", "|", "m", "|", "append_measurement", "(", "payload", ",", "table", ",", "m", ")", "}", "payload", "end" ]
Generate a payload from the list of measurements The payload is an array, with the number of elements in the string table The string table, and measurements
[ "Generate", "a", "payload", "from", "the", "list", "of", "measurements", "The", "payload", "is", "an", "array", "with", "the", "number", "of", "elements", "in", "the", "string", "table", "The", "string", "table", "and", "measurements" ]
0022320f729ea716ca0d12123caf07668e137e0f
https://github.com/Netflix/spectator-rb/blob/0022320f729ea716ca0d12123caf07668e137e0f/lib/spectator/registry.rb#L256-L264
16,958
Netflix/spectator-rb
lib/spectator/registry.rb
Spectator.Publisher.send_metrics_now
def send_metrics_now ms = registry_measurements if ms.empty? Spectator.logger.debug 'No measurements to send' else uri = @registry.config[:uri] ms.each_slice(@registry.batch_size) do |batch| payload = payload_for_measurements(batch) Spectator.logger.info "Sending #{batch.length} measurements to #{uri}" @http.post_json(uri, payload) end end end
ruby
def send_metrics_now ms = registry_measurements if ms.empty? Spectator.logger.debug 'No measurements to send' else uri = @registry.config[:uri] ms.each_slice(@registry.batch_size) do |batch| payload = payload_for_measurements(batch) Spectator.logger.info "Sending #{batch.length} measurements to #{uri}" @http.post_json(uri, payload) end end end
[ "def", "send_metrics_now", "ms", "=", "registry_measurements", "if", "ms", ".", "empty?", "Spectator", ".", "logger", ".", "debug", "'No measurements to send'", "else", "uri", "=", "@registry", ".", "config", "[", ":uri", "]", "ms", ".", "each_slice", "(", "@registry", ".", "batch_size", ")", "do", "|", "batch", "|", "payload", "=", "payload_for_measurements", "(", "batch", ")", "Spectator", ".", "logger", ".", "info", "\"Sending #{batch.length} measurements to #{uri}\"", "@http", ".", "post_json", "(", "uri", ",", "payload", ")", "end", "end", "end" ]
Send the current measurements to our aggregator service
[ "Send", "the", "current", "measurements", "to", "our", "aggregator", "service" ]
0022320f729ea716ca0d12123caf07668e137e0f
https://github.com/Netflix/spectator-rb/blob/0022320f729ea716ca0d12123caf07668e137e0f/lib/spectator/registry.rb#L272-L285
16,959
troessner/transitions
lib/transitions/event.rb
Transitions.Event.timestamp=
def timestamp=(values) values.each do |value| case value when String, Symbol, TrueClass @timestamps << value else fail ArgumentError, 'timestamp must be either: true, a String or a Symbol' end end end
ruby
def timestamp=(values) values.each do |value| case value when String, Symbol, TrueClass @timestamps << value else fail ArgumentError, 'timestamp must be either: true, a String or a Symbol' end end end
[ "def", "timestamp", "=", "(", "values", ")", "values", ".", "each", "do", "|", "value", "|", "case", "value", "when", "String", ",", "Symbol", ",", "TrueClass", "@timestamps", "<<", "value", "else", "fail", "ArgumentError", ",", "'timestamp must be either: true, a String or a Symbol'", "end", "end", "end" ]
Set the timestamp attribute. @raise [ArgumentError] timestamp should be either a String, Symbol or true
[ "Set", "the", "timestamp", "attribute", "." ]
c31ea6247bf65920fa4a489940ea17d985d2c9df
https://github.com/troessner/transitions/blob/c31ea6247bf65920fa4a489940ea17d985d2c9df/lib/transitions/event.rb#L90-L99
16,960
troessner/transitions
lib/transitions/event.rb
Transitions.Event.timestamp_attribute_name
def timestamp_attribute_name(obj, next_state, user_timestamp) user_timestamp == true ? default_timestamp_name(obj, next_state) : user_timestamp end
ruby
def timestamp_attribute_name(obj, next_state, user_timestamp) user_timestamp == true ? default_timestamp_name(obj, next_state) : user_timestamp end
[ "def", "timestamp_attribute_name", "(", "obj", ",", "next_state", ",", "user_timestamp", ")", "user_timestamp", "==", "true", "?", "default_timestamp_name", "(", "obj", ",", "next_state", ")", ":", "user_timestamp", "end" ]
Returns the name of the timestamp attribute for this event If the timestamp was simply true it returns the default_timestamp_name otherwise, returns the user-specified timestamp name
[ "Returns", "the", "name", "of", "the", "timestamp", "attribute", "for", "this", "event", "If", "the", "timestamp", "was", "simply", "true", "it", "returns", "the", "default_timestamp_name", "otherwise", "returns", "the", "user", "-", "specified", "timestamp", "name" ]
c31ea6247bf65920fa4a489940ea17d985d2c9df
https://github.com/troessner/transitions/blob/c31ea6247bf65920fa4a489940ea17d985d2c9df/lib/transitions/event.rb#L106-L108
16,961
glebm/rails_email_preview
app/controllers/rails_email_preview/emails_controller.rb
RailsEmailPreview.EmailsController.show
def show prevent_browser_caching cms_edit_links! with_email_locale do if @preview.respond_to?(:preview_mail) @mail, body = mail_and_body @mail_body_html = render_to_string(inline: body, layout: 'rails_email_preview/email') else raise ArgumentError.new("#{@preview} is not a preview class, does not respond_to?(:preview_mail)") end end end
ruby
def show prevent_browser_caching cms_edit_links! with_email_locale do if @preview.respond_to?(:preview_mail) @mail, body = mail_and_body @mail_body_html = render_to_string(inline: body, layout: 'rails_email_preview/email') else raise ArgumentError.new("#{@preview} is not a preview class, does not respond_to?(:preview_mail)") end end end
[ "def", "show", "prevent_browser_caching", "cms_edit_links!", "with_email_locale", "do", "if", "@preview", ".", "respond_to?", "(", ":preview_mail", ")", "@mail", ",", "body", "=", "mail_and_body", "@mail_body_html", "=", "render_to_string", "(", "inline", ":", "body", ",", "layout", ":", "'rails_email_preview/email'", ")", "else", "raise", "ArgumentError", ".", "new", "(", "\"#{@preview} is not a preview class, does not respond_to?(:preview_mail)\"", ")", "end", "end", "end" ]
Preview an email
[ "Preview", "an", "email" ]
723c126fbbbc4d19f75a9e457817e31d7954ea76
https://github.com/glebm/rails_email_preview/blob/723c126fbbbc4d19f75a9e457817e31d7954ea76/app/controllers/rails_email_preview/emails_controller.rb#L17-L28
16,962
glebm/rails_email_preview
app/controllers/rails_email_preview/emails_controller.rb
RailsEmailPreview.EmailsController.show_headers
def show_headers mail = with_email_locale { mail_and_body.first } render partial: 'rails_email_preview/emails/headers', locals: {mail: mail} end
ruby
def show_headers mail = with_email_locale { mail_and_body.first } render partial: 'rails_email_preview/emails/headers', locals: {mail: mail} end
[ "def", "show_headers", "mail", "=", "with_email_locale", "{", "mail_and_body", ".", "first", "}", "render", "partial", ":", "'rails_email_preview/emails/headers'", ",", "locals", ":", "{", "mail", ":", "mail", "}", "end" ]
Render headers partial. Used by the CMS integration to refetch headers after editing.
[ "Render", "headers", "partial", ".", "Used", "by", "the", "CMS", "integration", "to", "refetch", "headers", "after", "editing", "." ]
723c126fbbbc4d19f75a9e457817e31d7954ea76
https://github.com/glebm/rails_email_preview/blob/723c126fbbbc4d19f75a9e457817e31d7954ea76/app/controllers/rails_email_preview/emails_controller.rb#L59-L62
16,963
glebm/rails_email_preview
app/controllers/rails_email_preview/emails_controller.rb
RailsEmailPreview.EmailsController.show_body
def show_body prevent_browser_caching cms_edit_links! with_email_locale do _, body = mail_and_body render inline: body, layout: 'rails_email_preview/email' end end
ruby
def show_body prevent_browser_caching cms_edit_links! with_email_locale do _, body = mail_and_body render inline: body, layout: 'rails_email_preview/email' end end
[ "def", "show_body", "prevent_browser_caching", "cms_edit_links!", "with_email_locale", "do", "_", ",", "body", "=", "mail_and_body", "render", "inline", ":", "body", ",", "layout", ":", "'rails_email_preview/email'", "end", "end" ]
Render email body iframe HTML. Used by the CMS integration to provide a link back to Show from Edit.
[ "Render", "email", "body", "iframe", "HTML", ".", "Used", "by", "the", "CMS", "integration", "to", "provide", "a", "link", "back", "to", "Show", "from", "Edit", "." ]
723c126fbbbc4d19f75a9e457817e31d7954ea76
https://github.com/glebm/rails_email_preview/blob/723c126fbbbc4d19f75a9e457817e31d7954ea76/app/controllers/rails_email_preview/emails_controller.rb#L65-L72
16,964
ricardochimal/taps
lib/taps/utils.rb
Taps.Utils.incorrect_blobs
def incorrect_blobs(db, table) return [] if (db.url =~ /mysql:\/\//).nil? columns = [] db.schema(table).each do |data| column, cdata = data columns << column if cdata[:db_type] =~ /text/ end columns end
ruby
def incorrect_blobs(db, table) return [] if (db.url =~ /mysql:\/\//).nil? columns = [] db.schema(table).each do |data| column, cdata = data columns << column if cdata[:db_type] =~ /text/ end columns end
[ "def", "incorrect_blobs", "(", "db", ",", "table", ")", "return", "[", "]", "if", "(", "db", ".", "url", "=~", "/", "\\/", "\\/", "/", ")", ".", "nil?", "columns", "=", "[", "]", "db", ".", "schema", "(", "table", ")", ".", "each", "do", "|", "data", "|", "column", ",", "cdata", "=", "data", "columns", "<<", "column", "if", "cdata", "[", ":db_type", "]", "=~", "/", "/", "end", "columns", "end" ]
mysql text and blobs fields are handled the same way internally this is not true for other databases so we must check if the field is actually text and manually convert it back to a string
[ "mysql", "text", "and", "blobs", "fields", "are", "handled", "the", "same", "way", "internally", "this", "is", "not", "true", "for", "other", "databases", "so", "we", "must", "check", "if", "the", "field", "is", "actually", "text", "and", "manually", "convert", "it", "back", "to", "a", "string" ]
93bd2723df7fc14bc7aa9567f4c070c19145e956
https://github.com/ricardochimal/taps/blob/93bd2723df7fc14bc7aa9567f4c070c19145e956/lib/taps/utils.rb#L78-L87
16,965
ricardochimal/taps
lib/taps/utils.rb
Taps.Utils.server_error_handling
def server_error_handling(&blk) begin blk.call rescue Sequel::DatabaseError => e if e.message =~ /duplicate key value/i raise Taps::DuplicatePrimaryKeyError, e.message else raise end end end
ruby
def server_error_handling(&blk) begin blk.call rescue Sequel::DatabaseError => e if e.message =~ /duplicate key value/i raise Taps::DuplicatePrimaryKeyError, e.message else raise end end end
[ "def", "server_error_handling", "(", "&", "blk", ")", "begin", "blk", ".", "call", "rescue", "Sequel", "::", "DatabaseError", "=>", "e", "if", "e", ".", "message", "=~", "/", "/i", "raise", "Taps", "::", "DuplicatePrimaryKeyError", ",", "e", ".", "message", "else", "raise", "end", "end", "end" ]
try to detect server side errors to give the client a more useful error message
[ "try", "to", "detect", "server", "side", "errors", "to", "give", "the", "client", "a", "more", "useful", "error", "message" ]
93bd2723df7fc14bc7aa9567f4c070c19145e956
https://github.com/ricardochimal/taps/blob/93bd2723df7fc14bc7aa9567f4c070c19145e956/lib/taps/utils.rb#L159-L169
16,966
ricardochimal/taps
lib/taps/data_stream.rb
Taps.DataStream.fetch_rows
def fetch_rows state[:chunksize] = fetch_chunksize ds = table.order(*order_by).limit(state[:chunksize], state[:offset]) log.debug "DataStream#fetch_rows SQL -> #{ds.sql}" rows = Taps::Utils.format_data(ds.all, :string_columns => string_columns, :schema => db.schema(table_name), :table => table_name ) update_chunksize_stats rows end
ruby
def fetch_rows state[:chunksize] = fetch_chunksize ds = table.order(*order_by).limit(state[:chunksize], state[:offset]) log.debug "DataStream#fetch_rows SQL -> #{ds.sql}" rows = Taps::Utils.format_data(ds.all, :string_columns => string_columns, :schema => db.schema(table_name), :table => table_name ) update_chunksize_stats rows end
[ "def", "fetch_rows", "state", "[", ":chunksize", "]", "=", "fetch_chunksize", "ds", "=", "table", ".", "order", "(", "order_by", ")", ".", "limit", "(", "state", "[", ":chunksize", "]", ",", "state", "[", ":offset", "]", ")", "log", ".", "debug", "\"DataStream#fetch_rows SQL -> #{ds.sql}\"", "rows", "=", "Taps", "::", "Utils", ".", "format_data", "(", "ds", ".", "all", ",", ":string_columns", "=>", "string_columns", ",", ":schema", "=>", "db", ".", "schema", "(", "table_name", ")", ",", ":table", "=>", "table_name", ")", "update_chunksize_stats", "rows", "end" ]
keep a record of the average chunksize within the first few hundred thousand records, after chunksize goes below 100 or maybe if offset is > 1000
[ "keep", "a", "record", "of", "the", "average", "chunksize", "within", "the", "first", "few", "hundred", "thousand", "records", "after", "chunksize", "goes", "below", "100", "or", "maybe", "if", "offset", "is", ">", "1000" ]
93bd2723df7fc14bc7aa9567f4c070c19145e956
https://github.com/ricardochimal/taps/blob/93bd2723df7fc14bc7aa9567f4c070c19145e956/lib/taps/data_stream.rb#L76-L87
16,967
ricardochimal/taps
lib/taps/data_stream.rb
Taps.DataStream.fetch_remote_in_server
def fetch_remote_in_server(params) json = self.class.parse_json(params[:json]) encoded_data = params[:encoded_data] rows = parse_encoded_data(encoded_data, json[:checksum]) @complete = rows == { } unless @complete import_rows(rows) rows[:data].size else 0 end end
ruby
def fetch_remote_in_server(params) json = self.class.parse_json(params[:json]) encoded_data = params[:encoded_data] rows = parse_encoded_data(encoded_data, json[:checksum]) @complete = rows == { } unless @complete import_rows(rows) rows[:data].size else 0 end end
[ "def", "fetch_remote_in_server", "(", "params", ")", "json", "=", "self", ".", "class", ".", "parse_json", "(", "params", "[", ":json", "]", ")", "encoded_data", "=", "params", "[", ":encoded_data", "]", "rows", "=", "parse_encoded_data", "(", "encoded_data", ",", "json", "[", ":checksum", "]", ")", "@complete", "=", "rows", "==", "{", "}", "unless", "@complete", "import_rows", "(", "rows", ")", "rows", "[", ":data", "]", ".", "size", "else", "0", "end", "end" ]
this one is used inside the server process
[ "this", "one", "is", "used", "inside", "the", "server", "process" ]
93bd2723df7fc14bc7aa9567f4c070c19145e956
https://github.com/ricardochimal/taps/blob/93bd2723df7fc14bc7aa9567f4c070c19145e956/lib/taps/data_stream.rb#L150-L163
16,968
cinchrb/cinch
lib/cinch/handler.rb
Cinch.Handler.stop
def stop @bot.loggers.debug "[Stopping handler] Stopping all threads of handler #{self}: #{@thread_group.list.size} threads..." @thread_group.list.each do |thread| Thread.new do @bot.loggers.debug "[Ending thread] Waiting 10 seconds for #{thread} to finish..." thread.join(10) @bot.loggers.debug "[Killing thread] Killing #{thread}" thread.kill end end end
ruby
def stop @bot.loggers.debug "[Stopping handler] Stopping all threads of handler #{self}: #{@thread_group.list.size} threads..." @thread_group.list.each do |thread| Thread.new do @bot.loggers.debug "[Ending thread] Waiting 10 seconds for #{thread} to finish..." thread.join(10) @bot.loggers.debug "[Killing thread] Killing #{thread}" thread.kill end end end
[ "def", "stop", "@bot", ".", "loggers", ".", "debug", "\"[Stopping handler] Stopping all threads of handler #{self}: #{@thread_group.list.size} threads...\"", "@thread_group", ".", "list", ".", "each", "do", "|", "thread", "|", "Thread", ".", "new", "do", "@bot", ".", "loggers", ".", "debug", "\"[Ending thread] Waiting 10 seconds for #{thread} to finish...\"", "thread", ".", "join", "(", "10", ")", "@bot", ".", "loggers", ".", "debug", "\"[Killing thread] Killing #{thread}\"", "thread", ".", "kill", "end", "end", "end" ]
Stops execution of the handler. This means stopping and killing all associated threads. @return [void]
[ "Stops", "execution", "of", "the", "handler", ".", "This", "means", "stopping", "and", "killing", "all", "associated", "threads", "." ]
2e149ffcf94d0f4eb6c1566a8e39d7e6d8be4ee0
https://github.com/cinchrb/cinch/blob/2e149ffcf94d0f4eb6c1566a8e39d7e6d8be4ee0/lib/cinch/handler.rb#L71-L81
16,969
cinchrb/cinch
lib/cinch/handler.rb
Cinch.Handler.call
def call(message, captures, arguments) bargs = captures + arguments thread = Thread.new { @bot.loggers.debug "[New thread] For #{self}: #{Thread.current} -- #{@thread_group.list.size} in total." begin if @execute_in_callback @bot.callback.instance_exec(message, *@args, *bargs, &@block) else @block.call(message, *@args, *bargs) end rescue => e @bot.loggers.exception(e) ensure @bot.loggers.debug "[Thread done] For #{self}: #{Thread.current} -- #{@thread_group.list.size - 1} remaining." end } @thread_group.add(thread) thread end
ruby
def call(message, captures, arguments) bargs = captures + arguments thread = Thread.new { @bot.loggers.debug "[New thread] For #{self}: #{Thread.current} -- #{@thread_group.list.size} in total." begin if @execute_in_callback @bot.callback.instance_exec(message, *@args, *bargs, &@block) else @block.call(message, *@args, *bargs) end rescue => e @bot.loggers.exception(e) ensure @bot.loggers.debug "[Thread done] For #{self}: #{Thread.current} -- #{@thread_group.list.size - 1} remaining." end } @thread_group.add(thread) thread end
[ "def", "call", "(", "message", ",", "captures", ",", "arguments", ")", "bargs", "=", "captures", "+", "arguments", "thread", "=", "Thread", ".", "new", "{", "@bot", ".", "loggers", ".", "debug", "\"[New thread] For #{self}: #{Thread.current} -- #{@thread_group.list.size} in total.\"", "begin", "if", "@execute_in_callback", "@bot", ".", "callback", ".", "instance_exec", "(", "message", ",", "@args", ",", "bargs", ",", "@block", ")", "else", "@block", ".", "call", "(", "message", ",", "@args", ",", "bargs", ")", "end", "rescue", "=>", "e", "@bot", ".", "loggers", ".", "exception", "(", "e", ")", "ensure", "@bot", ".", "loggers", ".", "debug", "\"[Thread done] For #{self}: #{Thread.current} -- #{@thread_group.list.size - 1} remaining.\"", "end", "}", "@thread_group", ".", "add", "(", "thread", ")", "thread", "end" ]
Executes the handler. @param [Message] message Message that caused the invocation @param [Array] captures Capture groups of the pattern that are being passed as arguments @return [Thread]
[ "Executes", "the", "handler", "." ]
2e149ffcf94d0f4eb6c1566a8e39d7e6d8be4ee0
https://github.com/cinchrb/cinch/blob/2e149ffcf94d0f4eb6c1566a8e39d7e6d8be4ee0/lib/cinch/handler.rb#L89-L110
16,970
cinchrb/cinch
lib/cinch/syncable.rb
Cinch.Syncable.wait_until_synced
def wait_until_synced(attr) attr = attr.to_sym waited = 0 while true return if attribute_synced?(attr) waited += 1 if waited % 100 == 0 bot.loggers.warn "A synced attribute ('%s' for %s) has not been available for %d seconds, still waiting" % [attr, self.inspect, waited / 10] bot.loggers.warn caller.map {|s| " #{s}"} if waited / 10 >= 30 bot.loggers.warn " Giving up..." raise Exceptions::SyncedAttributeNotAvailable, "'%s' for %s" % [attr, self.inspect] end end sleep 0.1 end end
ruby
def wait_until_synced(attr) attr = attr.to_sym waited = 0 while true return if attribute_synced?(attr) waited += 1 if waited % 100 == 0 bot.loggers.warn "A synced attribute ('%s' for %s) has not been available for %d seconds, still waiting" % [attr, self.inspect, waited / 10] bot.loggers.warn caller.map {|s| " #{s}"} if waited / 10 >= 30 bot.loggers.warn " Giving up..." raise Exceptions::SyncedAttributeNotAvailable, "'%s' for %s" % [attr, self.inspect] end end sleep 0.1 end end
[ "def", "wait_until_synced", "(", "attr", ")", "attr", "=", "attr", ".", "to_sym", "waited", "=", "0", "while", "true", "return", "if", "attribute_synced?", "(", "attr", ")", "waited", "+=", "1", "if", "waited", "%", "100", "==", "0", "bot", ".", "loggers", ".", "warn", "\"A synced attribute ('%s' for %s) has not been available for %d seconds, still waiting\"", "%", "[", "attr", ",", "self", ".", "inspect", ",", "waited", "/", "10", "]", "bot", ".", "loggers", ".", "warn", "caller", ".", "map", "{", "|", "s", "|", "\" #{s}\"", "}", "if", "waited", "/", "10", ">=", "30", "bot", ".", "loggers", ".", "warn", "\" Giving up...\"", "raise", "Exceptions", "::", "SyncedAttributeNotAvailable", ",", "\"'%s' for %s\"", "%", "[", "attr", ",", "self", ".", "inspect", "]", "end", "end", "sleep", "0.1", "end", "end" ]
Blocks until the object is synced. @return [void] @api private
[ "Blocks", "until", "the", "object", "is", "synced", "." ]
2e149ffcf94d0f4eb6c1566a8e39d7e6d8be4ee0
https://github.com/cinchrb/cinch/blob/2e149ffcf94d0f4eb6c1566a8e39d7e6d8be4ee0/lib/cinch/syncable.rb#L8-L26
16,971
cinchrb/cinch
lib/cinch/configuration.rb
Cinch.Configuration.load
def load(new_config, from_default = false) if from_default @table = self.class.default_config end new_config.each do |option, value| if value.is_a?(Hash) if self[option].is_a?(Configuration) self[option].load(value) else # recursive merging is handled by subclasses like # Configuration::Plugins self[option] = value end else self[option] = value end end end
ruby
def load(new_config, from_default = false) if from_default @table = self.class.default_config end new_config.each do |option, value| if value.is_a?(Hash) if self[option].is_a?(Configuration) self[option].load(value) else # recursive merging is handled by subclasses like # Configuration::Plugins self[option] = value end else self[option] = value end end end
[ "def", "load", "(", "new_config", ",", "from_default", "=", "false", ")", "if", "from_default", "@table", "=", "self", ".", "class", ".", "default_config", "end", "new_config", ".", "each", "do", "|", "option", ",", "value", "|", "if", "value", ".", "is_a?", "(", "Hash", ")", "if", "self", "[", "option", "]", ".", "is_a?", "(", "Configuration", ")", "self", "[", "option", "]", ".", "load", "(", "value", ")", "else", "# recursive merging is handled by subclasses like", "# Configuration::Plugins", "self", "[", "option", "]", "=", "value", "end", "else", "self", "[", "option", "]", "=", "value", "end", "end", "end" ]
Loads a configuration from a hash by merging the hash with either the current configuration or the default configuration. @param [Hash] new_config The configuration to load @param [Boolean] from_default If true, the configuration won't be merged with the currently set up configuration (by prior calls to {#load} or {Bot#configure}) but with the default configuration. @return [void]
[ "Loads", "a", "configuration", "from", "a", "hash", "by", "merging", "the", "hash", "with", "either", "the", "current", "configuration", "or", "the", "default", "configuration", "." ]
2e149ffcf94d0f4eb6c1566a8e39d7e6d8be4ee0
https://github.com/cinchrb/cinch/blob/2e149ffcf94d0f4eb6c1566a8e39d7e6d8be4ee0/lib/cinch/configuration.rb#L44-L62
16,972
cinchrb/cinch
lib/cinch/user_list.rb
Cinch.UserList.find
def find(nick) if nick == @bot.nick return @bot end downcased_nick = nick.irc_downcase(@bot.irc.isupport["CASEMAPPING"]) @mutex.synchronize do return @cache[downcased_nick] end end
ruby
def find(nick) if nick == @bot.nick return @bot end downcased_nick = nick.irc_downcase(@bot.irc.isupport["CASEMAPPING"]) @mutex.synchronize do return @cache[downcased_nick] end end
[ "def", "find", "(", "nick", ")", "if", "nick", "==", "@bot", ".", "nick", "return", "@bot", "end", "downcased_nick", "=", "nick", ".", "irc_downcase", "(", "@bot", ".", "irc", ".", "isupport", "[", "\"CASEMAPPING\"", "]", ")", "@mutex", ".", "synchronize", "do", "return", "@cache", "[", "downcased_nick", "]", "end", "end" ]
Finds a user. @param [String] nick nick of a user @return [User, nil]
[ "Finds", "a", "user", "." ]
2e149ffcf94d0f4eb6c1566a8e39d7e6d8be4ee0
https://github.com/cinchrb/cinch/blob/2e149ffcf94d0f4eb6c1566a8e39d7e6d8be4ee0/lib/cinch/user_list.rb#L61-L70
16,973
cinchrb/cinch
lib/cinch/user.rb
Cinch.User.refresh
def refresh return if @in_whois @data.keys.each do |attr| unsync attr end @in_whois = true if @bot.irc.network.whois_only_one_argument? @bot.irc.send "WHOIS #@name" else @bot.irc.send "WHOIS #@name #@name" end end
ruby
def refresh return if @in_whois @data.keys.each do |attr| unsync attr end @in_whois = true if @bot.irc.network.whois_only_one_argument? @bot.irc.send "WHOIS #@name" else @bot.irc.send "WHOIS #@name #@name" end end
[ "def", "refresh", "return", "if", "@in_whois", "@data", ".", "keys", ".", "each", "do", "|", "attr", "|", "unsync", "attr", "end", "@in_whois", "=", "true", "if", "@bot", ".", "irc", ".", "network", ".", "whois_only_one_argument?", "@bot", ".", "irc", ".", "send", "\"WHOIS #@name\"", "else", "@bot", ".", "irc", ".", "send", "\"WHOIS #@name #@name\"", "end", "end" ]
Queries the IRC server for information on the user. This will set the User's state to not synced. After all information are received, the object will be set back to synced. @return [void] @note The alias `whois` is deprecated and will be removed in a future version.
[ "Queries", "the", "IRC", "server", "for", "information", "on", "the", "user", ".", "This", "will", "set", "the", "User", "s", "state", "to", "not", "synced", ".", "After", "all", "information", "are", "received", "the", "object", "will", "be", "set", "back", "to", "synced", "." ]
2e149ffcf94d0f4eb6c1566a8e39d7e6d8be4ee0
https://github.com/cinchrb/cinch/blob/2e149ffcf94d0f4eb6c1566a8e39d7e6d8be4ee0/lib/cinch/user.rb#L249-L261
16,974
cinchrb/cinch
lib/cinch/user.rb
Cinch.User.mask
def mask(s = "%n!%u@%h") s = s.gsub(/%(.)/) { case $1 when "n" @name when "u" self.user when "h" self.host when "r" self.realname when "a" self.authname end } Mask.new(s) end
ruby
def mask(s = "%n!%u@%h") s = s.gsub(/%(.)/) { case $1 when "n" @name when "u" self.user when "h" self.host when "r" self.realname when "a" self.authname end } Mask.new(s) end
[ "def", "mask", "(", "s", "=", "\"%n!%u@%h\"", ")", "s", "=", "s", ".", "gsub", "(", "/", "/", ")", "{", "case", "$1", "when", "\"n\"", "@name", "when", "\"u\"", "self", ".", "user", "when", "\"h\"", "self", ".", "host", "when", "\"r\"", "self", ".", "realname", "when", "\"a\"", "self", ".", "authname", "end", "}", "Mask", ".", "new", "(", "s", ")", "end" ]
Generates a mask for the user. @param [String] s a pattern for generating the mask. - %n = nickname - %u = username - %h = host - %r = realname - %a = authname @return [Mask]
[ "Generates", "a", "mask", "for", "the", "user", "." ]
2e149ffcf94d0f4eb6c1566a8e39d7e6d8be4ee0
https://github.com/cinchrb/cinch/blob/2e149ffcf94d0f4eb6c1566a8e39d7e6d8be4ee0/lib/cinch/user.rb#L353-L370
16,975
cinchrb/cinch
lib/cinch/user.rb
Cinch.User.monitor
def monitor if @bot.irc.isupport["MONITOR"] > 0 @bot.irc.send "MONITOR + #@name" else refresh @monitored_timer = Timer.new(@bot, interval: 30) { refresh } @monitored_timer.start end @monitored = true end
ruby
def monitor if @bot.irc.isupport["MONITOR"] > 0 @bot.irc.send "MONITOR + #@name" else refresh @monitored_timer = Timer.new(@bot, interval: 30) { refresh } @monitored_timer.start end @monitored = true end
[ "def", "monitor", "if", "@bot", ".", "irc", ".", "isupport", "[", "\"MONITOR\"", "]", ">", "0", "@bot", ".", "irc", ".", "send", "\"MONITOR + #@name\"", "else", "refresh", "@monitored_timer", "=", "Timer", ".", "new", "(", "@bot", ",", "interval", ":", "30", ")", "{", "refresh", "}", "@monitored_timer", ".", "start", "end", "@monitored", "=", "true", "end" ]
Starts monitoring a user's online state by either using MONITOR or periodically running WHOIS. @since 2.0.0 @return [void] @see #unmonitor
[ "Starts", "monitoring", "a", "user", "s", "online", "state", "by", "either", "using", "MONITOR", "or", "periodically", "running", "WHOIS", "." ]
2e149ffcf94d0f4eb6c1566a8e39d7e6d8be4ee0
https://github.com/cinchrb/cinch/blob/2e149ffcf94d0f4eb6c1566a8e39d7e6d8be4ee0/lib/cinch/user.rb#L387-L399
16,976
cinchrb/cinch
lib/cinch/user.rb
Cinch.User.online=
def online=(bool) notify = self.__send__("online?_unsynced") != bool && @monitored sync(:online?, bool, true) return unless notify if bool @bot.handlers.dispatch(:online, nil, self) else @bot.handlers.dispatch(:offline, nil, self) end end
ruby
def online=(bool) notify = self.__send__("online?_unsynced") != bool && @monitored sync(:online?, bool, true) return unless notify if bool @bot.handlers.dispatch(:online, nil, self) else @bot.handlers.dispatch(:offline, nil, self) end end
[ "def", "online", "=", "(", "bool", ")", "notify", "=", "self", ".", "__send__", "(", "\"online?_unsynced\"", ")", "!=", "bool", "&&", "@monitored", "sync", "(", ":online?", ",", "bool", ",", "true", ")", "return", "unless", "notify", "if", "bool", "@bot", ".", "handlers", ".", "dispatch", "(", ":online", ",", "nil", ",", "self", ")", "else", "@bot", ".", "handlers", ".", "dispatch", "(", ":offline", ",", "nil", ",", "self", ")", "end", "end" ]
Updates the user's online state and dispatch the correct event. @since 2.0.0 @return [void] @api private
[ "Updates", "the", "user", "s", "online", "state", "and", "dispatch", "the", "correct", "event", "." ]
2e149ffcf94d0f4eb6c1566a8e39d7e6d8be4ee0
https://github.com/cinchrb/cinch/blob/2e149ffcf94d0f4eb6c1566a8e39d7e6d8be4ee0/lib/cinch/user.rb#L462-L472
16,977
cinchrb/cinch
lib/cinch/irc.rb
Cinch.IRC.start
def start setup if connect @sasl_remaining_methods = @bot.config.sasl.mechanisms.reverse send_cap_ls send_login reading_thread = start_reading_thread sending_thread = start_sending_thread ping_thread = start_ping_thread reading_thread.join sending_thread.kill ping_thread.kill end end
ruby
def start setup if connect @sasl_remaining_methods = @bot.config.sasl.mechanisms.reverse send_cap_ls send_login reading_thread = start_reading_thread sending_thread = start_sending_thread ping_thread = start_ping_thread reading_thread.join sending_thread.kill ping_thread.kill end end
[ "def", "start", "setup", "if", "connect", "@sasl_remaining_methods", "=", "@bot", ".", "config", ".", "sasl", ".", "mechanisms", ".", "reverse", "send_cap_ls", "send_login", "reading_thread", "=", "start_reading_thread", "sending_thread", "=", "start_sending_thread", "ping_thread", "=", "start_ping_thread", "reading_thread", ".", "join", "sending_thread", ".", "kill", "ping_thread", ".", "kill", "end", "end" ]
Establish a connection. @return [void] @since 2.0.0
[ "Establish", "a", "connection", "." ]
2e149ffcf94d0f4eb6c1566a8e39d7e6d8be4ee0
https://github.com/cinchrb/cinch/blob/2e149ffcf94d0f4eb6c1566a8e39d7e6d8be4ee0/lib/cinch/irc.rb#L210-L225
16,978
cinchrb/cinch
lib/cinch/logger.rb
Cinch.Logger.log
def log(messages, event = :debug, level = event) return unless will_log?(level) @mutex.synchronize do Array(messages).each do |message| message = format_general(message) message = format_message(message, event) next if message.nil? @output.puts message.encode("locale", {:invalid => :replace, :undef => :replace}) end end end
ruby
def log(messages, event = :debug, level = event) return unless will_log?(level) @mutex.synchronize do Array(messages).each do |message| message = format_general(message) message = format_message(message, event) next if message.nil? @output.puts message.encode("locale", {:invalid => :replace, :undef => :replace}) end end end
[ "def", "log", "(", "messages", ",", "event", "=", ":debug", ",", "level", "=", "event", ")", "return", "unless", "will_log?", "(", "level", ")", "@mutex", ".", "synchronize", "do", "Array", "(", "messages", ")", ".", "each", "do", "|", "message", "|", "message", "=", "format_general", "(", "message", ")", "message", "=", "format_message", "(", "message", ",", "event", ")", "next", "if", "message", ".", "nil?", "@output", ".", "puts", "message", ".", "encode", "(", "\"locale\"", ",", "{", ":invalid", "=>", ":replace", ",", ":undef", "=>", ":replace", "}", ")", "end", "end", "end" ]
Logs a message. @param [String, Array] messages The message(s) to log @param [:debug, :incoming, :outgoing, :info, :warn, :exception, :error, :fatal] event The kind of event that triggered the message @param [:debug, :info, :warn, :error, :fatal] level The level of the message @return [void] @version 2.0.0
[ "Logs", "a", "message", "." ]
2e149ffcf94d0f4eb6c1566a8e39d7e6d8be4ee0
https://github.com/cinchrb/cinch/blob/2e149ffcf94d0f4eb6c1566a8e39d7e6d8be4ee0/lib/cinch/logger.rb#L110-L121
16,979
cinchrb/cinch
lib/cinch/channel_list.rb
Cinch.ChannelList.find_ensured
def find_ensured(name) downcased_name = name.irc_downcase(@bot.irc.isupport["CASEMAPPING"]) @mutex.synchronize do @cache[downcased_name] ||= Channel.new(name, @bot) end end
ruby
def find_ensured(name) downcased_name = name.irc_downcase(@bot.irc.isupport["CASEMAPPING"]) @mutex.synchronize do @cache[downcased_name] ||= Channel.new(name, @bot) end end
[ "def", "find_ensured", "(", "name", ")", "downcased_name", "=", "name", ".", "irc_downcase", "(", "@bot", ".", "irc", ".", "isupport", "[", "\"CASEMAPPING\"", "]", ")", "@mutex", ".", "synchronize", "do", "@cache", "[", "downcased_name", "]", "||=", "Channel", ".", "new", "(", "name", ",", "@bot", ")", "end", "end" ]
Finds or creates a channel. @param [String] name name of a channel @return [Channel] @see Helpers#Channel
[ "Finds", "or", "creates", "a", "channel", "." ]
2e149ffcf94d0f4eb6c1566a8e39d7e6d8be4ee0
https://github.com/cinchrb/cinch/blob/2e149ffcf94d0f4eb6c1566a8e39d7e6d8be4ee0/lib/cinch/channel_list.rb#L13-L18
16,980
cinchrb/cinch
lib/cinch/channel.rb
Cinch.Channel.topic=
def topic=(new_topic) if new_topic.size > @bot.irc.isupport["TOPICLEN"] && @bot.strict? raise Exceptions::TopicTooLong, new_topic end @bot.irc.send "TOPIC #@name :#{new_topic}" end
ruby
def topic=(new_topic) if new_topic.size > @bot.irc.isupport["TOPICLEN"] && @bot.strict? raise Exceptions::TopicTooLong, new_topic end @bot.irc.send "TOPIC #@name :#{new_topic}" end
[ "def", "topic", "=", "(", "new_topic", ")", "if", "new_topic", ".", "size", ">", "@bot", ".", "irc", ".", "isupport", "[", "\"TOPICLEN\"", "]", "&&", "@bot", ".", "strict?", "raise", "Exceptions", "::", "TopicTooLong", ",", "new_topic", "end", "@bot", ".", "irc", ".", "send", "\"TOPIC #@name :#{new_topic}\"", "end" ]
Sets the topic. @param [String] new_topic the new topic @raise [Exceptions::TopicTooLong] Raised if the bot is operating in {Bot#strict? strict mode} and when the new topic is too long.
[ "Sets", "the", "topic", "." ]
2e149ffcf94d0f4eb6c1566a8e39d7e6d8be4ee0
https://github.com/cinchrb/cinch/blob/2e149ffcf94d0f4eb6c1566a8e39d7e6d8be4ee0/lib/cinch/channel.rb#L316-L322
16,981
cinchrb/cinch
lib/cinch/channel.rb
Cinch.Channel.kick
def kick(user, reason = nil) if reason.to_s.size > @bot.irc.isupport["KICKLEN"] && @bot.strict? raise Exceptions::KickReasonTooLong, reason end @bot.irc.send("KICK #@name #{user} :#{reason}") end
ruby
def kick(user, reason = nil) if reason.to_s.size > @bot.irc.isupport["KICKLEN"] && @bot.strict? raise Exceptions::KickReasonTooLong, reason end @bot.irc.send("KICK #@name #{user} :#{reason}") end
[ "def", "kick", "(", "user", ",", "reason", "=", "nil", ")", "if", "reason", ".", "to_s", ".", "size", ">", "@bot", ".", "irc", ".", "isupport", "[", "\"KICKLEN\"", "]", "&&", "@bot", ".", "strict?", "raise", "Exceptions", "::", "KickReasonTooLong", ",", "reason", "end", "@bot", ".", "irc", ".", "send", "(", "\"KICK #@name #{user} :#{reason}\"", ")", "end" ]
Kicks a user from the channel. @param [String, User] user the user to kick @param [String] reason a reason for the kick @raise [Exceptions::KickReasonTooLong] @return [void]
[ "Kicks", "a", "user", "from", "the", "channel", "." ]
2e149ffcf94d0f4eb6c1566a8e39d7e6d8be4ee0
https://github.com/cinchrb/cinch/blob/2e149ffcf94d0f4eb6c1566a8e39d7e6d8be4ee0/lib/cinch/channel.rb#L330-L336
16,982
cinchrb/cinch
lib/cinch/channel.rb
Cinch.Channel.join
def join(key = nil) if key.nil? and self.key != true key = self.key end @bot.irc.send "JOIN #{[@name, key].compact.join(" ")}" end
ruby
def join(key = nil) if key.nil? and self.key != true key = self.key end @bot.irc.send "JOIN #{[@name, key].compact.join(" ")}" end
[ "def", "join", "(", "key", "=", "nil", ")", "if", "key", ".", "nil?", "and", "self", ".", "key", "!=", "true", "key", "=", "self", ".", "key", "end", "@bot", ".", "irc", ".", "send", "\"JOIN #{[@name, key].compact.join(\" \")}\"", "end" ]
Joins the channel @param [String] key the channel key, if any. If none is specified but @key is set, @key will be used @return [void]
[ "Joins", "the", "channel" ]
2e149ffcf94d0f4eb6c1566a8e39d7e6d8be4ee0
https://github.com/cinchrb/cinch/blob/2e149ffcf94d0f4eb6c1566a8e39d7e6d8be4ee0/lib/cinch/channel.rb#L377-L382
16,983
cinchrb/cinch
lib/cinch/target.rb
Cinch.Target.send
def send(text, notice = false) # TODO deprecate `notice` argument, put splitting into own # method text = text.to_s split_start = @bot.config.message_split_start || "" split_end = @bot.config.message_split_end || "" command = notice ? "NOTICE" : "PRIVMSG" prefix = ":#{@bot.mask} #{command} #{@name} :" text.lines.map(&:chomp).each do |line| splitted = split_message(line, prefix, split_start, split_end) splitted[0, (@bot.config.max_messages || splitted.size)].each do |string| @bot.irc.send("#{command} #@name :#{string}") end end end
ruby
def send(text, notice = false) # TODO deprecate `notice` argument, put splitting into own # method text = text.to_s split_start = @bot.config.message_split_start || "" split_end = @bot.config.message_split_end || "" command = notice ? "NOTICE" : "PRIVMSG" prefix = ":#{@bot.mask} #{command} #{@name} :" text.lines.map(&:chomp).each do |line| splitted = split_message(line, prefix, split_start, split_end) splitted[0, (@bot.config.max_messages || splitted.size)].each do |string| @bot.irc.send("#{command} #@name :#{string}") end end end
[ "def", "send", "(", "text", ",", "notice", "=", "false", ")", "# TODO deprecate `notice` argument, put splitting into own", "# method", "text", "=", "text", ".", "to_s", "split_start", "=", "@bot", ".", "config", ".", "message_split_start", "||", "\"\"", "split_end", "=", "@bot", ".", "config", ".", "message_split_end", "||", "\"\"", "command", "=", "notice", "?", "\"NOTICE\"", ":", "\"PRIVMSG\"", "prefix", "=", "\":#{@bot.mask} #{command} #{@name} :\"", "text", ".", "lines", ".", "map", "(", ":chomp", ")", ".", "each", "do", "|", "line", "|", "splitted", "=", "split_message", "(", "line", ",", "prefix", ",", "split_start", ",", "split_end", ")", "splitted", "[", "0", ",", "(", "@bot", ".", "config", ".", "max_messages", "||", "splitted", ".", "size", ")", "]", ".", "each", "do", "|", "string", "|", "@bot", ".", "irc", ".", "send", "(", "\"#{command} #@name :#{string}\"", ")", "end", "end", "end" ]
Sends a PRIVMSG to the target. @param [#to_s] text the message to send @param [Boolean] notice Use NOTICE instead of PRIVMSG? @return [void] @see #safe_msg @note The aliases `msg` and `privmsg` are deprecated and will be removed in a future version.
[ "Sends", "a", "PRIVMSG", "to", "the", "target", "." ]
2e149ffcf94d0f4eb6c1566a8e39d7e6d8be4ee0
https://github.com/cinchrb/cinch/blob/2e149ffcf94d0f4eb6c1566a8e39d7e6d8be4ee0/lib/cinch/target.rb#L32-L48
16,984
cinchrb/cinch
lib/cinch/bot.rb
Cinch.Bot.start
def start(plugins = true) @reconnects = 0 @plugins.register_plugins(@config.plugins.plugins) if plugins begin @user_list.each do |user| user.in_whois = false user.unsync_all end # reset state of all users @channel_list.each do |channel| channel.unsync_all end # reset state of all channels @channels = [] # reset list of channels the bot is in @join_handler.unregister if @join_handler @join_timer.stop if @join_timer join_lambda = lambda { @config.channels.each { |channel| Channel(channel).join }} if @config.delay_joins.is_a?(Symbol) @join_handler = join_handler = on(@config.delay_joins) { join_handler.unregister join_lambda.call } else @join_timer = Timer.new(self, interval: @config.delay_joins, shots: 1) { join_lambda.call } end @modes = [] @loggers.info "Connecting to #{@config.server}:#{@config.port}" @irc = IRC.new(self) @irc.start if @config.reconnect && !@quitting # double the delay for each unsuccesful reconnection attempt if @last_connection_was_successful @reconnects = 0 @last_connection_was_successful = false else @reconnects += 1 end # Throttle reconnect attempts wait = 2**@reconnects wait = @config.max_reconnect_delay if wait > @config.max_reconnect_delay @loggers.info "Waiting #{wait} seconds before reconnecting" start_time = Time.now while !@quitting && (Time.now - start_time) < wait sleep 1 end end end while @config.reconnect and not @quitting end
ruby
def start(plugins = true) @reconnects = 0 @plugins.register_plugins(@config.plugins.plugins) if plugins begin @user_list.each do |user| user.in_whois = false user.unsync_all end # reset state of all users @channel_list.each do |channel| channel.unsync_all end # reset state of all channels @channels = [] # reset list of channels the bot is in @join_handler.unregister if @join_handler @join_timer.stop if @join_timer join_lambda = lambda { @config.channels.each { |channel| Channel(channel).join }} if @config.delay_joins.is_a?(Symbol) @join_handler = join_handler = on(@config.delay_joins) { join_handler.unregister join_lambda.call } else @join_timer = Timer.new(self, interval: @config.delay_joins, shots: 1) { join_lambda.call } end @modes = [] @loggers.info "Connecting to #{@config.server}:#{@config.port}" @irc = IRC.new(self) @irc.start if @config.reconnect && !@quitting # double the delay for each unsuccesful reconnection attempt if @last_connection_was_successful @reconnects = 0 @last_connection_was_successful = false else @reconnects += 1 end # Throttle reconnect attempts wait = 2**@reconnects wait = @config.max_reconnect_delay if wait > @config.max_reconnect_delay @loggers.info "Waiting #{wait} seconds before reconnecting" start_time = Time.now while !@quitting && (Time.now - start_time) < wait sleep 1 end end end while @config.reconnect and not @quitting end
[ "def", "start", "(", "plugins", "=", "true", ")", "@reconnects", "=", "0", "@plugins", ".", "register_plugins", "(", "@config", ".", "plugins", ".", "plugins", ")", "if", "plugins", "begin", "@user_list", ".", "each", "do", "|", "user", "|", "user", ".", "in_whois", "=", "false", "user", ".", "unsync_all", "end", "# reset state of all users", "@channel_list", ".", "each", "do", "|", "channel", "|", "channel", ".", "unsync_all", "end", "# reset state of all channels", "@channels", "=", "[", "]", "# reset list of channels the bot is in", "@join_handler", ".", "unregister", "if", "@join_handler", "@join_timer", ".", "stop", "if", "@join_timer", "join_lambda", "=", "lambda", "{", "@config", ".", "channels", ".", "each", "{", "|", "channel", "|", "Channel", "(", "channel", ")", ".", "join", "}", "}", "if", "@config", ".", "delay_joins", ".", "is_a?", "(", "Symbol", ")", "@join_handler", "=", "join_handler", "=", "on", "(", "@config", ".", "delay_joins", ")", "{", "join_handler", ".", "unregister", "join_lambda", ".", "call", "}", "else", "@join_timer", "=", "Timer", ".", "new", "(", "self", ",", "interval", ":", "@config", ".", "delay_joins", ",", "shots", ":", "1", ")", "{", "join_lambda", ".", "call", "}", "end", "@modes", "=", "[", "]", "@loggers", ".", "info", "\"Connecting to #{@config.server}:#{@config.port}\"", "@irc", "=", "IRC", ".", "new", "(", "self", ")", "@irc", ".", "start", "if", "@config", ".", "reconnect", "&&", "!", "@quitting", "# double the delay for each unsuccesful reconnection attempt", "if", "@last_connection_was_successful", "@reconnects", "=", "0", "@last_connection_was_successful", "=", "false", "else", "@reconnects", "+=", "1", "end", "# Throttle reconnect attempts", "wait", "=", "2", "**", "@reconnects", "wait", "=", "@config", ".", "max_reconnect_delay", "if", "wait", ">", "@config", ".", "max_reconnect_delay", "@loggers", ".", "info", "\"Waiting #{wait} seconds before reconnecting\"", "start_time", "=", "Time", ".", "now", "while", "!", "@quitting", "&&", "(", "Time", ".", "now", "-", "start_time", ")", "<", "wait", "sleep", "1", "end", "end", "end", "while", "@config", ".", "reconnect", "and", "not", "@quitting", "end" ]
Connects the bot to a server. @param [Boolean] plugins Automatically register plugins from `@config.plugins.plugins`? @return [void]
[ "Connects", "the", "bot", "to", "a", "server", "." ]
2e149ffcf94d0f4eb6c1566a8e39d7e6d8be4ee0
https://github.com/cinchrb/cinch/blob/2e149ffcf94d0f4eb6c1566a8e39d7e6d8be4ee0/lib/cinch/bot.rb#L237-L294
16,985
cinchrb/cinch
lib/cinch/bot.rb
Cinch.Bot.part
def part(channel, reason = nil) channel = Channel(channel) channel.part(reason) channel end
ruby
def part(channel, reason = nil) channel = Channel(channel) channel.part(reason) channel end
[ "def", "part", "(", "channel", ",", "reason", "=", "nil", ")", "channel", "=", "Channel", "(", "channel", ")", "channel", ".", "part", "(", "reason", ")", "channel", "end" ]
Part a channel. @param [String, Channel] channel either the name of a channel or a {Channel} object @param [String] reason an optional reason/part message @return [Channel] The channel that was left @see Channel#part
[ "Part", "a", "channel", "." ]
2e149ffcf94d0f4eb6c1566a8e39d7e6d8be4ee0
https://github.com/cinchrb/cinch/blob/2e149ffcf94d0f4eb6c1566a8e39d7e6d8be4ee0/lib/cinch/bot.rb#L318-L323
16,986
cinchrb/cinch
lib/cinch/bot.rb
Cinch.Bot.generate_next_nick!
def generate_next_nick!(base = nil) nicks = @config.nicks || [] if base # if `base` is not in our list of nicks to try, assume that it's # custom and just append an underscore if !nicks.include?(base) new_nick = base + "_" else # if we have a base, try the next nick or append an # underscore if no more nicks are left new_index = nicks.index(base) + 1 if nicks[new_index] new_nick = nicks[new_index] else new_nick = base + "_" end end else # if we have no base, try the first possible nick new_nick = @config.nicks ? @config.nicks.first : @config.nick end @config.nick = new_nick end
ruby
def generate_next_nick!(base = nil) nicks = @config.nicks || [] if base # if `base` is not in our list of nicks to try, assume that it's # custom and just append an underscore if !nicks.include?(base) new_nick = base + "_" else # if we have a base, try the next nick or append an # underscore if no more nicks are left new_index = nicks.index(base) + 1 if nicks[new_index] new_nick = nicks[new_index] else new_nick = base + "_" end end else # if we have no base, try the first possible nick new_nick = @config.nicks ? @config.nicks.first : @config.nick end @config.nick = new_nick end
[ "def", "generate_next_nick!", "(", "base", "=", "nil", ")", "nicks", "=", "@config", ".", "nicks", "||", "[", "]", "if", "base", "# if `base` is not in our list of nicks to try, assume that it's", "# custom and just append an underscore", "if", "!", "nicks", ".", "include?", "(", "base", ")", "new_nick", "=", "base", "+", "\"_\"", "else", "# if we have a base, try the next nick or append an", "# underscore if no more nicks are left", "new_index", "=", "nicks", ".", "index", "(", "base", ")", "+", "1", "if", "nicks", "[", "new_index", "]", "new_nick", "=", "nicks", "[", "new_index", "]", "else", "new_nick", "=", "base", "+", "\"_\"", "end", "end", "else", "# if we have no base, try the first possible nick", "new_nick", "=", "@config", ".", "nicks", "?", "@config", ".", "nicks", ".", "first", ":", "@config", ".", "nick", "end", "@config", ".", "nick", "=", "new_nick", "end" ]
Try to create a free nick, first by cycling through all available alternatives and then by appending underscores. @param [String] base The base nick to start trying from @api private @return [String] @since 2.0.0
[ "Try", "to", "create", "a", "free", "nick", "first", "by", "cycling", "through", "all", "available", "alternatives", "and", "then", "by", "appending", "underscores", "." ]
2e149ffcf94d0f4eb6c1566a8e39d7e6d8be4ee0
https://github.com/cinchrb/cinch/blob/2e149ffcf94d0f4eb6c1566a8e39d7e6d8be4ee0/lib/cinch/bot.rb#L448-L472
16,987
cookpad/garage
lib/garage/representer.rb
Garage::Representer.ClassMethods.metadata
def metadata {:definitions => representer_attrs.grep(Definition).map {|definition| definition.name}, :links => representer_attrs.grep(Link).map {|link| link.options[:as] ? {link.rel => {'as' => link.options[:as]}} : link.rel} } end
ruby
def metadata {:definitions => representer_attrs.grep(Definition).map {|definition| definition.name}, :links => representer_attrs.grep(Link).map {|link| link.options[:as] ? {link.rel => {'as' => link.options[:as]}} : link.rel} } end
[ "def", "metadata", "{", ":definitions", "=>", "representer_attrs", ".", "grep", "(", "Definition", ")", ".", "map", "{", "|", "definition", "|", "definition", ".", "name", "}", ",", ":links", "=>", "representer_attrs", ".", "grep", "(", "Link", ")", ".", "map", "{", "|", "link", "|", "link", ".", "options", "[", ":as", "]", "?", "{", "link", ".", "rel", "=>", "{", "'as'", "=>", "link", ".", "options", "[", ":as", "]", "}", "}", ":", "link", ".", "rel", "}", "}", "end" ]
represents the representer's schema in JSON format
[ "represents", "the", "representer", "s", "schema", "in", "JSON", "format" ]
97444551c75709f132746b3e18183e0cd0ca1a20
https://github.com/cookpad/garage/blob/97444551c75709f132746b3e18183e0cd0ca1a20/lib/garage/representer.rb#L113-L117
16,988
cookpad/garage
lib/garage/controller_helper.rb
Garage.ControllerHelper.requested_by?
def requested_by?(resource) user = resource.respond_to?(:owner) ? resource.owner : resource case when current_resource_owner.nil? false when !user.is_a?(current_resource_owner.class) false when current_resource_owner.id == user.id true else false end end
ruby
def requested_by?(resource) user = resource.respond_to?(:owner) ? resource.owner : resource case when current_resource_owner.nil? false when !user.is_a?(current_resource_owner.class) false when current_resource_owner.id == user.id true else false end end
[ "def", "requested_by?", "(", "resource", ")", "user", "=", "resource", ".", "respond_to?", "(", ":owner", ")", "?", "resource", ".", "owner", ":", "resource", "case", "when", "current_resource_owner", ".", "nil?", "false", "when", "!", "user", ".", "is_a?", "(", "current_resource_owner", ".", "class", ")", "false", "when", "current_resource_owner", ".", "id", "==", "user", ".", "id", "true", "else", "false", "end", "end" ]
Check if the current resource is the same as the requester. The resource must respond to `resource.id` method.
[ "Check", "if", "the", "current", "resource", "is", "the", "same", "as", "the", "requester", ".", "The", "resource", "must", "respond", "to", "resource", ".", "id", "method", "." ]
97444551c75709f132746b3e18183e0cd0ca1a20
https://github.com/cookpad/garage/blob/97444551c75709f132746b3e18183e0cd0ca1a20/lib/garage/controller_helper.rb#L53-L65
16,989
piotrmurach/loaf
lib/loaf/options_validator.rb
Loaf.OptionsValidator.valid?
def valid?(options) valid_options = Loaf::Configuration::VALID_ATTRIBUTES options.each_key do |key| unless valid_options.include?(key) fail Loaf::InvalidOptions.new(key, valid_options) end end true end
ruby
def valid?(options) valid_options = Loaf::Configuration::VALID_ATTRIBUTES options.each_key do |key| unless valid_options.include?(key) fail Loaf::InvalidOptions.new(key, valid_options) end end true end
[ "def", "valid?", "(", "options", ")", "valid_options", "=", "Loaf", "::", "Configuration", "::", "VALID_ATTRIBUTES", "options", ".", "each_key", "do", "|", "key", "|", "unless", "valid_options", ".", "include?", "(", "key", ")", "fail", "Loaf", "::", "InvalidOptions", ".", "new", "(", "key", ",", "valid_options", ")", "end", "end", "true", "end" ]
Check if options are valid or not @param [Hash] options @return [Boolean] @api public
[ "Check", "if", "options", "are", "valid", "or", "not" ]
001dfad8361690051be76afdea11691b2aca8f14
https://github.com/piotrmurach/loaf/blob/001dfad8361690051be76afdea11691b2aca8f14/lib/loaf/options_validator.rb#L15-L23
16,990
piotrmurach/loaf
lib/loaf/configuration.rb
Loaf.Configuration.to_hash
def to_hash VALID_ATTRIBUTES.reduce({}) { |acc, k| acc[k] = send(k); acc } end
ruby
def to_hash VALID_ATTRIBUTES.reduce({}) { |acc, k| acc[k] = send(k); acc } end
[ "def", "to_hash", "VALID_ATTRIBUTES", ".", "reduce", "(", "{", "}", ")", "{", "|", "acc", ",", "k", "|", "acc", "[", "k", "]", "=", "send", "(", "k", ")", ";", "acc", "}", "end" ]
Setup this configuration @api public Convert all properties into hash @return [Hash] @api public
[ "Setup", "this", "configuration" ]
001dfad8361690051be76afdea11691b2aca8f14
https://github.com/piotrmurach/loaf/blob/001dfad8361690051be76afdea11691b2aca8f14/lib/loaf/configuration.rb#L32-L34
16,991
piotrmurach/loaf
lib/loaf/view_extensions.rb
Loaf.ViewExtensions.breadcrumb
def breadcrumb(name, url, options = {}) _breadcrumbs << Loaf::Crumb.new(name, url, options) end
ruby
def breadcrumb(name, url, options = {}) _breadcrumbs << Loaf::Crumb.new(name, url, options) end
[ "def", "breadcrumb", "(", "name", ",", "url", ",", "options", "=", "{", "}", ")", "_breadcrumbs", "<<", "Loaf", "::", "Crumb", ".", "new", "(", "name", ",", "url", ",", "options", ")", "end" ]
Adds breadcrumbs inside view. @param [String] name the breadcrumb name @param [Object] url the breadcrumb url @param [Hash] options the breadcrumb options @api public
[ "Adds", "breadcrumbs", "inside", "view", "." ]
001dfad8361690051be76afdea11691b2aca8f14
https://github.com/piotrmurach/loaf/blob/001dfad8361690051be76afdea11691b2aca8f14/lib/loaf/view_extensions.rb#L37-L39
16,992
piotrmurach/loaf
lib/loaf/view_extensions.rb
Loaf.ViewExtensions.breadcrumb_trail
def breadcrumb_trail(options = {}) return enum_for(:breadcrumb_trail) unless block_given? valid?(options) options = Loaf.configuration.to_hash.merge(options) _breadcrumbs.each do |crumb| name = title_for(crumb.name) path = url_for(_expand_url(crumb.url)) current = current_crumb?(path, crumb.match) yield(Loaf::Breadcrumb[name, path, current]) end end
ruby
def breadcrumb_trail(options = {}) return enum_for(:breadcrumb_trail) unless block_given? valid?(options) options = Loaf.configuration.to_hash.merge(options) _breadcrumbs.each do |crumb| name = title_for(crumb.name) path = url_for(_expand_url(crumb.url)) current = current_crumb?(path, crumb.match) yield(Loaf::Breadcrumb[name, path, current]) end end
[ "def", "breadcrumb_trail", "(", "options", "=", "{", "}", ")", "return", "enum_for", "(", ":breadcrumb_trail", ")", "unless", "block_given?", "valid?", "(", "options", ")", "options", "=", "Loaf", ".", "configuration", ".", "to_hash", ".", "merge", "(", "options", ")", "_breadcrumbs", ".", "each", "do", "|", "crumb", "|", "name", "=", "title_for", "(", "crumb", ".", "name", ")", "path", "=", "url_for", "(", "_expand_url", "(", "crumb", ".", "url", ")", ")", "current", "=", "current_crumb?", "(", "path", ",", "crumb", ".", "match", ")", "yield", "(", "Loaf", "::", "Breadcrumb", "[", "name", ",", "path", ",", "current", "]", ")", "end", "end" ]
Renders breadcrumbs inside view. @param [Hash] options @api public
[ "Renders", "breadcrumbs", "inside", "view", "." ]
001dfad8361690051be76afdea11691b2aca8f14
https://github.com/piotrmurach/loaf/blob/001dfad8361690051be76afdea11691b2aca8f14/lib/loaf/view_extensions.rb#L47-L59
16,993
piotrmurach/loaf
lib/loaf/view_extensions.rb
Loaf.ViewExtensions._expand_url
def _expand_url(url) case url when String, Symbol respond_to?(url) ? send(url) : url when Proc url.call(self) else url end end
ruby
def _expand_url(url) case url when String, Symbol respond_to?(url) ? send(url) : url when Proc url.call(self) else url end end
[ "def", "_expand_url", "(", "url", ")", "case", "url", "when", "String", ",", "Symbol", "respond_to?", "(", "url", ")", "?", "send", "(", "url", ")", ":", "url", "when", "Proc", "url", ".", "call", "(", "self", ")", "else", "url", "end", "end" ]
Expand url in the current context of the view @api private
[ "Expand", "url", "in", "the", "current", "context", "of", "the", "view" ]
001dfad8361690051be76afdea11691b2aca8f14
https://github.com/piotrmurach/loaf/blob/001dfad8361690051be76afdea11691b2aca8f14/lib/loaf/view_extensions.rb#L121-L130
16,994
piotrmurach/loaf
lib/loaf/translation.rb
Loaf.Translation.find_title
def find_title(title, options = {}) return title if title.nil? || title.empty? options[:scope] ||= translation_scope options[:default] = Array(options[:default]) options[:default] << title if options[:default].empty? I18n.t(title.to_s, options) end
ruby
def find_title(title, options = {}) return title if title.nil? || title.empty? options[:scope] ||= translation_scope options[:default] = Array(options[:default]) options[:default] << title if options[:default].empty? I18n.t(title.to_s, options) end
[ "def", "find_title", "(", "title", ",", "options", "=", "{", "}", ")", "return", "title", "if", "title", ".", "nil?", "||", "title", ".", "empty?", "options", "[", ":scope", "]", "||=", "translation_scope", "options", "[", ":default", "]", "=", "Array", "(", "options", "[", ":default", "]", ")", "options", "[", ":default", "]", "<<", "title", "if", "options", "[", ":default", "]", ".", "empty?", "I18n", ".", "t", "(", "title", ".", "to_s", ",", "options", ")", "end" ]
Translate breadcrumb title @param [String] :title @param [Hash] options @option options [String] :scope The translation scope @option options [String] :default The default translation @return [String] @api public
[ "Translate", "breadcrumb", "title" ]
001dfad8361690051be76afdea11691b2aca8f14
https://github.com/piotrmurach/loaf/blob/001dfad8361690051be76afdea11691b2aca8f14/lib/loaf/translation.rb#L27-L34
16,995
puppetlabs/beaker-hostgenerator
lib/beaker-hostgenerator/parser.rb
BeakerHostGenerator.Parser.tokenize_layout
def tokenize_layout(layout_spec) # Here we allow dashes in certain parts of the spec string # i.e. "centos6-64m{hostname=foo-bar}-debian8-32" # by first replacing all occurrences of - with | that exist within # the braces {...}. # # So we'd end up with: # "centos6-64m{hostname=foo|bar}-debian8-32" # # Which we can then simply split on - into: # ["centos6", "64m{hostname=foo|bar}", "debian8", "32"] # # And then finally turn the | back into - now that we've # properly decomposed the spec string: # ["centos6", "64m{hostname=foo-bar}", "debian8", "32"] # # NOTE we've specifically chosen to use the pipe character | # due to its unlikely occurrence in the user input string. spec = String.new(layout_spec) # Copy so we can replace characters inline within_braces = false spec.chars.each_with_index do |char, index| case char when '{' within_braces = true when '}' within_braces = false when '-' spec[index] = '|' if within_braces end end tokens = spec.split('-') tokens.map { |t| t.gsub('|', '-') } end
ruby
def tokenize_layout(layout_spec) # Here we allow dashes in certain parts of the spec string # i.e. "centos6-64m{hostname=foo-bar}-debian8-32" # by first replacing all occurrences of - with | that exist within # the braces {...}. # # So we'd end up with: # "centos6-64m{hostname=foo|bar}-debian8-32" # # Which we can then simply split on - into: # ["centos6", "64m{hostname=foo|bar}", "debian8", "32"] # # And then finally turn the | back into - now that we've # properly decomposed the spec string: # ["centos6", "64m{hostname=foo-bar}", "debian8", "32"] # # NOTE we've specifically chosen to use the pipe character | # due to its unlikely occurrence in the user input string. spec = String.new(layout_spec) # Copy so we can replace characters inline within_braces = false spec.chars.each_with_index do |char, index| case char when '{' within_braces = true when '}' within_braces = false when '-' spec[index] = '|' if within_braces end end tokens = spec.split('-') tokens.map { |t| t.gsub('|', '-') } end
[ "def", "tokenize_layout", "(", "layout_spec", ")", "# Here we allow dashes in certain parts of the spec string", "# i.e. \"centos6-64m{hostname=foo-bar}-debian8-32\"", "# by first replacing all occurrences of - with | that exist within", "# the braces {...}.", "#", "# So we'd end up with:", "# \"centos6-64m{hostname=foo|bar}-debian8-32\"", "#", "# Which we can then simply split on - into:", "# [\"centos6\", \"64m{hostname=foo|bar}\", \"debian8\", \"32\"]", "#", "# And then finally turn the | back into - now that we've", "# properly decomposed the spec string:", "# [\"centos6\", \"64m{hostname=foo-bar}\", \"debian8\", \"32\"]", "#", "# NOTE we've specifically chosen to use the pipe character |", "# due to its unlikely occurrence in the user input string.", "spec", "=", "String", ".", "new", "(", "layout_spec", ")", "# Copy so we can replace characters inline", "within_braces", "=", "false", "spec", ".", "chars", ".", "each_with_index", "do", "|", "char", ",", "index", "|", "case", "char", "when", "'{'", "within_braces", "=", "true", "when", "'}'", "within_braces", "=", "false", "when", "'-'", "spec", "[", "index", "]", "=", "'|'", "if", "within_braces", "end", "end", "tokens", "=", "spec", ".", "split", "(", "'-'", ")", "tokens", ".", "map", "{", "|", "t", "|", "t", ".", "gsub", "(", "'|'", ",", "'-'", ")", "}", "end" ]
Breaks apart the host input string into chunks suitable for processing by the generator. Returns an array of substrings of the input spec string. The input string is expected to be properly formatted using the dash `-` character as a delimiter. Dashes may also be used within braces `{...}`, which are used to define arbitrary key-values on a node. @param spec [String] Well-formatted string specification of the hosts to generate. For example `"centos6-64m-debian8-32a"`. @returns [Array<String>] Input string split into substrings suitable for processing by the generator. For example `["centos6", "64m", "debian8", "32a"]`.
[ "Breaks", "apart", "the", "host", "input", "string", "into", "chunks", "suitable", "for", "processing", "by", "the", "generator", ".", "Returns", "an", "array", "of", "substrings", "of", "the", "input", "spec", "string", "." ]
276830215efedf00f133ddedc8b636c25d7510c4
https://github.com/puppetlabs/beaker-hostgenerator/blob/276830215efedf00f133ddedc8b636c25d7510c4/lib/beaker-hostgenerator/parser.rb#L93-L125
16,996
puppetlabs/beaker-hostgenerator
lib/beaker-hostgenerator/parser.rb
BeakerHostGenerator.Parser.settings_string_to_map
def settings_string_to_map(host_settings) stringscan = StringScanner.new(host_settings) object = nil object_depth = [] current_depth = 0 # This loop scans until the next delimiter character is found. When # the next delimiter is recognized, there is enough context in the # substring to determine a course of action to modify the primary # object. The `object_depth` object tracks which current object is # being modified, and pops it off the end of the array when that # data structure is completed. # # This algorithm would also support a base array, but since there # is no need for that functionality, we just assume the string is # always a representation of a hash. loop do blob = stringscan.scan_until(/\[|{|}|\]|,/) break if blob.nil? if stringscan.pos() == 1 object = {} object_depth.push(object) next end current_type = object_depth[current_depth].class current_object = object_depth[current_depth] if blob == '[' current_object.push([]) object_depth.push(current_object.last) current_depth = current_depth.next next end if blob.start_with?('{') current_object.push({}) object_depth.push(current_object.last) current_depth = current_depth.next next end if blob == ']' or blob == '}' object_depth.pop current_depth = current_depth.pred next end # When there is assignment happening, we need to create a new # corresponding data structure, add it to the object depth, and # then change the current depth if blob[-2] == '=' raise Beaker::HostGenerator::Exceptions::InvalidNodeSpecError unless blob.end_with?('{','[') if blob[-1] == '{' current_object[blob[0..-3]] = {} else current_object[blob[0..-3]] = [] end object_depth.push(current_object[blob[0..-3]]) current_depth = current_depth.next next end if blob[-1] == '}' raise Beaker::HostGenerator::Exceptions::InvalidNodeSpecError if blob.count('=') != 1 key_pair = blob[0..-2].split('=') raise Beaker::HostGenerator::Exceptions::InvalidNodeSpecError if key_pair.size != 2 key_pair.each do |element| raise Beaker::HostGenerator::Exceptions::InvalidNodeSpecError if element.empty? end current_object[key_pair[0]] = key_pair[1] object_depth.pop current_depth = current_depth.pred next end if blob == ',' next end if blob[-1] == ',' if current_type == Hash key_pair = blob[0..-2].split('=') raise Beaker::HostGenerator::Exceptions::InvalidNodeSpecError if key_pair.size != 2 key_pair.each do |element| raise Beaker::HostGenerator::Exceptions::InvalidNodeSpecError if element.empty? end current_object[key_pair[0]] = key_pair[1] next elsif current_type == Array current_object.push(blob[0..-2]) next end end if blob[-1] == ']' current_object.push(blob[0..-2]) object_depth.pop current_depth = current_depth.pred next end end object rescue Exception => e raise BeakerHostGenerator::Exceptions::InvalidNodeSpecError, "Malformed host settings: #{host_settings}" end
ruby
def settings_string_to_map(host_settings) stringscan = StringScanner.new(host_settings) object = nil object_depth = [] current_depth = 0 # This loop scans until the next delimiter character is found. When # the next delimiter is recognized, there is enough context in the # substring to determine a course of action to modify the primary # object. The `object_depth` object tracks which current object is # being modified, and pops it off the end of the array when that # data structure is completed. # # This algorithm would also support a base array, but since there # is no need for that functionality, we just assume the string is # always a representation of a hash. loop do blob = stringscan.scan_until(/\[|{|}|\]|,/) break if blob.nil? if stringscan.pos() == 1 object = {} object_depth.push(object) next end current_type = object_depth[current_depth].class current_object = object_depth[current_depth] if blob == '[' current_object.push([]) object_depth.push(current_object.last) current_depth = current_depth.next next end if blob.start_with?('{') current_object.push({}) object_depth.push(current_object.last) current_depth = current_depth.next next end if blob == ']' or blob == '}' object_depth.pop current_depth = current_depth.pred next end # When there is assignment happening, we need to create a new # corresponding data structure, add it to the object depth, and # then change the current depth if blob[-2] == '=' raise Beaker::HostGenerator::Exceptions::InvalidNodeSpecError unless blob.end_with?('{','[') if blob[-1] == '{' current_object[blob[0..-3]] = {} else current_object[blob[0..-3]] = [] end object_depth.push(current_object[blob[0..-3]]) current_depth = current_depth.next next end if blob[-1] == '}' raise Beaker::HostGenerator::Exceptions::InvalidNodeSpecError if blob.count('=') != 1 key_pair = blob[0..-2].split('=') raise Beaker::HostGenerator::Exceptions::InvalidNodeSpecError if key_pair.size != 2 key_pair.each do |element| raise Beaker::HostGenerator::Exceptions::InvalidNodeSpecError if element.empty? end current_object[key_pair[0]] = key_pair[1] object_depth.pop current_depth = current_depth.pred next end if blob == ',' next end if blob[-1] == ',' if current_type == Hash key_pair = blob[0..-2].split('=') raise Beaker::HostGenerator::Exceptions::InvalidNodeSpecError if key_pair.size != 2 key_pair.each do |element| raise Beaker::HostGenerator::Exceptions::InvalidNodeSpecError if element.empty? end current_object[key_pair[0]] = key_pair[1] next elsif current_type == Array current_object.push(blob[0..-2]) next end end if blob[-1] == ']' current_object.push(blob[0..-2]) object_depth.pop current_depth = current_depth.pred next end end object rescue Exception => e raise BeakerHostGenerator::Exceptions::InvalidNodeSpecError, "Malformed host settings: #{host_settings}" end
[ "def", "settings_string_to_map", "(", "host_settings", ")", "stringscan", "=", "StringScanner", ".", "new", "(", "host_settings", ")", "object", "=", "nil", "object_depth", "=", "[", "]", "current_depth", "=", "0", "# This loop scans until the next delimiter character is found. When", "# the next delimiter is recognized, there is enough context in the", "# substring to determine a course of action to modify the primary", "# object. The `object_depth` object tracks which current object is", "# being modified, and pops it off the end of the array when that", "# data structure is completed.", "#", "# This algorithm would also support a base array, but since there", "# is no need for that functionality, we just assume the string is", "# always a representation of a hash.", "loop", "do", "blob", "=", "stringscan", ".", "scan_until", "(", "/", "\\[", "\\]", "/", ")", "break", "if", "blob", ".", "nil?", "if", "stringscan", ".", "pos", "(", ")", "==", "1", "object", "=", "{", "}", "object_depth", ".", "push", "(", "object", ")", "next", "end", "current_type", "=", "object_depth", "[", "current_depth", "]", ".", "class", "current_object", "=", "object_depth", "[", "current_depth", "]", "if", "blob", "==", "'['", "current_object", ".", "push", "(", "[", "]", ")", "object_depth", ".", "push", "(", "current_object", ".", "last", ")", "current_depth", "=", "current_depth", ".", "next", "next", "end", "if", "blob", ".", "start_with?", "(", "'{'", ")", "current_object", ".", "push", "(", "{", "}", ")", "object_depth", ".", "push", "(", "current_object", ".", "last", ")", "current_depth", "=", "current_depth", ".", "next", "next", "end", "if", "blob", "==", "']'", "or", "blob", "==", "'}'", "object_depth", ".", "pop", "current_depth", "=", "current_depth", ".", "pred", "next", "end", "# When there is assignment happening, we need to create a new", "# corresponding data structure, add it to the object depth, and", "# then change the current depth", "if", "blob", "[", "-", "2", "]", "==", "'='", "raise", "Beaker", "::", "HostGenerator", "::", "Exceptions", "::", "InvalidNodeSpecError", "unless", "blob", ".", "end_with?", "(", "'{'", ",", "'['", ")", "if", "blob", "[", "-", "1", "]", "==", "'{'", "current_object", "[", "blob", "[", "0", "..", "-", "3", "]", "]", "=", "{", "}", "else", "current_object", "[", "blob", "[", "0", "..", "-", "3", "]", "]", "=", "[", "]", "end", "object_depth", ".", "push", "(", "current_object", "[", "blob", "[", "0", "..", "-", "3", "]", "]", ")", "current_depth", "=", "current_depth", ".", "next", "next", "end", "if", "blob", "[", "-", "1", "]", "==", "'}'", "raise", "Beaker", "::", "HostGenerator", "::", "Exceptions", "::", "InvalidNodeSpecError", "if", "blob", ".", "count", "(", "'='", ")", "!=", "1", "key_pair", "=", "blob", "[", "0", "..", "-", "2", "]", ".", "split", "(", "'='", ")", "raise", "Beaker", "::", "HostGenerator", "::", "Exceptions", "::", "InvalidNodeSpecError", "if", "key_pair", ".", "size", "!=", "2", "key_pair", ".", "each", "do", "|", "element", "|", "raise", "Beaker", "::", "HostGenerator", "::", "Exceptions", "::", "InvalidNodeSpecError", "if", "element", ".", "empty?", "end", "current_object", "[", "key_pair", "[", "0", "]", "]", "=", "key_pair", "[", "1", "]", "object_depth", ".", "pop", "current_depth", "=", "current_depth", ".", "pred", "next", "end", "if", "blob", "==", "','", "next", "end", "if", "blob", "[", "-", "1", "]", "==", "','", "if", "current_type", "==", "Hash", "key_pair", "=", "blob", "[", "0", "..", "-", "2", "]", ".", "split", "(", "'='", ")", "raise", "Beaker", "::", "HostGenerator", "::", "Exceptions", "::", "InvalidNodeSpecError", "if", "key_pair", ".", "size", "!=", "2", "key_pair", ".", "each", "do", "|", "element", "|", "raise", "Beaker", "::", "HostGenerator", "::", "Exceptions", "::", "InvalidNodeSpecError", "if", "element", ".", "empty?", "end", "current_object", "[", "key_pair", "[", "0", "]", "]", "=", "key_pair", "[", "1", "]", "next", "elsif", "current_type", "==", "Array", "current_object", ".", "push", "(", "blob", "[", "0", "..", "-", "2", "]", ")", "next", "end", "end", "if", "blob", "[", "-", "1", "]", "==", "']'", "current_object", ".", "push", "(", "blob", "[", "0", "..", "-", "2", "]", ")", "object_depth", ".", "pop", "current_depth", "=", "current_depth", ".", "pred", "next", "end", "end", "object", "rescue", "Exception", "=>", "e", "raise", "BeakerHostGenerator", "::", "Exceptions", "::", "InvalidNodeSpecError", ",", "\"Malformed host settings: #{host_settings}\"", "end" ]
Transforms the arbitrary host settings map from a string representation to a proper hash map data structure for merging into the host configuration. Supports arbitrary nested hashes and arrays. The string is expected to be of the form "{key1=value1,key2=[v2,v3],...}". Nesting looks like "{key1={nested_key=nested_value},list=[[list1, list2]]}". Whitespace is expected to be properly quoted as it will not be treated any different than non-whitespace characters. Throws an exception of the string is malformed in any way. @param host_settings [String] Non-nil user input string that defines host specific settings. @returns [Hash{String=>String|Array|Hash}] The host_settings string as a map.
[ "Transforms", "the", "arbitrary", "host", "settings", "map", "from", "a", "string", "representation", "to", "a", "proper", "hash", "map", "data", "structure", "for", "merging", "into", "the", "host", "configuration", ".", "Supports", "arbitrary", "nested", "hashes", "and", "arrays", "." ]
276830215efedf00f133ddedc8b636c25d7510c4
https://github.com/puppetlabs/beaker-hostgenerator/blob/276830215efedf00f133ddedc8b636c25d7510c4/lib/beaker-hostgenerator/parser.rb#L211-L323
16,997
puppetlabs/beaker-hostgenerator
lib/beaker-hostgenerator/data.rb
BeakerHostGenerator.Data.get_platform_info
def get_platform_info(bhg_version, platform, hypervisor) info = get_osinfo(bhg_version)[platform] {}.deep_merge!(info[:general]).deep_merge!(info[hypervisor]) end
ruby
def get_platform_info(bhg_version, platform, hypervisor) info = get_osinfo(bhg_version)[platform] {}.deep_merge!(info[:general]).deep_merge!(info[hypervisor]) end
[ "def", "get_platform_info", "(", "bhg_version", ",", "platform", ",", "hypervisor", ")", "info", "=", "get_osinfo", "(", "bhg_version", ")", "[", "platform", "]", "{", "}", ".", "deep_merge!", "(", "info", "[", ":general", "]", ")", ".", "deep_merge!", "(", "info", "[", "hypervisor", "]", ")", "end" ]
Returns the fully parsed map of information of the specified OS platform for the specified hypervisor. This map should be suitable for outputting to the user as it will have the intermediate organizational branches of the `get_osinfo` map removed. This is intended to be the primary way to access OS info from hypervisor implementations when generating host definitions. @param [Integer] bhg_version The version of OS info to use. @param [String] platform The OS platform to access from the OS info map. @param [Symbol] hypervisor The symbol representing which hypervisor submap to extract from the general OS info map. @example Getting CentOS 6 64-bit information for the VMPooler hypervisor Given the OS info map looks like: ... 'centos6-64' => { :general => { 'platform' => 'el-6-x86_64' }, :vmpooler => { 'template' => 'centos-6-x86_64' } } ... Then get_platform_info(0, 'centos6-64', :vmpooler) returns: { 'platform' => 'el-6-x86_64', 'template' => 'centos-6-x86_64' }
[ "Returns", "the", "fully", "parsed", "map", "of", "information", "of", "the", "specified", "OS", "platform", "for", "the", "specified", "hypervisor", ".", "This", "map", "should", "be", "suitable", "for", "outputting", "to", "the", "user", "as", "it", "will", "have", "the", "intermediate", "organizational", "branches", "of", "the", "get_osinfo", "map", "removed", "." ]
276830215efedf00f133ddedc8b636c25d7510c4
https://github.com/puppetlabs/beaker-hostgenerator/blob/276830215efedf00f133ddedc8b636c25d7510c4/lib/beaker-hostgenerator/data.rb#L1768-L1771
16,998
puppetlabs/beaker-hostgenerator
lib/beaker-hostgenerator/abs_support.rb
BeakerHostGenerator.AbsSupport.extract_templates
def extract_templates(config) templates_hosts = config['HOSTS'].values.group_by { |h| h['template'] } templates_hosts.each do |template, hosts| templates_hosts[template] = hosts.count end end
ruby
def extract_templates(config) templates_hosts = config['HOSTS'].values.group_by { |h| h['template'] } templates_hosts.each do |template, hosts| templates_hosts[template] = hosts.count end end
[ "def", "extract_templates", "(", "config", ")", "templates_hosts", "=", "config", "[", "'HOSTS'", "]", ".", "values", ".", "group_by", "{", "|", "h", "|", "h", "[", "'template'", "]", "}", "templates_hosts", ".", "each", "do", "|", "template", ",", "hosts", "|", "templates_hosts", "[", "template", "]", "=", "hosts", ".", "count", "end", "end" ]
Given an existing, fully-specified host configuration, count the number of hosts using each template, and return a map of template name to host count. For example, given the following config (parts omitted for brevity): {"HOSTS"=> {"centos6-64-1"=> {"template"=>"centos-6-x86_64", ...}, "redhat7-64-1"=> {"template"=>"redhat-7-x86_64", ...}, "centos6-64-2"=> {"template"=>"centos-6-x86_64", ...}}, ... }} Returns the following map: {"centos-6-x86_64"=>2, "redhat-7-x86_64"=>1}
[ "Given", "an", "existing", "fully", "-", "specified", "host", "configuration", "count", "the", "number", "of", "hosts", "using", "each", "template", "and", "return", "a", "map", "of", "template", "name", "to", "host", "count", "." ]
276830215efedf00f133ddedc8b636c25d7510c4
https://github.com/puppetlabs/beaker-hostgenerator/blob/276830215efedf00f133ddedc8b636c25d7510c4/lib/beaker-hostgenerator/abs_support.rb#L23-L28
16,999
puppetlabs/beaker-hostgenerator
lib/beaker-hostgenerator/generator.rb
BeakerHostGenerator.Generator.generate
def generate(layout, options) layout = prepare(layout) tokens = tokenize_layout(layout) config = {}.deep_merge(BASE_CONFIG) nodeid = Hash.new(1) ostype = nil bhg_version = options[:osinfo_version] || 0 tokens.each do |token| if is_ostype_token?(token, bhg_version) if nodeid[ostype] == 1 and ostype != nil raise "Error: no nodes generated for #{ostype}" end ostype = token next end node_info = parse_node_info_token(token) # Build node host name platform = "#{ostype}-#{node_info['bits']}" host_name = "#{platform}-#{nodeid[ostype]}" node_info['platform'] = platform node_info['ostype'] = ostype node_info['nodeid'] = nodeid[ostype] host_config = base_host_config(options) # Delegate to the hypervisor hypervisor = BeakerHostGenerator::Hypervisor.create(node_info, options) host_config = hypervisor.generate_node(node_info, host_config, bhg_version) config['CONFIG'].deep_merge!(hypervisor.global_config()) # Merge in any arbitrary key-value host settings. Treat the 'hostname' # setting specially, and don't merge it in as an arbitrary setting. arbitrary_settings = node_info['host_settings'] host_name = arbitrary_settings.delete('hostname') if arbitrary_settings.has_key?('hostname') host_config.merge!(arbitrary_settings) if PE_USE_WIN32 && ostype =~ /windows/ && node_info['bits'] == "64" host_config['ruby_arch'] = 'x86' host_config['install_32'] = true end generate_host_roles!(host_config, node_info, options) config['HOSTS'][host_name] = host_config nodeid[ostype] += 1 end # Merge in global configuration settings after the hypervisor defaults if options[:global_config] decoded = prepare(options[:global_config]) # Support for strings without '{}' was introduced, so just double # check here to ensure that we pass in values surrounded by '{}'. if !decoded.start_with?('{') decoded = "{#{decoded}}" end global_config = settings_string_to_map(decoded) config['CONFIG'].deep_merge!(global_config) end # Munge non-string scalar values into proper data types unstringify_values!(config) return config end
ruby
def generate(layout, options) layout = prepare(layout) tokens = tokenize_layout(layout) config = {}.deep_merge(BASE_CONFIG) nodeid = Hash.new(1) ostype = nil bhg_version = options[:osinfo_version] || 0 tokens.each do |token| if is_ostype_token?(token, bhg_version) if nodeid[ostype] == 1 and ostype != nil raise "Error: no nodes generated for #{ostype}" end ostype = token next end node_info = parse_node_info_token(token) # Build node host name platform = "#{ostype}-#{node_info['bits']}" host_name = "#{platform}-#{nodeid[ostype]}" node_info['platform'] = platform node_info['ostype'] = ostype node_info['nodeid'] = nodeid[ostype] host_config = base_host_config(options) # Delegate to the hypervisor hypervisor = BeakerHostGenerator::Hypervisor.create(node_info, options) host_config = hypervisor.generate_node(node_info, host_config, bhg_version) config['CONFIG'].deep_merge!(hypervisor.global_config()) # Merge in any arbitrary key-value host settings. Treat the 'hostname' # setting specially, and don't merge it in as an arbitrary setting. arbitrary_settings = node_info['host_settings'] host_name = arbitrary_settings.delete('hostname') if arbitrary_settings.has_key?('hostname') host_config.merge!(arbitrary_settings) if PE_USE_WIN32 && ostype =~ /windows/ && node_info['bits'] == "64" host_config['ruby_arch'] = 'x86' host_config['install_32'] = true end generate_host_roles!(host_config, node_info, options) config['HOSTS'][host_name] = host_config nodeid[ostype] += 1 end # Merge in global configuration settings after the hypervisor defaults if options[:global_config] decoded = prepare(options[:global_config]) # Support for strings without '{}' was introduced, so just double # check here to ensure that we pass in values surrounded by '{}'. if !decoded.start_with?('{') decoded = "{#{decoded}}" end global_config = settings_string_to_map(decoded) config['CONFIG'].deep_merge!(global_config) end # Munge non-string scalar values into proper data types unstringify_values!(config) return config end
[ "def", "generate", "(", "layout", ",", "options", ")", "layout", "=", "prepare", "(", "layout", ")", "tokens", "=", "tokenize_layout", "(", "layout", ")", "config", "=", "{", "}", ".", "deep_merge", "(", "BASE_CONFIG", ")", "nodeid", "=", "Hash", ".", "new", "(", "1", ")", "ostype", "=", "nil", "bhg_version", "=", "options", "[", ":osinfo_version", "]", "||", "0", "tokens", ".", "each", "do", "|", "token", "|", "if", "is_ostype_token?", "(", "token", ",", "bhg_version", ")", "if", "nodeid", "[", "ostype", "]", "==", "1", "and", "ostype", "!=", "nil", "raise", "\"Error: no nodes generated for #{ostype}\"", "end", "ostype", "=", "token", "next", "end", "node_info", "=", "parse_node_info_token", "(", "token", ")", "# Build node host name", "platform", "=", "\"#{ostype}-#{node_info['bits']}\"", "host_name", "=", "\"#{platform}-#{nodeid[ostype]}\"", "node_info", "[", "'platform'", "]", "=", "platform", "node_info", "[", "'ostype'", "]", "=", "ostype", "node_info", "[", "'nodeid'", "]", "=", "nodeid", "[", "ostype", "]", "host_config", "=", "base_host_config", "(", "options", ")", "# Delegate to the hypervisor", "hypervisor", "=", "BeakerHostGenerator", "::", "Hypervisor", ".", "create", "(", "node_info", ",", "options", ")", "host_config", "=", "hypervisor", ".", "generate_node", "(", "node_info", ",", "host_config", ",", "bhg_version", ")", "config", "[", "'CONFIG'", "]", ".", "deep_merge!", "(", "hypervisor", ".", "global_config", "(", ")", ")", "# Merge in any arbitrary key-value host settings. Treat the 'hostname'", "# setting specially, and don't merge it in as an arbitrary setting.", "arbitrary_settings", "=", "node_info", "[", "'host_settings'", "]", "host_name", "=", "arbitrary_settings", ".", "delete", "(", "'hostname'", ")", "if", "arbitrary_settings", ".", "has_key?", "(", "'hostname'", ")", "host_config", ".", "merge!", "(", "arbitrary_settings", ")", "if", "PE_USE_WIN32", "&&", "ostype", "=~", "/", "/", "&&", "node_info", "[", "'bits'", "]", "==", "\"64\"", "host_config", "[", "'ruby_arch'", "]", "=", "'x86'", "host_config", "[", "'install_32'", "]", "=", "true", "end", "generate_host_roles!", "(", "host_config", ",", "node_info", ",", "options", ")", "config", "[", "'HOSTS'", "]", "[", "host_name", "]", "=", "host_config", "nodeid", "[", "ostype", "]", "+=", "1", "end", "# Merge in global configuration settings after the hypervisor defaults", "if", "options", "[", ":global_config", "]", "decoded", "=", "prepare", "(", "options", "[", ":global_config", "]", ")", "# Support for strings without '{}' was introduced, so just double", "# check here to ensure that we pass in values surrounded by '{}'.", "if", "!", "decoded", ".", "start_with?", "(", "'{'", ")", "decoded", "=", "\"{#{decoded}}\"", "end", "global_config", "=", "settings_string_to_map", "(", "decoded", ")", "config", "[", "'CONFIG'", "]", ".", "deep_merge!", "(", "global_config", ")", "end", "# Munge non-string scalar values into proper data types", "unstringify_values!", "(", "config", ")", "return", "config", "end" ]
Main host generation entry point, returns a Ruby map for the given host specification and optional configuration. @param layout [String] The raw hosts specification user input. For example `"centos6-64m-redhat7-64a"`. @param options [Hash] Global, optional configuration such as the default hypervisor or OS info version. @returns [Hash] A complete Ruby map as defining the HOSTS and CONFIG sections as required by Beaker.
[ "Main", "host", "generation", "entry", "point", "returns", "a", "Ruby", "map", "for", "the", "given", "host", "specification", "and", "optional", "configuration", "." ]
276830215efedf00f133ddedc8b636c25d7510c4
https://github.com/puppetlabs/beaker-hostgenerator/blob/276830215efedf00f133ddedc8b636c25d7510c4/lib/beaker-hostgenerator/generator.rb#L22-L90