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
|
|---|---|---|---|---|---|---|---|---|---|---|---|
15,100
|
stffn/declarative_authorization
|
lib/declarative_authorization/authorization.rb
|
Authorization.Engine.flatten_privileges
|
def flatten_privileges (privileges, context = nil, flattened_privileges = Set.new)
# TODO caching?
raise AuthorizationUsageError, "No context given or inferable from object" unless context
privileges.reject {|priv| flattened_privileges.include?(priv)}.each do |priv|
flattened_privileges << priv
flatten_privileges(rev_priv_hierarchy[[priv, nil]], context, flattened_privileges) if rev_priv_hierarchy[[priv, nil]]
flatten_privileges(rev_priv_hierarchy[[priv, context]], context, flattened_privileges) if rev_priv_hierarchy[[priv, context]]
end
flattened_privileges.to_a
end
|
ruby
|
def flatten_privileges (privileges, context = nil, flattened_privileges = Set.new)
# TODO caching?
raise AuthorizationUsageError, "No context given or inferable from object" unless context
privileges.reject {|priv| flattened_privileges.include?(priv)}.each do |priv|
flattened_privileges << priv
flatten_privileges(rev_priv_hierarchy[[priv, nil]], context, flattened_privileges) if rev_priv_hierarchy[[priv, nil]]
flatten_privileges(rev_priv_hierarchy[[priv, context]], context, flattened_privileges) if rev_priv_hierarchy[[priv, context]]
end
flattened_privileges.to_a
end
|
[
"def",
"flatten_privileges",
"(",
"privileges",
",",
"context",
"=",
"nil",
",",
"flattened_privileges",
"=",
"Set",
".",
"new",
")",
"# TODO caching?",
"raise",
"AuthorizationUsageError",
",",
"\"No context given or inferable from object\"",
"unless",
"context",
"privileges",
".",
"reject",
"{",
"|",
"priv",
"|",
"flattened_privileges",
".",
"include?",
"(",
"priv",
")",
"}",
".",
"each",
"do",
"|",
"priv",
"|",
"flattened_privileges",
"<<",
"priv",
"flatten_privileges",
"(",
"rev_priv_hierarchy",
"[",
"[",
"priv",
",",
"nil",
"]",
"]",
",",
"context",
",",
"flattened_privileges",
")",
"if",
"rev_priv_hierarchy",
"[",
"[",
"priv",
",",
"nil",
"]",
"]",
"flatten_privileges",
"(",
"rev_priv_hierarchy",
"[",
"[",
"priv",
",",
"context",
"]",
"]",
",",
"context",
",",
"flattened_privileges",
")",
"if",
"rev_priv_hierarchy",
"[",
"[",
"priv",
",",
"context",
"]",
"]",
"end",
"flattened_privileges",
".",
"to_a",
"end"
] |
Returns the privilege hierarchy flattened for given privileges in context.
|
[
"Returns",
"the",
"privilege",
"hierarchy",
"flattened",
"for",
"given",
"privileges",
"in",
"context",
"."
] |
45e91af20eba71b2828c5c84066bcce3ef032e8a
|
https://github.com/stffn/declarative_authorization/blob/45e91af20eba71b2828c5c84066bcce3ef032e8a/lib/declarative_authorization/authorization.rb#L347-L356
|
15,101
|
stffn/declarative_authorization
|
lib/declarative_authorization/authorization.rb
|
Authorization.Attribute.obligation
|
def obligation (attr_validator, hash = nil)
hash = (hash || @conditions_hash).clone
hash.each do |attr, value|
if value.is_a?(Hash)
hash[attr] = obligation(attr_validator, value)
elsif value.is_a?(Array) and value.length == 2
hash[attr] = [value[0], attr_validator.evaluate(value[1])]
else
raise AuthorizationError, "Wrong conditions hash format"
end
end
hash
end
|
ruby
|
def obligation (attr_validator, hash = nil)
hash = (hash || @conditions_hash).clone
hash.each do |attr, value|
if value.is_a?(Hash)
hash[attr] = obligation(attr_validator, value)
elsif value.is_a?(Array) and value.length == 2
hash[attr] = [value[0], attr_validator.evaluate(value[1])]
else
raise AuthorizationError, "Wrong conditions hash format"
end
end
hash
end
|
[
"def",
"obligation",
"(",
"attr_validator",
",",
"hash",
"=",
"nil",
")",
"hash",
"=",
"(",
"hash",
"||",
"@conditions_hash",
")",
".",
"clone",
"hash",
".",
"each",
"do",
"|",
"attr",
",",
"value",
"|",
"if",
"value",
".",
"is_a?",
"(",
"Hash",
")",
"hash",
"[",
"attr",
"]",
"=",
"obligation",
"(",
"attr_validator",
",",
"value",
")",
"elsif",
"value",
".",
"is_a?",
"(",
"Array",
")",
"and",
"value",
".",
"length",
"==",
"2",
"hash",
"[",
"attr",
"]",
"=",
"[",
"value",
"[",
"0",
"]",
",",
"attr_validator",
".",
"evaluate",
"(",
"value",
"[",
"1",
"]",
")",
"]",
"else",
"raise",
"AuthorizationError",
",",
"\"Wrong conditions hash format\"",
"end",
"end",
"hash",
"end"
] |
resolves all the values in condition_hash
|
[
"resolves",
"all",
"the",
"values",
"in",
"condition_hash"
] |
45e91af20eba71b2828c5c84066bcce3ef032e8a
|
https://github.com/stffn/declarative_authorization/blob/45e91af20eba71b2828c5c84066bcce3ef032e8a/lib/declarative_authorization/authorization.rb#L605-L617
|
15,102
|
stffn/declarative_authorization
|
lib/declarative_authorization/authorization.rb
|
Authorization.AttributeWithPermission.obligation
|
def obligation (attr_validator, hash_or_attr = nil, path = [])
hash_or_attr ||= @attr_hash
case hash_or_attr
when Symbol
@context ||= begin
rule_model = attr_validator.context.to_s.classify.constantize
context_reflection = self.class.reflection_for_path(rule_model, path + [hash_or_attr])
if context_reflection.klass.respond_to?(:decl_auth_context)
context_reflection.klass.decl_auth_context
else
context_reflection.klass.name.tableize.to_sym
end
rescue # missing model, reflections
hash_or_attr.to_s.pluralize.to_sym
end
obligations = attr_validator.engine.obligations(@privilege,
:context => @context,
:user => attr_validator.user)
obligations.collect {|obl| {hash_or_attr => obl} }
when Hash
obligations_array_attrs = []
obligations =
hash_or_attr.inject({}) do |all, pair|
attr, sub_hash = pair
all[attr] = obligation(attr_validator, sub_hash, path + [attr])
if all[attr].length > 1
obligations_array_attrs << attr
else
all[attr] = all[attr].first
end
all
end
obligations = [obligations]
obligations_array_attrs.each do |attr|
next_array_size = obligations.first[attr].length
obligations = obligations.collect do |obls|
(0...next_array_size).collect do |idx|
obls_wo_array = obls.clone
obls_wo_array[attr] = obls_wo_array[attr][idx]
obls_wo_array
end
end.flatten
end
obligations
when NilClass
attr_validator.engine.obligations(@privilege,
:context => attr_validator.context,
:user => attr_validator.user)
else
raise AuthorizationError, "Wrong conditions hash format: #{hash_or_attr.inspect}"
end
end
|
ruby
|
def obligation (attr_validator, hash_or_attr = nil, path = [])
hash_or_attr ||= @attr_hash
case hash_or_attr
when Symbol
@context ||= begin
rule_model = attr_validator.context.to_s.classify.constantize
context_reflection = self.class.reflection_for_path(rule_model, path + [hash_or_attr])
if context_reflection.klass.respond_to?(:decl_auth_context)
context_reflection.klass.decl_auth_context
else
context_reflection.klass.name.tableize.to_sym
end
rescue # missing model, reflections
hash_or_attr.to_s.pluralize.to_sym
end
obligations = attr_validator.engine.obligations(@privilege,
:context => @context,
:user => attr_validator.user)
obligations.collect {|obl| {hash_or_attr => obl} }
when Hash
obligations_array_attrs = []
obligations =
hash_or_attr.inject({}) do |all, pair|
attr, sub_hash = pair
all[attr] = obligation(attr_validator, sub_hash, path + [attr])
if all[attr].length > 1
obligations_array_attrs << attr
else
all[attr] = all[attr].first
end
all
end
obligations = [obligations]
obligations_array_attrs.each do |attr|
next_array_size = obligations.first[attr].length
obligations = obligations.collect do |obls|
(0...next_array_size).collect do |idx|
obls_wo_array = obls.clone
obls_wo_array[attr] = obls_wo_array[attr][idx]
obls_wo_array
end
end.flatten
end
obligations
when NilClass
attr_validator.engine.obligations(@privilege,
:context => attr_validator.context,
:user => attr_validator.user)
else
raise AuthorizationError, "Wrong conditions hash format: #{hash_or_attr.inspect}"
end
end
|
[
"def",
"obligation",
"(",
"attr_validator",
",",
"hash_or_attr",
"=",
"nil",
",",
"path",
"=",
"[",
"]",
")",
"hash_or_attr",
"||=",
"@attr_hash",
"case",
"hash_or_attr",
"when",
"Symbol",
"@context",
"||=",
"begin",
"rule_model",
"=",
"attr_validator",
".",
"context",
".",
"to_s",
".",
"classify",
".",
"constantize",
"context_reflection",
"=",
"self",
".",
"class",
".",
"reflection_for_path",
"(",
"rule_model",
",",
"path",
"+",
"[",
"hash_or_attr",
"]",
")",
"if",
"context_reflection",
".",
"klass",
".",
"respond_to?",
"(",
":decl_auth_context",
")",
"context_reflection",
".",
"klass",
".",
"decl_auth_context",
"else",
"context_reflection",
".",
"klass",
".",
"name",
".",
"tableize",
".",
"to_sym",
"end",
"rescue",
"# missing model, reflections",
"hash_or_attr",
".",
"to_s",
".",
"pluralize",
".",
"to_sym",
"end",
"obligations",
"=",
"attr_validator",
".",
"engine",
".",
"obligations",
"(",
"@privilege",
",",
":context",
"=>",
"@context",
",",
":user",
"=>",
"attr_validator",
".",
"user",
")",
"obligations",
".",
"collect",
"{",
"|",
"obl",
"|",
"{",
"hash_or_attr",
"=>",
"obl",
"}",
"}",
"when",
"Hash",
"obligations_array_attrs",
"=",
"[",
"]",
"obligations",
"=",
"hash_or_attr",
".",
"inject",
"(",
"{",
"}",
")",
"do",
"|",
"all",
",",
"pair",
"|",
"attr",
",",
"sub_hash",
"=",
"pair",
"all",
"[",
"attr",
"]",
"=",
"obligation",
"(",
"attr_validator",
",",
"sub_hash",
",",
"path",
"+",
"[",
"attr",
"]",
")",
"if",
"all",
"[",
"attr",
"]",
".",
"length",
">",
"1",
"obligations_array_attrs",
"<<",
"attr",
"else",
"all",
"[",
"attr",
"]",
"=",
"all",
"[",
"attr",
"]",
".",
"first",
"end",
"all",
"end",
"obligations",
"=",
"[",
"obligations",
"]",
"obligations_array_attrs",
".",
"each",
"do",
"|",
"attr",
"|",
"next_array_size",
"=",
"obligations",
".",
"first",
"[",
"attr",
"]",
".",
"length",
"obligations",
"=",
"obligations",
".",
"collect",
"do",
"|",
"obls",
"|",
"(",
"0",
"...",
"next_array_size",
")",
".",
"collect",
"do",
"|",
"idx",
"|",
"obls_wo_array",
"=",
"obls",
".",
"clone",
"obls_wo_array",
"[",
"attr",
"]",
"=",
"obls_wo_array",
"[",
"attr",
"]",
"[",
"idx",
"]",
"obls_wo_array",
"end",
"end",
".",
"flatten",
"end",
"obligations",
"when",
"NilClass",
"attr_validator",
".",
"engine",
".",
"obligations",
"(",
"@privilege",
",",
":context",
"=>",
"attr_validator",
".",
"context",
",",
":user",
"=>",
"attr_validator",
".",
"user",
")",
"else",
"raise",
"AuthorizationError",
",",
"\"Wrong conditions hash format: #{hash_or_attr.inspect}\"",
"end",
"end"
] |
may return an array of obligations to be OR'ed
|
[
"may",
"return",
"an",
"array",
"of",
"obligations",
"to",
"be",
"OR",
"ed"
] |
45e91af20eba71b2828c5c84066bcce3ef032e8a
|
https://github.com/stffn/declarative_authorization/blob/45e91af20eba71b2828c5c84066bcce3ef032e8a/lib/declarative_authorization/authorization.rb#L714-L767
|
15,103
|
stffn/declarative_authorization
|
lib/declarative_authorization/obligation_scope.rb
|
Authorization.ObligationScope.parse!
|
def parse!( obligation )
@current_obligation = obligation
@join_table_joins = Set.new
obligation_conditions[@current_obligation] ||= {}
follow_path( obligation )
rebuild_condition_options!
rebuild_join_options!
end
|
ruby
|
def parse!( obligation )
@current_obligation = obligation
@join_table_joins = Set.new
obligation_conditions[@current_obligation] ||= {}
follow_path( obligation )
rebuild_condition_options!
rebuild_join_options!
end
|
[
"def",
"parse!",
"(",
"obligation",
")",
"@current_obligation",
"=",
"obligation",
"@join_table_joins",
"=",
"Set",
".",
"new",
"obligation_conditions",
"[",
"@current_obligation",
"]",
"||=",
"{",
"}",
"follow_path",
"(",
"obligation",
")",
"rebuild_condition_options!",
"rebuild_join_options!",
"end"
] |
Consumes the given obligation, converting it into scope join and condition options.
|
[
"Consumes",
"the",
"given",
"obligation",
"converting",
"it",
"into",
"scope",
"join",
"and",
"condition",
"options",
"."
] |
45e91af20eba71b2828c5c84066bcce3ef032e8a
|
https://github.com/stffn/declarative_authorization/blob/45e91af20eba71b2828c5c84066bcce3ef032e8a/lib/declarative_authorization/obligation_scope.rb#L68-L76
|
15,104
|
stffn/declarative_authorization
|
lib/declarative_authorization/obligation_scope.rb
|
Authorization.ObligationScope.follow_path
|
def follow_path( steps, past_steps = [] )
if steps.is_a?( Hash )
steps.each do |step, next_steps|
path_to_this_point = [past_steps, step].flatten
reflection = reflection_for( path_to_this_point ) rescue nil
if reflection
follow_path( next_steps, path_to_this_point )
else
follow_comparison( next_steps, past_steps, step )
end
end
elsif steps.is_a?( Array ) && steps.length == 2
if reflection_for( past_steps )
follow_comparison( steps, past_steps, :id )
else
follow_comparison( steps, past_steps[0..-2], past_steps[-1] )
end
else
raise "invalid obligation path #{[past_steps, steps].inspect}"
end
end
|
ruby
|
def follow_path( steps, past_steps = [] )
if steps.is_a?( Hash )
steps.each do |step, next_steps|
path_to_this_point = [past_steps, step].flatten
reflection = reflection_for( path_to_this_point ) rescue nil
if reflection
follow_path( next_steps, path_to_this_point )
else
follow_comparison( next_steps, past_steps, step )
end
end
elsif steps.is_a?( Array ) && steps.length == 2
if reflection_for( past_steps )
follow_comparison( steps, past_steps, :id )
else
follow_comparison( steps, past_steps[0..-2], past_steps[-1] )
end
else
raise "invalid obligation path #{[past_steps, steps].inspect}"
end
end
|
[
"def",
"follow_path",
"(",
"steps",
",",
"past_steps",
"=",
"[",
"]",
")",
"if",
"steps",
".",
"is_a?",
"(",
"Hash",
")",
"steps",
".",
"each",
"do",
"|",
"step",
",",
"next_steps",
"|",
"path_to_this_point",
"=",
"[",
"past_steps",
",",
"step",
"]",
".",
"flatten",
"reflection",
"=",
"reflection_for",
"(",
"path_to_this_point",
")",
"rescue",
"nil",
"if",
"reflection",
"follow_path",
"(",
"next_steps",
",",
"path_to_this_point",
")",
"else",
"follow_comparison",
"(",
"next_steps",
",",
"past_steps",
",",
"step",
")",
"end",
"end",
"elsif",
"steps",
".",
"is_a?",
"(",
"Array",
")",
"&&",
"steps",
".",
"length",
"==",
"2",
"if",
"reflection_for",
"(",
"past_steps",
")",
"follow_comparison",
"(",
"steps",
",",
"past_steps",
",",
":id",
")",
"else",
"follow_comparison",
"(",
"steps",
",",
"past_steps",
"[",
"0",
"..",
"-",
"2",
"]",
",",
"past_steps",
"[",
"-",
"1",
"]",
")",
"end",
"else",
"raise",
"\"invalid obligation path #{[past_steps, steps].inspect}\"",
"end",
"end"
] |
Parses the next step in the association path. If it's an association, we advance down the
path. Otherwise, it's an attribute, and we need to evaluate it as a comparison operation.
|
[
"Parses",
"the",
"next",
"step",
"in",
"the",
"association",
"path",
".",
"If",
"it",
"s",
"an",
"association",
"we",
"advance",
"down",
"the",
"path",
".",
"Otherwise",
"it",
"s",
"an",
"attribute",
"and",
"we",
"need",
"to",
"evaluate",
"it",
"as",
"a",
"comparison",
"operation",
"."
] |
45e91af20eba71b2828c5c84066bcce3ef032e8a
|
https://github.com/stffn/declarative_authorization/blob/45e91af20eba71b2828c5c84066bcce3ef032e8a/lib/declarative_authorization/obligation_scope.rb#L82-L102
|
15,105
|
stffn/declarative_authorization
|
lib/declarative_authorization/obligation_scope.rb
|
Authorization.ObligationScope.add_obligation_condition_for
|
def add_obligation_condition_for( path, expression )
raise "invalid expression #{expression.inspect}" unless expression.is_a?( Array ) && expression.length == 3
add_obligation_join_for( path )
obligation_conditions[@current_obligation] ||= {}
( obligation_conditions[@current_obligation][path] ||= Set.new ) << expression
end
|
ruby
|
def add_obligation_condition_for( path, expression )
raise "invalid expression #{expression.inspect}" unless expression.is_a?( Array ) && expression.length == 3
add_obligation_join_for( path )
obligation_conditions[@current_obligation] ||= {}
( obligation_conditions[@current_obligation][path] ||= Set.new ) << expression
end
|
[
"def",
"add_obligation_condition_for",
"(",
"path",
",",
"expression",
")",
"raise",
"\"invalid expression #{expression.inspect}\"",
"unless",
"expression",
".",
"is_a?",
"(",
"Array",
")",
"&&",
"expression",
".",
"length",
"==",
"3",
"add_obligation_join_for",
"(",
"path",
")",
"obligation_conditions",
"[",
"@current_obligation",
"]",
"||=",
"{",
"}",
"(",
"obligation_conditions",
"[",
"@current_obligation",
"]",
"[",
"path",
"]",
"||=",
"Set",
".",
"new",
")",
"<<",
"expression",
"end"
] |
Adds the given expression to the current obligation's indicated path's conditions.
Condition expressions must follow the format +[ <attribute>, <operator>, <value> ]+.
|
[
"Adds",
"the",
"given",
"expression",
"to",
"the",
"current",
"obligation",
"s",
"indicated",
"path",
"s",
"conditions",
"."
] |
45e91af20eba71b2828c5c84066bcce3ef032e8a
|
https://github.com/stffn/declarative_authorization/blob/45e91af20eba71b2828c5c84066bcce3ef032e8a/lib/declarative_authorization/obligation_scope.rb#L131-L136
|
15,106
|
stffn/declarative_authorization
|
lib/declarative_authorization/obligation_scope.rb
|
Authorization.ObligationScope.model_for
|
def model_for (path)
reflection = reflection_for(path)
if Authorization.is_a_association_proxy?(reflection)
if Rails.version < "3.2"
reflection.proxy_reflection.klass
else
reflection.proxy_association.reflection.klass
end
elsif reflection.respond_to?(:klass)
reflection.klass
else
reflection
end
end
|
ruby
|
def model_for (path)
reflection = reflection_for(path)
if Authorization.is_a_association_proxy?(reflection)
if Rails.version < "3.2"
reflection.proxy_reflection.klass
else
reflection.proxy_association.reflection.klass
end
elsif reflection.respond_to?(:klass)
reflection.klass
else
reflection
end
end
|
[
"def",
"model_for",
"(",
"path",
")",
"reflection",
"=",
"reflection_for",
"(",
"path",
")",
"if",
"Authorization",
".",
"is_a_association_proxy?",
"(",
"reflection",
")",
"if",
"Rails",
".",
"version",
"<",
"\"3.2\"",
"reflection",
".",
"proxy_reflection",
".",
"klass",
"else",
"reflection",
".",
"proxy_association",
".",
"reflection",
".",
"klass",
"end",
"elsif",
"reflection",
".",
"respond_to?",
"(",
":klass",
")",
"reflection",
".",
"klass",
"else",
"reflection",
"end",
"end"
] |
Returns the model associated with the given path.
|
[
"Returns",
"the",
"model",
"associated",
"with",
"the",
"given",
"path",
"."
] |
45e91af20eba71b2828c5c84066bcce3ef032e8a
|
https://github.com/stffn/declarative_authorization/blob/45e91af20eba71b2828c5c84066bcce3ef032e8a/lib/declarative_authorization/obligation_scope.rb#L144-L158
|
15,107
|
stffn/declarative_authorization
|
lib/declarative_authorization/obligation_scope.rb
|
Authorization.ObligationScope.reflection_for
|
def reflection_for(path, for_join_table_only = false)
@join_table_joins << path if for_join_table_only and !reflections[path]
reflections[path] ||= map_reflection_for( path )
end
|
ruby
|
def reflection_for(path, for_join_table_only = false)
@join_table_joins << path if for_join_table_only and !reflections[path]
reflections[path] ||= map_reflection_for( path )
end
|
[
"def",
"reflection_for",
"(",
"path",
",",
"for_join_table_only",
"=",
"false",
")",
"@join_table_joins",
"<<",
"path",
"if",
"for_join_table_only",
"and",
"!",
"reflections",
"[",
"path",
"]",
"reflections",
"[",
"path",
"]",
"||=",
"map_reflection_for",
"(",
"path",
")",
"end"
] |
Returns the reflection corresponding to the given path.
|
[
"Returns",
"the",
"reflection",
"corresponding",
"to",
"the",
"given",
"path",
"."
] |
45e91af20eba71b2828c5c84066bcce3ef032e8a
|
https://github.com/stffn/declarative_authorization/blob/45e91af20eba71b2828c5c84066bcce3ef032e8a/lib/declarative_authorization/obligation_scope.rb#L161-L164
|
15,108
|
stffn/declarative_authorization
|
lib/declarative_authorization/obligation_scope.rb
|
Authorization.ObligationScope.map_reflection_for
|
def map_reflection_for( path )
raise "reflection for #{path.inspect} already exists" unless reflections[path].nil?
reflection = path.empty? ? top_level_model : begin
parent = reflection_for( path[0..-2] )
if !Authorization.is_a_association_proxy?(parent) and parent.respond_to?(:klass)
parent.klass.reflect_on_association( path.last )
else
parent.reflect_on_association( path.last )
end
rescue
parent.reflect_on_association( path.last )
end
raise "invalid path #{path.inspect}" if reflection.nil?
reflections[path] = reflection
map_table_alias_for( path ) # Claim a table alias for the path.
# Claim alias for join table
# TODO change how this is checked
if !Authorization.is_a_association_proxy?(reflection) and !reflection.respond_to?(:proxy_scope) and reflection.is_a?(ActiveRecord::Reflection::ThroughReflection)
join_table_path = path[0..-2] + [reflection.options[:through]]
reflection_for(join_table_path, true)
end
reflection
end
|
ruby
|
def map_reflection_for( path )
raise "reflection for #{path.inspect} already exists" unless reflections[path].nil?
reflection = path.empty? ? top_level_model : begin
parent = reflection_for( path[0..-2] )
if !Authorization.is_a_association_proxy?(parent) and parent.respond_to?(:klass)
parent.klass.reflect_on_association( path.last )
else
parent.reflect_on_association( path.last )
end
rescue
parent.reflect_on_association( path.last )
end
raise "invalid path #{path.inspect}" if reflection.nil?
reflections[path] = reflection
map_table_alias_for( path ) # Claim a table alias for the path.
# Claim alias for join table
# TODO change how this is checked
if !Authorization.is_a_association_proxy?(reflection) and !reflection.respond_to?(:proxy_scope) and reflection.is_a?(ActiveRecord::Reflection::ThroughReflection)
join_table_path = path[0..-2] + [reflection.options[:through]]
reflection_for(join_table_path, true)
end
reflection
end
|
[
"def",
"map_reflection_for",
"(",
"path",
")",
"raise",
"\"reflection for #{path.inspect} already exists\"",
"unless",
"reflections",
"[",
"path",
"]",
".",
"nil?",
"reflection",
"=",
"path",
".",
"empty?",
"?",
"top_level_model",
":",
"begin",
"parent",
"=",
"reflection_for",
"(",
"path",
"[",
"0",
"..",
"-",
"2",
"]",
")",
"if",
"!",
"Authorization",
".",
"is_a_association_proxy?",
"(",
"parent",
")",
"and",
"parent",
".",
"respond_to?",
"(",
":klass",
")",
"parent",
".",
"klass",
".",
"reflect_on_association",
"(",
"path",
".",
"last",
")",
"else",
"parent",
".",
"reflect_on_association",
"(",
"path",
".",
"last",
")",
"end",
"rescue",
"parent",
".",
"reflect_on_association",
"(",
"path",
".",
"last",
")",
"end",
"raise",
"\"invalid path #{path.inspect}\"",
"if",
"reflection",
".",
"nil?",
"reflections",
"[",
"path",
"]",
"=",
"reflection",
"map_table_alias_for",
"(",
"path",
")",
"# Claim a table alias for the path.",
"# Claim alias for join table",
"# TODO change how this is checked",
"if",
"!",
"Authorization",
".",
"is_a_association_proxy?",
"(",
"reflection",
")",
"and",
"!",
"reflection",
".",
"respond_to?",
"(",
":proxy_scope",
")",
"and",
"reflection",
".",
"is_a?",
"(",
"ActiveRecord",
"::",
"Reflection",
"::",
"ThroughReflection",
")",
"join_table_path",
"=",
"path",
"[",
"0",
"..",
"-",
"2",
"]",
"+",
"[",
"reflection",
".",
"options",
"[",
":through",
"]",
"]",
"reflection_for",
"(",
"join_table_path",
",",
"true",
")",
"end",
"reflection",
"end"
] |
Attempts to map a reflection for the given path. Raises if already defined.
|
[
"Attempts",
"to",
"map",
"a",
"reflection",
"for",
"the",
"given",
"path",
".",
"Raises",
"if",
"already",
"defined",
"."
] |
45e91af20eba71b2828c5c84066bcce3ef032e8a
|
https://github.com/stffn/declarative_authorization/blob/45e91af20eba71b2828c5c84066bcce3ef032e8a/lib/declarative_authorization/obligation_scope.rb#L172-L198
|
15,109
|
stffn/declarative_authorization
|
lib/declarative_authorization/obligation_scope.rb
|
Authorization.ObligationScope.map_table_alias_for
|
def map_table_alias_for( path )
return "table alias for #{path.inspect} already exists" unless table_aliases[path].nil?
reflection = reflection_for( path )
table_alias = reflection.table_name
if table_aliases.values.include?( table_alias )
max_length = reflection.active_record.connection.table_alias_length
# Rails seems to pluralize reflection names
table_alias = "#{reflection.name.to_s.pluralize}_#{reflection.active_record.table_name}".to(max_length-1)
end
while table_aliases.values.include?( table_alias )
if table_alias =~ /\w(_\d+?)$/
table_index = $1.succ
table_alias = "#{table_alias[0..-(table_index.length+1)]}_#{table_index}"
else
table_alias = "#{table_alias[0..(max_length-3)]}_2"
end
end
table_aliases[path] = table_alias
end
|
ruby
|
def map_table_alias_for( path )
return "table alias for #{path.inspect} already exists" unless table_aliases[path].nil?
reflection = reflection_for( path )
table_alias = reflection.table_name
if table_aliases.values.include?( table_alias )
max_length = reflection.active_record.connection.table_alias_length
# Rails seems to pluralize reflection names
table_alias = "#{reflection.name.to_s.pluralize}_#{reflection.active_record.table_name}".to(max_length-1)
end
while table_aliases.values.include?( table_alias )
if table_alias =~ /\w(_\d+?)$/
table_index = $1.succ
table_alias = "#{table_alias[0..-(table_index.length+1)]}_#{table_index}"
else
table_alias = "#{table_alias[0..(max_length-3)]}_2"
end
end
table_aliases[path] = table_alias
end
|
[
"def",
"map_table_alias_for",
"(",
"path",
")",
"return",
"\"table alias for #{path.inspect} already exists\"",
"unless",
"table_aliases",
"[",
"path",
"]",
".",
"nil?",
"reflection",
"=",
"reflection_for",
"(",
"path",
")",
"table_alias",
"=",
"reflection",
".",
"table_name",
"if",
"table_aliases",
".",
"values",
".",
"include?",
"(",
"table_alias",
")",
"max_length",
"=",
"reflection",
".",
"active_record",
".",
"connection",
".",
"table_alias_length",
"# Rails seems to pluralize reflection names",
"table_alias",
"=",
"\"#{reflection.name.to_s.pluralize}_#{reflection.active_record.table_name}\"",
".",
"to",
"(",
"max_length",
"-",
"1",
")",
"end",
"while",
"table_aliases",
".",
"values",
".",
"include?",
"(",
"table_alias",
")",
"if",
"table_alias",
"=~",
"/",
"\\w",
"\\d",
"/",
"table_index",
"=",
"$1",
".",
"succ",
"table_alias",
"=",
"\"#{table_alias[0..-(table_index.length+1)]}_#{table_index}\"",
"else",
"table_alias",
"=",
"\"#{table_alias[0..(max_length-3)]}_2\"",
"end",
"end",
"table_aliases",
"[",
"path",
"]",
"=",
"table_alias",
"end"
] |
Attempts to map a table alias for the given path. Raises if already defined.
|
[
"Attempts",
"to",
"map",
"a",
"table",
"alias",
"for",
"the",
"given",
"path",
".",
"Raises",
"if",
"already",
"defined",
"."
] |
45e91af20eba71b2828c5c84066bcce3ef032e8a
|
https://github.com/stffn/declarative_authorization/blob/45e91af20eba71b2828c5c84066bcce3ef032e8a/lib/declarative_authorization/obligation_scope.rb#L201-L220
|
15,110
|
stffn/declarative_authorization
|
lib/declarative_authorization/in_model.rb
|
Authorization.AuthorizationInModel.permitted_to?
|
def permitted_to? (privilege, options = {}, &block)
options = {
:user => Authorization.current_user,
:object => self
}.merge(options)
Authorization::Engine.instance.permit?(privilege,
{:user => options[:user],
:object => options[:object]},
&block)
end
|
ruby
|
def permitted_to? (privilege, options = {}, &block)
options = {
:user => Authorization.current_user,
:object => self
}.merge(options)
Authorization::Engine.instance.permit?(privilege,
{:user => options[:user],
:object => options[:object]},
&block)
end
|
[
"def",
"permitted_to?",
"(",
"privilege",
",",
"options",
"=",
"{",
"}",
",",
"&",
"block",
")",
"options",
"=",
"{",
":user",
"=>",
"Authorization",
".",
"current_user",
",",
":object",
"=>",
"self",
"}",
".",
"merge",
"(",
"options",
")",
"Authorization",
"::",
"Engine",
".",
"instance",
".",
"permit?",
"(",
"privilege",
",",
"{",
":user",
"=>",
"options",
"[",
":user",
"]",
",",
":object",
"=>",
"options",
"[",
":object",
"]",
"}",
",",
"block",
")",
"end"
] |
If the user meets the given privilege, permitted_to? returns true
and yields to the optional block.
|
[
"If",
"the",
"user",
"meets",
"the",
"given",
"privilege",
"permitted_to?",
"returns",
"true",
"and",
"yields",
"to",
"the",
"optional",
"block",
"."
] |
45e91af20eba71b2828c5c84066bcce3ef032e8a
|
https://github.com/stffn/declarative_authorization/blob/45e91af20eba71b2828c5c84066bcce3ef032e8a/lib/declarative_authorization/in_model.rb#L11-L20
|
15,111
|
stffn/declarative_authorization
|
lib/declarative_authorization/in_controller.rb
|
Authorization.AuthorizationInController.has_role?
|
def has_role? (*roles, &block)
user_roles = authorization_engine.roles_for(current_user)
result = roles.all? do |role|
user_roles.include?(role)
end
yield if result and block_given?
result
end
|
ruby
|
def has_role? (*roles, &block)
user_roles = authorization_engine.roles_for(current_user)
result = roles.all? do |role|
user_roles.include?(role)
end
yield if result and block_given?
result
end
|
[
"def",
"has_role?",
"(",
"*",
"roles",
",",
"&",
"block",
")",
"user_roles",
"=",
"authorization_engine",
".",
"roles_for",
"(",
"current_user",
")",
"result",
"=",
"roles",
".",
"all?",
"do",
"|",
"role",
"|",
"user_roles",
".",
"include?",
"(",
"role",
")",
"end",
"yield",
"if",
"result",
"and",
"block_given?",
"result",
"end"
] |
While permitted_to? is used for authorization, in some cases
content should only be shown to some users without being concerned
with authorization. E.g. to only show the most relevant menu options
to a certain group of users. That is what has_role? should be used for.
|
[
"While",
"permitted_to?",
"is",
"used",
"for",
"authorization",
"in",
"some",
"cases",
"content",
"should",
"only",
"be",
"shown",
"to",
"some",
"users",
"without",
"being",
"concerned",
"with",
"authorization",
".",
"E",
".",
"g",
".",
"to",
"only",
"show",
"the",
"most",
"relevant",
"menu",
"options",
"to",
"a",
"certain",
"group",
"of",
"users",
".",
"That",
"is",
"what",
"has_role?",
"should",
"be",
"used",
"for",
"."
] |
45e91af20eba71b2828c5c84066bcce3ef032e8a
|
https://github.com/stffn/declarative_authorization/blob/45e91af20eba71b2828c5c84066bcce3ef032e8a/lib/declarative_authorization/in_controller.rb#L64-L71
|
15,112
|
stffn/declarative_authorization
|
lib/declarative_authorization/in_controller.rb
|
Authorization.AuthorizationInController.has_any_role?
|
def has_any_role?(*roles,&block)
user_roles = authorization_engine.roles_for(current_user)
result = roles.any? do |role|
user_roles.include?(role)
end
yield if result and block_given?
result
end
|
ruby
|
def has_any_role?(*roles,&block)
user_roles = authorization_engine.roles_for(current_user)
result = roles.any? do |role|
user_roles.include?(role)
end
yield if result and block_given?
result
end
|
[
"def",
"has_any_role?",
"(",
"*",
"roles",
",",
"&",
"block",
")",
"user_roles",
"=",
"authorization_engine",
".",
"roles_for",
"(",
"current_user",
")",
"result",
"=",
"roles",
".",
"any?",
"do",
"|",
"role",
"|",
"user_roles",
".",
"include?",
"(",
"role",
")",
"end",
"yield",
"if",
"result",
"and",
"block_given?",
"result",
"end"
] |
Intended to be used where you want to allow users with any single listed role to view
the content in question
|
[
"Intended",
"to",
"be",
"used",
"where",
"you",
"want",
"to",
"allow",
"users",
"with",
"any",
"single",
"listed",
"role",
"to",
"view",
"the",
"content",
"in",
"question"
] |
45e91af20eba71b2828c5c84066bcce3ef032e8a
|
https://github.com/stffn/declarative_authorization/blob/45e91af20eba71b2828c5c84066bcce3ef032e8a/lib/declarative_authorization/in_controller.rb#L75-L82
|
15,113
|
stffn/declarative_authorization
|
lib/declarative_authorization/in_controller.rb
|
Authorization.AuthorizationInController.has_role_with_hierarchy?
|
def has_role_with_hierarchy?(*roles, &block)
user_roles = authorization_engine.roles_with_hierarchy_for(current_user)
result = roles.all? do |role|
user_roles.include?(role)
end
yield if result and block_given?
result
end
|
ruby
|
def has_role_with_hierarchy?(*roles, &block)
user_roles = authorization_engine.roles_with_hierarchy_for(current_user)
result = roles.all? do |role|
user_roles.include?(role)
end
yield if result and block_given?
result
end
|
[
"def",
"has_role_with_hierarchy?",
"(",
"*",
"roles",
",",
"&",
"block",
")",
"user_roles",
"=",
"authorization_engine",
".",
"roles_with_hierarchy_for",
"(",
"current_user",
")",
"result",
"=",
"roles",
".",
"all?",
"do",
"|",
"role",
"|",
"user_roles",
".",
"include?",
"(",
"role",
")",
"end",
"yield",
"if",
"result",
"and",
"block_given?",
"result",
"end"
] |
As has_role? except checks all roles included in the role hierarchy
|
[
"As",
"has_role?",
"except",
"checks",
"all",
"roles",
"included",
"in",
"the",
"role",
"hierarchy"
] |
45e91af20eba71b2828c5c84066bcce3ef032e8a
|
https://github.com/stffn/declarative_authorization/blob/45e91af20eba71b2828c5c84066bcce3ef032e8a/lib/declarative_authorization/in_controller.rb#L85-L92
|
15,114
|
stffn/declarative_authorization
|
lib/declarative_authorization/in_controller.rb
|
Authorization.AuthorizationInController.has_any_role_with_hierarchy?
|
def has_any_role_with_hierarchy?(*roles, &block)
user_roles = authorization_engine.roles_with_hierarchy_for(current_user)
result = roles.any? do |role|
user_roles.include?(role)
end
yield if result and block_given?
result
end
|
ruby
|
def has_any_role_with_hierarchy?(*roles, &block)
user_roles = authorization_engine.roles_with_hierarchy_for(current_user)
result = roles.any? do |role|
user_roles.include?(role)
end
yield if result and block_given?
result
end
|
[
"def",
"has_any_role_with_hierarchy?",
"(",
"*",
"roles",
",",
"&",
"block",
")",
"user_roles",
"=",
"authorization_engine",
".",
"roles_with_hierarchy_for",
"(",
"current_user",
")",
"result",
"=",
"roles",
".",
"any?",
"do",
"|",
"role",
"|",
"user_roles",
".",
"include?",
"(",
"role",
")",
"end",
"yield",
"if",
"result",
"and",
"block_given?",
"result",
"end"
] |
As has_any_role? except checks all roles included in the role hierarchy
|
[
"As",
"has_any_role?",
"except",
"checks",
"all",
"roles",
"included",
"in",
"the",
"role",
"hierarchy"
] |
45e91af20eba71b2828c5c84066bcce3ef032e8a
|
https://github.com/stffn/declarative_authorization/blob/45e91af20eba71b2828c5c84066bcce3ef032e8a/lib/declarative_authorization/in_controller.rb#L95-L102
|
15,115
|
litaio/lita
|
lib/lita/room.rb
|
Lita.Room.save
|
def save
ensure_name_metadata_set
redis.pipelined do
redis.hmset("id:#{id}", *metadata.to_a.flatten)
redis.set("name:#{name}", id)
end
end
|
ruby
|
def save
ensure_name_metadata_set
redis.pipelined do
redis.hmset("id:#{id}", *metadata.to_a.flatten)
redis.set("name:#{name}", id)
end
end
|
[
"def",
"save",
"ensure_name_metadata_set",
"redis",
".",
"pipelined",
"do",
"redis",
".",
"hmset",
"(",
"\"id:#{id}\"",
",",
"metadata",
".",
"to_a",
".",
"flatten",
")",
"redis",
".",
"set",
"(",
"\"name:#{name}\"",
",",
"id",
")",
"end",
"end"
] |
Generates a +Fixnum+ hash value for this user object. Implemented to support equality.
@return [Fixnum] The hash value.
@see Object#hash
Saves the room record to Redis, overwriting any previous data for the current ID.
@return [void]
|
[
"Generates",
"a",
"+",
"Fixnum",
"+",
"hash",
"value",
"for",
"this",
"user",
"object",
".",
"Implemented",
"to",
"support",
"equality",
"."
] |
c1a1f85f791b74e40ee6a1e2d53f19b5f7cbe0ba
|
https://github.com/litaio/lita/blob/c1a1f85f791b74e40ee6a1e2d53f19b5f7cbe0ba/lib/lita/room.rb#L96-L103
|
15,116
|
litaio/lita
|
lib/lita/robot.rb
|
Lita.Robot.join
|
def join(room)
room_object = find_room(room)
if room_object
redis.sadd("persisted_rooms", room_object.id)
adapter.join(room_object.id)
else
adapter.join(room)
end
end
|
ruby
|
def join(room)
room_object = find_room(room)
if room_object
redis.sadd("persisted_rooms", room_object.id)
adapter.join(room_object.id)
else
adapter.join(room)
end
end
|
[
"def",
"join",
"(",
"room",
")",
"room_object",
"=",
"find_room",
"(",
"room",
")",
"if",
"room_object",
"redis",
".",
"sadd",
"(",
"\"persisted_rooms\"",
",",
"room_object",
".",
"id",
")",
"adapter",
".",
"join",
"(",
"room_object",
".",
"id",
")",
"else",
"adapter",
".",
"join",
"(",
"room",
")",
"end",
"end"
] |
Makes the robot join a room with the specified ID.
@param room [Room, String] The room to join, as a {Room} object or a string identifier.
@return [void]
@since 3.0.0
|
[
"Makes",
"the",
"robot",
"join",
"a",
"room",
"with",
"the",
"specified",
"ID",
"."
] |
c1a1f85f791b74e40ee6a1e2d53f19b5f7cbe0ba
|
https://github.com/litaio/lita/blob/c1a1f85f791b74e40ee6a1e2d53f19b5f7cbe0ba/lib/lita/robot.rb#L115-L124
|
15,117
|
litaio/lita
|
lib/lita/robot.rb
|
Lita.Robot.part
|
def part(room)
room_object = find_room(room)
if room_object
redis.srem("persisted_rooms", room_object.id)
adapter.part(room_object.id)
else
adapter.part(room)
end
end
|
ruby
|
def part(room)
room_object = find_room(room)
if room_object
redis.srem("persisted_rooms", room_object.id)
adapter.part(room_object.id)
else
adapter.part(room)
end
end
|
[
"def",
"part",
"(",
"room",
")",
"room_object",
"=",
"find_room",
"(",
"room",
")",
"if",
"room_object",
"redis",
".",
"srem",
"(",
"\"persisted_rooms\"",
",",
"room_object",
".",
"id",
")",
"adapter",
".",
"part",
"(",
"room_object",
".",
"id",
")",
"else",
"adapter",
".",
"part",
"(",
"room",
")",
"end",
"end"
] |
Makes the robot part from the room with the specified ID.
@param room [Room, String] The room to leave, as a {Room} object or a string identifier.
@return [void]
@since 3.0.0
|
[
"Makes",
"the",
"robot",
"part",
"from",
"the",
"room",
"with",
"the",
"specified",
"ID",
"."
] |
c1a1f85f791b74e40ee6a1e2d53f19b5f7cbe0ba
|
https://github.com/litaio/lita/blob/c1a1f85f791b74e40ee6a1e2d53f19b5f7cbe0ba/lib/lita/robot.rb#L130-L139
|
15,118
|
litaio/lita
|
lib/lita/robot.rb
|
Lita.Robot.send_messages_with_mention
|
def send_messages_with_mention(target, *strings)
return send_messages(target, *strings) if target.private_message?
mention_name = target.user.mention_name
prefixed_strings = strings.map do |s|
"#{adapter.mention_format(mention_name).strip} #{s}"
end
send_messages(target, *prefixed_strings)
end
|
ruby
|
def send_messages_with_mention(target, *strings)
return send_messages(target, *strings) if target.private_message?
mention_name = target.user.mention_name
prefixed_strings = strings.map do |s|
"#{adapter.mention_format(mention_name).strip} #{s}"
end
send_messages(target, *prefixed_strings)
end
|
[
"def",
"send_messages_with_mention",
"(",
"target",
",",
"*",
"strings",
")",
"return",
"send_messages",
"(",
"target",
",",
"strings",
")",
"if",
"target",
".",
"private_message?",
"mention_name",
"=",
"target",
".",
"user",
".",
"mention_name",
"prefixed_strings",
"=",
"strings",
".",
"map",
"do",
"|",
"s",
"|",
"\"#{adapter.mention_format(mention_name).strip} #{s}\"",
"end",
"send_messages",
"(",
"target",
",",
"prefixed_strings",
")",
"end"
] |
Sends one or more messages to a user or room. If sending to a room,
prefixes each message with the user's mention name.
@param target [Source] The user or room to send to. If the Source
has a room, it will choose the room. Otherwise, it will send to the
user.
@param strings [String, Array<String>] One or more strings to send.
@return [void]
@since 3.1.0
|
[
"Sends",
"one",
"or",
"more",
"messages",
"to",
"a",
"user",
"or",
"room",
".",
"If",
"sending",
"to",
"a",
"room",
"prefixes",
"each",
"message",
"with",
"the",
"user",
"s",
"mention",
"name",
"."
] |
c1a1f85f791b74e40ee6a1e2d53f19b5f7cbe0ba
|
https://github.com/litaio/lita/blob/c1a1f85f791b74e40ee6a1e2d53f19b5f7cbe0ba/lib/lita/robot.rb#L167-L176
|
15,119
|
litaio/lita
|
lib/lita/robot.rb
|
Lita.Robot.trigger
|
def trigger(event_name, payload = {})
handlers.each do |handler|
next unless handler.respond_to?(:trigger)
handler.trigger(self, event_name, payload)
end
end
|
ruby
|
def trigger(event_name, payload = {})
handlers.each do |handler|
next unless handler.respond_to?(:trigger)
handler.trigger(self, event_name, payload)
end
end
|
[
"def",
"trigger",
"(",
"event_name",
",",
"payload",
"=",
"{",
"}",
")",
"handlers",
".",
"each",
"do",
"|",
"handler",
"|",
"next",
"unless",
"handler",
".",
"respond_to?",
"(",
":trigger",
")",
"handler",
".",
"trigger",
"(",
"self",
",",
"event_name",
",",
"payload",
")",
"end",
"end"
] |
Triggers an event, instructing all registered handlers to invoke any
methods subscribed to the event, and passing them a payload hash of
arbitrary data.
@param event_name [String, Symbol] The name of the event to trigger.
@param payload [Hash] An optional hash of arbitrary data.
@return [void]
|
[
"Triggers",
"an",
"event",
"instructing",
"all",
"registered",
"handlers",
"to",
"invoke",
"any",
"methods",
"subscribed",
"to",
"the",
"event",
"and",
"passing",
"them",
"a",
"payload",
"hash",
"of",
"arbitrary",
"data",
"."
] |
c1a1f85f791b74e40ee6a1e2d53f19b5f7cbe0ba
|
https://github.com/litaio/lita/blob/c1a1f85f791b74e40ee6a1e2d53f19b5f7cbe0ba/lib/lita/robot.rb#L205-L211
|
15,120
|
litaio/lita
|
lib/lita/robot.rb
|
Lita.Robot.load_adapter
|
def load_adapter
adapter_name = config.robot.adapter
adapter_class = adapters[adapter_name.to_sym]
unless adapter_class
logger.fatal I18n.t("lita.robot.unknown_adapter", adapter: adapter_name)
abort
end
adapter_class.new(self)
end
|
ruby
|
def load_adapter
adapter_name = config.robot.adapter
adapter_class = adapters[adapter_name.to_sym]
unless adapter_class
logger.fatal I18n.t("lita.robot.unknown_adapter", adapter: adapter_name)
abort
end
adapter_class.new(self)
end
|
[
"def",
"load_adapter",
"adapter_name",
"=",
"config",
".",
"robot",
".",
"adapter",
"adapter_class",
"=",
"adapters",
"[",
"adapter_name",
".",
"to_sym",
"]",
"unless",
"adapter_class",
"logger",
".",
"fatal",
"I18n",
".",
"t",
"(",
"\"lita.robot.unknown_adapter\"",
",",
"adapter",
":",
"adapter_name",
")",
"abort",
"end",
"adapter_class",
".",
"new",
"(",
"self",
")",
"end"
] |
Loads the selected adapter.
|
[
"Loads",
"the",
"selected",
"adapter",
"."
] |
c1a1f85f791b74e40ee6a1e2d53f19b5f7cbe0ba
|
https://github.com/litaio/lita/blob/c1a1f85f791b74e40ee6a1e2d53f19b5f7cbe0ba/lib/lita/robot.rb#L231-L241
|
15,121
|
litaio/lita
|
lib/lita/robot.rb
|
Lita.Robot.run_app
|
def run_app
http_config = config.http
@server_thread = Thread.new do
@server = Puma::Server.new(app)
begin
@server.add_tcp_listener(http_config.host, http_config.port.to_i)
rescue Errno::EADDRINUSE, Errno::EACCES => e
logger.fatal I18n.t(
"lita.http.exception",
message: e.message,
backtrace: e.backtrace.join("\n")
)
abort
end
@server.min_threads = http_config.min_threads
@server.max_threads = http_config.max_threads
@server.run
end
@server_thread.abort_on_exception = true
end
|
ruby
|
def run_app
http_config = config.http
@server_thread = Thread.new do
@server = Puma::Server.new(app)
begin
@server.add_tcp_listener(http_config.host, http_config.port.to_i)
rescue Errno::EADDRINUSE, Errno::EACCES => e
logger.fatal I18n.t(
"lita.http.exception",
message: e.message,
backtrace: e.backtrace.join("\n")
)
abort
end
@server.min_threads = http_config.min_threads
@server.max_threads = http_config.max_threads
@server.run
end
@server_thread.abort_on_exception = true
end
|
[
"def",
"run_app",
"http_config",
"=",
"config",
".",
"http",
"@server_thread",
"=",
"Thread",
".",
"new",
"do",
"@server",
"=",
"Puma",
"::",
"Server",
".",
"new",
"(",
"app",
")",
"begin",
"@server",
".",
"add_tcp_listener",
"(",
"http_config",
".",
"host",
",",
"http_config",
".",
"port",
".",
"to_i",
")",
"rescue",
"Errno",
"::",
"EADDRINUSE",
",",
"Errno",
"::",
"EACCES",
"=>",
"e",
"logger",
".",
"fatal",
"I18n",
".",
"t",
"(",
"\"lita.http.exception\"",
",",
"message",
":",
"e",
".",
"message",
",",
"backtrace",
":",
"e",
".",
"backtrace",
".",
"join",
"(",
"\"\\n\"",
")",
")",
"abort",
"end",
"@server",
".",
"min_threads",
"=",
"http_config",
".",
"min_threads",
"@server",
".",
"max_threads",
"=",
"http_config",
".",
"max_threads",
"@server",
".",
"run",
"end",
"@server_thread",
".",
"abort_on_exception",
"=",
"true",
"end"
] |
Starts the web server.
|
[
"Starts",
"the",
"web",
"server",
"."
] |
c1a1f85f791b74e40ee6a1e2d53f19b5f7cbe0ba
|
https://github.com/litaio/lita/blob/c1a1f85f791b74e40ee6a1e2d53f19b5f7cbe0ba/lib/lita/robot.rb#L244-L265
|
15,122
|
litaio/lita
|
lib/lita/http_route.rb
|
Lita.HTTPRoute.register_route
|
def register_route(http_method, path, callback, options)
route = new_route(http_method, path, callback, options)
route.to(HTTPCallback.new(handler_class, callback))
handler_class.http_routes << route
end
|
ruby
|
def register_route(http_method, path, callback, options)
route = new_route(http_method, path, callback, options)
route.to(HTTPCallback.new(handler_class, callback))
handler_class.http_routes << route
end
|
[
"def",
"register_route",
"(",
"http_method",
",",
"path",
",",
"callback",
",",
"options",
")",
"route",
"=",
"new_route",
"(",
"http_method",
",",
"path",
",",
"callback",
",",
"options",
")",
"route",
".",
"to",
"(",
"HTTPCallback",
".",
"new",
"(",
"handler_class",
",",
"callback",
")",
")",
"handler_class",
".",
"http_routes",
"<<",
"route",
"end"
] |
Adds a new HTTP route for the handler.
|
[
"Adds",
"a",
"new",
"HTTP",
"route",
"for",
"the",
"handler",
"."
] |
c1a1f85f791b74e40ee6a1e2d53f19b5f7cbe0ba
|
https://github.com/litaio/lita/blob/c1a1f85f791b74e40ee6a1e2d53f19b5f7cbe0ba/lib/lita/http_route.rb#L66-L70
|
15,123
|
litaio/lita
|
lib/lita/http_route.rb
|
Lita.HTTPRoute.new_route
|
def new_route(http_method, path, callback, options)
route = ExtendedRoute.new
route.path = path
route.name = callback.method_name
route.add_match_with(options)
route.add_request_method(http_method)
route.add_request_method("HEAD") if http_method == "GET"
route
end
|
ruby
|
def new_route(http_method, path, callback, options)
route = ExtendedRoute.new
route.path = path
route.name = callback.method_name
route.add_match_with(options)
route.add_request_method(http_method)
route.add_request_method("HEAD") if http_method == "GET"
route
end
|
[
"def",
"new_route",
"(",
"http_method",
",",
"path",
",",
"callback",
",",
"options",
")",
"route",
"=",
"ExtendedRoute",
".",
"new",
"route",
".",
"path",
"=",
"path",
"route",
".",
"name",
"=",
"callback",
".",
"method_name",
"route",
".",
"add_match_with",
"(",
"options",
")",
"route",
".",
"add_request_method",
"(",
"http_method",
")",
"route",
".",
"add_request_method",
"(",
"\"HEAD\"",
")",
"if",
"http_method",
"==",
"\"GET\"",
"route",
"end"
] |
Creates and configures a new HTTP route.
|
[
"Creates",
"and",
"configures",
"a",
"new",
"HTTP",
"route",
"."
] |
c1a1f85f791b74e40ee6a1e2d53f19b5f7cbe0ba
|
https://github.com/litaio/lita/blob/c1a1f85f791b74e40ee6a1e2d53f19b5f7cbe0ba/lib/lita/http_route.rb#L73-L81
|
15,124
|
litaio/lita
|
lib/lita/user.rb
|
Lita.User.save
|
def save
mention_name = metadata[:mention_name] || metadata["mention_name"]
current_keys = metadata.keys
redis_keys = redis.hkeys("id:#{id}")
delete_keys = (redis_keys - current_keys)
redis.pipelined do
redis.hdel("id:#{id}", *delete_keys) if delete_keys.any?
redis.hmset("id:#{id}", *metadata.to_a.flatten)
redis.set("name:#{name}", id)
redis.set("mention_name:#{mention_name}", id) if mention_name
end
end
|
ruby
|
def save
mention_name = metadata[:mention_name] || metadata["mention_name"]
current_keys = metadata.keys
redis_keys = redis.hkeys("id:#{id}")
delete_keys = (redis_keys - current_keys)
redis.pipelined do
redis.hdel("id:#{id}", *delete_keys) if delete_keys.any?
redis.hmset("id:#{id}", *metadata.to_a.flatten)
redis.set("name:#{name}", id)
redis.set("mention_name:#{mention_name}", id) if mention_name
end
end
|
[
"def",
"save",
"mention_name",
"=",
"metadata",
"[",
":mention_name",
"]",
"||",
"metadata",
"[",
"\"mention_name\"",
"]",
"current_keys",
"=",
"metadata",
".",
"keys",
"redis_keys",
"=",
"redis",
".",
"hkeys",
"(",
"\"id:#{id}\"",
")",
"delete_keys",
"=",
"(",
"redis_keys",
"-",
"current_keys",
")",
"redis",
".",
"pipelined",
"do",
"redis",
".",
"hdel",
"(",
"\"id:#{id}\"",
",",
"delete_keys",
")",
"if",
"delete_keys",
".",
"any?",
"redis",
".",
"hmset",
"(",
"\"id:#{id}\"",
",",
"metadata",
".",
"to_a",
".",
"flatten",
")",
"redis",
".",
"set",
"(",
"\"name:#{name}\"",
",",
"id",
")",
"redis",
".",
"set",
"(",
"\"mention_name:#{mention_name}\"",
",",
"id",
")",
"if",
"mention_name",
"end",
"end"
] |
Saves the user record to Redis, overwriting any previous data for the
current ID and user name.
@return [void]
|
[
"Saves",
"the",
"user",
"record",
"to",
"Redis",
"overwriting",
"any",
"previous",
"data",
"for",
"the",
"current",
"ID",
"and",
"user",
"name",
"."
] |
c1a1f85f791b74e40ee6a1e2d53f19b5f7cbe0ba
|
https://github.com/litaio/lita/blob/c1a1f85f791b74e40ee6a1e2d53f19b5f7cbe0ba/lib/lita/user.rb#L112-L125
|
15,125
|
litaio/lita
|
lib/lita/message.rb
|
Lita.Message.reply_privately
|
def reply_privately(*strings)
private_source = source.clone
private_source.private_message!
@robot.send_messages(private_source, *strings)
end
|
ruby
|
def reply_privately(*strings)
private_source = source.clone
private_source.private_message!
@robot.send_messages(private_source, *strings)
end
|
[
"def",
"reply_privately",
"(",
"*",
"strings",
")",
"private_source",
"=",
"source",
".",
"clone",
"private_source",
".",
"private_message!",
"@robot",
".",
"send_messages",
"(",
"private_source",
",",
"strings",
")",
"end"
] |
Replies by sending the given strings back to the user who sent the
message directly, even if the message was sent in a room.
@param strings [String, Array<String>] The strings to send back.
@return [void]
|
[
"Replies",
"by",
"sending",
"the",
"given",
"strings",
"back",
"to",
"the",
"user",
"who",
"sent",
"the",
"message",
"directly",
"even",
"if",
"the",
"message",
"was",
"sent",
"in",
"a",
"room",
"."
] |
c1a1f85f791b74e40ee6a1e2d53f19b5f7cbe0ba
|
https://github.com/litaio/lita/blob/c1a1f85f791b74e40ee6a1e2d53f19b5f7cbe0ba/lib/lita/message.rb#L108-L112
|
15,126
|
litaio/lita
|
lib/lita/configuration_validator.rb
|
Lita.ConfigurationValidator.validate
|
def validate(type, plugin, attributes, attribute_namespace = [])
attributes.each do |attribute|
if attribute.children?
validate(type, plugin, attribute.children, attribute_namespace.clone.push(attribute.name))
elsif attribute.required? && attribute.value.nil?
registry.logger.fatal I18n.t(
"lita.config.missing_required_#{type}_attribute",
type => plugin.namespace,
attribute: full_attribute_name(attribute_namespace, attribute.name)
)
abort
end
end
end
|
ruby
|
def validate(type, plugin, attributes, attribute_namespace = [])
attributes.each do |attribute|
if attribute.children?
validate(type, plugin, attribute.children, attribute_namespace.clone.push(attribute.name))
elsif attribute.required? && attribute.value.nil?
registry.logger.fatal I18n.t(
"lita.config.missing_required_#{type}_attribute",
type => plugin.namespace,
attribute: full_attribute_name(attribute_namespace, attribute.name)
)
abort
end
end
end
|
[
"def",
"validate",
"(",
"type",
",",
"plugin",
",",
"attributes",
",",
"attribute_namespace",
"=",
"[",
"]",
")",
"attributes",
".",
"each",
"do",
"|",
"attribute",
"|",
"if",
"attribute",
".",
"children?",
"validate",
"(",
"type",
",",
"plugin",
",",
"attribute",
".",
"children",
",",
"attribute_namespace",
".",
"clone",
".",
"push",
"(",
"attribute",
".",
"name",
")",
")",
"elsif",
"attribute",
".",
"required?",
"&&",
"attribute",
".",
"value",
".",
"nil?",
"registry",
".",
"logger",
".",
"fatal",
"I18n",
".",
"t",
"(",
"\"lita.config.missing_required_#{type}_attribute\"",
",",
"type",
"=>",
"plugin",
".",
"namespace",
",",
"attribute",
":",
"full_attribute_name",
"(",
"attribute_namespace",
",",
"attribute",
".",
"name",
")",
")",
"abort",
"end",
"end",
"end"
] |
Validates an array of attributes, recursing if any nested attributes are encountered.
|
[
"Validates",
"an",
"array",
"of",
"attributes",
"recursing",
"if",
"any",
"nested",
"attributes",
"are",
"encountered",
"."
] |
c1a1f85f791b74e40ee6a1e2d53f19b5f7cbe0ba
|
https://github.com/litaio/lita/blob/c1a1f85f791b74e40ee6a1e2d53f19b5f7cbe0ba/lib/lita/configuration_validator.rb#L57-L70
|
15,127
|
litaio/lita
|
lib/lita/default_configuration.rb
|
Lita.DefaultConfiguration.adapters_config
|
def adapters_config
adapters = registry.adapters
root.config :adapters do
adapters.each do |key, adapter|
combine(key, adapter.configuration_builder)
end
end
end
|
ruby
|
def adapters_config
adapters = registry.adapters
root.config :adapters do
adapters.each do |key, adapter|
combine(key, adapter.configuration_builder)
end
end
end
|
[
"def",
"adapters_config",
"adapters",
"=",
"registry",
".",
"adapters",
"root",
".",
"config",
":adapters",
"do",
"adapters",
".",
"each",
"do",
"|",
"key",
",",
"adapter",
"|",
"combine",
"(",
"key",
",",
"adapter",
".",
"configuration_builder",
")",
"end",
"end",
"end"
] |
Builds config.adapters
|
[
"Builds",
"config",
".",
"adapters"
] |
c1a1f85f791b74e40ee6a1e2d53f19b5f7cbe0ba
|
https://github.com/litaio/lita/blob/c1a1f85f791b74e40ee6a1e2d53f19b5f7cbe0ba/lib/lita/default_configuration.rb#L43-L51
|
15,128
|
litaio/lita
|
lib/lita/default_configuration.rb
|
Lita.DefaultConfiguration.handlers_config
|
def handlers_config
handlers = registry.handlers
root.config :handlers do
handlers.each do |handler|
if handler.configuration_builder.children?
combine(handler.namespace, handler.configuration_builder)
end
end
end
end
|
ruby
|
def handlers_config
handlers = registry.handlers
root.config :handlers do
handlers.each do |handler|
if handler.configuration_builder.children?
combine(handler.namespace, handler.configuration_builder)
end
end
end
end
|
[
"def",
"handlers_config",
"handlers",
"=",
"registry",
".",
"handlers",
"root",
".",
"config",
":handlers",
"do",
"handlers",
".",
"each",
"do",
"|",
"handler",
"|",
"if",
"handler",
".",
"configuration_builder",
".",
"children?",
"combine",
"(",
"handler",
".",
"namespace",
",",
"handler",
".",
"configuration_builder",
")",
"end",
"end",
"end",
"end"
] |
Builds config.handlers
|
[
"Builds",
"config",
".",
"handlers"
] |
c1a1f85f791b74e40ee6a1e2d53f19b5f7cbe0ba
|
https://github.com/litaio/lita/blob/c1a1f85f791b74e40ee6a1e2d53f19b5f7cbe0ba/lib/lita/default_configuration.rb#L54-L64
|
15,129
|
litaio/lita
|
lib/lita/default_configuration.rb
|
Lita.DefaultConfiguration.http_config
|
def http_config
root.config :http do
config :host, type: String, default: "0.0.0.0"
config :port, type: [Integer, String], default: 8080
config :min_threads, type: [Integer, String], default: 0
config :max_threads, type: [Integer, String], default: 16
config :middleware, type: MiddlewareRegistry, default: MiddlewareRegistry.new
end
end
|
ruby
|
def http_config
root.config :http do
config :host, type: String, default: "0.0.0.0"
config :port, type: [Integer, String], default: 8080
config :min_threads, type: [Integer, String], default: 0
config :max_threads, type: [Integer, String], default: 16
config :middleware, type: MiddlewareRegistry, default: MiddlewareRegistry.new
end
end
|
[
"def",
"http_config",
"root",
".",
"config",
":http",
"do",
"config",
":host",
",",
"type",
":",
"String",
",",
"default",
":",
"\"0.0.0.0\"",
"config",
":port",
",",
"type",
":",
"[",
"Integer",
",",
"String",
"]",
",",
"default",
":",
"8080",
"config",
":min_threads",
",",
"type",
":",
"[",
"Integer",
",",
"String",
"]",
",",
"default",
":",
"0",
"config",
":max_threads",
",",
"type",
":",
"[",
"Integer",
",",
"String",
"]",
",",
"default",
":",
"16",
"config",
":middleware",
",",
"type",
":",
"MiddlewareRegistry",
",",
"default",
":",
"MiddlewareRegistry",
".",
"new",
"end",
"end"
] |
Builds config.http
|
[
"Builds",
"config",
".",
"http"
] |
c1a1f85f791b74e40ee6a1e2d53f19b5f7cbe0ba
|
https://github.com/litaio/lita/blob/c1a1f85f791b74e40ee6a1e2d53f19b5f7cbe0ba/lib/lita/default_configuration.rb#L67-L75
|
15,130
|
litaio/lita
|
lib/lita/default_configuration.rb
|
Lita.DefaultConfiguration.robot_config
|
def robot_config
root.config :robot do
config :name, type: String, default: "Lita"
config :mention_name, type: String
config :alias, type: String
config :adapter, types: [String, Symbol], default: :shell
config :locale, types: [String, Symbol], default: I18n.locale
config :log_level, types: [String, Symbol], default: :info do
validate do |value|
unless LOG_LEVELS.include?(value.to_s.downcase.strip)
"must be one of: #{LOG_LEVELS.join(', ')}"
end
end
end
config :log_formatter, type: Proc, default: (lambda do |severity, datetime, _progname, msg|
"[#{datetime.utc}] #{severity}: #{msg}\n"
end)
config :admins
config :error_handler, default: ->(_error, _metadata) {} do
validate do |value|
"must respond to #call" unless value.respond_to?(:call)
end
end
end
end
|
ruby
|
def robot_config
root.config :robot do
config :name, type: String, default: "Lita"
config :mention_name, type: String
config :alias, type: String
config :adapter, types: [String, Symbol], default: :shell
config :locale, types: [String, Symbol], default: I18n.locale
config :log_level, types: [String, Symbol], default: :info do
validate do |value|
unless LOG_LEVELS.include?(value.to_s.downcase.strip)
"must be one of: #{LOG_LEVELS.join(', ')}"
end
end
end
config :log_formatter, type: Proc, default: (lambda do |severity, datetime, _progname, msg|
"[#{datetime.utc}] #{severity}: #{msg}\n"
end)
config :admins
config :error_handler, default: ->(_error, _metadata) {} do
validate do |value|
"must respond to #call" unless value.respond_to?(:call)
end
end
end
end
|
[
"def",
"robot_config",
"root",
".",
"config",
":robot",
"do",
"config",
":name",
",",
"type",
":",
"String",
",",
"default",
":",
"\"Lita\"",
"config",
":mention_name",
",",
"type",
":",
"String",
"config",
":alias",
",",
"type",
":",
"String",
"config",
":adapter",
",",
"types",
":",
"[",
"String",
",",
"Symbol",
"]",
",",
"default",
":",
":shell",
"config",
":locale",
",",
"types",
":",
"[",
"String",
",",
"Symbol",
"]",
",",
"default",
":",
"I18n",
".",
"locale",
"config",
":log_level",
",",
"types",
":",
"[",
"String",
",",
"Symbol",
"]",
",",
"default",
":",
":info",
"do",
"validate",
"do",
"|",
"value",
"|",
"unless",
"LOG_LEVELS",
".",
"include?",
"(",
"value",
".",
"to_s",
".",
"downcase",
".",
"strip",
")",
"\"must be one of: #{LOG_LEVELS.join(', ')}\"",
"end",
"end",
"end",
"config",
":log_formatter",
",",
"type",
":",
"Proc",
",",
"default",
":",
"(",
"lambda",
"do",
"|",
"severity",
",",
"datetime",
",",
"_progname",
",",
"msg",
"|",
"\"[#{datetime.utc}] #{severity}: #{msg}\\n\"",
"end",
")",
"config",
":admins",
"config",
":error_handler",
",",
"default",
":",
"->",
"(",
"_error",
",",
"_metadata",
")",
"{",
"}",
"do",
"validate",
"do",
"|",
"value",
"|",
"\"must respond to #call\"",
"unless",
"value",
".",
"respond_to?",
"(",
":call",
")",
"end",
"end",
"end",
"end"
] |
Builds config.robot
|
[
"Builds",
"config",
".",
"robot"
] |
c1a1f85f791b74e40ee6a1e2d53f19b5f7cbe0ba
|
https://github.com/litaio/lita/blob/c1a1f85f791b74e40ee6a1e2d53f19b5f7cbe0ba/lib/lita/default_configuration.rb#L83-L107
|
15,131
|
litaio/lita
|
lib/lita/configurable.rb
|
Lita.Configurable.config
|
def config(*args, **kwargs, &block)
if block
configuration_builder.config(*args, **kwargs, &block)
else
configuration_builder.config(*args, **kwargs)
end
end
|
ruby
|
def config(*args, **kwargs, &block)
if block
configuration_builder.config(*args, **kwargs, &block)
else
configuration_builder.config(*args, **kwargs)
end
end
|
[
"def",
"config",
"(",
"*",
"args",
",",
"**",
"kwargs",
",",
"&",
"block",
")",
"if",
"block",
"configuration_builder",
".",
"config",
"(",
"args",
",",
"**",
"kwargs",
",",
"block",
")",
"else",
"configuration_builder",
".",
"config",
"(",
"args",
",",
"**",
"kwargs",
")",
"end",
"end"
] |
Sets a configuration attribute on the plugin.
@return [void]
@since 4.0.0
@see ConfigurationBuilder#config
|
[
"Sets",
"a",
"configuration",
"attribute",
"on",
"the",
"plugin",
"."
] |
c1a1f85f791b74e40ee6a1e2d53f19b5f7cbe0ba
|
https://github.com/litaio/lita/blob/c1a1f85f791b74e40ee6a1e2d53f19b5f7cbe0ba/lib/lita/configurable.rb#L33-L39
|
15,132
|
litaio/lita
|
lib/lita/configuration_builder.rb
|
Lita.ConfigurationBuilder.config
|
def config(name, types: nil, type: nil, required: false, default: nil, &block)
attribute = self.class.new
attribute.name = name
attribute.types = types || type
attribute.required = required
attribute.value = default
attribute.instance_exec(&block) if block
children << attribute
end
|
ruby
|
def config(name, types: nil, type: nil, required: false, default: nil, &block)
attribute = self.class.new
attribute.name = name
attribute.types = types || type
attribute.required = required
attribute.value = default
attribute.instance_exec(&block) if block
children << attribute
end
|
[
"def",
"config",
"(",
"name",
",",
"types",
":",
"nil",
",",
"type",
":",
"nil",
",",
"required",
":",
"false",
",",
"default",
":",
"nil",
",",
"&",
"block",
")",
"attribute",
"=",
"self",
".",
"class",
".",
"new",
"attribute",
".",
"name",
"=",
"name",
"attribute",
".",
"types",
"=",
"types",
"||",
"type",
"attribute",
".",
"required",
"=",
"required",
"attribute",
".",
"value",
"=",
"default",
"attribute",
".",
"instance_exec",
"(",
"block",
")",
"if",
"block",
"children",
"<<",
"attribute",
"end"
] |
Declares a configuration attribute.
@param name [String, Symbol] The attribute's name.
@param types [Object, Array<Object>] Optional: One or more types that the attribute's value
must be.
@param type [Object, Array<Object>] Optional: One or more types that the attribute's value
must be.
@param required [Boolean] Whether or not this attribute must be set. If required, and Lita
is run without it set, Lita will abort on start up with a message about it.
@param default [Object] An optional default value for the attribute.
@yield A block to be evaluated in the context of the new attribute. Used for
defining nested configuration attributes and validators.
@return [void]
|
[
"Declares",
"a",
"configuration",
"attribute",
"."
] |
c1a1f85f791b74e40ee6a1e2d53f19b5f7cbe0ba
|
https://github.com/litaio/lita/blob/c1a1f85f791b74e40ee6a1e2d53f19b5f7cbe0ba/lib/lita/configuration_builder.rb#L131-L140
|
15,133
|
litaio/lita
|
lib/lita/configuration_builder.rb
|
Lita.ConfigurationBuilder.build_leaf
|
def build_leaf(object)
this = self
run_validator = method(:run_validator)
check_types = method(:check_types)
object.instance_exec do
define_singleton_method(this.name) { this.value }
define_singleton_method("#{this.name}=") do |value|
run_validator.call(value)
check_types.call(value)
this.value = value
end
end
object
end
|
ruby
|
def build_leaf(object)
this = self
run_validator = method(:run_validator)
check_types = method(:check_types)
object.instance_exec do
define_singleton_method(this.name) { this.value }
define_singleton_method("#{this.name}=") do |value|
run_validator.call(value)
check_types.call(value)
this.value = value
end
end
object
end
|
[
"def",
"build_leaf",
"(",
"object",
")",
"this",
"=",
"self",
"run_validator",
"=",
"method",
"(",
":run_validator",
")",
"check_types",
"=",
"method",
"(",
":check_types",
")",
"object",
".",
"instance_exec",
"do",
"define_singleton_method",
"(",
"this",
".",
"name",
")",
"{",
"this",
".",
"value",
"}",
"define_singleton_method",
"(",
"\"#{this.name}=\"",
")",
"do",
"|",
"value",
"|",
"run_validator",
".",
"call",
"(",
"value",
")",
"check_types",
".",
"call",
"(",
"value",
")",
"this",
".",
"value",
"=",
"value",
"end",
"end",
"object",
"end"
] |
Finalize a nested object.
|
[
"Finalize",
"a",
"nested",
"object",
"."
] |
c1a1f85f791b74e40ee6a1e2d53f19b5f7cbe0ba
|
https://github.com/litaio/lita/blob/c1a1f85f791b74e40ee6a1e2d53f19b5f7cbe0ba/lib/lita/configuration_builder.rb#L180-L195
|
15,134
|
litaio/lita
|
lib/lita/configuration_builder.rb
|
Lita.ConfigurationBuilder.build_nested
|
def build_nested(object)
this = self
nested_object = Configuration.new
children.each { |child| child.build(nested_object) }
object.instance_exec { define_singleton_method(this.name) { nested_object } }
object
end
|
ruby
|
def build_nested(object)
this = self
nested_object = Configuration.new
children.each { |child| child.build(nested_object) }
object.instance_exec { define_singleton_method(this.name) { nested_object } }
object
end
|
[
"def",
"build_nested",
"(",
"object",
")",
"this",
"=",
"self",
"nested_object",
"=",
"Configuration",
".",
"new",
"children",
".",
"each",
"{",
"|",
"child",
"|",
"child",
".",
"build",
"(",
"nested_object",
")",
"}",
"object",
".",
"instance_exec",
"{",
"define_singleton_method",
"(",
"this",
".",
"name",
")",
"{",
"nested_object",
"}",
"}",
"object",
"end"
] |
Finalize the root builder or any builder with children.
|
[
"Finalize",
"the",
"root",
"builder",
"or",
"any",
"builder",
"with",
"children",
"."
] |
c1a1f85f791b74e40ee6a1e2d53f19b5f7cbe0ba
|
https://github.com/litaio/lita/blob/c1a1f85f791b74e40ee6a1e2d53f19b5f7cbe0ba/lib/lita/configuration_builder.rb#L198-L206
|
15,135
|
litaio/lita
|
lib/lita/configuration_builder.rb
|
Lita.ConfigurationBuilder.check_types
|
def check_types(value)
if types&.none? { |type| type === value }
Lita.logger.fatal(
I18n.t("lita.config.type_error", attribute: name, types: types.join(", "))
)
raise ValidationError
end
end
|
ruby
|
def check_types(value)
if types&.none? { |type| type === value }
Lita.logger.fatal(
I18n.t("lita.config.type_error", attribute: name, types: types.join(", "))
)
raise ValidationError
end
end
|
[
"def",
"check_types",
"(",
"value",
")",
"if",
"types",
"&.",
"none?",
"{",
"|",
"type",
"|",
"type",
"===",
"value",
"}",
"Lita",
".",
"logger",
".",
"fatal",
"(",
"I18n",
".",
"t",
"(",
"\"lita.config.type_error\"",
",",
"attribute",
":",
"name",
",",
"types",
":",
"types",
".",
"join",
"(",
"\", \"",
")",
")",
")",
"raise",
"ValidationError",
"end",
"end"
] |
Check's the value's type from inside the finalized object.
|
[
"Check",
"s",
"the",
"value",
"s",
"type",
"from",
"inside",
"the",
"finalized",
"object",
"."
] |
c1a1f85f791b74e40ee6a1e2d53f19b5f7cbe0ba
|
https://github.com/litaio/lita/blob/c1a1f85f791b74e40ee6a1e2d53f19b5f7cbe0ba/lib/lita/configuration_builder.rb#L209-L217
|
15,136
|
litaio/lita
|
lib/lita/rack_app.rb
|
Lita.RackApp.recognize
|
def recognize(env)
env["lita.robot"] = robot
recognized_routes_for(env).map { |match| match.route.name }
end
|
ruby
|
def recognize(env)
env["lita.robot"] = robot
recognized_routes_for(env).map { |match| match.route.name }
end
|
[
"def",
"recognize",
"(",
"env",
")",
"env",
"[",
"\"lita.robot\"",
"]",
"=",
"robot",
"recognized_routes_for",
"(",
"env",
")",
".",
"map",
"{",
"|",
"match",
"|",
"match",
".",
"route",
".",
"name",
"}",
"end"
] |
Finds the first route that matches the request environment, if any. Does not trigger the
route.
@param env [Hash] A Rack environment.
@return [Array] An array of the name of the first matching route.
@since 4.0.0
|
[
"Finds",
"the",
"first",
"route",
"that",
"matches",
"the",
"request",
"environment",
"if",
"any",
".",
"Does",
"not",
"trigger",
"the",
"route",
"."
] |
c1a1f85f791b74e40ee6a1e2d53f19b5f7cbe0ba
|
https://github.com/litaio/lita/blob/c1a1f85f791b74e40ee6a1e2d53f19b5f7cbe0ba/lib/lita/rack_app.rb#L62-L65
|
15,137
|
litaio/lita
|
lib/lita/rack_app.rb
|
Lita.RackApp.compile
|
def compile
robot.handlers.each do |handler|
next unless handler.respond_to?(:http_routes)
handler.http_routes.each { |route| router.add_route(route) }
end
end
|
ruby
|
def compile
robot.handlers.each do |handler|
next unless handler.respond_to?(:http_routes)
handler.http_routes.each { |route| router.add_route(route) }
end
end
|
[
"def",
"compile",
"robot",
".",
"handlers",
".",
"each",
"do",
"|",
"handler",
"|",
"next",
"unless",
"handler",
".",
"respond_to?",
"(",
":http_routes",
")",
"handler",
".",
"http_routes",
".",
"each",
"{",
"|",
"route",
"|",
"router",
".",
"add_route",
"(",
"route",
")",
"}",
"end",
"end"
] |
Registers routes in the router for each handler's defined routes.
|
[
"Registers",
"routes",
"in",
"the",
"router",
"for",
"each",
"handler",
"s",
"defined",
"routes",
"."
] |
c1a1f85f791b74e40ee6a1e2d53f19b5f7cbe0ba
|
https://github.com/litaio/lita/blob/c1a1f85f791b74e40ee6a1e2d53f19b5f7cbe0ba/lib/lita/rack_app.rb#L70-L76
|
15,138
|
litaio/lita
|
lib/lita/authorization.rb
|
Lita.Authorization.user_in_group?
|
def user_in_group?(user, group)
group = normalize_group(group)
return user_is_admin?(user) if group == "admins"
redis.sismember(group, user.id)
end
|
ruby
|
def user_in_group?(user, group)
group = normalize_group(group)
return user_is_admin?(user) if group == "admins"
redis.sismember(group, user.id)
end
|
[
"def",
"user_in_group?",
"(",
"user",
",",
"group",
")",
"group",
"=",
"normalize_group",
"(",
"group",
")",
"return",
"user_is_admin?",
"(",
"user",
")",
"if",
"group",
"==",
"\"admins\"",
"redis",
".",
"sismember",
"(",
"group",
",",
"user",
".",
"id",
")",
"end"
] |
Checks if a user is in an authorization group.
@param user [User] The user.
@param group [Symbol, String] The name of the group.
@return [Boolean] Whether or not the user is in the group.
|
[
"Checks",
"if",
"a",
"user",
"is",
"in",
"an",
"authorization",
"group",
"."
] |
c1a1f85f791b74e40ee6a1e2d53f19b5f7cbe0ba
|
https://github.com/litaio/lita/blob/c1a1f85f791b74e40ee6a1e2d53f19b5f7cbe0ba/lib/lita/authorization.rb#L66-L70
|
15,139
|
litaio/lita
|
lib/lita/authorization.rb
|
Lita.Authorization.user_is_admin?
|
def user_is_admin?(user)
Array(robot.config.robot.admins).include?(user.id)
end
|
ruby
|
def user_is_admin?(user)
Array(robot.config.robot.admins).include?(user.id)
end
|
[
"def",
"user_is_admin?",
"(",
"user",
")",
"Array",
"(",
"robot",
".",
"config",
".",
"robot",
".",
"admins",
")",
".",
"include?",
"(",
"user",
".",
"id",
")",
"end"
] |
Checks if a user is an administrator.
@param user [User] The user.
@return [Boolean] Whether or not the user is an administrator.
|
[
"Checks",
"if",
"a",
"user",
"is",
"an",
"administrator",
"."
] |
c1a1f85f791b74e40ee6a1e2d53f19b5f7cbe0ba
|
https://github.com/litaio/lita/blob/c1a1f85f791b74e40ee6a1e2d53f19b5f7cbe0ba/lib/lita/authorization.rb#L75-L77
|
15,140
|
litaio/lita
|
lib/lita/authorization.rb
|
Lita.Authorization.groups_with_users
|
def groups_with_users
groups.reduce({}) do |list, group|
list[group] = redis.smembers(group).map do |user_id|
User.find_by_id(user_id)
end
list
end
end
|
ruby
|
def groups_with_users
groups.reduce({}) do |list, group|
list[group] = redis.smembers(group).map do |user_id|
User.find_by_id(user_id)
end
list
end
end
|
[
"def",
"groups_with_users",
"groups",
".",
"reduce",
"(",
"{",
"}",
")",
"do",
"|",
"list",
",",
"group",
"|",
"list",
"[",
"group",
"]",
"=",
"redis",
".",
"smembers",
"(",
"group",
")",
".",
"map",
"do",
"|",
"user_id",
"|",
"User",
".",
"find_by_id",
"(",
"user_id",
")",
"end",
"list",
"end",
"end"
] |
Returns a hash of authorization group names and the users in them.
@return [Hash] A map of +Symbol+ group names to {User} objects.
|
[
"Returns",
"a",
"hash",
"of",
"authorization",
"group",
"names",
"and",
"the",
"users",
"in",
"them",
"."
] |
c1a1f85f791b74e40ee6a1e2d53f19b5f7cbe0ba
|
https://github.com/litaio/lita/blob/c1a1f85f791b74e40ee6a1e2d53f19b5f7cbe0ba/lib/lita/authorization.rb#L87-L94
|
15,141
|
litaio/lita
|
lib/lita/route_validator.rb
|
Lita.RouteValidator.passes_route_hooks?
|
def passes_route_hooks?(route, message, robot)
robot.hooks[:validate_route].all? do |hook|
hook.call(handler: handler, route: route, message: message, robot: robot)
end
end
|
ruby
|
def passes_route_hooks?(route, message, robot)
robot.hooks[:validate_route].all? do |hook|
hook.call(handler: handler, route: route, message: message, robot: robot)
end
end
|
[
"def",
"passes_route_hooks?",
"(",
"route",
",",
"message",
",",
"robot",
")",
"robot",
".",
"hooks",
"[",
":validate_route",
"]",
".",
"all?",
"do",
"|",
"hook",
"|",
"hook",
".",
"call",
"(",
"handler",
":",
"handler",
",",
"route",
":",
"route",
",",
"message",
":",
"message",
",",
"robot",
":",
"robot",
")",
"end",
"end"
] |
Allow custom route hooks to reject the route
|
[
"Allow",
"custom",
"route",
"hooks",
"to",
"reject",
"the",
"route"
] |
c1a1f85f791b74e40ee6a1e2d53f19b5f7cbe0ba
|
https://github.com/litaio/lita/blob/c1a1f85f791b74e40ee6a1e2d53f19b5f7cbe0ba/lib/lita/route_validator.rb#L68-L72
|
15,142
|
litaio/lita
|
lib/lita/route_validator.rb
|
Lita.RouteValidator.authorized?
|
def authorized?(robot, user, required_groups)
required_groups.nil? || required_groups.any? do |group|
robot.auth.user_in_group?(user, group)
end
end
|
ruby
|
def authorized?(robot, user, required_groups)
required_groups.nil? || required_groups.any? do |group|
robot.auth.user_in_group?(user, group)
end
end
|
[
"def",
"authorized?",
"(",
"robot",
",",
"user",
",",
"required_groups",
")",
"required_groups",
".",
"nil?",
"||",
"required_groups",
".",
"any?",
"do",
"|",
"group",
"|",
"robot",
".",
"auth",
".",
"user_in_group?",
"(",
"user",
",",
"group",
")",
"end",
"end"
] |
User must be in auth group if route is restricted.
|
[
"User",
"must",
"be",
"in",
"auth",
"group",
"if",
"route",
"is",
"restricted",
"."
] |
c1a1f85f791b74e40ee6a1e2d53f19b5f7cbe0ba
|
https://github.com/litaio/lita/blob/c1a1f85f791b74e40ee6a1e2d53f19b5f7cbe0ba/lib/lita/route_validator.rb#L75-L79
|
15,143
|
litaio/lita
|
lib/lita/template.rb
|
Lita.Template.context_binding
|
def context_binding(variables)
context = TemplateEvaluationContext.new
helpers.each { |helper| context.extend(helper) }
variables.each do |k, v|
context.instance_variable_set("@#{k}", v)
end
context.__get_binding
end
|
ruby
|
def context_binding(variables)
context = TemplateEvaluationContext.new
helpers.each { |helper| context.extend(helper) }
variables.each do |k, v|
context.instance_variable_set("@#{k}", v)
end
context.__get_binding
end
|
[
"def",
"context_binding",
"(",
"variables",
")",
"context",
"=",
"TemplateEvaluationContext",
".",
"new",
"helpers",
".",
"each",
"{",
"|",
"helper",
"|",
"context",
".",
"extend",
"(",
"helper",
")",
"}",
"variables",
".",
"each",
"do",
"|",
"k",
",",
"v",
"|",
"context",
".",
"instance_variable_set",
"(",
"\"@#{k}\"",
",",
"v",
")",
"end",
"context",
".",
"__get_binding",
"end"
] |
Create an empty object to use as the ERB context and set any provided variables in it.
|
[
"Create",
"an",
"empty",
"object",
"to",
"use",
"as",
"the",
"ERB",
"context",
"and",
"set",
"any",
"provided",
"variables",
"in",
"it",
"."
] |
c1a1f85f791b74e40ee6a1e2d53f19b5f7cbe0ba
|
https://github.com/litaio/lita/blob/c1a1f85f791b74e40ee6a1e2d53f19b5f7cbe0ba/lib/lita/template.rb#L56-L66
|
15,144
|
litaio/lita
|
lib/lita/cli.rb
|
Lita.CLI.start
|
def start
check_ruby_verison
check_default_handlers
begin
Bundler.require
rescue Bundler::GemfileNotFound
say I18n.t("lita.cli.no_gemfile_warning"), :red
abort
end
Lita.run(options[:config])
end
|
ruby
|
def start
check_ruby_verison
check_default_handlers
begin
Bundler.require
rescue Bundler::GemfileNotFound
say I18n.t("lita.cli.no_gemfile_warning"), :red
abort
end
Lita.run(options[:config])
end
|
[
"def",
"start",
"check_ruby_verison",
"check_default_handlers",
"begin",
"Bundler",
".",
"require",
"rescue",
"Bundler",
"::",
"GemfileNotFound",
"say",
"I18n",
".",
"t",
"(",
"\"lita.cli.no_gemfile_warning\"",
")",
",",
":red",
"abort",
"end",
"Lita",
".",
"run",
"(",
"options",
"[",
":config",
"]",
")",
"end"
] |
Starts Lita.
@return [void]
|
[
"Starts",
"Lita",
"."
] |
c1a1f85f791b74e40ee6a1e2d53f19b5f7cbe0ba
|
https://github.com/litaio/lita/blob/c1a1f85f791b74e40ee6a1e2d53f19b5f7cbe0ba/lib/lita/cli.rb#L62-L74
|
15,145
|
litaio/lita
|
lib/lita/cli.rb
|
Lita.CLI.validate
|
def validate
check_ruby_verison
check_default_handlers
begin
Bundler.require
rescue Bundler::GemfileNotFound
say I18n.t("lita.cli.no_gemfile_warning"), :red
abort
end
Lita.load_config(options[:config])
end
|
ruby
|
def validate
check_ruby_verison
check_default_handlers
begin
Bundler.require
rescue Bundler::GemfileNotFound
say I18n.t("lita.cli.no_gemfile_warning"), :red
abort
end
Lita.load_config(options[:config])
end
|
[
"def",
"validate",
"check_ruby_verison",
"check_default_handlers",
"begin",
"Bundler",
".",
"require",
"rescue",
"Bundler",
"::",
"GemfileNotFound",
"say",
"I18n",
".",
"t",
"(",
"\"lita.cli.no_gemfile_warning\"",
")",
",",
":red",
"abort",
"end",
"Lita",
".",
"load_config",
"(",
"options",
"[",
":config",
"]",
")",
"end"
] |
Outputs detailed stacktrace when there is a problem or exit 0 when OK.
You can use this as a pre-check script for any automation
@return [void]
|
[
"Outputs",
"detailed",
"stacktrace",
"when",
"there",
"is",
"a",
"problem",
"or",
"exit",
"0",
"when",
"OK",
".",
"You",
"can",
"use",
"this",
"as",
"a",
"pre",
"-",
"check",
"script",
"for",
"any",
"automation"
] |
c1a1f85f791b74e40ee6a1e2d53f19b5f7cbe0ba
|
https://github.com/litaio/lita/blob/c1a1f85f791b74e40ee6a1e2d53f19b5f7cbe0ba/lib/lita/cli.rb#L131-L143
|
15,146
|
interagent/prmd
|
lib/prmd/schema.rb
|
Prmd.Schema.merge!
|
def merge!(schema)
if schema.is_a?(Schema)
@data.merge!(schema.data)
else
@data.merge!(schema)
end
end
|
ruby
|
def merge!(schema)
if schema.is_a?(Schema)
@data.merge!(schema.data)
else
@data.merge!(schema)
end
end
|
[
"def",
"merge!",
"(",
"schema",
")",
"if",
"schema",
".",
"is_a?",
"(",
"Schema",
")",
"@data",
".",
"merge!",
"(",
"schema",
".",
"data",
")",
"else",
"@data",
".",
"merge!",
"(",
"schema",
")",
"end",
"end"
] |
Merge schema data with provided schema
@param [Hash, Prmd::Schema] schema
@return [void]
|
[
"Merge",
"schema",
"data",
"with",
"provided",
"schema"
] |
d4908cba5153a76cced9979e6ec17bd217b96865
|
https://github.com/interagent/prmd/blob/d4908cba5153a76cced9979e6ec17bd217b96865/lib/prmd/schema.rb#L72-L78
|
15,147
|
interagent/prmd
|
lib/prmd/schema.rb
|
Prmd.Schema.to_json
|
def to_json
new_json = JSON.pretty_generate(@data)
# nuke empty lines
new_json = new_json.split("\n").reject(&:empty?).join("\n") + "\n"
new_json
end
|
ruby
|
def to_json
new_json = JSON.pretty_generate(@data)
# nuke empty lines
new_json = new_json.split("\n").reject(&:empty?).join("\n") + "\n"
new_json
end
|
[
"def",
"to_json",
"new_json",
"=",
"JSON",
".",
"pretty_generate",
"(",
"@data",
")",
"# nuke empty lines",
"new_json",
"=",
"new_json",
".",
"split",
"(",
"\"\\n\"",
")",
".",
"reject",
"(",
":empty?",
")",
".",
"join",
"(",
"\"\\n\"",
")",
"+",
"\"\\n\"",
"new_json",
"end"
] |
Convert Schema to JSON
@return [String]
|
[
"Convert",
"Schema",
"to",
"JSON"
] |
d4908cba5153a76cced9979e6ec17bd217b96865
|
https://github.com/interagent/prmd/blob/d4908cba5153a76cced9979e6ec17bd217b96865/lib/prmd/schema.rb#L181-L186
|
15,148
|
igrigorik/http-2
|
lib/http/2/framer.rb
|
HTTP2.Framer.common_header
|
def common_header(frame)
header = []
unless FRAME_TYPES[frame[:type]]
fail CompressionError, "Invalid frame type (#{frame[:type]})"
end
if frame[:length] > @max_frame_size
fail CompressionError, "Frame size is too large: #{frame[:length]}"
end
if frame[:length] < 0
fail CompressionError, "Frame size is invalid: #{frame[:length]}"
end
if frame[:stream] > MAX_STREAM_ID
fail CompressionError, "Stream ID (#{frame[:stream]}) is too large"
end
if frame[:type] == :window_update && frame[:increment] > MAX_WINDOWINC
fail CompressionError, "Window increment (#{frame[:increment]}) is too large"
end
header << (frame[:length] >> FRAME_LENGTH_HISHIFT)
header << (frame[:length] & FRAME_LENGTH_LOMASK)
header << FRAME_TYPES[frame[:type]]
header << frame[:flags].reduce(0) do |acc, f|
position = FRAME_FLAGS[frame[:type]][f]
unless position
fail CompressionError, "Invalid frame flag (#{f}) for #{frame[:type]}"
end
acc | (1 << position)
end
header << frame[:stream]
header.pack(HEADERPACK) # 8+16,8,8,32
end
|
ruby
|
def common_header(frame)
header = []
unless FRAME_TYPES[frame[:type]]
fail CompressionError, "Invalid frame type (#{frame[:type]})"
end
if frame[:length] > @max_frame_size
fail CompressionError, "Frame size is too large: #{frame[:length]}"
end
if frame[:length] < 0
fail CompressionError, "Frame size is invalid: #{frame[:length]}"
end
if frame[:stream] > MAX_STREAM_ID
fail CompressionError, "Stream ID (#{frame[:stream]}) is too large"
end
if frame[:type] == :window_update && frame[:increment] > MAX_WINDOWINC
fail CompressionError, "Window increment (#{frame[:increment]}) is too large"
end
header << (frame[:length] >> FRAME_LENGTH_HISHIFT)
header << (frame[:length] & FRAME_LENGTH_LOMASK)
header << FRAME_TYPES[frame[:type]]
header << frame[:flags].reduce(0) do |acc, f|
position = FRAME_FLAGS[frame[:type]][f]
unless position
fail CompressionError, "Invalid frame flag (#{f}) for #{frame[:type]}"
end
acc | (1 << position)
end
header << frame[:stream]
header.pack(HEADERPACK) # 8+16,8,8,32
end
|
[
"def",
"common_header",
"(",
"frame",
")",
"header",
"=",
"[",
"]",
"unless",
"FRAME_TYPES",
"[",
"frame",
"[",
":type",
"]",
"]",
"fail",
"CompressionError",
",",
"\"Invalid frame type (#{frame[:type]})\"",
"end",
"if",
"frame",
"[",
":length",
"]",
">",
"@max_frame_size",
"fail",
"CompressionError",
",",
"\"Frame size is too large: #{frame[:length]}\"",
"end",
"if",
"frame",
"[",
":length",
"]",
"<",
"0",
"fail",
"CompressionError",
",",
"\"Frame size is invalid: #{frame[:length]}\"",
"end",
"if",
"frame",
"[",
":stream",
"]",
">",
"MAX_STREAM_ID",
"fail",
"CompressionError",
",",
"\"Stream ID (#{frame[:stream]}) is too large\"",
"end",
"if",
"frame",
"[",
":type",
"]",
"==",
":window_update",
"&&",
"frame",
"[",
":increment",
"]",
">",
"MAX_WINDOWINC",
"fail",
"CompressionError",
",",
"\"Window increment (#{frame[:increment]}) is too large\"",
"end",
"header",
"<<",
"(",
"frame",
"[",
":length",
"]",
">>",
"FRAME_LENGTH_HISHIFT",
")",
"header",
"<<",
"(",
"frame",
"[",
":length",
"]",
"&",
"FRAME_LENGTH_LOMASK",
")",
"header",
"<<",
"FRAME_TYPES",
"[",
"frame",
"[",
":type",
"]",
"]",
"header",
"<<",
"frame",
"[",
":flags",
"]",
".",
"reduce",
"(",
"0",
")",
"do",
"|",
"acc",
",",
"f",
"|",
"position",
"=",
"FRAME_FLAGS",
"[",
"frame",
"[",
":type",
"]",
"]",
"[",
"f",
"]",
"unless",
"position",
"fail",
"CompressionError",
",",
"\"Invalid frame flag (#{f}) for #{frame[:type]}\"",
"end",
"acc",
"|",
"(",
"1",
"<<",
"position",
")",
"end",
"header",
"<<",
"frame",
"[",
":stream",
"]",
"header",
".",
"pack",
"(",
"HEADERPACK",
")",
"# 8+16,8,8,32",
"end"
] |
Initializes new framer object.
Generates common 9-byte frame header.
- http://tools.ietf.org/html/draft-ietf-httpbis-http2-16#section-4.1
@param frame [Hash]
@return [String]
|
[
"Initializes",
"new",
"framer",
"object",
"."
] |
d52934f144db97fc7534e4c6025ed6ae86909b6a
|
https://github.com/igrigorik/http-2/blob/d52934f144db97fc7534e4c6025ed6ae86909b6a/lib/http/2/framer.rb#L115-L152
|
15,149
|
igrigorik/http-2
|
lib/http/2/framer.rb
|
HTTP2.Framer.read_common_header
|
def read_common_header(buf)
frame = {}
len_hi, len_lo, type, flags, stream = buf.slice(0, 9).unpack(HEADERPACK)
frame[:length] = (len_hi << FRAME_LENGTH_HISHIFT) | len_lo
frame[:type], _ = FRAME_TYPES.find { |_t, pos| type == pos }
if frame[:type]
frame[:flags] = FRAME_FLAGS[frame[:type]].each_with_object([]) do |(name, pos), acc|
acc << name if (flags & (1 << pos)) > 0
end
end
frame[:stream] = stream & RBIT
frame
end
|
ruby
|
def read_common_header(buf)
frame = {}
len_hi, len_lo, type, flags, stream = buf.slice(0, 9).unpack(HEADERPACK)
frame[:length] = (len_hi << FRAME_LENGTH_HISHIFT) | len_lo
frame[:type], _ = FRAME_TYPES.find { |_t, pos| type == pos }
if frame[:type]
frame[:flags] = FRAME_FLAGS[frame[:type]].each_with_object([]) do |(name, pos), acc|
acc << name if (flags & (1 << pos)) > 0
end
end
frame[:stream] = stream & RBIT
frame
end
|
[
"def",
"read_common_header",
"(",
"buf",
")",
"frame",
"=",
"{",
"}",
"len_hi",
",",
"len_lo",
",",
"type",
",",
"flags",
",",
"stream",
"=",
"buf",
".",
"slice",
"(",
"0",
",",
"9",
")",
".",
"unpack",
"(",
"HEADERPACK",
")",
"frame",
"[",
":length",
"]",
"=",
"(",
"len_hi",
"<<",
"FRAME_LENGTH_HISHIFT",
")",
"|",
"len_lo",
"frame",
"[",
":type",
"]",
",",
"_",
"=",
"FRAME_TYPES",
".",
"find",
"{",
"|",
"_t",
",",
"pos",
"|",
"type",
"==",
"pos",
"}",
"if",
"frame",
"[",
":type",
"]",
"frame",
"[",
":flags",
"]",
"=",
"FRAME_FLAGS",
"[",
"frame",
"[",
":type",
"]",
"]",
".",
"each_with_object",
"(",
"[",
"]",
")",
"do",
"|",
"(",
"name",
",",
"pos",
")",
",",
"acc",
"|",
"acc",
"<<",
"name",
"if",
"(",
"flags",
"&",
"(",
"1",
"<<",
"pos",
")",
")",
">",
"0",
"end",
"end",
"frame",
"[",
":stream",
"]",
"=",
"stream",
"&",
"RBIT",
"frame",
"end"
] |
Decodes common 9-byte header.
@param buf [Buffer]
|
[
"Decodes",
"common",
"9",
"-",
"byte",
"header",
"."
] |
d52934f144db97fc7534e4c6025ed6ae86909b6a
|
https://github.com/igrigorik/http-2/blob/d52934f144db97fc7534e4c6025ed6ae86909b6a/lib/http/2/framer.rb#L157-L171
|
15,150
|
igrigorik/http-2
|
lib/http/2/flow_buffer.rb
|
HTTP2.FlowBuffer.send_data
|
def send_data(frame = nil, encode = false)
@send_buffer.push frame unless frame.nil?
# FIXME: Frames with zero length with the END_STREAM flag set (that
# is, an empty DATA frame) MAY be sent if there is no available space
# in either flow control window.
while @remote_window > 0 && !@send_buffer.empty?
frame = @send_buffer.shift
sent, frame_size = 0, frame[:payload].bytesize
if frame_size > @remote_window
payload = frame.delete(:payload)
chunk = frame.dup
# Split frame so that it fits in the window
# TODO: consider padding!
frame[:payload] = payload.slice!(0, @remote_window)
chunk[:length] = payload.bytesize
chunk[:payload] = payload
# if no longer last frame in sequence...
frame[:flags] -= [:end_stream] if frame[:flags].include? :end_stream
@send_buffer.unshift chunk
sent = @remote_window
else
sent = frame_size
end
manage_state(frame) do
frames = encode ? encode(frame) : [frame]
frames.each { |f| emit(:frame, f) }
@remote_window -= sent
end
end
end
|
ruby
|
def send_data(frame = nil, encode = false)
@send_buffer.push frame unless frame.nil?
# FIXME: Frames with zero length with the END_STREAM flag set (that
# is, an empty DATA frame) MAY be sent if there is no available space
# in either flow control window.
while @remote_window > 0 && !@send_buffer.empty?
frame = @send_buffer.shift
sent, frame_size = 0, frame[:payload].bytesize
if frame_size > @remote_window
payload = frame.delete(:payload)
chunk = frame.dup
# Split frame so that it fits in the window
# TODO: consider padding!
frame[:payload] = payload.slice!(0, @remote_window)
chunk[:length] = payload.bytesize
chunk[:payload] = payload
# if no longer last frame in sequence...
frame[:flags] -= [:end_stream] if frame[:flags].include? :end_stream
@send_buffer.unshift chunk
sent = @remote_window
else
sent = frame_size
end
manage_state(frame) do
frames = encode ? encode(frame) : [frame]
frames.each { |f| emit(:frame, f) }
@remote_window -= sent
end
end
end
|
[
"def",
"send_data",
"(",
"frame",
"=",
"nil",
",",
"encode",
"=",
"false",
")",
"@send_buffer",
".",
"push",
"frame",
"unless",
"frame",
".",
"nil?",
"# FIXME: Frames with zero length with the END_STREAM flag set (that",
"# is, an empty DATA frame) MAY be sent if there is no available space",
"# in either flow control window.",
"while",
"@remote_window",
">",
"0",
"&&",
"!",
"@send_buffer",
".",
"empty?",
"frame",
"=",
"@send_buffer",
".",
"shift",
"sent",
",",
"frame_size",
"=",
"0",
",",
"frame",
"[",
":payload",
"]",
".",
"bytesize",
"if",
"frame_size",
">",
"@remote_window",
"payload",
"=",
"frame",
".",
"delete",
"(",
":payload",
")",
"chunk",
"=",
"frame",
".",
"dup",
"# Split frame so that it fits in the window",
"# TODO: consider padding!",
"frame",
"[",
":payload",
"]",
"=",
"payload",
".",
"slice!",
"(",
"0",
",",
"@remote_window",
")",
"chunk",
"[",
":length",
"]",
"=",
"payload",
".",
"bytesize",
"chunk",
"[",
":payload",
"]",
"=",
"payload",
"# if no longer last frame in sequence...",
"frame",
"[",
":flags",
"]",
"-=",
"[",
":end_stream",
"]",
"if",
"frame",
"[",
":flags",
"]",
".",
"include?",
":end_stream",
"@send_buffer",
".",
"unshift",
"chunk",
"sent",
"=",
"@remote_window",
"else",
"sent",
"=",
"frame_size",
"end",
"manage_state",
"(",
"frame",
")",
"do",
"frames",
"=",
"encode",
"?",
"encode",
"(",
"frame",
")",
":",
"[",
"frame",
"]",
"frames",
".",
"each",
"{",
"|",
"f",
"|",
"emit",
"(",
":frame",
",",
"f",
")",
"}",
"@remote_window",
"-=",
"sent",
"end",
"end",
"end"
] |
Buffers outgoing DATA frames and applies flow control logic to split
and emit DATA frames based on current flow control window. If the
window is large enough, the data is sent immediately. Otherwise, the
data is buffered until the flow control window is updated.
Buffered DATA frames are emitted in FIFO order.
@param frame [Hash]
@param encode [Boolean] set to true by co
|
[
"Buffers",
"outgoing",
"DATA",
"frames",
"and",
"applies",
"flow",
"control",
"logic",
"to",
"split",
"and",
"emit",
"DATA",
"frames",
"based",
"on",
"current",
"flow",
"control",
"window",
".",
"If",
"the",
"window",
"is",
"large",
"enough",
"the",
"data",
"is",
"sent",
"immediately",
".",
"Otherwise",
"the",
"data",
"is",
"buffered",
"until",
"the",
"flow",
"control",
"window",
"is",
"updated",
"."
] |
d52934f144db97fc7534e4c6025ed6ae86909b6a
|
https://github.com/igrigorik/http-2/blob/d52934f144db97fc7534e4c6025ed6ae86909b6a/lib/http/2/flow_buffer.rb#L56-L92
|
15,151
|
igrigorik/http-2
|
lib/http/2/client.rb
|
HTTP2.Client.send_connection_preface
|
def send_connection_preface
return unless @state == :waiting_connection_preface
@state = :connected
emit(:frame, CONNECTION_PREFACE_MAGIC)
payload = @local_settings.reject { |k, v| v == SPEC_DEFAULT_CONNECTION_SETTINGS[k] }
settings(payload)
end
|
ruby
|
def send_connection_preface
return unless @state == :waiting_connection_preface
@state = :connected
emit(:frame, CONNECTION_PREFACE_MAGIC)
payload = @local_settings.reject { |k, v| v == SPEC_DEFAULT_CONNECTION_SETTINGS[k] }
settings(payload)
end
|
[
"def",
"send_connection_preface",
"return",
"unless",
"@state",
"==",
":waiting_connection_preface",
"@state",
"=",
":connected",
"emit",
"(",
":frame",
",",
"CONNECTION_PREFACE_MAGIC",
")",
"payload",
"=",
"@local_settings",
".",
"reject",
"{",
"|",
"k",
",",
"v",
"|",
"v",
"==",
"SPEC_DEFAULT_CONNECTION_SETTINGS",
"[",
"k",
"]",
"}",
"settings",
"(",
"payload",
")",
"end"
] |
Emit the connection preface if not yet
|
[
"Emit",
"the",
"connection",
"preface",
"if",
"not",
"yet"
] |
d52934f144db97fc7534e4c6025ed6ae86909b6a
|
https://github.com/igrigorik/http-2/blob/d52934f144db97fc7534e4c6025ed6ae86909b6a/lib/http/2/client.rb#L54-L61
|
15,152
|
igrigorik/http-2
|
lib/http/2/stream.rb
|
HTTP2.Stream.receive
|
def receive(frame)
transition(frame, false)
case frame[:type]
when :data
update_local_window(frame)
# Emit DATA frame
emit(:data, frame[:payload]) unless frame[:ignore]
calculate_window_update(@local_window_max_size)
when :headers
emit(:headers, frame[:payload]) unless frame[:ignore]
when :push_promise
emit(:promise_headers, frame[:payload]) unless frame[:ignore]
when :priority
process_priority(frame)
when :window_update
process_window_update(frame)
when :altsvc
# 4. The ALTSVC HTTP/2 Frame
# An ALTSVC frame on a
# stream other than stream 0 containing non-empty "Origin" information
# is invalid and MUST be ignored.
if !frame[:origin] || frame[:origin].empty?
emit(frame[:type], frame)
end
when :blocked
emit(frame[:type], frame)
end
complete_transition(frame)
end
|
ruby
|
def receive(frame)
transition(frame, false)
case frame[:type]
when :data
update_local_window(frame)
# Emit DATA frame
emit(:data, frame[:payload]) unless frame[:ignore]
calculate_window_update(@local_window_max_size)
when :headers
emit(:headers, frame[:payload]) unless frame[:ignore]
when :push_promise
emit(:promise_headers, frame[:payload]) unless frame[:ignore]
when :priority
process_priority(frame)
when :window_update
process_window_update(frame)
when :altsvc
# 4. The ALTSVC HTTP/2 Frame
# An ALTSVC frame on a
# stream other than stream 0 containing non-empty "Origin" information
# is invalid and MUST be ignored.
if !frame[:origin] || frame[:origin].empty?
emit(frame[:type], frame)
end
when :blocked
emit(frame[:type], frame)
end
complete_transition(frame)
end
|
[
"def",
"receive",
"(",
"frame",
")",
"transition",
"(",
"frame",
",",
"false",
")",
"case",
"frame",
"[",
":type",
"]",
"when",
":data",
"update_local_window",
"(",
"frame",
")",
"# Emit DATA frame",
"emit",
"(",
":data",
",",
"frame",
"[",
":payload",
"]",
")",
"unless",
"frame",
"[",
":ignore",
"]",
"calculate_window_update",
"(",
"@local_window_max_size",
")",
"when",
":headers",
"emit",
"(",
":headers",
",",
"frame",
"[",
":payload",
"]",
")",
"unless",
"frame",
"[",
":ignore",
"]",
"when",
":push_promise",
"emit",
"(",
":promise_headers",
",",
"frame",
"[",
":payload",
"]",
")",
"unless",
"frame",
"[",
":ignore",
"]",
"when",
":priority",
"process_priority",
"(",
"frame",
")",
"when",
":window_update",
"process_window_update",
"(",
"frame",
")",
"when",
":altsvc",
"# 4. The ALTSVC HTTP/2 Frame",
"# An ALTSVC frame on a",
"# stream other than stream 0 containing non-empty \"Origin\" information",
"# is invalid and MUST be ignored.",
"if",
"!",
"frame",
"[",
":origin",
"]",
"||",
"frame",
"[",
":origin",
"]",
".",
"empty?",
"emit",
"(",
"frame",
"[",
":type",
"]",
",",
"frame",
")",
"end",
"when",
":blocked",
"emit",
"(",
"frame",
"[",
":type",
"]",
",",
"frame",
")",
"end",
"complete_transition",
"(",
"frame",
")",
"end"
] |
Processes incoming HTTP 2.0 frames. The frames must be decoded upstream.
@param frame [Hash]
|
[
"Processes",
"incoming",
"HTTP",
"2",
".",
"0",
"frames",
".",
"The",
"frames",
"must",
"be",
"decoded",
"upstream",
"."
] |
d52934f144db97fc7534e4c6025ed6ae86909b6a
|
https://github.com/igrigorik/http-2/blob/d52934f144db97fc7534e4c6025ed6ae86909b6a/lib/http/2/stream.rb#L101-L131
|
15,153
|
igrigorik/http-2
|
lib/http/2/stream.rb
|
HTTP2.Stream.send
|
def send(frame)
process_priority(frame) if frame[:type] == :priority
case frame[:type]
when :data
# @remote_window is maintained in send_data
send_data(frame)
when :window_update
manage_state(frame) do
@local_window += frame[:increment]
emit(:frame, frame)
end
else
manage_state(frame) do
emit(:frame, frame)
end
end
end
|
ruby
|
def send(frame)
process_priority(frame) if frame[:type] == :priority
case frame[:type]
when :data
# @remote_window is maintained in send_data
send_data(frame)
when :window_update
manage_state(frame) do
@local_window += frame[:increment]
emit(:frame, frame)
end
else
manage_state(frame) do
emit(:frame, frame)
end
end
end
|
[
"def",
"send",
"(",
"frame",
")",
"process_priority",
"(",
"frame",
")",
"if",
"frame",
"[",
":type",
"]",
"==",
":priority",
"case",
"frame",
"[",
":type",
"]",
"when",
":data",
"# @remote_window is maintained in send_data",
"send_data",
"(",
"frame",
")",
"when",
":window_update",
"manage_state",
"(",
"frame",
")",
"do",
"@local_window",
"+=",
"frame",
"[",
":increment",
"]",
"emit",
"(",
":frame",
",",
"frame",
")",
"end",
"else",
"manage_state",
"(",
"frame",
")",
"do",
"emit",
"(",
":frame",
",",
"frame",
")",
"end",
"end",
"end"
] |
Processes outgoing HTTP 2.0 frames. Data frames may be automatically
split and buffered based on maximum frame size and current stream flow
control window size.
@param frame [Hash]
|
[
"Processes",
"outgoing",
"HTTP",
"2",
".",
"0",
"frames",
".",
"Data",
"frames",
"may",
"be",
"automatically",
"split",
"and",
"buffered",
"based",
"on",
"maximum",
"frame",
"size",
"and",
"current",
"stream",
"flow",
"control",
"window",
"size",
"."
] |
d52934f144db97fc7534e4c6025ed6ae86909b6a
|
https://github.com/igrigorik/http-2/blob/d52934f144db97fc7534e4c6025ed6ae86909b6a/lib/http/2/stream.rb#L139-L156
|
15,154
|
igrigorik/http-2
|
lib/http/2/stream.rb
|
HTTP2.Stream.headers
|
def headers(headers, end_headers: true, end_stream: false)
flags = []
flags << :end_headers if end_headers
flags << :end_stream if end_stream
send(type: :headers, flags: flags, payload: headers)
end
|
ruby
|
def headers(headers, end_headers: true, end_stream: false)
flags = []
flags << :end_headers if end_headers
flags << :end_stream if end_stream
send(type: :headers, flags: flags, payload: headers)
end
|
[
"def",
"headers",
"(",
"headers",
",",
"end_headers",
":",
"true",
",",
"end_stream",
":",
"false",
")",
"flags",
"=",
"[",
"]",
"flags",
"<<",
":end_headers",
"if",
"end_headers",
"flags",
"<<",
":end_stream",
"if",
"end_stream",
"send",
"(",
"type",
":",
":headers",
",",
"flags",
":",
"flags",
",",
"payload",
":",
"headers",
")",
"end"
] |
Sends a HEADERS frame containing HTTP response headers.
All pseudo-header fields MUST appear in the header block before regular header fields.
@param headers [Array or Hash] Array of key-value pairs or Hash
@param end_headers [Boolean] indicates that no more headers will be sent
@param end_stream [Boolean] indicates that no payload will be sent
|
[
"Sends",
"a",
"HEADERS",
"frame",
"containing",
"HTTP",
"response",
"headers",
".",
"All",
"pseudo",
"-",
"header",
"fields",
"MUST",
"appear",
"in",
"the",
"header",
"block",
"before",
"regular",
"header",
"fields",
"."
] |
d52934f144db97fc7534e4c6025ed6ae86909b6a
|
https://github.com/igrigorik/http-2/blob/d52934f144db97fc7534e4c6025ed6ae86909b6a/lib/http/2/stream.rb#L164-L170
|
15,155
|
igrigorik/http-2
|
lib/http/2/stream.rb
|
HTTP2.Stream.data
|
def data(payload, end_stream: true)
# Split data according to each frame is smaller enough
# TODO: consider padding?
max_size = @connection.remote_settings[:settings_max_frame_size]
if payload.bytesize > max_size
payload = chunk_data(payload, max_size) do |chunk|
send(type: :data, flags: [], payload: chunk)
end
end
flags = []
flags << :end_stream if end_stream
send(type: :data, flags: flags, payload: payload)
end
|
ruby
|
def data(payload, end_stream: true)
# Split data according to each frame is smaller enough
# TODO: consider padding?
max_size = @connection.remote_settings[:settings_max_frame_size]
if payload.bytesize > max_size
payload = chunk_data(payload, max_size) do |chunk|
send(type: :data, flags: [], payload: chunk)
end
end
flags = []
flags << :end_stream if end_stream
send(type: :data, flags: flags, payload: payload)
end
|
[
"def",
"data",
"(",
"payload",
",",
"end_stream",
":",
"true",
")",
"# Split data according to each frame is smaller enough",
"# TODO: consider padding?",
"max_size",
"=",
"@connection",
".",
"remote_settings",
"[",
":settings_max_frame_size",
"]",
"if",
"payload",
".",
"bytesize",
">",
"max_size",
"payload",
"=",
"chunk_data",
"(",
"payload",
",",
"max_size",
")",
"do",
"|",
"chunk",
"|",
"send",
"(",
"type",
":",
":data",
",",
"flags",
":",
"[",
"]",
",",
"payload",
":",
"chunk",
")",
"end",
"end",
"flags",
"=",
"[",
"]",
"flags",
"<<",
":end_stream",
"if",
"end_stream",
"send",
"(",
"type",
":",
":data",
",",
"flags",
":",
"flags",
",",
"payload",
":",
"payload",
")",
"end"
] |
Sends DATA frame containing response payload.
@param payload [String]
@param end_stream [Boolean] indicates last response DATA frame
|
[
"Sends",
"DATA",
"frame",
"containing",
"response",
"payload",
"."
] |
d52934f144db97fc7534e4c6025ed6ae86909b6a
|
https://github.com/igrigorik/http-2/blob/d52934f144db97fc7534e4c6025ed6ae86909b6a/lib/http/2/stream.rb#L193-L207
|
15,156
|
igrigorik/http-2
|
lib/http/2/stream.rb
|
HTTP2.Stream.chunk_data
|
def chunk_data(payload, max_size)
total = payload.bytesize
cursor = 0
while (total - cursor) > max_size
yield payload.byteslice(cursor, max_size)
cursor += max_size
end
payload.byteslice(cursor, total - cursor)
end
|
ruby
|
def chunk_data(payload, max_size)
total = payload.bytesize
cursor = 0
while (total - cursor) > max_size
yield payload.byteslice(cursor, max_size)
cursor += max_size
end
payload.byteslice(cursor, total - cursor)
end
|
[
"def",
"chunk_data",
"(",
"payload",
",",
"max_size",
")",
"total",
"=",
"payload",
".",
"bytesize",
"cursor",
"=",
"0",
"while",
"(",
"total",
"-",
"cursor",
")",
">",
"max_size",
"yield",
"payload",
".",
"byteslice",
"(",
"cursor",
",",
"max_size",
")",
"cursor",
"+=",
"max_size",
"end",
"payload",
".",
"byteslice",
"(",
"cursor",
",",
"total",
"-",
"cursor",
")",
"end"
] |
Chunk data into max_size, yield each chunk, then return final chunk
|
[
"Chunk",
"data",
"into",
"max_size",
"yield",
"each",
"chunk",
"then",
"return",
"final",
"chunk"
] |
d52934f144db97fc7534e4c6025ed6ae86909b6a
|
https://github.com/igrigorik/http-2/blob/d52934f144db97fc7534e4c6025ed6ae86909b6a/lib/http/2/stream.rb#L211-L219
|
15,157
|
igrigorik/http-2
|
lib/http/2/server.rb
|
HTTP2.Server.promise
|
def promise(*args, &callback)
parent, headers, flags = *args
promise = new_stream(parent: parent)
promise.send(
type: :push_promise,
flags: flags,
stream: parent.id,
promise_stream: promise.id,
payload: headers.to_a,
)
callback.call(promise)
end
|
ruby
|
def promise(*args, &callback)
parent, headers, flags = *args
promise = new_stream(parent: parent)
promise.send(
type: :push_promise,
flags: flags,
stream: parent.id,
promise_stream: promise.id,
payload: headers.to_a,
)
callback.call(promise)
end
|
[
"def",
"promise",
"(",
"*",
"args",
",",
"&",
"callback",
")",
"parent",
",",
"headers",
",",
"flags",
"=",
"args",
"promise",
"=",
"new_stream",
"(",
"parent",
":",
"parent",
")",
"promise",
".",
"send",
"(",
"type",
":",
":push_promise",
",",
"flags",
":",
"flags",
",",
"stream",
":",
"parent",
".",
"id",
",",
"promise_stream",
":",
"promise",
".",
"id",
",",
"payload",
":",
"headers",
".",
"to_a",
",",
")",
"callback",
".",
"call",
"(",
"promise",
")",
"end"
] |
Handle locally initiated server-push event emitted by the stream.
@param args [Array]
@param callback [Proc]
|
[
"Handle",
"locally",
"initiated",
"server",
"-",
"push",
"event",
"emitted",
"by",
"the",
"stream",
"."
] |
d52934f144db97fc7534e4c6025ed6ae86909b6a
|
https://github.com/igrigorik/http-2/blob/d52934f144db97fc7534e4c6025ed6ae86909b6a/lib/http/2/server.rb#L119-L131
|
15,158
|
igrigorik/http-2
|
lib/http/2/emitter.rb
|
HTTP2.Emitter.add_listener
|
def add_listener(event, &block)
fail ArgumentError, 'must provide callback' unless block_given?
listeners(event.to_sym).push block
end
|
ruby
|
def add_listener(event, &block)
fail ArgumentError, 'must provide callback' unless block_given?
listeners(event.to_sym).push block
end
|
[
"def",
"add_listener",
"(",
"event",
",",
"&",
"block",
")",
"fail",
"ArgumentError",
",",
"'must provide callback'",
"unless",
"block_given?",
"listeners",
"(",
"event",
".",
"to_sym",
")",
".",
"push",
"block",
"end"
] |
Subscribe to all future events for specified type.
@param event [Symbol]
@param block [Proc] callback function
|
[
"Subscribe",
"to",
"all",
"future",
"events",
"for",
"specified",
"type",
"."
] |
d52934f144db97fc7534e4c6025ed6ae86909b6a
|
https://github.com/igrigorik/http-2/blob/d52934f144db97fc7534e4c6025ed6ae86909b6a/lib/http/2/emitter.rb#L10-L13
|
15,159
|
igrigorik/http-2
|
lib/http/2/emitter.rb
|
HTTP2.Emitter.emit
|
def emit(event, *args, &block)
listeners(event).delete_if do |cb|
cb.call(*args, &block) == :delete
end
end
|
ruby
|
def emit(event, *args, &block)
listeners(event).delete_if do |cb|
cb.call(*args, &block) == :delete
end
end
|
[
"def",
"emit",
"(",
"event",
",",
"*",
"args",
",",
"&",
"block",
")",
"listeners",
"(",
"event",
")",
".",
"delete_if",
"do",
"|",
"cb",
"|",
"cb",
".",
"call",
"(",
"args",
",",
"block",
")",
"==",
":delete",
"end",
"end"
] |
Emit event with provided arguments.
@param event [Symbol]
@param args [Array] arguments to be passed to the callbacks
@param block [Proc] callback function
|
[
"Emit",
"event",
"with",
"provided",
"arguments",
"."
] |
d52934f144db97fc7534e4c6025ed6ae86909b6a
|
https://github.com/igrigorik/http-2/blob/d52934f144db97fc7534e4c6025ed6ae86909b6a/lib/http/2/emitter.rb#L32-L36
|
15,160
|
igrigorik/http-2
|
lib/http/2/connection.rb
|
HTTP2.Connection.new_stream
|
def new_stream(**args)
fail ConnectionClosed if @state == :closed
fail StreamLimitExceeded if @active_stream_count >= @remote_settings[:settings_max_concurrent_streams]
stream = activate_stream(id: @stream_id, **args)
@stream_id += 2
stream
end
|
ruby
|
def new_stream(**args)
fail ConnectionClosed if @state == :closed
fail StreamLimitExceeded if @active_stream_count >= @remote_settings[:settings_max_concurrent_streams]
stream = activate_stream(id: @stream_id, **args)
@stream_id += 2
stream
end
|
[
"def",
"new_stream",
"(",
"**",
"args",
")",
"fail",
"ConnectionClosed",
"if",
"@state",
"==",
":closed",
"fail",
"StreamLimitExceeded",
"if",
"@active_stream_count",
">=",
"@remote_settings",
"[",
":settings_max_concurrent_streams",
"]",
"stream",
"=",
"activate_stream",
"(",
"id",
":",
"@stream_id",
",",
"**",
"args",
")",
"@stream_id",
"+=",
"2",
"stream",
"end"
] |
Allocates new stream for current connection.
@param priority [Integer]
@param window [Integer]
@param parent [Stream]
|
[
"Allocates",
"new",
"stream",
"for",
"current",
"connection",
"."
] |
d52934f144db97fc7534e4c6025ed6ae86909b6a
|
https://github.com/igrigorik/http-2/blob/d52934f144db97fc7534e4c6025ed6ae86909b6a/lib/http/2/connection.rb#L109-L117
|
15,161
|
igrigorik/http-2
|
lib/http/2/connection.rb
|
HTTP2.Connection.ping
|
def ping(payload, &blk)
send(type: :ping, stream: 0, payload: payload)
once(:ack, &blk) if blk
end
|
ruby
|
def ping(payload, &blk)
send(type: :ping, stream: 0, payload: payload)
once(:ack, &blk) if blk
end
|
[
"def",
"ping",
"(",
"payload",
",",
"&",
"blk",
")",
"send",
"(",
"type",
":",
":ping",
",",
"stream",
":",
"0",
",",
"payload",
":",
"payload",
")",
"once",
"(",
":ack",
",",
"blk",
")",
"if",
"blk",
"end"
] |
Sends PING frame to the peer.
@param payload [String] optional payload must be 8 bytes long
@param blk [Proc] callback to execute when PONG is received
|
[
"Sends",
"PING",
"frame",
"to",
"the",
"peer",
"."
] |
d52934f144db97fc7534e4c6025ed6ae86909b6a
|
https://github.com/igrigorik/http-2/blob/d52934f144db97fc7534e4c6025ed6ae86909b6a/lib/http/2/connection.rb#L123-L126
|
15,162
|
igrigorik/http-2
|
lib/http/2/connection.rb
|
HTTP2.Connection.goaway
|
def goaway(error = :no_error, payload = nil)
last_stream = if (max = @streams.max)
max.first
else
0
end
send(type: :goaway, last_stream: last_stream,
error: error, payload: payload)
@state = :closed
@closed_since = Time.now
end
|
ruby
|
def goaway(error = :no_error, payload = nil)
last_stream = if (max = @streams.max)
max.first
else
0
end
send(type: :goaway, last_stream: last_stream,
error: error, payload: payload)
@state = :closed
@closed_since = Time.now
end
|
[
"def",
"goaway",
"(",
"error",
"=",
":no_error",
",",
"payload",
"=",
"nil",
")",
"last_stream",
"=",
"if",
"(",
"max",
"=",
"@streams",
".",
"max",
")",
"max",
".",
"first",
"else",
"0",
"end",
"send",
"(",
"type",
":",
":goaway",
",",
"last_stream",
":",
"last_stream",
",",
"error",
":",
"error",
",",
"payload",
":",
"payload",
")",
"@state",
"=",
":closed",
"@closed_since",
"=",
"Time",
".",
"now",
"end"
] |
Sends a GOAWAY frame indicating that the peer should stop creating
new streams for current connection.
Endpoints MAY append opaque data to the payload of any GOAWAY frame.
Additional debug data is intended for diagnostic purposes only and
carries no semantic value. Debug data MUST NOT be persistently stored,
since it could contain sensitive information.
@param error [Symbol]
@param payload [String]
|
[
"Sends",
"a",
"GOAWAY",
"frame",
"indicating",
"that",
"the",
"peer",
"should",
"stop",
"creating",
"new",
"streams",
"for",
"current",
"connection",
"."
] |
d52934f144db97fc7534e4c6025ed6ae86909b6a
|
https://github.com/igrigorik/http-2/blob/d52934f144db97fc7534e4c6025ed6ae86909b6a/lib/http/2/connection.rb#L138-L149
|
15,163
|
igrigorik/http-2
|
lib/http/2/connection.rb
|
HTTP2.Connection.settings
|
def settings(payload)
payload = payload.to_a
connection_error if validate_settings(@local_role, payload)
@pending_settings << payload
send(type: :settings, stream: 0, payload: payload)
@pending_settings << payload
end
|
ruby
|
def settings(payload)
payload = payload.to_a
connection_error if validate_settings(@local_role, payload)
@pending_settings << payload
send(type: :settings, stream: 0, payload: payload)
@pending_settings << payload
end
|
[
"def",
"settings",
"(",
"payload",
")",
"payload",
"=",
"payload",
".",
"to_a",
"connection_error",
"if",
"validate_settings",
"(",
"@local_role",
",",
"payload",
")",
"@pending_settings",
"<<",
"payload",
"send",
"(",
"type",
":",
":settings",
",",
"stream",
":",
"0",
",",
"payload",
":",
"payload",
")",
"@pending_settings",
"<<",
"payload",
"end"
] |
Sends a connection SETTINGS frame to the peer.
The values are reflected when the corresponding ACK is received.
@param settings [Array or Hash]
|
[
"Sends",
"a",
"connection",
"SETTINGS",
"frame",
"to",
"the",
"peer",
".",
"The",
"values",
"are",
"reflected",
"when",
"the",
"corresponding",
"ACK",
"is",
"received",
"."
] |
d52934f144db97fc7534e4c6025ed6ae86909b6a
|
https://github.com/igrigorik/http-2/blob/d52934f144db97fc7534e4c6025ed6ae86909b6a/lib/http/2/connection.rb#L163-L169
|
15,164
|
igrigorik/http-2
|
lib/http/2/connection.rb
|
HTTP2.Connection.encode
|
def encode(frame)
frames = if frame[:type] == :headers || frame[:type] == :push_promise
encode_headers(frame) # HEADERS and PUSH_PROMISE may create more than one frame
else
[frame] # otherwise one frame
end
frames.map { |f| @framer.generate(f) }
end
|
ruby
|
def encode(frame)
frames = if frame[:type] == :headers || frame[:type] == :push_promise
encode_headers(frame) # HEADERS and PUSH_PROMISE may create more than one frame
else
[frame] # otherwise one frame
end
frames.map { |f| @framer.generate(f) }
end
|
[
"def",
"encode",
"(",
"frame",
")",
"frames",
"=",
"if",
"frame",
"[",
":type",
"]",
"==",
":headers",
"||",
"frame",
"[",
":type",
"]",
"==",
":push_promise",
"encode_headers",
"(",
"frame",
")",
"# HEADERS and PUSH_PROMISE may create more than one frame",
"else",
"[",
"frame",
"]",
"# otherwise one frame",
"end",
"frames",
".",
"map",
"{",
"|",
"f",
"|",
"@framer",
".",
"generate",
"(",
"f",
")",
"}",
"end"
] |
Applies HTTP 2.0 binary encoding to the frame.
@param frame [Hash]
@return [Array of Buffer] encoded frame
|
[
"Applies",
"HTTP",
"2",
".",
"0",
"binary",
"encoding",
"to",
"the",
"frame",
"."
] |
d52934f144db97fc7534e4c6025ed6ae86909b6a
|
https://github.com/igrigorik/http-2/blob/d52934f144db97fc7534e4c6025ed6ae86909b6a/lib/http/2/connection.rb#L399-L407
|
15,165
|
igrigorik/http-2
|
lib/http/2/connection.rb
|
HTTP2.Connection.validate_settings
|
def validate_settings(role, settings)
settings.each do |key, v|
case key
when :settings_header_table_size
# Any value is valid
when :settings_enable_push
case role
when :server
# Section 8.2
# Clients MUST reject any attempt to change the
# SETTINGS_ENABLE_PUSH setting to a value other than 0 by treating the
# message as a connection error (Section 5.4.1) of type PROTOCOL_ERROR.
return ProtocolError.new("invalid #{key} value") unless v.zero?
when :client
# Any value other than 0 or 1 MUST be treated as a
# connection error (Section 5.4.1) of type PROTOCOL_ERROR.
unless v.zero? || v == 1
return ProtocolError.new("invalid #{key} value")
end
end
when :settings_max_concurrent_streams
# Any value is valid
when :settings_initial_window_size
# Values above the maximum flow control window size of 2^31-1 MUST
# be treated as a connection error (Section 5.4.1) of type
# FLOW_CONTROL_ERROR.
unless v <= 0x7fffffff
return FlowControlError.new("invalid #{key} value")
end
when :settings_max_frame_size
# The initial value is 2^14 (16,384) octets. The value advertised
# by an endpoint MUST be between this initial value and the maximum
# allowed frame size (2^24-1 or 16,777,215 octets), inclusive.
# Values outside this range MUST be treated as a connection error
# (Section 5.4.1) of type PROTOCOL_ERROR.
unless v >= 16_384 && v <= 16_777_215
return ProtocolError.new("invalid #{key} value")
end
when :settings_max_header_list_size
# Any value is valid
# else # ignore unknown settings
end
end
nil
end
|
ruby
|
def validate_settings(role, settings)
settings.each do |key, v|
case key
when :settings_header_table_size
# Any value is valid
when :settings_enable_push
case role
when :server
# Section 8.2
# Clients MUST reject any attempt to change the
# SETTINGS_ENABLE_PUSH setting to a value other than 0 by treating the
# message as a connection error (Section 5.4.1) of type PROTOCOL_ERROR.
return ProtocolError.new("invalid #{key} value") unless v.zero?
when :client
# Any value other than 0 or 1 MUST be treated as a
# connection error (Section 5.4.1) of type PROTOCOL_ERROR.
unless v.zero? || v == 1
return ProtocolError.new("invalid #{key} value")
end
end
when :settings_max_concurrent_streams
# Any value is valid
when :settings_initial_window_size
# Values above the maximum flow control window size of 2^31-1 MUST
# be treated as a connection error (Section 5.4.1) of type
# FLOW_CONTROL_ERROR.
unless v <= 0x7fffffff
return FlowControlError.new("invalid #{key} value")
end
when :settings_max_frame_size
# The initial value is 2^14 (16,384) octets. The value advertised
# by an endpoint MUST be between this initial value and the maximum
# allowed frame size (2^24-1 or 16,777,215 octets), inclusive.
# Values outside this range MUST be treated as a connection error
# (Section 5.4.1) of type PROTOCOL_ERROR.
unless v >= 16_384 && v <= 16_777_215
return ProtocolError.new("invalid #{key} value")
end
when :settings_max_header_list_size
# Any value is valid
# else # ignore unknown settings
end
end
nil
end
|
[
"def",
"validate_settings",
"(",
"role",
",",
"settings",
")",
"settings",
".",
"each",
"do",
"|",
"key",
",",
"v",
"|",
"case",
"key",
"when",
":settings_header_table_size",
"# Any value is valid",
"when",
":settings_enable_push",
"case",
"role",
"when",
":server",
"# Section 8.2",
"# Clients MUST reject any attempt to change the",
"# SETTINGS_ENABLE_PUSH setting to a value other than 0 by treating the",
"# message as a connection error (Section 5.4.1) of type PROTOCOL_ERROR.",
"return",
"ProtocolError",
".",
"new",
"(",
"\"invalid #{key} value\"",
")",
"unless",
"v",
".",
"zero?",
"when",
":client",
"# Any value other than 0 or 1 MUST be treated as a",
"# connection error (Section 5.4.1) of type PROTOCOL_ERROR.",
"unless",
"v",
".",
"zero?",
"||",
"v",
"==",
"1",
"return",
"ProtocolError",
".",
"new",
"(",
"\"invalid #{key} value\"",
")",
"end",
"end",
"when",
":settings_max_concurrent_streams",
"# Any value is valid",
"when",
":settings_initial_window_size",
"# Values above the maximum flow control window size of 2^31-1 MUST",
"# be treated as a connection error (Section 5.4.1) of type",
"# FLOW_CONTROL_ERROR.",
"unless",
"v",
"<=",
"0x7fffffff",
"return",
"FlowControlError",
".",
"new",
"(",
"\"invalid #{key} value\"",
")",
"end",
"when",
":settings_max_frame_size",
"# The initial value is 2^14 (16,384) octets. The value advertised",
"# by an endpoint MUST be between this initial value and the maximum",
"# allowed frame size (2^24-1 or 16,777,215 octets), inclusive.",
"# Values outside this range MUST be treated as a connection error",
"# (Section 5.4.1) of type PROTOCOL_ERROR.",
"unless",
"v",
">=",
"16_384",
"&&",
"v",
"<=",
"16_777_215",
"return",
"ProtocolError",
".",
"new",
"(",
"\"invalid #{key} value\"",
")",
"end",
"when",
":settings_max_header_list_size",
"# Any value is valid",
"# else # ignore unknown settings",
"end",
"end",
"nil",
"end"
] |
Validate settings parameters. See sepc Section 6.5.2.
@param role [Symbol] The sender's role: :client or :server
@return nil if no error. Exception object in case of any error.
|
[
"Validate",
"settings",
"parameters",
".",
"See",
"sepc",
"Section",
"6",
".",
"5",
".",
"2",
"."
] |
d52934f144db97fc7534e4c6025ed6ae86909b6a
|
https://github.com/igrigorik/http-2/blob/d52934f144db97fc7534e4c6025ed6ae86909b6a/lib/http/2/connection.rb#L479-L523
|
15,166
|
igrigorik/http-2
|
lib/http/2/connection.rb
|
HTTP2.Connection.connection_settings
|
def connection_settings(frame)
connection_error unless frame[:type] == :settings && (frame[:stream]).zero?
# Apply settings.
# side =
# local: previously sent and pended our settings should be effective
# remote: just received peer settings should immediately be effective
settings, side = if frame[:flags].include?(:ack)
# Process pending settings we have sent.
[@pending_settings.shift, :local]
else
connection_error(check) if validate_settings(@remote_role, frame[:payload])
[frame[:payload], :remote]
end
settings.each do |key, v|
case side
when :local
@local_settings[key] = v
when :remote
@remote_settings[key] = v
end
case key
when :settings_max_concurrent_streams
# Do nothing.
# The value controls at the next attempt of stream creation.
when :settings_initial_window_size
# A change to SETTINGS_INITIAL_WINDOW_SIZE could cause the available
# space in a flow control window to become negative. A sender MUST
# track the negative flow control window, and MUST NOT send new flow
# controlled frames until it receives WINDOW_UPDATE frames that cause
# the flow control window to become positive.
case side
when :local
@local_window = @local_window - @local_window_limit + v
@streams.each do |_id, stream|
stream.emit(:local_window, stream.local_window - @local_window_limit + v)
end
@local_window_limit = v
when :remote
@remote_window = @remote_window - @remote_window_limit + v
@streams.each do |_id, stream|
# Event name is :window, not :remote_window
stream.emit(:window, stream.remote_window - @remote_window_limit + v)
end
@remote_window_limit = v
end
when :settings_header_table_size
# Setting header table size might cause some headers evicted
case side
when :local
@compressor.table_size = v
when :remote
@decompressor.table_size = v
end
when :settings_enable_push
# nothing to do
when :settings_max_frame_size
# nothing to do
# else # ignore unknown settings
end
end
case side
when :local
# Received a settings_ack. Notify application layer.
emit(:settings_ack, frame, @pending_settings.size)
when :remote
unless @state == :closed || @h2c_upgrade == :start
# Send ack to peer
send(type: :settings, stream: 0, payload: [], flags: [:ack])
end
end
end
|
ruby
|
def connection_settings(frame)
connection_error unless frame[:type] == :settings && (frame[:stream]).zero?
# Apply settings.
# side =
# local: previously sent and pended our settings should be effective
# remote: just received peer settings should immediately be effective
settings, side = if frame[:flags].include?(:ack)
# Process pending settings we have sent.
[@pending_settings.shift, :local]
else
connection_error(check) if validate_settings(@remote_role, frame[:payload])
[frame[:payload], :remote]
end
settings.each do |key, v|
case side
when :local
@local_settings[key] = v
when :remote
@remote_settings[key] = v
end
case key
when :settings_max_concurrent_streams
# Do nothing.
# The value controls at the next attempt of stream creation.
when :settings_initial_window_size
# A change to SETTINGS_INITIAL_WINDOW_SIZE could cause the available
# space in a flow control window to become negative. A sender MUST
# track the negative flow control window, and MUST NOT send new flow
# controlled frames until it receives WINDOW_UPDATE frames that cause
# the flow control window to become positive.
case side
when :local
@local_window = @local_window - @local_window_limit + v
@streams.each do |_id, stream|
stream.emit(:local_window, stream.local_window - @local_window_limit + v)
end
@local_window_limit = v
when :remote
@remote_window = @remote_window - @remote_window_limit + v
@streams.each do |_id, stream|
# Event name is :window, not :remote_window
stream.emit(:window, stream.remote_window - @remote_window_limit + v)
end
@remote_window_limit = v
end
when :settings_header_table_size
# Setting header table size might cause some headers evicted
case side
when :local
@compressor.table_size = v
when :remote
@decompressor.table_size = v
end
when :settings_enable_push
# nothing to do
when :settings_max_frame_size
# nothing to do
# else # ignore unknown settings
end
end
case side
when :local
# Received a settings_ack. Notify application layer.
emit(:settings_ack, frame, @pending_settings.size)
when :remote
unless @state == :closed || @h2c_upgrade == :start
# Send ack to peer
send(type: :settings, stream: 0, payload: [], flags: [:ack])
end
end
end
|
[
"def",
"connection_settings",
"(",
"frame",
")",
"connection_error",
"unless",
"frame",
"[",
":type",
"]",
"==",
":settings",
"&&",
"(",
"frame",
"[",
":stream",
"]",
")",
".",
"zero?",
"# Apply settings.",
"# side =",
"# local: previously sent and pended our settings should be effective",
"# remote: just received peer settings should immediately be effective",
"settings",
",",
"side",
"=",
"if",
"frame",
"[",
":flags",
"]",
".",
"include?",
"(",
":ack",
")",
"# Process pending settings we have sent.",
"[",
"@pending_settings",
".",
"shift",
",",
":local",
"]",
"else",
"connection_error",
"(",
"check",
")",
"if",
"validate_settings",
"(",
"@remote_role",
",",
"frame",
"[",
":payload",
"]",
")",
"[",
"frame",
"[",
":payload",
"]",
",",
":remote",
"]",
"end",
"settings",
".",
"each",
"do",
"|",
"key",
",",
"v",
"|",
"case",
"side",
"when",
":local",
"@local_settings",
"[",
"key",
"]",
"=",
"v",
"when",
":remote",
"@remote_settings",
"[",
"key",
"]",
"=",
"v",
"end",
"case",
"key",
"when",
":settings_max_concurrent_streams",
"# Do nothing.",
"# The value controls at the next attempt of stream creation.",
"when",
":settings_initial_window_size",
"# A change to SETTINGS_INITIAL_WINDOW_SIZE could cause the available",
"# space in a flow control window to become negative. A sender MUST",
"# track the negative flow control window, and MUST NOT send new flow",
"# controlled frames until it receives WINDOW_UPDATE frames that cause",
"# the flow control window to become positive.",
"case",
"side",
"when",
":local",
"@local_window",
"=",
"@local_window",
"-",
"@local_window_limit",
"+",
"v",
"@streams",
".",
"each",
"do",
"|",
"_id",
",",
"stream",
"|",
"stream",
".",
"emit",
"(",
":local_window",
",",
"stream",
".",
"local_window",
"-",
"@local_window_limit",
"+",
"v",
")",
"end",
"@local_window_limit",
"=",
"v",
"when",
":remote",
"@remote_window",
"=",
"@remote_window",
"-",
"@remote_window_limit",
"+",
"v",
"@streams",
".",
"each",
"do",
"|",
"_id",
",",
"stream",
"|",
"# Event name is :window, not :remote_window",
"stream",
".",
"emit",
"(",
":window",
",",
"stream",
".",
"remote_window",
"-",
"@remote_window_limit",
"+",
"v",
")",
"end",
"@remote_window_limit",
"=",
"v",
"end",
"when",
":settings_header_table_size",
"# Setting header table size might cause some headers evicted",
"case",
"side",
"when",
":local",
"@compressor",
".",
"table_size",
"=",
"v",
"when",
":remote",
"@decompressor",
".",
"table_size",
"=",
"v",
"end",
"when",
":settings_enable_push",
"# nothing to do",
"when",
":settings_max_frame_size",
"# nothing to do",
"# else # ignore unknown settings",
"end",
"end",
"case",
"side",
"when",
":local",
"# Received a settings_ack. Notify application layer.",
"emit",
"(",
":settings_ack",
",",
"frame",
",",
"@pending_settings",
".",
"size",
")",
"when",
":remote",
"unless",
"@state",
"==",
":closed",
"||",
"@h2c_upgrade",
"==",
":start",
"# Send ack to peer",
"send",
"(",
"type",
":",
":settings",
",",
"stream",
":",
"0",
",",
"payload",
":",
"[",
"]",
",",
"flags",
":",
"[",
":ack",
"]",
")",
"end",
"end",
"end"
] |
Update connection settings based on parameters set by the peer.
@param frame [Hash]
|
[
"Update",
"connection",
"settings",
"based",
"on",
"parameters",
"set",
"by",
"the",
"peer",
"."
] |
d52934f144db97fc7534e4c6025ed6ae86909b6a
|
https://github.com/igrigorik/http-2/blob/d52934f144db97fc7534e4c6025ed6ae86909b6a/lib/http/2/connection.rb#L528-L609
|
15,167
|
igrigorik/http-2
|
lib/http/2/connection.rb
|
HTTP2.Connection.decode_headers
|
def decode_headers(frame)
if frame[:payload].is_a? Buffer
frame[:payload] = @decompressor.decode(frame[:payload])
end
rescue CompressionError => e
connection_error(:compression_error, e: e)
rescue ProtocolError => e
connection_error(:protocol_error, e: e)
rescue StandardError => e
connection_error(:internal_error, e: e)
end
|
ruby
|
def decode_headers(frame)
if frame[:payload].is_a? Buffer
frame[:payload] = @decompressor.decode(frame[:payload])
end
rescue CompressionError => e
connection_error(:compression_error, e: e)
rescue ProtocolError => e
connection_error(:protocol_error, e: e)
rescue StandardError => e
connection_error(:internal_error, e: e)
end
|
[
"def",
"decode_headers",
"(",
"frame",
")",
"if",
"frame",
"[",
":payload",
"]",
".",
"is_a?",
"Buffer",
"frame",
"[",
":payload",
"]",
"=",
"@decompressor",
".",
"decode",
"(",
"frame",
"[",
":payload",
"]",
")",
"end",
"rescue",
"CompressionError",
"=>",
"e",
"connection_error",
"(",
":compression_error",
",",
"e",
":",
"e",
")",
"rescue",
"ProtocolError",
"=>",
"e",
"connection_error",
"(",
":protocol_error",
",",
"e",
":",
"e",
")",
"rescue",
"StandardError",
"=>",
"e",
"connection_error",
"(",
":internal_error",
",",
"e",
":",
"e",
")",
"end"
] |
Decode headers payload and update connection decompressor state.
The receiver endpoint reassembles the header block by concatenating
the individual fragments, then decompresses the block to reconstruct
the header set - aka, header payloads are buffered until END_HEADERS,
or an END_PROMISE flag is seen.
@param frame [Hash]
|
[
"Decode",
"headers",
"payload",
"and",
"update",
"connection",
"decompressor",
"state",
"."
] |
d52934f144db97fc7534e4c6025ed6ae86909b6a
|
https://github.com/igrigorik/http-2/blob/d52934f144db97fc7534e4c6025ed6ae86909b6a/lib/http/2/connection.rb#L619-L630
|
15,168
|
igrigorik/http-2
|
lib/http/2/connection.rb
|
HTTP2.Connection.encode_headers
|
def encode_headers(frame)
payload = frame[:payload]
payload = @compressor.encode(payload) unless payload.is_a? Buffer
frames = []
while payload.bytesize > 0
cont = frame.dup
cont[:type] = :continuation
cont[:flags] = []
cont[:payload] = payload.slice!(0, @remote_settings[:settings_max_frame_size])
frames << cont
end
if frames.empty?
frames = [frame]
else
frames.first[:type] = frame[:type]
frames.first[:flags] = frame[:flags] - [:end_headers]
frames.last[:flags] << :end_headers
end
frames
rescue StandardError => e
connection_error(:compression_error, e: e)
nil
end
|
ruby
|
def encode_headers(frame)
payload = frame[:payload]
payload = @compressor.encode(payload) unless payload.is_a? Buffer
frames = []
while payload.bytesize > 0
cont = frame.dup
cont[:type] = :continuation
cont[:flags] = []
cont[:payload] = payload.slice!(0, @remote_settings[:settings_max_frame_size])
frames << cont
end
if frames.empty?
frames = [frame]
else
frames.first[:type] = frame[:type]
frames.first[:flags] = frame[:flags] - [:end_headers]
frames.last[:flags] << :end_headers
end
frames
rescue StandardError => e
connection_error(:compression_error, e: e)
nil
end
|
[
"def",
"encode_headers",
"(",
"frame",
")",
"payload",
"=",
"frame",
"[",
":payload",
"]",
"payload",
"=",
"@compressor",
".",
"encode",
"(",
"payload",
")",
"unless",
"payload",
".",
"is_a?",
"Buffer",
"frames",
"=",
"[",
"]",
"while",
"payload",
".",
"bytesize",
">",
"0",
"cont",
"=",
"frame",
".",
"dup",
"cont",
"[",
":type",
"]",
"=",
":continuation",
"cont",
"[",
":flags",
"]",
"=",
"[",
"]",
"cont",
"[",
":payload",
"]",
"=",
"payload",
".",
"slice!",
"(",
"0",
",",
"@remote_settings",
"[",
":settings_max_frame_size",
"]",
")",
"frames",
"<<",
"cont",
"end",
"if",
"frames",
".",
"empty?",
"frames",
"=",
"[",
"frame",
"]",
"else",
"frames",
".",
"first",
"[",
":type",
"]",
"=",
"frame",
"[",
":type",
"]",
"frames",
".",
"first",
"[",
":flags",
"]",
"=",
"frame",
"[",
":flags",
"]",
"-",
"[",
":end_headers",
"]",
"frames",
".",
"last",
"[",
":flags",
"]",
"<<",
":end_headers",
"end",
"frames",
"rescue",
"StandardError",
"=>",
"e",
"connection_error",
"(",
":compression_error",
",",
"e",
":",
"e",
")",
"nil",
"end"
] |
Encode headers payload and update connection compressor state.
@param frame [Hash]
@return [Array of Frame]
|
[
"Encode",
"headers",
"payload",
"and",
"update",
"connection",
"compressor",
"state",
"."
] |
d52934f144db97fc7534e4c6025ed6ae86909b6a
|
https://github.com/igrigorik/http-2/blob/d52934f144db97fc7534e4c6025ed6ae86909b6a/lib/http/2/connection.rb#L636-L662
|
15,169
|
igrigorik/http-2
|
lib/http/2/connection.rb
|
HTTP2.Connection.activate_stream
|
def activate_stream(id: nil, **args)
connection_error(msg: 'Stream ID already exists') if @streams.key?(id)
stream = Stream.new({ connection: self, id: id }.merge(args))
# Streams that are in the "open" state, or either of the "half closed"
# states count toward the maximum number of streams that an endpoint is
# permitted to open.
stream.once(:active) { @active_stream_count += 1 }
stream.once(:close) do
@active_stream_count -= 1
# Store a reference to the closed stream, such that we can respond
# to any in-flight frames while close is registered on both sides.
# References to such streams will be purged whenever another stream
# is closed, with a minimum of 15s RTT time window.
@streams_recently_closed[id] = Time.now
to_delete = @streams_recently_closed.select { |_, v| (Time.now - v) > 15 }
to_delete.each do |stream_id|
@streams.delete stream_id
@streams_recently_closed.delete stream_id
end
end
stream.on(:promise, &method(:promise)) if self.is_a? Server
stream.on(:frame, &method(:send))
@streams[id] = stream
end
|
ruby
|
def activate_stream(id: nil, **args)
connection_error(msg: 'Stream ID already exists') if @streams.key?(id)
stream = Stream.new({ connection: self, id: id }.merge(args))
# Streams that are in the "open" state, or either of the "half closed"
# states count toward the maximum number of streams that an endpoint is
# permitted to open.
stream.once(:active) { @active_stream_count += 1 }
stream.once(:close) do
@active_stream_count -= 1
# Store a reference to the closed stream, such that we can respond
# to any in-flight frames while close is registered on both sides.
# References to such streams will be purged whenever another stream
# is closed, with a minimum of 15s RTT time window.
@streams_recently_closed[id] = Time.now
to_delete = @streams_recently_closed.select { |_, v| (Time.now - v) > 15 }
to_delete.each do |stream_id|
@streams.delete stream_id
@streams_recently_closed.delete stream_id
end
end
stream.on(:promise, &method(:promise)) if self.is_a? Server
stream.on(:frame, &method(:send))
@streams[id] = stream
end
|
[
"def",
"activate_stream",
"(",
"id",
":",
"nil",
",",
"**",
"args",
")",
"connection_error",
"(",
"msg",
":",
"'Stream ID already exists'",
")",
"if",
"@streams",
".",
"key?",
"(",
"id",
")",
"stream",
"=",
"Stream",
".",
"new",
"(",
"{",
"connection",
":",
"self",
",",
"id",
":",
"id",
"}",
".",
"merge",
"(",
"args",
")",
")",
"# Streams that are in the \"open\" state, or either of the \"half closed\"",
"# states count toward the maximum number of streams that an endpoint is",
"# permitted to open.",
"stream",
".",
"once",
"(",
":active",
")",
"{",
"@active_stream_count",
"+=",
"1",
"}",
"stream",
".",
"once",
"(",
":close",
")",
"do",
"@active_stream_count",
"-=",
"1",
"# Store a reference to the closed stream, such that we can respond",
"# to any in-flight frames while close is registered on both sides.",
"# References to such streams will be purged whenever another stream",
"# is closed, with a minimum of 15s RTT time window.",
"@streams_recently_closed",
"[",
"id",
"]",
"=",
"Time",
".",
"now",
"to_delete",
"=",
"@streams_recently_closed",
".",
"select",
"{",
"|",
"_",
",",
"v",
"|",
"(",
"Time",
".",
"now",
"-",
"v",
")",
">",
"15",
"}",
"to_delete",
".",
"each",
"do",
"|",
"stream_id",
"|",
"@streams",
".",
"delete",
"stream_id",
"@streams_recently_closed",
".",
"delete",
"stream_id",
"end",
"end",
"stream",
".",
"on",
"(",
":promise",
",",
"method",
"(",
":promise",
")",
")",
"if",
"self",
".",
"is_a?",
"Server",
"stream",
".",
"on",
"(",
":frame",
",",
"method",
"(",
":send",
")",
")",
"@streams",
"[",
"id",
"]",
"=",
"stream",
"end"
] |
Activates new incoming or outgoing stream and registers appropriate
connection managemet callbacks.
@param id [Integer]
@param priority [Integer]
@param window [Integer]
@param parent [Stream]
|
[
"Activates",
"new",
"incoming",
"or",
"outgoing",
"stream",
"and",
"registers",
"appropriate",
"connection",
"managemet",
"callbacks",
"."
] |
d52934f144db97fc7534e4c6025ed6ae86909b6a
|
https://github.com/igrigorik/http-2/blob/d52934f144db97fc7534e4c6025ed6ae86909b6a/lib/http/2/connection.rb#L671-L699
|
15,170
|
igrigorik/http-2
|
lib/http/2/connection.rb
|
HTTP2.Connection.connection_error
|
def connection_error(error = :protocol_error, msg: nil, e: nil)
goaway(error) unless @state == :closed || @state == :new
@state, @error = :closed, error
klass = error.to_s.split('_').map(&:capitalize).join
msg ||= e && e.message
backtrace = (e && e.backtrace) || []
fail Error.const_get(klass), msg, backtrace
end
|
ruby
|
def connection_error(error = :protocol_error, msg: nil, e: nil)
goaway(error) unless @state == :closed || @state == :new
@state, @error = :closed, error
klass = error.to_s.split('_').map(&:capitalize).join
msg ||= e && e.message
backtrace = (e && e.backtrace) || []
fail Error.const_get(klass), msg, backtrace
end
|
[
"def",
"connection_error",
"(",
"error",
"=",
":protocol_error",
",",
"msg",
":",
"nil",
",",
"e",
":",
"nil",
")",
"goaway",
"(",
"error",
")",
"unless",
"@state",
"==",
":closed",
"||",
"@state",
"==",
":new",
"@state",
",",
"@error",
"=",
":closed",
",",
"error",
"klass",
"=",
"error",
".",
"to_s",
".",
"split",
"(",
"'_'",
")",
".",
"map",
"(",
":capitalize",
")",
".",
"join",
"msg",
"||=",
"e",
"&&",
"e",
".",
"message",
"backtrace",
"=",
"(",
"e",
"&&",
"e",
".",
"backtrace",
")",
"||",
"[",
"]",
"fail",
"Error",
".",
"const_get",
"(",
"klass",
")",
",",
"msg",
",",
"backtrace",
"end"
] |
Emit GOAWAY error indicating to peer that the connection is being
aborted, and once sent, raise a local exception.
@param error [Symbol]
@option error [Symbol] :no_error
@option error [Symbol] :internal_error
@option error [Symbol] :flow_control_error
@option error [Symbol] :stream_closed
@option error [Symbol] :frame_too_large
@option error [Symbol] :compression_error
@param msg [String]
|
[
"Emit",
"GOAWAY",
"error",
"indicating",
"to",
"peer",
"that",
"the",
"connection",
"is",
"being",
"aborted",
"and",
"once",
"sent",
"raise",
"a",
"local",
"exception",
"."
] |
d52934f144db97fc7534e4c6025ed6ae86909b6a
|
https://github.com/igrigorik/http-2/blob/d52934f144db97fc7534e4c6025ed6ae86909b6a/lib/http/2/connection.rb#L712-L720
|
15,171
|
github/janky
|
lib/janky/branch.rb
|
Janky.Branch.build_for
|
def build_for(commit, user, room_id = nil, compare = nil)
if compare.nil? && build = commit.last_build
compare = build.compare
end
room_id = room_id.to_s
if room_id.empty? || room_id == "0"
room_id = repository.room_id
end
builds.create!(
:compare => compare,
:user => user,
:commit => commit,
:room_id => room_id
)
end
|
ruby
|
def build_for(commit, user, room_id = nil, compare = nil)
if compare.nil? && build = commit.last_build
compare = build.compare
end
room_id = room_id.to_s
if room_id.empty? || room_id == "0"
room_id = repository.room_id
end
builds.create!(
:compare => compare,
:user => user,
:commit => commit,
:room_id => room_id
)
end
|
[
"def",
"build_for",
"(",
"commit",
",",
"user",
",",
"room_id",
"=",
"nil",
",",
"compare",
"=",
"nil",
")",
"if",
"compare",
".",
"nil?",
"&&",
"build",
"=",
"commit",
".",
"last_build",
"compare",
"=",
"build",
".",
"compare",
"end",
"room_id",
"=",
"room_id",
".",
"to_s",
"if",
"room_id",
".",
"empty?",
"||",
"room_id",
"==",
"\"0\"",
"room_id",
"=",
"repository",
".",
"room_id",
"end",
"builds",
".",
"create!",
"(",
":compare",
"=>",
"compare",
",",
":user",
"=>",
"user",
",",
":commit",
"=>",
"commit",
",",
":room_id",
"=>",
"room_id",
")",
"end"
] |
Create a build for the given commit.
commit - the Janky::Commit instance to build.
user - The login of the GitHub user who pushed.
compare - optional String GitHub Compare View URL. Defaults to the
commit last build, if any.
room_id - optional String room ID. Defaults to the room set on
the repository.
Returns the newly created Janky::Build.
|
[
"Create",
"a",
"build",
"for",
"the",
"given",
"commit",
"."
] |
59c17b0b9beb8e126bcf2a2e641203fbca7ded06
|
https://github.com/github/janky/blob/59c17b0b9beb8e126bcf2a2e641203fbca7ded06/lib/janky/branch.rb#L64-L80
|
15,172
|
github/janky
|
lib/janky/branch.rb
|
Janky.Branch.head_build_for
|
def head_build_for(room_id, user)
sha_to_build = GitHub.branch_head_sha(repository.nwo, name)
return if !sha_to_build
commit = repository.commit_for_sha(sha_to_build)
current_sha = current_build ? current_build.sha1 : "#{sha_to_build}^"
compare_url = repository.github_url("compare/#{current_sha}...#{commit.sha1}")
build_for(commit, user, room_id, compare_url)
end
|
ruby
|
def head_build_for(room_id, user)
sha_to_build = GitHub.branch_head_sha(repository.nwo, name)
return if !sha_to_build
commit = repository.commit_for_sha(sha_to_build)
current_sha = current_build ? current_build.sha1 : "#{sha_to_build}^"
compare_url = repository.github_url("compare/#{current_sha}...#{commit.sha1}")
build_for(commit, user, room_id, compare_url)
end
|
[
"def",
"head_build_for",
"(",
"room_id",
",",
"user",
")",
"sha_to_build",
"=",
"GitHub",
".",
"branch_head_sha",
"(",
"repository",
".",
"nwo",
",",
"name",
")",
"return",
"if",
"!",
"sha_to_build",
"commit",
"=",
"repository",
".",
"commit_for_sha",
"(",
"sha_to_build",
")",
"current_sha",
"=",
"current_build",
"?",
"current_build",
".",
"sha1",
":",
"\"#{sha_to_build}^\"",
"compare_url",
"=",
"repository",
".",
"github_url",
"(",
"\"compare/#{current_sha}...#{commit.sha1}\"",
")",
"build_for",
"(",
"commit",
",",
"user",
",",
"room_id",
",",
"compare_url",
")",
"end"
] |
Fetch the HEAD commit of this branch using the GitHub API and create a
build and commit record.
room_id - See build_for documentation. This is passed as is to the
build_for method.
user - Ditto.
Returns the newly created Janky::Build.
|
[
"Fetch",
"the",
"HEAD",
"commit",
"of",
"this",
"branch",
"using",
"the",
"GitHub",
"API",
"and",
"create",
"a",
"build",
"and",
"commit",
"record",
"."
] |
59c17b0b9beb8e126bcf2a2e641203fbca7ded06
|
https://github.com/github/janky/blob/59c17b0b9beb8e126bcf2a2e641203fbca7ded06/lib/janky/branch.rb#L90-L99
|
15,173
|
github/janky
|
lib/janky/branch.rb
|
Janky.Branch.status
|
def status
if current_build && current_build.building?
"building"
elsif build = completed_builds.first
if build.green?
"green"
elsif build.red?
"red"
end
elsif completed_builds.empty? || builds.empty?
"no build"
else
raise Error, "unexpected branch status: #{id.inspect}"
end
end
|
ruby
|
def status
if current_build && current_build.building?
"building"
elsif build = completed_builds.first
if build.green?
"green"
elsif build.red?
"red"
end
elsif completed_builds.empty? || builds.empty?
"no build"
else
raise Error, "unexpected branch status: #{id.inspect}"
end
end
|
[
"def",
"status",
"if",
"current_build",
"&&",
"current_build",
".",
"building?",
"\"building\"",
"elsif",
"build",
"=",
"completed_builds",
".",
"first",
"if",
"build",
".",
"green?",
"\"green\"",
"elsif",
"build",
".",
"red?",
"\"red\"",
"end",
"elsif",
"completed_builds",
".",
"empty?",
"||",
"builds",
".",
"empty?",
"\"no build\"",
"else",
"raise",
"Error",
",",
"\"unexpected branch status: #{id.inspect}\"",
"end",
"end"
] |
Human readable status of this branch
Returns a String.
|
[
"Human",
"readable",
"status",
"of",
"this",
"branch"
] |
59c17b0b9beb8e126bcf2a2e641203fbca7ded06
|
https://github.com/github/janky/blob/59c17b0b9beb8e126bcf2a2e641203fbca7ded06/lib/janky/branch.rb#L111-L125
|
15,174
|
github/janky
|
lib/janky/branch.rb
|
Janky.Branch.to_hash
|
def to_hash
{
:name => repository.name,
:status => status,
:sha1 => (current_build && current_build.sha1),
:compare => (current_build && current_build.compare)
}
end
|
ruby
|
def to_hash
{
:name => repository.name,
:status => status,
:sha1 => (current_build && current_build.sha1),
:compare => (current_build && current_build.compare)
}
end
|
[
"def",
"to_hash",
"{",
":name",
"=>",
"repository",
".",
"name",
",",
":status",
"=>",
"status",
",",
":sha1",
"=>",
"(",
"current_build",
"&&",
"current_build",
".",
"sha1",
")",
",",
":compare",
"=>",
"(",
"current_build",
"&&",
"current_build",
".",
"compare",
")",
"}",
"end"
] |
Hash representation of this branch status.
Returns a Hash with the name, status, sha1 and compare url.
|
[
"Hash",
"representation",
"of",
"this",
"branch",
"status",
"."
] |
59c17b0b9beb8e126bcf2a2e641203fbca7ded06
|
https://github.com/github/janky/blob/59c17b0b9beb8e126bcf2a2e641203fbca7ded06/lib/janky/branch.rb#L130-L137
|
15,175
|
github/janky
|
lib/janky/repository.rb
|
Janky.Repository.job_name
|
def job_name
md5 = Digest::MD5.new
md5 << name
md5 << uri
md5 << job_config_path.read
md5 << builder.callback_url.to_s
"#{name}-#{md5.hexdigest[0,12]}"
end
|
ruby
|
def job_name
md5 = Digest::MD5.new
md5 << name
md5 << uri
md5 << job_config_path.read
md5 << builder.callback_url.to_s
"#{name}-#{md5.hexdigest[0,12]}"
end
|
[
"def",
"job_name",
"md5",
"=",
"Digest",
"::",
"MD5",
".",
"new",
"md5",
"<<",
"name",
"md5",
"<<",
"uri",
"md5",
"<<",
"job_config_path",
".",
"read",
"md5",
"<<",
"builder",
".",
"callback_url",
".",
"to_s",
"\"#{name}-#{md5.hexdigest[0,12]}\"",
"end"
] |
Calculate the name of the Jenkins job.
Returns a String hash of this Repository name and uri.
|
[
"Calculate",
"the",
"name",
"of",
"the",
"Jenkins",
"job",
"."
] |
59c17b0b9beb8e126bcf2a2e641203fbca7ded06
|
https://github.com/github/janky/blob/59c17b0b9beb8e126bcf2a2e641203fbca7ded06/lib/janky/repository.rb#L234-L241
|
15,176
|
github/janky
|
lib/janky/build.rb
|
Janky.Build.rerun
|
def rerun(new_room_id = nil)
build = branch.build_for(commit, new_room_id)
build.run
build
end
|
ruby
|
def rerun(new_room_id = nil)
build = branch.build_for(commit, new_room_id)
build.run
build
end
|
[
"def",
"rerun",
"(",
"new_room_id",
"=",
"nil",
")",
"build",
"=",
"branch",
".",
"build_for",
"(",
"commit",
",",
"new_room_id",
")",
"build",
".",
"run",
"build",
"end"
] |
Run a copy of itself. Typically used to force a build in case of
temporary test failure or when auto-build is disabled.
new_room_id - optional Campfire room String ID. Defaults to the room of the
build being re-run.
Returns the build copy.
|
[
"Run",
"a",
"copy",
"of",
"itself",
".",
"Typically",
"used",
"to",
"force",
"a",
"build",
"in",
"case",
"of",
"temporary",
"test",
"failure",
"or",
"when",
"auto",
"-",
"build",
"is",
"disabled",
"."
] |
59c17b0b9beb8e126bcf2a2e641203fbca7ded06
|
https://github.com/github/janky/blob/59c17b0b9beb8e126bcf2a2e641203fbca7ded06/lib/janky/build.rb#L138-L142
|
15,177
|
github/janky
|
lib/janky/build.rb
|
Janky.Build.start
|
def start(url, now)
if started?
raise Error, "Build #{id} already started"
elsif completed?
raise Error, "Build #{id} already completed"
else
update_attributes!(:url => url, :started_at => now)
Notifier.started(self)
end
end
|
ruby
|
def start(url, now)
if started?
raise Error, "Build #{id} already started"
elsif completed?
raise Error, "Build #{id} already completed"
else
update_attributes!(:url => url, :started_at => now)
Notifier.started(self)
end
end
|
[
"def",
"start",
"(",
"url",
",",
"now",
")",
"if",
"started?",
"raise",
"Error",
",",
"\"Build #{id} already started\"",
"elsif",
"completed?",
"raise",
"Error",
",",
"\"Build #{id} already completed\"",
"else",
"update_attributes!",
"(",
":url",
"=>",
"url",
",",
":started_at",
"=>",
"now",
")",
"Notifier",
".",
"started",
"(",
"self",
")",
"end",
"end"
] |
Mark the build as started.
url - the full String URL of the build on the Jenkins server.
now - the Time at which the build started.
Returns nothing or raise an Error for weird transitions.
|
[
"Mark",
"the",
"build",
"as",
"started",
"."
] |
59c17b0b9beb8e126bcf2a2e641203fbca7ded06
|
https://github.com/github/janky/blob/59c17b0b9beb8e126bcf2a2e641203fbca7ded06/lib/janky/build.rb#L172-L181
|
15,178
|
github/janky
|
lib/janky/build.rb
|
Janky.Build.complete
|
def complete(green, now)
if ! started?
raise Error, "Build #{id} not started"
elsif completed?
raise Error, "Build #{id} already completed"
else
update_attributes!(
:green => green,
:completed_at => now,
:output => output_remote
)
Notifier.completed(self)
end
end
|
ruby
|
def complete(green, now)
if ! started?
raise Error, "Build #{id} not started"
elsif completed?
raise Error, "Build #{id} already completed"
else
update_attributes!(
:green => green,
:completed_at => now,
:output => output_remote
)
Notifier.completed(self)
end
end
|
[
"def",
"complete",
"(",
"green",
",",
"now",
")",
"if",
"!",
"started?",
"raise",
"Error",
",",
"\"Build #{id} not started\"",
"elsif",
"completed?",
"raise",
"Error",
",",
"\"Build #{id} already completed\"",
"else",
"update_attributes!",
"(",
":green",
"=>",
"green",
",",
":completed_at",
"=>",
"now",
",",
":output",
"=>",
"output_remote",
")",
"Notifier",
".",
"completed",
"(",
"self",
")",
"end",
"end"
] |
Mark the build as complete, store the build output and notify Campfire.
green - Boolean indicating build success.
now - the Time at which the build completed.
Returns nothing or raise an Error for weird transitions.
|
[
"Mark",
"the",
"build",
"as",
"complete",
"store",
"the",
"build",
"output",
"and",
"notify",
"Campfire",
"."
] |
59c17b0b9beb8e126bcf2a2e641203fbca7ded06
|
https://github.com/github/janky/blob/59c17b0b9beb8e126bcf2a2e641203fbca7ded06/lib/janky/build.rb#L189-L202
|
15,179
|
discourse/logster
|
lib/logster/message.rb
|
Logster.Message.solved_keys
|
def solved_keys
if Array === env
versions = env.map { |single_env| single_env["application_version"] }
else
versions = env["application_version"]
end
if versions && backtrace && backtrace.length > 0
versions = [versions] if String === versions
versions.map do |version|
Digest::SHA1.hexdigest "#{version} #{backtrace}"
end
end
end
|
ruby
|
def solved_keys
if Array === env
versions = env.map { |single_env| single_env["application_version"] }
else
versions = env["application_version"]
end
if versions && backtrace && backtrace.length > 0
versions = [versions] if String === versions
versions.map do |version|
Digest::SHA1.hexdigest "#{version} #{backtrace}"
end
end
end
|
[
"def",
"solved_keys",
"if",
"Array",
"===",
"env",
"versions",
"=",
"env",
".",
"map",
"{",
"|",
"single_env",
"|",
"single_env",
"[",
"\"application_version\"",
"]",
"}",
"else",
"versions",
"=",
"env",
"[",
"\"application_version\"",
"]",
"end",
"if",
"versions",
"&&",
"backtrace",
"&&",
"backtrace",
".",
"length",
">",
"0",
"versions",
"=",
"[",
"versions",
"]",
"if",
"String",
"===",
"versions",
"versions",
".",
"map",
"do",
"|",
"version",
"|",
"Digest",
"::",
"SHA1",
".",
"hexdigest",
"\"#{version} #{backtrace}\"",
"end",
"end",
"end"
] |
todo - memoize?
|
[
"todo",
"-",
"memoize?"
] |
5cdcb76bccf7d79f7b864f11fd4f586fa685b7fc
|
https://github.com/discourse/logster/blob/5cdcb76bccf7d79f7b864f11fd4f586fa685b7fc/lib/logster/message.rb#L112-L126
|
15,180
|
bogdan/datagrid
|
lib/datagrid/helper.rb
|
Datagrid.Helper.datagrid_rows
|
def datagrid_rows(grid, assets = grid.assets, **options, &block)
datagrid_renderer.rows(grid, assets, options, &block)
end
|
ruby
|
def datagrid_rows(grid, assets = grid.assets, **options, &block)
datagrid_renderer.rows(grid, assets, options, &block)
end
|
[
"def",
"datagrid_rows",
"(",
"grid",
",",
"assets",
"=",
"grid",
".",
"assets",
",",
"**",
"options",
",",
"&",
"block",
")",
"datagrid_renderer",
".",
"rows",
"(",
"grid",
",",
"assets",
",",
"options",
",",
"block",
")",
"end"
] |
Renders HTML table rows using given grid definition using columns defined in it.
Allows to provide a custom layout for each for in place with a block
Supported options:
* <tt>:columns</tt> - Array of column names to display.
Used in case when same grid class is used in different places
and needs different columns. Default: all defined columns.
* <tt>:partials</tt> - Path for partials lookup.
Default: 'datagrid'.
= datagrid_rows(grid) # Generic table rows Layout
= datagrid_rows(grid) do |row| # Custom Layout
%tr
%td= row.project_name
%td.project-status{class: row.status}= row.status
|
[
"Renders",
"HTML",
"table",
"rows",
"using",
"given",
"grid",
"definition",
"using",
"columns",
"defined",
"in",
"it",
".",
"Allows",
"to",
"provide",
"a",
"custom",
"layout",
"for",
"each",
"for",
"in",
"place",
"with",
"a",
"block"
] |
bd54295b5e7476a86113c317a6c980a8cd5a2f82
|
https://github.com/bogdan/datagrid/blob/bd54295b5e7476a86113c317a6c980a8cd5a2f82/lib/datagrid/helper.rb#L75-L77
|
15,181
|
bogdan/datagrid
|
lib/datagrid/helper.rb
|
Datagrid.Helper.datagrid_row
|
def datagrid_row(grid, asset, &block)
HtmlRow.new(self, grid, asset).tap do |row|
if block_given?
return capture(row, &block)
end
end
end
|
ruby
|
def datagrid_row(grid, asset, &block)
HtmlRow.new(self, grid, asset).tap do |row|
if block_given?
return capture(row, &block)
end
end
end
|
[
"def",
"datagrid_row",
"(",
"grid",
",",
"asset",
",",
"&",
"block",
")",
"HtmlRow",
".",
"new",
"(",
"self",
",",
"grid",
",",
"asset",
")",
".",
"tap",
"do",
"|",
"row",
"|",
"if",
"block_given?",
"return",
"capture",
"(",
"row",
",",
"block",
")",
"end",
"end",
"end"
] |
Provides access to datagrid columns data.
# Suppose that <tt>grid</tt> has first_name and last_name columns
<%= datagrid_row(grid, user) do |row| %>
<tr>
<td><%= row.first_name %></td>
<td><%= row.last_name %></td>
</tr>
<% end %>
Used in case you want to build html table completelly manually
|
[
"Provides",
"access",
"to",
"datagrid",
"columns",
"data",
"."
] |
bd54295b5e7476a86113c317a6c980a8cd5a2f82
|
https://github.com/bogdan/datagrid/blob/bd54295b5e7476a86113c317a6c980a8cd5a2f82/lib/datagrid/helper.rb#L111-L117
|
15,182
|
bogdan/datagrid
|
lib/datagrid/helper.rb
|
Datagrid.Helper.datagrid_order_path
|
def datagrid_order_path(grid, column, descending)
datagrid_renderer.order_path(grid, column, descending, request)
end
|
ruby
|
def datagrid_order_path(grid, column, descending)
datagrid_renderer.order_path(grid, column, descending, request)
end
|
[
"def",
"datagrid_order_path",
"(",
"grid",
",",
"column",
",",
"descending",
")",
"datagrid_renderer",
".",
"order_path",
"(",
"grid",
",",
"column",
",",
"descending",
",",
"request",
")",
"end"
] |
Generates an ascending or descending order url for the given column
|
[
"Generates",
"an",
"ascending",
"or",
"descending",
"order",
"url",
"for",
"the",
"given",
"column"
] |
bd54295b5e7476a86113c317a6c980a8cd5a2f82
|
https://github.com/bogdan/datagrid/blob/bd54295b5e7476a86113c317a6c980a8cd5a2f82/lib/datagrid/helper.rb#L120-L122
|
15,183
|
bogdan/datagrid
|
lib/datagrid/form_builder.rb
|
Datagrid.FormBuilder.datagrid_filter
|
def datagrid_filter(filter_or_attribute, options = {}, &block)
filter = datagrid_get_filter(filter_or_attribute)
options = add_html_classes(options, filter.name, datagrid_filter_html_class(filter))
# Prevent partials option from appearing in HTML attributes
options.delete(:partials) # Legacy option
self.send(filter.form_builder_helper_name, filter, options, &block)
end
|
ruby
|
def datagrid_filter(filter_or_attribute, options = {}, &block)
filter = datagrid_get_filter(filter_or_attribute)
options = add_html_classes(options, filter.name, datagrid_filter_html_class(filter))
# Prevent partials option from appearing in HTML attributes
options.delete(:partials) # Legacy option
self.send(filter.form_builder_helper_name, filter, options, &block)
end
|
[
"def",
"datagrid_filter",
"(",
"filter_or_attribute",
",",
"options",
"=",
"{",
"}",
",",
"&",
"block",
")",
"filter",
"=",
"datagrid_get_filter",
"(",
"filter_or_attribute",
")",
"options",
"=",
"add_html_classes",
"(",
"options",
",",
"filter",
".",
"name",
",",
"datagrid_filter_html_class",
"(",
"filter",
")",
")",
"# Prevent partials option from appearing in HTML attributes",
"options",
".",
"delete",
"(",
":partials",
")",
"# Legacy option",
"self",
".",
"send",
"(",
"filter",
".",
"form_builder_helper_name",
",",
"filter",
",",
"options",
",",
"block",
")",
"end"
] |
Returns a form input html for the corresponding filter name
|
[
"Returns",
"a",
"form",
"input",
"html",
"for",
"the",
"corresponding",
"filter",
"name"
] |
bd54295b5e7476a86113c317a6c980a8cd5a2f82
|
https://github.com/bogdan/datagrid/blob/bd54295b5e7476a86113c317a6c980a8cd5a2f82/lib/datagrid/form_builder.rb#L7-L13
|
15,184
|
bogdan/datagrid
|
lib/datagrid/form_builder.rb
|
Datagrid.FormBuilder.datagrid_label
|
def datagrid_label(filter_or_attribute, options_or_text = {}, options = {}, &block)
filter = datagrid_get_filter(filter_or_attribute)
text, options = options_or_text.is_a?(Hash) ? [filter.header, options_or_text] : [options_or_text, options]
label(filter.name, text, options, &block)
end
|
ruby
|
def datagrid_label(filter_or_attribute, options_or_text = {}, options = {}, &block)
filter = datagrid_get_filter(filter_or_attribute)
text, options = options_or_text.is_a?(Hash) ? [filter.header, options_or_text] : [options_or_text, options]
label(filter.name, text, options, &block)
end
|
[
"def",
"datagrid_label",
"(",
"filter_or_attribute",
",",
"options_or_text",
"=",
"{",
"}",
",",
"options",
"=",
"{",
"}",
",",
"&",
"block",
")",
"filter",
"=",
"datagrid_get_filter",
"(",
"filter_or_attribute",
")",
"text",
",",
"options",
"=",
"options_or_text",
".",
"is_a?",
"(",
"Hash",
")",
"?",
"[",
"filter",
".",
"header",
",",
"options_or_text",
"]",
":",
"[",
"options_or_text",
",",
"options",
"]",
"label",
"(",
"filter",
".",
"name",
",",
"text",
",",
"options",
",",
"block",
")",
"end"
] |
Returns a form label html for the corresponding filter name
|
[
"Returns",
"a",
"form",
"label",
"html",
"for",
"the",
"corresponding",
"filter",
"name"
] |
bd54295b5e7476a86113c317a6c980a8cd5a2f82
|
https://github.com/bogdan/datagrid/blob/bd54295b5e7476a86113c317a6c980a8cd5a2f82/lib/datagrid/form_builder.rb#L16-L20
|
15,185
|
rzane/baby_squeel
|
lib/baby_squeel/dsl.rb
|
BabySqueel.DSL._
|
def _(expr)
expr = Arel.sql(expr.to_sql) if expr.is_a? ::ActiveRecord::Relation
Nodes.wrap Arel::Nodes::Grouping.new(expr)
end
|
ruby
|
def _(expr)
expr = Arel.sql(expr.to_sql) if expr.is_a? ::ActiveRecord::Relation
Nodes.wrap Arel::Nodes::Grouping.new(expr)
end
|
[
"def",
"_",
"(",
"expr",
")",
"expr",
"=",
"Arel",
".",
"sql",
"(",
"expr",
".",
"to_sql",
")",
"if",
"expr",
".",
"is_a?",
"::",
"ActiveRecord",
"::",
"Relation",
"Nodes",
".",
"wrap",
"Arel",
"::",
"Nodes",
"::",
"Grouping",
".",
"new",
"(",
"expr",
")",
"end"
] |
Create a Grouping node. This allows you to set balanced
pairs of parentheses around your SQL.
==== Arguments
* +expr+ - The expression to group.
==== Example
Post.where.has{_([summary, description]).in(...)}
#=> SELECT "posts".* FROM "posts" WHERE ("posts"."summary", "posts"."description") IN (...)"
Post.select{[id, _(Comment.where.has{post_id == posts.id}.selecting{COUNT(id)})]}.as('comment_count')}
#=> SELECT "posts"."id", (SELECT COUNT("comments"."id") FROM "comments" WHERE "comments.post_id" = "posts"."id") AS "comment_count" FROM "posts"
|
[
"Create",
"a",
"Grouping",
"node",
".",
"This",
"allows",
"you",
"to",
"set",
"balanced",
"pairs",
"of",
"parentheses",
"around",
"your",
"SQL",
"."
] |
a71a46290f49261071031b3f5a868d574f2e96c8
|
https://github.com/rzane/baby_squeel/blob/a71a46290f49261071031b3f5a868d574f2e96c8/lib/baby_squeel/dsl.rb#L32-L35
|
15,186
|
ErwinM/acts_as_tenant
|
lib/acts_as_tenant/controller_extensions.rb
|
ActsAsTenant.ControllerExtensions.set_current_tenant_by_subdomain
|
def set_current_tenant_by_subdomain(tenant = :account, column = :subdomain )
self.class_eval do
cattr_accessor :tenant_class, :tenant_column
end
self.tenant_class = tenant.to_s.camelcase.constantize
self.tenant_column = column.to_sym
self.class_eval do
before_action :find_tenant_by_subdomain
helper_method :current_tenant if respond_to?(:helper_method)
private
def find_tenant_by_subdomain
if request.subdomains.last
ActsAsTenant.current_tenant = tenant_class.where(tenant_column => request.subdomains.last.downcase).first
end
end
def current_tenant
ActsAsTenant.current_tenant
end
end
end
|
ruby
|
def set_current_tenant_by_subdomain(tenant = :account, column = :subdomain )
self.class_eval do
cattr_accessor :tenant_class, :tenant_column
end
self.tenant_class = tenant.to_s.camelcase.constantize
self.tenant_column = column.to_sym
self.class_eval do
before_action :find_tenant_by_subdomain
helper_method :current_tenant if respond_to?(:helper_method)
private
def find_tenant_by_subdomain
if request.subdomains.last
ActsAsTenant.current_tenant = tenant_class.where(tenant_column => request.subdomains.last.downcase).first
end
end
def current_tenant
ActsAsTenant.current_tenant
end
end
end
|
[
"def",
"set_current_tenant_by_subdomain",
"(",
"tenant",
"=",
":account",
",",
"column",
"=",
":subdomain",
")",
"self",
".",
"class_eval",
"do",
"cattr_accessor",
":tenant_class",
",",
":tenant_column",
"end",
"self",
".",
"tenant_class",
"=",
"tenant",
".",
"to_s",
".",
"camelcase",
".",
"constantize",
"self",
".",
"tenant_column",
"=",
"column",
".",
"to_sym",
"self",
".",
"class_eval",
"do",
"before_action",
":find_tenant_by_subdomain",
"helper_method",
":current_tenant",
"if",
"respond_to?",
"(",
":helper_method",
")",
"private",
"def",
"find_tenant_by_subdomain",
"if",
"request",
".",
"subdomains",
".",
"last",
"ActsAsTenant",
".",
"current_tenant",
"=",
"tenant_class",
".",
"where",
"(",
"tenant_column",
"=>",
"request",
".",
"subdomains",
".",
"last",
".",
"downcase",
")",
".",
"first",
"end",
"end",
"def",
"current_tenant",
"ActsAsTenant",
".",
"current_tenant",
"end",
"end",
"end"
] |
this method allows setting the current_tenant by reading the subdomain and looking
it up in the tenant-model passed to the method. The method will look for the subdomain
in a column referenced by the second argument.
|
[
"this",
"method",
"allows",
"setting",
"the",
"current_tenant",
"by",
"reading",
"the",
"subdomain",
"and",
"looking",
"it",
"up",
"in",
"the",
"tenant",
"-",
"model",
"passed",
"to",
"the",
"method",
".",
"The",
"method",
"will",
"look",
"for",
"the",
"subdomain",
"in",
"a",
"column",
"referenced",
"by",
"the",
"second",
"argument",
"."
] |
6014ca8d670a4cbc5380dc3278ed985a80fae791
|
https://github.com/ErwinM/acts_as_tenant/blob/6014ca8d670a4cbc5380dc3278ed985a80fae791/lib/acts_as_tenant/controller_extensions.rb#L7-L32
|
15,187
|
ErwinM/acts_as_tenant
|
lib/acts_as_tenant/controller_extensions.rb
|
ActsAsTenant.ControllerExtensions.set_current_tenant_through_filter
|
def set_current_tenant_through_filter
self.class_eval do
helper_method :current_tenant if respond_to?(:helper_method)
private
def set_current_tenant(current_tenant_object)
ActsAsTenant.current_tenant = current_tenant_object
end
def current_tenant
ActsAsTenant.current_tenant
end
end
end
|
ruby
|
def set_current_tenant_through_filter
self.class_eval do
helper_method :current_tenant if respond_to?(:helper_method)
private
def set_current_tenant(current_tenant_object)
ActsAsTenant.current_tenant = current_tenant_object
end
def current_tenant
ActsAsTenant.current_tenant
end
end
end
|
[
"def",
"set_current_tenant_through_filter",
"self",
".",
"class_eval",
"do",
"helper_method",
":current_tenant",
"if",
"respond_to?",
"(",
":helper_method",
")",
"private",
"def",
"set_current_tenant",
"(",
"current_tenant_object",
")",
"ActsAsTenant",
".",
"current_tenant",
"=",
"current_tenant_object",
"end",
"def",
"current_tenant",
"ActsAsTenant",
".",
"current_tenant",
"end",
"end",
"end"
] |
This method sets up a method that allows manual setting of the current_tenant. This method should
be used in a before_action. In addition, a helper is setup that returns the current_tenant
|
[
"This",
"method",
"sets",
"up",
"a",
"method",
"that",
"allows",
"manual",
"setting",
"of",
"the",
"current_tenant",
".",
"This",
"method",
"should",
"be",
"used",
"in",
"a",
"before_action",
".",
"In",
"addition",
"a",
"helper",
"is",
"setup",
"that",
"returns",
"the",
"current_tenant"
] |
6014ca8d670a4cbc5380dc3278ed985a80fae791
|
https://github.com/ErwinM/acts_as_tenant/blob/6014ca8d670a4cbc5380dc3278ed985a80fae791/lib/acts_as_tenant/controller_extensions.rb#L70-L83
|
15,188
|
mojombo/god
|
lib/god/metric.rb
|
God.Metric.condition
|
def condition(kind)
# Create the condition.
begin
c = Condition.generate(kind, self.watch)
rescue NoSuchConditionError => e
abort e.message
end
# Send to block so config can set attributes.
yield(c) if block_given?
# Prepare the condition.
c.prepare
# Test generic and specific validity.
unless Condition.valid?(c) && c.valid?
abort "Exiting on invalid condition"
end
# Inherit interval from watch if no poll condition specific interval was
# set.
if c.kind_of?(PollCondition) && !c.interval
if self.watch.interval
c.interval = self.watch.interval
else
abort "No interval set for Condition '#{c.class.name}' in Watch " +
"'#{self.watch.name}', and no default Watch interval from " +
"which to inherit."
end
end
# Add the condition to the list.
self.conditions << c
end
|
ruby
|
def condition(kind)
# Create the condition.
begin
c = Condition.generate(kind, self.watch)
rescue NoSuchConditionError => e
abort e.message
end
# Send to block so config can set attributes.
yield(c) if block_given?
# Prepare the condition.
c.prepare
# Test generic and specific validity.
unless Condition.valid?(c) && c.valid?
abort "Exiting on invalid condition"
end
# Inherit interval from watch if no poll condition specific interval was
# set.
if c.kind_of?(PollCondition) && !c.interval
if self.watch.interval
c.interval = self.watch.interval
else
abort "No interval set for Condition '#{c.class.name}' in Watch " +
"'#{self.watch.name}', and no default Watch interval from " +
"which to inherit."
end
end
# Add the condition to the list.
self.conditions << c
end
|
[
"def",
"condition",
"(",
"kind",
")",
"# Create the condition.",
"begin",
"c",
"=",
"Condition",
".",
"generate",
"(",
"kind",
",",
"self",
".",
"watch",
")",
"rescue",
"NoSuchConditionError",
"=>",
"e",
"abort",
"e",
".",
"message",
"end",
"# Send to block so config can set attributes.",
"yield",
"(",
"c",
")",
"if",
"block_given?",
"# Prepare the condition.",
"c",
".",
"prepare",
"# Test generic and specific validity.",
"unless",
"Condition",
".",
"valid?",
"(",
"c",
")",
"&&",
"c",
".",
"valid?",
"abort",
"\"Exiting on invalid condition\"",
"end",
"# Inherit interval from watch if no poll condition specific interval was",
"# set.",
"if",
"c",
".",
"kind_of?",
"(",
"PollCondition",
")",
"&&",
"!",
"c",
".",
"interval",
"if",
"self",
".",
"watch",
".",
"interval",
"c",
".",
"interval",
"=",
"self",
".",
"watch",
".",
"interval",
"else",
"abort",
"\"No interval set for Condition '#{c.class.name}' in Watch \"",
"+",
"\"'#{self.watch.name}', and no default Watch interval from \"",
"+",
"\"which to inherit.\"",
"end",
"end",
"# Add the condition to the list.",
"self",
".",
"conditions",
"<<",
"c",
"end"
] |
Initialize a new Metric.
watch - The Watch.
destination - The optional destination Hash in canonical hash form.
Public: Instantiate the given Condition and pass it into the optional
block. Attributes of the condition must be set in the config file.
kind - The Symbol name of the condition.
Returns nothing.
|
[
"Initialize",
"a",
"new",
"Metric",
"."
] |
92c06aa5f6293cf26498a306e9bb7ac856d7dca0
|
https://github.com/mojombo/god/blob/92c06aa5f6293cf26498a306e9bb7ac856d7dca0/lib/god/metric.rb#L32-L65
|
15,189
|
mojombo/god
|
lib/god/socket.rb
|
God.Socket.start
|
def start
begin
@drb ||= DRb.start_service(self.socket, self)
applog(nil, :info, "Started on #{DRb.uri}")
rescue Errno::EADDRINUSE
applog(nil, :info, "Socket already in use")
server = DRbObject.new(nil, self.socket)
begin
Timeout.timeout(5) do
server.ping
end
abort "Socket #{self.socket} already in use by another instance of god"
rescue StandardError, Timeout::Error
applog(nil, :info, "Socket is stale, reopening")
File.delete(self.socket_file) rescue nil
@drb ||= DRb.start_service(self.socket, self)
applog(nil, :info, "Started on #{DRb.uri}")
end
end
if File.exists?(self.socket_file)
if @user
user_method = @user.is_a?(Integer) ? :getpwuid : :getpwnam
uid = Etc.send(user_method, @user).uid
gid = Etc.send(user_method, @user).gid
end
if @group
group_method = @group.is_a?(Integer) ? :getgrgid : :getgrnam
gid = Etc.send(group_method, @group).gid
end
File.chmod(Integer(@perm), socket_file) if @perm
File.chown(uid, gid, socket_file) if uid or gid
end
end
|
ruby
|
def start
begin
@drb ||= DRb.start_service(self.socket, self)
applog(nil, :info, "Started on #{DRb.uri}")
rescue Errno::EADDRINUSE
applog(nil, :info, "Socket already in use")
server = DRbObject.new(nil, self.socket)
begin
Timeout.timeout(5) do
server.ping
end
abort "Socket #{self.socket} already in use by another instance of god"
rescue StandardError, Timeout::Error
applog(nil, :info, "Socket is stale, reopening")
File.delete(self.socket_file) rescue nil
@drb ||= DRb.start_service(self.socket, self)
applog(nil, :info, "Started on #{DRb.uri}")
end
end
if File.exists?(self.socket_file)
if @user
user_method = @user.is_a?(Integer) ? :getpwuid : :getpwnam
uid = Etc.send(user_method, @user).uid
gid = Etc.send(user_method, @user).gid
end
if @group
group_method = @group.is_a?(Integer) ? :getgrgid : :getgrnam
gid = Etc.send(group_method, @group).gid
end
File.chmod(Integer(@perm), socket_file) if @perm
File.chown(uid, gid, socket_file) if uid or gid
end
end
|
[
"def",
"start",
"begin",
"@drb",
"||=",
"DRb",
".",
"start_service",
"(",
"self",
".",
"socket",
",",
"self",
")",
"applog",
"(",
"nil",
",",
":info",
",",
"\"Started on #{DRb.uri}\"",
")",
"rescue",
"Errno",
"::",
"EADDRINUSE",
"applog",
"(",
"nil",
",",
":info",
",",
"\"Socket already in use\"",
")",
"server",
"=",
"DRbObject",
".",
"new",
"(",
"nil",
",",
"self",
".",
"socket",
")",
"begin",
"Timeout",
".",
"timeout",
"(",
"5",
")",
"do",
"server",
".",
"ping",
"end",
"abort",
"\"Socket #{self.socket} already in use by another instance of god\"",
"rescue",
"StandardError",
",",
"Timeout",
"::",
"Error",
"applog",
"(",
"nil",
",",
":info",
",",
"\"Socket is stale, reopening\"",
")",
"File",
".",
"delete",
"(",
"self",
".",
"socket_file",
")",
"rescue",
"nil",
"@drb",
"||=",
"DRb",
".",
"start_service",
"(",
"self",
".",
"socket",
",",
"self",
")",
"applog",
"(",
"nil",
",",
":info",
",",
"\"Started on #{DRb.uri}\"",
")",
"end",
"end",
"if",
"File",
".",
"exists?",
"(",
"self",
".",
"socket_file",
")",
"if",
"@user",
"user_method",
"=",
"@user",
".",
"is_a?",
"(",
"Integer",
")",
"?",
":getpwuid",
":",
":getpwnam",
"uid",
"=",
"Etc",
".",
"send",
"(",
"user_method",
",",
"@user",
")",
".",
"uid",
"gid",
"=",
"Etc",
".",
"send",
"(",
"user_method",
",",
"@user",
")",
".",
"gid",
"end",
"if",
"@group",
"group_method",
"=",
"@group",
".",
"is_a?",
"(",
"Integer",
")",
"?",
":getgrgid",
":",
":getgrnam",
"gid",
"=",
"Etc",
".",
"send",
"(",
"group_method",
",",
"@group",
")",
".",
"gid",
"end",
"File",
".",
"chmod",
"(",
"Integer",
"(",
"@perm",
")",
",",
"socket_file",
")",
"if",
"@perm",
"File",
".",
"chown",
"(",
"uid",
",",
"gid",
",",
"socket_file",
")",
"if",
"uid",
"or",
"gid",
"end",
"end"
] |
Start the DRb server. Abort if there is already a running god instance
on the socket.
Returns nothing
|
[
"Start",
"the",
"DRb",
"server",
".",
"Abort",
"if",
"there",
"is",
"already",
"a",
"running",
"god",
"instance",
"on",
"the",
"socket",
"."
] |
92c06aa5f6293cf26498a306e9bb7ac856d7dca0
|
https://github.com/mojombo/god/blob/92c06aa5f6293cf26498a306e9bb7ac856d7dca0/lib/god/socket.rb#L75-L110
|
15,190
|
mojombo/god
|
lib/god/task.rb
|
God.Task.valid?
|
def valid?
valid = true
# A name must be specified.
if self.name.nil?
valid = false
applog(self, :error, "No name String was specified.")
end
# Valid states must be specified.
if self.valid_states.nil?
valid = false
applog(self, :error, "No valid_states Array or Symbols was specified.")
end
# An initial state must be specified.
if self.initial_state.nil?
valid = false
applog(self, :error, "No initial_state Symbol was specified.")
end
valid
end
|
ruby
|
def valid?
valid = true
# A name must be specified.
if self.name.nil?
valid = false
applog(self, :error, "No name String was specified.")
end
# Valid states must be specified.
if self.valid_states.nil?
valid = false
applog(self, :error, "No valid_states Array or Symbols was specified.")
end
# An initial state must be specified.
if self.initial_state.nil?
valid = false
applog(self, :error, "No initial_state Symbol was specified.")
end
valid
end
|
[
"def",
"valid?",
"valid",
"=",
"true",
"# A name must be specified.",
"if",
"self",
".",
"name",
".",
"nil?",
"valid",
"=",
"false",
"applog",
"(",
"self",
",",
":error",
",",
"\"No name String was specified.\"",
")",
"end",
"# Valid states must be specified.",
"if",
"self",
".",
"valid_states",
".",
"nil?",
"valid",
"=",
"false",
"applog",
"(",
"self",
",",
":error",
",",
"\"No valid_states Array or Symbols was specified.\"",
")",
"end",
"# An initial state must be specified.",
"if",
"self",
".",
"initial_state",
".",
"nil?",
"valid",
"=",
"false",
"applog",
"(",
"self",
",",
":error",
",",
"\"No initial_state Symbol was specified.\"",
")",
"end",
"valid",
"end"
] |
Verify that the minimum set of configuration requirements has been met.
Returns true if valid, false if not.
|
[
"Verify",
"that",
"the",
"minimum",
"set",
"of",
"configuration",
"requirements",
"has",
"been",
"met",
"."
] |
92c06aa5f6293cf26498a306e9bb7ac856d7dca0
|
https://github.com/mojombo/god/blob/92c06aa5f6293cf26498a306e9bb7ac856d7dca0/lib/god/task.rb#L66-L88
|
15,191
|
mojombo/god
|
lib/god/task.rb
|
God.Task.move
|
def move(to_state)
if !self.driver.in_driver_context?
# Called from outside Driver. Send an async message to Driver.
self.driver.message(:move, [to_state])
else
# Called from within Driver. Record original info.
orig_to_state = to_state
from_state = self.state
# Log.
msg = "#{self.name} move '#{from_state}' to '#{to_state}'"
applog(self, :info, msg)
# Cleanup from current state.
self.driver.clear_events
self.metrics[from_state].each { |m| m.disable }
if to_state == :unmonitored
self.metrics[nil].each { |m| m.disable }
end
# Perform action.
self.action(to_state)
# Enable simple mode.
if [:start, :restart].include?(to_state) && self.metrics[to_state].empty?
to_state = :up
end
# Move to new state.
self.metrics[to_state].each { |m| m.enable }
# If no from state, enable lifecycle metric.
if from_state == :unmonitored
self.metrics[nil].each { |m| m.enable }
end
# Set state.
self.state = to_state
# Broadcast to interested TriggerConditions.
Trigger.broadcast(self, :state_change, [from_state, orig_to_state])
# Log.
msg = "#{self.name} moved '#{from_state}' to '#{to_state}'"
applog(self, :info, msg)
end
self
end
|
ruby
|
def move(to_state)
if !self.driver.in_driver_context?
# Called from outside Driver. Send an async message to Driver.
self.driver.message(:move, [to_state])
else
# Called from within Driver. Record original info.
orig_to_state = to_state
from_state = self.state
# Log.
msg = "#{self.name} move '#{from_state}' to '#{to_state}'"
applog(self, :info, msg)
# Cleanup from current state.
self.driver.clear_events
self.metrics[from_state].each { |m| m.disable }
if to_state == :unmonitored
self.metrics[nil].each { |m| m.disable }
end
# Perform action.
self.action(to_state)
# Enable simple mode.
if [:start, :restart].include?(to_state) && self.metrics[to_state].empty?
to_state = :up
end
# Move to new state.
self.metrics[to_state].each { |m| m.enable }
# If no from state, enable lifecycle metric.
if from_state == :unmonitored
self.metrics[nil].each { |m| m.enable }
end
# Set state.
self.state = to_state
# Broadcast to interested TriggerConditions.
Trigger.broadcast(self, :state_change, [from_state, orig_to_state])
# Log.
msg = "#{self.name} moved '#{from_state}' to '#{to_state}'"
applog(self, :info, msg)
end
self
end
|
[
"def",
"move",
"(",
"to_state",
")",
"if",
"!",
"self",
".",
"driver",
".",
"in_driver_context?",
"# Called from outside Driver. Send an async message to Driver.",
"self",
".",
"driver",
".",
"message",
"(",
":move",
",",
"[",
"to_state",
"]",
")",
"else",
"# Called from within Driver. Record original info.",
"orig_to_state",
"=",
"to_state",
"from_state",
"=",
"self",
".",
"state",
"# Log.",
"msg",
"=",
"\"#{self.name} move '#{from_state}' to '#{to_state}'\"",
"applog",
"(",
"self",
",",
":info",
",",
"msg",
")",
"# Cleanup from current state.",
"self",
".",
"driver",
".",
"clear_events",
"self",
".",
"metrics",
"[",
"from_state",
"]",
".",
"each",
"{",
"|",
"m",
"|",
"m",
".",
"disable",
"}",
"if",
"to_state",
"==",
":unmonitored",
"self",
".",
"metrics",
"[",
"nil",
"]",
".",
"each",
"{",
"|",
"m",
"|",
"m",
".",
"disable",
"}",
"end",
"# Perform action.",
"self",
".",
"action",
"(",
"to_state",
")",
"# Enable simple mode.",
"if",
"[",
":start",
",",
":restart",
"]",
".",
"include?",
"(",
"to_state",
")",
"&&",
"self",
".",
"metrics",
"[",
"to_state",
"]",
".",
"empty?",
"to_state",
"=",
":up",
"end",
"# Move to new state.",
"self",
".",
"metrics",
"[",
"to_state",
"]",
".",
"each",
"{",
"|",
"m",
"|",
"m",
".",
"enable",
"}",
"# If no from state, enable lifecycle metric.",
"if",
"from_state",
"==",
":unmonitored",
"self",
".",
"metrics",
"[",
"nil",
"]",
".",
"each",
"{",
"|",
"m",
"|",
"m",
".",
"enable",
"}",
"end",
"# Set state.",
"self",
".",
"state",
"=",
"to_state",
"# Broadcast to interested TriggerConditions.",
"Trigger",
".",
"broadcast",
"(",
"self",
",",
":state_change",
",",
"[",
"from_state",
",",
"orig_to_state",
"]",
")",
"# Log.",
"msg",
"=",
"\"#{self.name} moved '#{from_state}' to '#{to_state}'\"",
"applog",
"(",
"self",
",",
":info",
",",
"msg",
")",
"end",
"self",
"end"
] |
Move to the given state.
to_state - The Symbol representing the state to move to.
Returns this Task.
|
[
"Move",
"to",
"the",
"given",
"state",
"."
] |
92c06aa5f6293cf26498a306e9bb7ac856d7dca0
|
https://github.com/mojombo/god/blob/92c06aa5f6293cf26498a306e9bb7ac856d7dca0/lib/god/task.rb#L194-L242
|
15,192
|
mojombo/god
|
lib/god/task.rb
|
God.Task.action
|
def action(a, c = nil)
if !self.driver.in_driver_context?
# Called from outside Driver. Send an async message to Driver.
self.driver.message(:action, [a, c])
else
# Called from within Driver.
if self.respond_to?(a)
command = self.send(a)
case command
when String
msg = "#{self.name} #{a}: #{command}"
applog(self, :info, msg)
system(command)
when Proc
msg = "#{self.name} #{a}: lambda"
applog(self, :info, msg)
command.call
else
raise NotImplementedError
end
end
end
end
|
ruby
|
def action(a, c = nil)
if !self.driver.in_driver_context?
# Called from outside Driver. Send an async message to Driver.
self.driver.message(:action, [a, c])
else
# Called from within Driver.
if self.respond_to?(a)
command = self.send(a)
case command
when String
msg = "#{self.name} #{a}: #{command}"
applog(self, :info, msg)
system(command)
when Proc
msg = "#{self.name} #{a}: lambda"
applog(self, :info, msg)
command.call
else
raise NotImplementedError
end
end
end
end
|
[
"def",
"action",
"(",
"a",
",",
"c",
"=",
"nil",
")",
"if",
"!",
"self",
".",
"driver",
".",
"in_driver_context?",
"# Called from outside Driver. Send an async message to Driver.",
"self",
".",
"driver",
".",
"message",
"(",
":action",
",",
"[",
"a",
",",
"c",
"]",
")",
"else",
"# Called from within Driver.",
"if",
"self",
".",
"respond_to?",
"(",
"a",
")",
"command",
"=",
"self",
".",
"send",
"(",
"a",
")",
"case",
"command",
"when",
"String",
"msg",
"=",
"\"#{self.name} #{a}: #{command}\"",
"applog",
"(",
"self",
",",
":info",
",",
"msg",
")",
"system",
"(",
"command",
")",
"when",
"Proc",
"msg",
"=",
"\"#{self.name} #{a}: lambda\"",
"applog",
"(",
"self",
",",
":info",
",",
"msg",
")",
"command",
".",
"call",
"else",
"raise",
"NotImplementedError",
"end",
"end",
"end",
"end"
] |
Perform the given action.
a - The Symbol action.
c - The Condition.
Returns this Task.
|
[
"Perform",
"the",
"given",
"action",
"."
] |
92c06aa5f6293cf26498a306e9bb7ac856d7dca0
|
https://github.com/mojombo/god/blob/92c06aa5f6293cf26498a306e9bb7ac856d7dca0/lib/god/task.rb#L284-L309
|
15,193
|
mojombo/god
|
lib/god/task.rb
|
God.Task.handle_event
|
def handle_event(condition)
# Lookup metric.
metric = self.directory[condition]
# Log.
messages = self.log_line(self, metric, condition, true)
# Notify.
if condition.notify
self.notify(condition, messages.last)
end
# Get the destination.
dest =
if condition.transition
# Condition override.
condition.transition
else
# Regular.
metric.destination && metric.destination[true]
end
if dest
self.move(dest)
end
end
|
ruby
|
def handle_event(condition)
# Lookup metric.
metric = self.directory[condition]
# Log.
messages = self.log_line(self, metric, condition, true)
# Notify.
if condition.notify
self.notify(condition, messages.last)
end
# Get the destination.
dest =
if condition.transition
# Condition override.
condition.transition
else
# Regular.
metric.destination && metric.destination[true]
end
if dest
self.move(dest)
end
end
|
[
"def",
"handle_event",
"(",
"condition",
")",
"# Lookup metric.",
"metric",
"=",
"self",
".",
"directory",
"[",
"condition",
"]",
"# Log.",
"messages",
"=",
"self",
".",
"log_line",
"(",
"self",
",",
"metric",
",",
"condition",
",",
"true",
")",
"# Notify.",
"if",
"condition",
".",
"notify",
"self",
".",
"notify",
"(",
"condition",
",",
"messages",
".",
"last",
")",
"end",
"# Get the destination.",
"dest",
"=",
"if",
"condition",
".",
"transition",
"# Condition override.",
"condition",
".",
"transition",
"else",
"# Regular.",
"metric",
".",
"destination",
"&&",
"metric",
".",
"destination",
"[",
"true",
"]",
"end",
"if",
"dest",
"self",
".",
"move",
"(",
"dest",
")",
"end",
"end"
] |
Asynchronously evaluate and handle the given event condition. Handles
logging notifications, and moving to the new state if necessary.
condition - The Condition to handle.
Returns nothing.
|
[
"Asynchronously",
"evaluate",
"and",
"handle",
"the",
"given",
"event",
"condition",
".",
"Handles",
"logging",
"notifications",
"and",
"moving",
"to",
"the",
"new",
"state",
"if",
"necessary",
"."
] |
92c06aa5f6293cf26498a306e9bb7ac856d7dca0
|
https://github.com/mojombo/god/blob/92c06aa5f6293cf26498a306e9bb7ac856d7dca0/lib/god/task.rb#L421-L446
|
15,194
|
mojombo/god
|
lib/god/task.rb
|
God.Task.log_line
|
def log_line(watch, metric, condition, result)
status =
if self.trigger?(metric, result)
"[trigger]"
else
"[ok]"
end
messages = []
# Log info if available.
if condition.info
Array(condition.info).each do |condition_info|
messages << "#{watch.name} #{status} #{condition_info} (#{condition.base_name})"
applog(watch, :info, messages.last)
end
else
messages << "#{watch.name} #{status} (#{condition.base_name})"
applog(watch, :info, messages.last)
end
# Log.
debug_message = watch.name + ' ' + condition.base_name + " [#{result}] " + self.dest_desc(metric, condition)
applog(watch, :debug, debug_message)
messages
end
|
ruby
|
def log_line(watch, metric, condition, result)
status =
if self.trigger?(metric, result)
"[trigger]"
else
"[ok]"
end
messages = []
# Log info if available.
if condition.info
Array(condition.info).each do |condition_info|
messages << "#{watch.name} #{status} #{condition_info} (#{condition.base_name})"
applog(watch, :info, messages.last)
end
else
messages << "#{watch.name} #{status} (#{condition.base_name})"
applog(watch, :info, messages.last)
end
# Log.
debug_message = watch.name + ' ' + condition.base_name + " [#{result}] " + self.dest_desc(metric, condition)
applog(watch, :debug, debug_message)
messages
end
|
[
"def",
"log_line",
"(",
"watch",
",",
"metric",
",",
"condition",
",",
"result",
")",
"status",
"=",
"if",
"self",
".",
"trigger?",
"(",
"metric",
",",
"result",
")",
"\"[trigger]\"",
"else",
"\"[ok]\"",
"end",
"messages",
"=",
"[",
"]",
"# Log info if available.",
"if",
"condition",
".",
"info",
"Array",
"(",
"condition",
".",
"info",
")",
".",
"each",
"do",
"|",
"condition_info",
"|",
"messages",
"<<",
"\"#{watch.name} #{status} #{condition_info} (#{condition.base_name})\"",
"applog",
"(",
"watch",
",",
":info",
",",
"messages",
".",
"last",
")",
"end",
"else",
"messages",
"<<",
"\"#{watch.name} #{status} (#{condition.base_name})\"",
"applog",
"(",
"watch",
",",
":info",
",",
"messages",
".",
"last",
")",
"end",
"# Log.",
"debug_message",
"=",
"watch",
".",
"name",
"+",
"' '",
"+",
"condition",
".",
"base_name",
"+",
"\" [#{result}] \"",
"+",
"self",
".",
"dest_desc",
"(",
"metric",
",",
"condition",
")",
"applog",
"(",
"watch",
",",
":debug",
",",
"debug_message",
")",
"messages",
"end"
] |
Log info about the condition and return the list of messages logged.
watch - The Watch.
metric - The Metric.
condition - The Condition.
result - The Boolean result of the condition test evaluation.
Returns the Array of String messages.
|
[
"Log",
"info",
"about",
"the",
"condition",
"and",
"return",
"the",
"list",
"of",
"messages",
"logged",
"."
] |
92c06aa5f6293cf26498a306e9bb7ac856d7dca0
|
https://github.com/mojombo/god/blob/92c06aa5f6293cf26498a306e9bb7ac856d7dca0/lib/god/task.rb#L466-L492
|
15,195
|
mojombo/god
|
lib/god/task.rb
|
God.Task.dest_desc
|
def dest_desc(metric, condition)
if condition.transition
{true => condition.transition}.inspect
else
if metric.destination
metric.destination.inspect
else
'none'
end
end
end
|
ruby
|
def dest_desc(metric, condition)
if condition.transition
{true => condition.transition}.inspect
else
if metric.destination
metric.destination.inspect
else
'none'
end
end
end
|
[
"def",
"dest_desc",
"(",
"metric",
",",
"condition",
")",
"if",
"condition",
".",
"transition",
"{",
"true",
"=>",
"condition",
".",
"transition",
"}",
".",
"inspect",
"else",
"if",
"metric",
".",
"destination",
"metric",
".",
"destination",
".",
"inspect",
"else",
"'none'",
"end",
"end",
"end"
] |
Format the destination specification for use in debug logging.
metric - The Metric.
condition - The Condition.
Returns the formatted String.
|
[
"Format",
"the",
"destination",
"specification",
"for",
"use",
"in",
"debug",
"logging",
"."
] |
92c06aa5f6293cf26498a306e9bb7ac856d7dca0
|
https://github.com/mojombo/god/blob/92c06aa5f6293cf26498a306e9bb7ac856d7dca0/lib/god/task.rb#L500-L510
|
15,196
|
mojombo/god
|
lib/god/task.rb
|
God.Task.notify
|
def notify(condition, message)
spec = Contact.normalize(condition.notify)
unmatched = []
# Resolve contacts.
resolved_contacts =
spec[:contacts].inject([]) do |acc, contact_name_or_group|
cons = Array(God.contacts[contact_name_or_group] || God.contact_groups[contact_name_or_group])
unmatched << contact_name_or_group if cons.empty?
acc += cons
acc
end
# Warn about unmatched contacts.
unless unmatched.empty?
msg = "#{condition.watch.name} no matching contacts for '#{unmatched.join(", ")}'"
applog(condition.watch, :warn, msg)
end
# Notify each contact.
resolved_contacts.each do |c|
host = `hostname`.chomp rescue 'none'
begin
c.notify(message, Time.now, spec[:priority], spec[:category], host)
msg = "#{condition.watch.name} #{c.info ? c.info : "notification sent for contact: #{c.name}"} (#{c.base_name})"
applog(condition.watch, :info, msg % [])
rescue Exception => e
applog(condition.watch, :error, "#{e.message} #{e.backtrace}")
msg = "#{condition.watch.name} Failed to deliver notification for contact: #{c.name} (#{c.base_name})"
applog(condition.watch, :error, msg % [])
end
end
end
|
ruby
|
def notify(condition, message)
spec = Contact.normalize(condition.notify)
unmatched = []
# Resolve contacts.
resolved_contacts =
spec[:contacts].inject([]) do |acc, contact_name_or_group|
cons = Array(God.contacts[contact_name_or_group] || God.contact_groups[contact_name_or_group])
unmatched << contact_name_or_group if cons.empty?
acc += cons
acc
end
# Warn about unmatched contacts.
unless unmatched.empty?
msg = "#{condition.watch.name} no matching contacts for '#{unmatched.join(", ")}'"
applog(condition.watch, :warn, msg)
end
# Notify each contact.
resolved_contacts.each do |c|
host = `hostname`.chomp rescue 'none'
begin
c.notify(message, Time.now, spec[:priority], spec[:category], host)
msg = "#{condition.watch.name} #{c.info ? c.info : "notification sent for contact: #{c.name}"} (#{c.base_name})"
applog(condition.watch, :info, msg % [])
rescue Exception => e
applog(condition.watch, :error, "#{e.message} #{e.backtrace}")
msg = "#{condition.watch.name} Failed to deliver notification for contact: #{c.name} (#{c.base_name})"
applog(condition.watch, :error, msg % [])
end
end
end
|
[
"def",
"notify",
"(",
"condition",
",",
"message",
")",
"spec",
"=",
"Contact",
".",
"normalize",
"(",
"condition",
".",
"notify",
")",
"unmatched",
"=",
"[",
"]",
"# Resolve contacts.",
"resolved_contacts",
"=",
"spec",
"[",
":contacts",
"]",
".",
"inject",
"(",
"[",
"]",
")",
"do",
"|",
"acc",
",",
"contact_name_or_group",
"|",
"cons",
"=",
"Array",
"(",
"God",
".",
"contacts",
"[",
"contact_name_or_group",
"]",
"||",
"God",
".",
"contact_groups",
"[",
"contact_name_or_group",
"]",
")",
"unmatched",
"<<",
"contact_name_or_group",
"if",
"cons",
".",
"empty?",
"acc",
"+=",
"cons",
"acc",
"end",
"# Warn about unmatched contacts.",
"unless",
"unmatched",
".",
"empty?",
"msg",
"=",
"\"#{condition.watch.name} no matching contacts for '#{unmatched.join(\", \")}'\"",
"applog",
"(",
"condition",
".",
"watch",
",",
":warn",
",",
"msg",
")",
"end",
"# Notify each contact.",
"resolved_contacts",
".",
"each",
"do",
"|",
"c",
"|",
"host",
"=",
"`",
"`",
".",
"chomp",
"rescue",
"'none'",
"begin",
"c",
".",
"notify",
"(",
"message",
",",
"Time",
".",
"now",
",",
"spec",
"[",
":priority",
"]",
",",
"spec",
"[",
":category",
"]",
",",
"host",
")",
"msg",
"=",
"\"#{condition.watch.name} #{c.info ? c.info : \"notification sent for contact: #{c.name}\"} (#{c.base_name})\"",
"applog",
"(",
"condition",
".",
"watch",
",",
":info",
",",
"msg",
"%",
"[",
"]",
")",
"rescue",
"Exception",
"=>",
"e",
"applog",
"(",
"condition",
".",
"watch",
",",
":error",
",",
"\"#{e.message} #{e.backtrace}\"",
")",
"msg",
"=",
"\"#{condition.watch.name} Failed to deliver notification for contact: #{c.name} (#{c.base_name})\"",
"applog",
"(",
"condition",
".",
"watch",
",",
":error",
",",
"msg",
"%",
"[",
"]",
")",
"end",
"end",
"end"
] |
Notify all recipients of the given condition with the specified message.
condition - The Condition.
message - The String message to send.
Returns nothing.
|
[
"Notify",
"all",
"recipients",
"of",
"the",
"given",
"condition",
"with",
"the",
"specified",
"message",
"."
] |
92c06aa5f6293cf26498a306e9bb7ac856d7dca0
|
https://github.com/mojombo/god/blob/92c06aa5f6293cf26498a306e9bb7ac856d7dca0/lib/god/task.rb#L518-L550
|
15,197
|
mojombo/god
|
lib/god/logger.rb
|
God.Logger.level=
|
def level=(lev)
SysLogger.level = SimpleLogger::CONSTANT_TO_SYMBOL[lev] if Logger.syslog
super(lev)
end
|
ruby
|
def level=(lev)
SysLogger.level = SimpleLogger::CONSTANT_TO_SYMBOL[lev] if Logger.syslog
super(lev)
end
|
[
"def",
"level",
"=",
"(",
"lev",
")",
"SysLogger",
".",
"level",
"=",
"SimpleLogger",
"::",
"CONSTANT_TO_SYMBOL",
"[",
"lev",
"]",
"if",
"Logger",
".",
"syslog",
"super",
"(",
"lev",
")",
"end"
] |
Instantiate a new Logger object
|
[
"Instantiate",
"a",
"new",
"Logger",
"object"
] |
92c06aa5f6293cf26498a306e9bb7ac856d7dca0
|
https://github.com/mojombo/god/blob/92c06aa5f6293cf26498a306e9bb7ac856d7dca0/lib/god/logger.rb#L26-L29
|
15,198
|
mojombo/god
|
lib/god/logger.rb
|
God.Logger.watch_log_since
|
def watch_log_since(watch_name, since)
# initialize watch log if necessary
self.logs[watch_name] ||= Timeline.new(God::LOG_BUFFER_SIZE_DEFAULT)
# get and join lines since given time
@mutex.synchronize do
@spool = Time.now
self.logs[watch_name].select do |x|
x.first > since
end.map do |x|
x[1]
end.join
end
end
|
ruby
|
def watch_log_since(watch_name, since)
# initialize watch log if necessary
self.logs[watch_name] ||= Timeline.new(God::LOG_BUFFER_SIZE_DEFAULT)
# get and join lines since given time
@mutex.synchronize do
@spool = Time.now
self.logs[watch_name].select do |x|
x.first > since
end.map do |x|
x[1]
end.join
end
end
|
[
"def",
"watch_log_since",
"(",
"watch_name",
",",
"since",
")",
"# initialize watch log if necessary",
"self",
".",
"logs",
"[",
"watch_name",
"]",
"||=",
"Timeline",
".",
"new",
"(",
"God",
"::",
"LOG_BUFFER_SIZE_DEFAULT",
")",
"# get and join lines since given time",
"@mutex",
".",
"synchronize",
"do",
"@spool",
"=",
"Time",
".",
"now",
"self",
".",
"logs",
"[",
"watch_name",
"]",
".",
"select",
"do",
"|",
"x",
"|",
"x",
".",
"first",
">",
"since",
"end",
".",
"map",
"do",
"|",
"x",
"|",
"x",
"[",
"1",
"]",
"end",
".",
"join",
"end",
"end"
] |
Get all log output for a given Watch since a certain Time.
+watch_name+ is the String name of the Watch
+since+ is the Time since which to fetch log lines
Returns String
|
[
"Get",
"all",
"log",
"output",
"for",
"a",
"given",
"Watch",
"since",
"a",
"certain",
"Time",
".",
"+",
"watch_name",
"+",
"is",
"the",
"String",
"name",
"of",
"the",
"Watch",
"+",
"since",
"+",
"is",
"the",
"Time",
"since",
"which",
"to",
"fetch",
"log",
"lines"
] |
92c06aa5f6293cf26498a306e9bb7ac856d7dca0
|
https://github.com/mojombo/god/blob/92c06aa5f6293cf26498a306e9bb7ac856d7dca0/lib/god/logger.rb#L70-L83
|
15,199
|
mojombo/god
|
lib/god/process.rb
|
God.Process.pid
|
def pid
contents = File.read(self.pid_file).strip rescue ''
real_pid = contents =~ /^\d+$/ ? contents.to_i : nil
if real_pid
@pid = real_pid
real_pid
else
@pid
end
end
|
ruby
|
def pid
contents = File.read(self.pid_file).strip rescue ''
real_pid = contents =~ /^\d+$/ ? contents.to_i : nil
if real_pid
@pid = real_pid
real_pid
else
@pid
end
end
|
[
"def",
"pid",
"contents",
"=",
"File",
".",
"read",
"(",
"self",
".",
"pid_file",
")",
".",
"strip",
"rescue",
"''",
"real_pid",
"=",
"contents",
"=~",
"/",
"\\d",
"/",
"?",
"contents",
".",
"to_i",
":",
"nil",
"if",
"real_pid",
"@pid",
"=",
"real_pid",
"real_pid",
"else",
"@pid",
"end",
"end"
] |
Fetch the PID from pid_file. If the pid_file does not
exist, then use the PID from the last time it was read.
If it has never been read, then return nil.
Returns Integer(pid) or nil
|
[
"Fetch",
"the",
"PID",
"from",
"pid_file",
".",
"If",
"the",
"pid_file",
"does",
"not",
"exist",
"then",
"use",
"the",
"PID",
"from",
"the",
"last",
"time",
"it",
"was",
"read",
".",
"If",
"it",
"has",
"never",
"been",
"read",
"then",
"return",
"nil",
"."
] |
92c06aa5f6293cf26498a306e9bb7ac856d7dca0
|
https://github.com/mojombo/god/blob/92c06aa5f6293cf26498a306e9bb7ac856d7dca0/lib/god/process.rb#L171-L181
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.