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
sequence
docstring
stringlengths
8
16k
docstring_tokens
sequence
sha
stringlengths
40
40
url
stringlengths
94
266
partition
stringclasses
1 value
sass/ruby-sass
lib/sass/script/value/helpers.rb
Sass::Script::Value.Helpers.parse_compound_selector
def parse_compound_selector(value, name = nil, allow_parent_ref = false) assert_type value, :String, name selector = parse_selector(value, name, allow_parent_ref) seq = selector.members.first sseq = seq.members.first if selector.members.length == 1 && seq.members.length == 1 && sseq.is_a?(Sass::Selector::SimpleSequence) return sseq end err = "#{value.inspect} is not a compound selector" err = "$#{name.to_s.tr('_', '-')}: #{err}" if name raise ArgumentError.new(err) end
ruby
def parse_compound_selector(value, name = nil, allow_parent_ref = false) assert_type value, :String, name selector = parse_selector(value, name, allow_parent_ref) seq = selector.members.first sseq = seq.members.first if selector.members.length == 1 && seq.members.length == 1 && sseq.is_a?(Sass::Selector::SimpleSequence) return sseq end err = "#{value.inspect} is not a compound selector" err = "$#{name.to_s.tr('_', '-')}: #{err}" if name raise ArgumentError.new(err) end
[ "def", "parse_compound_selector", "(", "value", ",", "name", "=", "nil", ",", "allow_parent_ref", "=", "false", ")", "assert_type", "value", ",", ":String", ",", "name", "selector", "=", "parse_selector", "(", "value", ",", "name", ",", "allow_parent_ref", ")", "seq", "=", "selector", ".", "members", ".", "first", "sseq", "=", "seq", ".", "members", ".", "first", "if", "selector", ".", "members", ".", "length", "==", "1", "&&", "seq", ".", "members", ".", "length", "==", "1", "&&", "sseq", ".", "is_a?", "(", "Sass", "::", "Selector", "::", "SimpleSequence", ")", "return", "sseq", "end", "err", "=", "\"#{value.inspect} is not a compound selector\"", "err", "=", "\"$#{name.to_s.tr('_', '-')}: #{err}\"", "if", "name", "raise", "ArgumentError", ".", "new", "(", "err", ")", "end" ]
Parses a user-provided compound selector. A compound selector cannot contain combinators or commas. @param value [Sass::Script::Value::String] The selector to parse. @param name [Symbol, nil] If provided, the name of the selector argument. This is used for error reporting. @param allow_parent_ref [Boolean] Whether the parsed selector should allow parent references. @return [Sass::Selector::SimpleSequence] The parsed selector. @throw [ArgumentError] if the parse failed for any reason.
[ "Parses", "a", "user", "-", "provided", "compound", "selector", "." ]
7a50eae567260a23d3bbf4d5aaf1a76db43dec32
https://github.com/sass/ruby-sass/blob/7a50eae567260a23d3bbf4d5aaf1a76db43dec32/lib/sass/script/value/helpers.rb#L191-L204
train
sass/ruby-sass
lib/sass/script/value/helpers.rb
Sass::Script::Value.Helpers.normalize_selector
def normalize_selector(value, name) if (str = selector_to_str(value)) return str end err = "#{value.inspect} is not a valid selector: it must be a string,\n" + "a list of strings, or a list of lists of strings" err = "$#{name.to_s.tr('_', '-')}: #{err}" if name raise ArgumentError.new(err) end
ruby
def normalize_selector(value, name) if (str = selector_to_str(value)) return str end err = "#{value.inspect} is not a valid selector: it must be a string,\n" + "a list of strings, or a list of lists of strings" err = "$#{name.to_s.tr('_', '-')}: #{err}" if name raise ArgumentError.new(err) end
[ "def", "normalize_selector", "(", "value", ",", "name", ")", "if", "(", "str", "=", "selector_to_str", "(", "value", ")", ")", "return", "str", "end", "err", "=", "\"#{value.inspect} is not a valid selector: it must be a string,\\n\"", "+", "\"a list of strings, or a list of lists of strings\"", "err", "=", "\"$#{name.to_s.tr('_', '-')}: #{err}\"", "if", "name", "raise", "ArgumentError", ".", "new", "(", "err", ")", "end" ]
Converts a user-provided selector into string form or throws an ArgumentError if it's in an invalid format.
[ "Converts", "a", "user", "-", "provided", "selector", "into", "string", "form", "or", "throws", "an", "ArgumentError", "if", "it", "s", "in", "an", "invalid", "format", "." ]
7a50eae567260a23d3bbf4d5aaf1a76db43dec32
https://github.com/sass/ruby-sass/blob/7a50eae567260a23d3bbf4d5aaf1a76db43dec32/lib/sass/script/value/helpers.rb#L237-L246
train
sass/ruby-sass
lib/sass/script/value/helpers.rb
Sass::Script::Value.Helpers.selector_to_str
def selector_to_str(value) return value.value if value.is_a?(Sass::Script::String) return unless value.is_a?(Sass::Script::List) if value.separator == :comma return value.to_a.map do |complex| next complex.value if complex.is_a?(Sass::Script::String) return unless complex.is_a?(Sass::Script::List) && complex.separator == :space return unless (str = selector_to_str(complex)) str end.join(', ') end value.to_a.map do |compound| return unless compound.is_a?(Sass::Script::String) compound.value end.join(' ') end
ruby
def selector_to_str(value) return value.value if value.is_a?(Sass::Script::String) return unless value.is_a?(Sass::Script::List) if value.separator == :comma return value.to_a.map do |complex| next complex.value if complex.is_a?(Sass::Script::String) return unless complex.is_a?(Sass::Script::List) && complex.separator == :space return unless (str = selector_to_str(complex)) str end.join(', ') end value.to_a.map do |compound| return unless compound.is_a?(Sass::Script::String) compound.value end.join(' ') end
[ "def", "selector_to_str", "(", "value", ")", "return", "value", ".", "value", "if", "value", ".", "is_a?", "(", "Sass", "::", "Script", "::", "String", ")", "return", "unless", "value", ".", "is_a?", "(", "Sass", "::", "Script", "::", "List", ")", "if", "value", ".", "separator", "==", ":comma", "return", "value", ".", "to_a", ".", "map", "do", "|", "complex", "|", "next", "complex", ".", "value", "if", "complex", ".", "is_a?", "(", "Sass", "::", "Script", "::", "String", ")", "return", "unless", "complex", ".", "is_a?", "(", "Sass", "::", "Script", "::", "List", ")", "&&", "complex", ".", "separator", "==", ":space", "return", "unless", "(", "str", "=", "selector_to_str", "(", "complex", ")", ")", "str", "end", ".", "join", "(", "', '", ")", "end", "value", ".", "to_a", ".", "map", "do", "|", "compound", "|", "return", "unless", "compound", ".", "is_a?", "(", "Sass", "::", "Script", "::", "String", ")", "compound", ".", "value", "end", ".", "join", "(", "' '", ")", "end" ]
Converts a user-provided selector into string form or returns `nil` if it's in an invalid format.
[ "Converts", "a", "user", "-", "provided", "selector", "into", "string", "form", "or", "returns", "nil", "if", "it", "s", "in", "an", "invalid", "format", "." ]
7a50eae567260a23d3bbf4d5aaf1a76db43dec32
https://github.com/sass/ruby-sass/blob/7a50eae567260a23d3bbf4d5aaf1a76db43dec32/lib/sass/script/value/helpers.rb#L250-L267
train
sass/ruby-sass
lib/sass/error.rb
Sass.SyntaxError.backtrace
def backtrace return nil if super.nil? return super if sass_backtrace.all? {|h| h.empty?} sass_backtrace.map do |h| "#{h[:filename] || '(sass)'}:#{h[:line]}" + (h[:mixin] ? ":in `#{h[:mixin]}'" : "") end + super end
ruby
def backtrace return nil if super.nil? return super if sass_backtrace.all? {|h| h.empty?} sass_backtrace.map do |h| "#{h[:filename] || '(sass)'}:#{h[:line]}" + (h[:mixin] ? ":in `#{h[:mixin]}'" : "") end + super end
[ "def", "backtrace", "return", "nil", "if", "super", ".", "nil?", "return", "super", "if", "sass_backtrace", ".", "all?", "{", "|", "h", "|", "h", ".", "empty?", "}", "sass_backtrace", ".", "map", "do", "|", "h", "|", "\"#{h[:filename] || '(sass)'}:#{h[:line]}\"", "+", "(", "h", "[", ":mixin", "]", "?", "\":in `#{h[:mixin]}'\"", ":", "\"\"", ")", "end", "+", "super", "end" ]
Returns the standard exception backtrace, including the Sass backtrace. @return [Array<String>]
[ "Returns", "the", "standard", "exception", "backtrace", "including", "the", "Sass", "backtrace", "." ]
7a50eae567260a23d3bbf4d5aaf1a76db43dec32
https://github.com/sass/ruby-sass/blob/7a50eae567260a23d3bbf4d5aaf1a76db43dec32/lib/sass/error.rb#L126-L133
train
sass/ruby-sass
lib/sass/error.rb
Sass.SyntaxError.sass_backtrace_str
def sass_backtrace_str(default_filename = "an unknown file") lines = message.split("\n") msg = lines[0] + lines[1..-1]. map {|l| "\n" + (" " * "Error: ".size) + l}.join "Error: #{msg}" + sass_backtrace.each_with_index.map do |entry, i| "\n #{i == 0 ? 'on' : 'from'} line #{entry[:line]}" + " of #{entry[:filename] || default_filename}" + (entry[:mixin] ? ", in `#{entry[:mixin]}'" : "") end.join end
ruby
def sass_backtrace_str(default_filename = "an unknown file") lines = message.split("\n") msg = lines[0] + lines[1..-1]. map {|l| "\n" + (" " * "Error: ".size) + l}.join "Error: #{msg}" + sass_backtrace.each_with_index.map do |entry, i| "\n #{i == 0 ? 'on' : 'from'} line #{entry[:line]}" + " of #{entry[:filename] || default_filename}" + (entry[:mixin] ? ", in `#{entry[:mixin]}'" : "") end.join end
[ "def", "sass_backtrace_str", "(", "default_filename", "=", "\"an unknown file\"", ")", "lines", "=", "message", ".", "split", "(", "\"\\n\"", ")", "msg", "=", "lines", "[", "0", "]", "+", "lines", "[", "1", "..", "-", "1", "]", ".", "map", "{", "|", "l", "|", "\"\\n\"", "+", "(", "\" \"", "*", "\"Error: \"", ".", "size", ")", "+", "l", "}", ".", "join", "\"Error: #{msg}\"", "+", "sass_backtrace", ".", "each_with_index", ".", "map", "do", "|", "entry", ",", "i", "|", "\"\\n #{i == 0 ? 'on' : 'from'} line #{entry[:line]}\"", "+", "\" of #{entry[:filename] || default_filename}\"", "+", "(", "entry", "[", ":mixin", "]", "?", "\", in `#{entry[:mixin]}'\"", ":", "\"\"", ")", "end", ".", "join", "end" ]
Returns a string representation of the Sass backtrace. @param default_filename [String] The filename to use for unknown files @see #sass_backtrace @return [String]
[ "Returns", "a", "string", "representation", "of", "the", "Sass", "backtrace", "." ]
7a50eae567260a23d3bbf4d5aaf1a76db43dec32
https://github.com/sass/ruby-sass/blob/7a50eae567260a23d3bbf4d5aaf1a76db43dec32/lib/sass/error.rb#L140-L150
train
nesquena/rabl
lib/rabl/cache_engine.rb
Rabl.CacheEngine.fetch
def fetch(key, cache_options, &block) if defined?(Rails) Rails.cache.fetch(key, cache_options, &block) else @cache[key] ||= yield end end
ruby
def fetch(key, cache_options, &block) if defined?(Rails) Rails.cache.fetch(key, cache_options, &block) else @cache[key] ||= yield end end
[ "def", "fetch", "(", "key", ",", "cache_options", ",", "&", "block", ")", "if", "defined?", "(", "Rails", ")", "Rails", ".", "cache", ".", "fetch", "(", "key", ",", "cache_options", ",", "block", ")", "else", "@cache", "[", "key", "]", "||=", "yield", "end", "end" ]
Fetch given a key and options and a fallback block attempts to find the key in the cache and stores the block result in there if no key is found. cache = Rabl::CacheEngine.new; cache.fetch("some_key") { "fallback data" }
[ "Fetch", "given", "a", "key", "and", "options", "and", "a", "fallback", "block", "attempts", "to", "find", "the", "key", "in", "the", "cache", "and", "stores", "the", "block", "result", "in", "there", "if", "no", "key", "is", "found", "." ]
a112a4dd783996dab88299bbfead3fcb3d28f0d3
https://github.com/nesquena/rabl/blob/a112a4dd783996dab88299bbfead3fcb3d28f0d3/lib/rabl/cache_engine.rb#L43-L49
train
nesquena/rabl
lib/rabl/multi_builder.rb
Rabl.MultiBuilder.map_cache_key_to_engine
def map_cache_key_to_engine(engine) if cache_key = cache_key_for(engine) result_cache_key = ActiveSupport::Cache.expand_cache_key(cache_key, :rabl) @cache_key_to_engine[result_cache_key] = engine disable_cache_read_on_render(engine) end end
ruby
def map_cache_key_to_engine(engine) if cache_key = cache_key_for(engine) result_cache_key = ActiveSupport::Cache.expand_cache_key(cache_key, :rabl) @cache_key_to_engine[result_cache_key] = engine disable_cache_read_on_render(engine) end end
[ "def", "map_cache_key_to_engine", "(", "engine", ")", "if", "cache_key", "=", "cache_key_for", "(", "engine", ")", "result_cache_key", "=", "ActiveSupport", "::", "Cache", ".", "expand_cache_key", "(", "cache_key", ",", ":rabl", ")", "@cache_key_to_engine", "[", "result_cache_key", "]", "=", "engine", "disable_cache_read_on_render", "(", "engine", ")", "end", "end" ]
Maps a cache key to an engine
[ "Maps", "a", "cache", "key", "to", "an", "engine" ]
a112a4dd783996dab88299bbfead3fcb3d28f0d3
https://github.com/nesquena/rabl/blob/a112a4dd783996dab88299bbfead3fcb3d28f0d3/lib/rabl/multi_builder.rb#L54-L60
train
nesquena/rabl
lib/rabl/multi_builder.rb
Rabl.MultiBuilder.read_cache_results
def read_cache_results @cache_results ||= begin mutable_keys = @cache_key_to_engine.keys.map { |k| k.dup } if mutable_keys.empty? {} else Rabl.configuration.cache_engine.read_multi(*mutable_keys) end end end
ruby
def read_cache_results @cache_results ||= begin mutable_keys = @cache_key_to_engine.keys.map { |k| k.dup } if mutable_keys.empty? {} else Rabl.configuration.cache_engine.read_multi(*mutable_keys) end end end
[ "def", "read_cache_results", "@cache_results", "||=", "begin", "mutable_keys", "=", "@cache_key_to_engine", ".", "keys", ".", "map", "{", "|", "k", "|", "k", ".", "dup", "}", "if", "mutable_keys", ".", "empty?", "{", "}", "else", "Rabl", ".", "configuration", ".", "cache_engine", ".", "read_multi", "(", "mutable_keys", ")", "end", "end", "end" ]
Returns the items that were found in the cache
[ "Returns", "the", "items", "that", "were", "found", "in", "the", "cache" ]
a112a4dd783996dab88299bbfead3fcb3d28f0d3
https://github.com/nesquena/rabl/blob/a112a4dd783996dab88299bbfead3fcb3d28f0d3/lib/rabl/multi_builder.rb#L81-L90
train
nesquena/rabl
lib/rabl/multi_builder.rb
Rabl.MultiBuilder.replace_engines_with_cache_results
def replace_engines_with_cache_results @cache_results.each do |key, value| engine = @cache_key_to_engine[key] builder = @engine_to_builder[engine] builder.replace_engine(engine, value) if value end end
ruby
def replace_engines_with_cache_results @cache_results.each do |key, value| engine = @cache_key_to_engine[key] builder = @engine_to_builder[engine] builder.replace_engine(engine, value) if value end end
[ "def", "replace_engines_with_cache_results", "@cache_results", ".", "each", "do", "|", "key", ",", "value", "|", "engine", "=", "@cache_key_to_engine", "[", "key", "]", "builder", "=", "@engine_to_builder", "[", "engine", "]", "builder", ".", "replace_engine", "(", "engine", ",", "value", ")", "if", "value", "end", "end" ]
Maps the results from the cache back to the builders
[ "Maps", "the", "results", "from", "the", "cache", "back", "to", "the", "builders" ]
a112a4dd783996dab88299bbfead3fcb3d28f0d3
https://github.com/nesquena/rabl/blob/a112a4dd783996dab88299bbfead3fcb3d28f0d3/lib/rabl/multi_builder.rb#L93-L99
train
nesquena/rabl
lib/rabl/renderer.rb
Rabl.Renderer.process_source
def process_source(source) return source if source.is_a?(String) && source =~ /\n/ source, _ = engine.fetch_source(source, { :view_path => options[:view_path] }) source end
ruby
def process_source(source) return source if source.is_a?(String) && source =~ /\n/ source, _ = engine.fetch_source(source, { :view_path => options[:view_path] }) source end
[ "def", "process_source", "(", "source", ")", "return", "source", "if", "source", ".", "is_a?", "(", "String", ")", "&&", "source", "=~", "/", "\\n", "/", "source", ",", "_", "=", "engine", ".", "fetch_source", "(", "source", ",", "{", ":view_path", "=>", "options", "[", ":view_path", "]", "}", ")", "source", "end" ]
Returns the source given a relative template path
[ "Returns", "the", "source", "given", "a", "relative", "template", "path" ]
a112a4dd783996dab88299bbfead3fcb3d28f0d3
https://github.com/nesquena/rabl/blob/a112a4dd783996dab88299bbfead3fcb3d28f0d3/lib/rabl/renderer.rb#L63-L68
train
nesquena/rabl
lib/rabl/helpers.rb
Rabl.Helpers.determine_object_root
def determine_object_root(data_token, data_name = nil, include_root = true) return if object_root_name == false root_name = data_name.to_s if include_root if is_object?(data_token) || data_token.nil? root_name elsif is_collection?(data_token) object_root_name || (root_name.singularize if root_name) end end
ruby
def determine_object_root(data_token, data_name = nil, include_root = true) return if object_root_name == false root_name = data_name.to_s if include_root if is_object?(data_token) || data_token.nil? root_name elsif is_collection?(data_token) object_root_name || (root_name.singularize if root_name) end end
[ "def", "determine_object_root", "(", "data_token", ",", "data_name", "=", "nil", ",", "include_root", "=", "true", ")", "return", "if", "object_root_name", "==", "false", "root_name", "=", "data_name", ".", "to_s", "if", "include_root", "if", "is_object?", "(", "data_token", ")", "||", "data_token", ".", "nil?", "root_name", "elsif", "is_collection?", "(", "data_token", ")", "object_root_name", "||", "(", "root_name", ".", "singularize", "if", "root_name", ")", "end", "end" ]
Returns the object rootname based on if the root should be included Can be called with data as a collection or object determine_object_root(@user, :user, true) => "user" determine_object_root(@user, :person) => "person" determine_object_root([@user, @user]) => "user"
[ "Returns", "the", "object", "rootname", "based", "on", "if", "the", "root", "should", "be", "included", "Can", "be", "called", "with", "data", "as", "a", "collection", "or", "object", "determine_object_root", "(" ]
a112a4dd783996dab88299bbfead3fcb3d28f0d3
https://github.com/nesquena/rabl/blob/a112a4dd783996dab88299bbfead3fcb3d28f0d3/lib/rabl/helpers.rb#L62-L71
train
nesquena/rabl
lib/rabl/helpers.rb
Rabl.Helpers.is_collection?
def is_collection?(obj, follow_symbols = true) data_obj = follow_symbols ? data_object(obj) : obj data_obj && data_obj.is_a?(Enumerable) && !(data_obj.is_a?(Struct) || defined?(Hashie::Mash) && data_obj.is_a?(Hashie::Mash)) end
ruby
def is_collection?(obj, follow_symbols = true) data_obj = follow_symbols ? data_object(obj) : obj data_obj && data_obj.is_a?(Enumerable) && !(data_obj.is_a?(Struct) || defined?(Hashie::Mash) && data_obj.is_a?(Hashie::Mash)) end
[ "def", "is_collection?", "(", "obj", ",", "follow_symbols", "=", "true", ")", "data_obj", "=", "follow_symbols", "?", "data_object", "(", "obj", ")", ":", "obj", "data_obj", "&&", "data_obj", ".", "is_a?", "(", "Enumerable", ")", "&&", "!", "(", "data_obj", ".", "is_a?", "(", "Struct", ")", "||", "defined?", "(", "Hashie", "::", "Mash", ")", "&&", "data_obj", ".", "is_a?", "(", "Hashie", "::", "Mash", ")", ")", "end" ]
Returns true if the obj is a collection of items is_collection?(@user) => false is_collection?([]) => true
[ "Returns", "true", "if", "the", "obj", "is", "a", "collection", "of", "items", "is_collection?", "(" ]
a112a4dd783996dab88299bbfead3fcb3d28f0d3
https://github.com/nesquena/rabl/blob/a112a4dd783996dab88299bbfead3fcb3d28f0d3/lib/rabl/helpers.rb#L84-L90
train
nesquena/rabl
lib/rabl/helpers.rb
Rabl.Helpers.object_to_engine
def object_to_engine(object, options = {}, &block) return if object.nil? options.reverse_merge!({ :format => "hash".freeze, :view_path => view_path, :root => (options[:root] || false) }) Engine.new(options[:source], options).apply(context_scope, :object => object, :locals => options[:locals], &block) end
ruby
def object_to_engine(object, options = {}, &block) return if object.nil? options.reverse_merge!({ :format => "hash".freeze, :view_path => view_path, :root => (options[:root] || false) }) Engine.new(options[:source], options).apply(context_scope, :object => object, :locals => options[:locals], &block) end
[ "def", "object_to_engine", "(", "object", ",", "options", "=", "{", "}", ",", "&", "block", ")", "return", "if", "object", ".", "nil?", "options", ".", "reverse_merge!", "(", "{", ":format", "=>", "\"hash\"", ".", "freeze", ",", ":view_path", "=>", "view_path", ",", ":root", "=>", "(", "options", "[", ":root", "]", "||", "false", ")", "}", ")", "Engine", ".", "new", "(", "options", "[", ":source", "]", ",", "options", ")", ".", "apply", "(", "context_scope", ",", ":object", "=>", "object", ",", ":locals", "=>", "options", "[", ":locals", "]", ",", "block", ")", "end" ]
Returns an Engine based representation of any data object given ejs template block object_to_engine(@user) { attribute :full_name } => { ... } object_to_engine(@user, :source => "...") { attribute :full_name } => { ... } object_to_engine([@user], :source => "...") { attribute :full_name } => { ... } options must have :source (rabl file contents) options can have :source_location (source filename)
[ "Returns", "an", "Engine", "based", "representation", "of", "any", "data", "object", "given", "ejs", "template", "block", "object_to_engine", "(" ]
a112a4dd783996dab88299bbfead3fcb3d28f0d3
https://github.com/nesquena/rabl/blob/a112a4dd783996dab88299bbfead3fcb3d28f0d3/lib/rabl/helpers.rb#L127-L137
train
nesquena/rabl
lib/rabl/helpers.rb
Rabl.Helpers.template_cache_configured?
def template_cache_configured? if defined?(Rails) defined?(ActionController::Base) && ActionController::Base.perform_caching else Rabl.configuration.perform_caching end end
ruby
def template_cache_configured? if defined?(Rails) defined?(ActionController::Base) && ActionController::Base.perform_caching else Rabl.configuration.perform_caching end end
[ "def", "template_cache_configured?", "if", "defined?", "(", "Rails", ")", "defined?", "(", "ActionController", "::", "Base", ")", "&&", "ActionController", "::", "Base", ".", "perform_caching", "else", "Rabl", ".", "configuration", ".", "perform_caching", "end", "end" ]
Returns true if the cache has been enabled for the application
[ "Returns", "true", "if", "the", "cache", "has", "been", "enabled", "for", "the", "application" ]
a112a4dd783996dab88299bbfead3fcb3d28f0d3
https://github.com/nesquena/rabl/blob/a112a4dd783996dab88299bbfead3fcb3d28f0d3/lib/rabl/helpers.rb#L154-L160
train
nesquena/rabl
lib/rabl/engine.rb
Rabl.Engine.object
def object(template_data) current_data = (@_locals[:object].nil? || template_data == false) ? template_data : @_locals[:object] @_data_object = data_object(current_data) @_root_name_data = template_data.is_a?(Hash) && !current_data.is_a?(Hash) ? template_data : current_data @_root_name_data = @_root_name_data.values.first if @_root_name_data.is_a?(Hash) # If we turn this around, `@_root_name_date ==` may trigger data to be loaded unnecessarily. # TODO: is nil a different semantic? otherwise don't use `false ==`, use ! if false == @_root_name_data @_object_root_name = false @_collection_name = false end end
ruby
def object(template_data) current_data = (@_locals[:object].nil? || template_data == false) ? template_data : @_locals[:object] @_data_object = data_object(current_data) @_root_name_data = template_data.is_a?(Hash) && !current_data.is_a?(Hash) ? template_data : current_data @_root_name_data = @_root_name_data.values.first if @_root_name_data.is_a?(Hash) # If we turn this around, `@_root_name_date ==` may trigger data to be loaded unnecessarily. # TODO: is nil a different semantic? otherwise don't use `false ==`, use ! if false == @_root_name_data @_object_root_name = false @_collection_name = false end end
[ "def", "object", "(", "template_data", ")", "current_data", "=", "(", "@_locals", "[", ":object", "]", ".", "nil?", "||", "template_data", "==", "false", ")", "?", "template_data", ":", "@_locals", "[", ":object", "]", "@_data_object", "=", "data_object", "(", "current_data", ")", "@_root_name_data", "=", "template_data", ".", "is_a?", "(", "Hash", ")", "&&", "!", "current_data", ".", "is_a?", "(", "Hash", ")", "?", "template_data", ":", "current_data", "@_root_name_data", "=", "@_root_name_data", ".", "values", ".", "first", "if", "@_root_name_data", ".", "is_a?", "(", "Hash", ")", "# If we turn this around, `@_root_name_date ==` may trigger data to be loaded unnecessarily.", "# TODO: is nil a different semantic? otherwise don't use `false ==`, use !", "if", "false", "==", "@_root_name_data", "@_object_root_name", "=", "false", "@_collection_name", "=", "false", "end", "end" ]
Sets the object to be used as the data source for this template object(@user) object @user => :person object @users
[ "Sets", "the", "object", "to", "be", "used", "as", "the", "data", "source", "for", "this", "template", "object", "(" ]
a112a4dd783996dab88299bbfead3fcb3d28f0d3
https://github.com/nesquena/rabl/blob/a112a4dd783996dab88299bbfead3fcb3d28f0d3/lib/rabl/engine.rb#L163-L175
train
nesquena/rabl
lib/rabl/engine.rb
Rabl.Engine.collection
def collection(data, options = {}) @_collection_name = options[:root] if options[:root] @_collection_name ||= data.values.first if data.is_a?(Hash) @_object_root_name = options[:object_root] if options.has_key?(:object_root) object(data_object(data) || []) end
ruby
def collection(data, options = {}) @_collection_name = options[:root] if options[:root] @_collection_name ||= data.values.first if data.is_a?(Hash) @_object_root_name = options[:object_root] if options.has_key?(:object_root) object(data_object(data) || []) end
[ "def", "collection", "(", "data", ",", "options", "=", "{", "}", ")", "@_collection_name", "=", "options", "[", ":root", "]", "if", "options", "[", ":root", "]", "@_collection_name", "||=", "data", ".", "values", ".", "first", "if", "data", ".", "is_a?", "(", "Hash", ")", "@_object_root_name", "=", "options", "[", ":object_root", "]", "if", "options", ".", "has_key?", "(", ":object_root", ")", "object", "(", "data_object", "(", "data", ")", "||", "[", "]", ")", "end" ]
Sets the object as a collection casted to a simple array collection @users collection @users => :people collection @users, :root => :person collection @users, :object_root => :person
[ "Sets", "the", "object", "as", "a", "collection", "casted", "to", "a", "simple", "array", "collection" ]
a112a4dd783996dab88299bbfead3fcb3d28f0d3
https://github.com/nesquena/rabl/blob/a112a4dd783996dab88299bbfead3fcb3d28f0d3/lib/rabl/engine.rb#L201-L208
train
nesquena/rabl
lib/rabl/engine.rb
Rabl.Engine.default_object
def default_object return unless context_scope.respond_to?(:controller) controller_name = context_scope.controller.controller_name stripped_name = controller_name.split(%r{::|\/}).last ivar_object = instance_variable_get("@#{stripped_name}") ivar_object if is_object?(ivar_object) end
ruby
def default_object return unless context_scope.respond_to?(:controller) controller_name = context_scope.controller.controller_name stripped_name = controller_name.split(%r{::|\/}).last ivar_object = instance_variable_get("@#{stripped_name}") ivar_object if is_object?(ivar_object) end
[ "def", "default_object", "return", "unless", "context_scope", ".", "respond_to?", "(", ":controller", ")", "controller_name", "=", "context_scope", ".", "controller", ".", "controller_name", "stripped_name", "=", "controller_name", ".", "split", "(", "%r{", "\\/", "}", ")", ".", "last", "ivar_object", "=", "instance_variable_get", "(", "\"@#{stripped_name}\"", ")", "ivar_object", "if", "is_object?", "(", "ivar_object", ")", "end" ]
Returns a guess at the default object for this template default_object => @user
[ "Returns", "a", "guess", "at", "the", "default", "object", "for", "this", "template", "default_object", "=", ">" ]
a112a4dd783996dab88299bbfead3fcb3d28f0d3
https://github.com/nesquena/rabl/blob/a112a4dd783996dab88299bbfead3fcb3d28f0d3/lib/rabl/engine.rb#L301-L308
train
nesquena/rabl
lib/rabl/engine.rb
Rabl.Engine.request_format
def request_format format = request_params[:format] if format.nil? && context_scope.respond_to?(:request) request = context_scope.request format = request.format.to_sym.to_s if request.respond_to?(:format) end format = "json" unless format && respond_to?("to_#{format}") format end
ruby
def request_format format = request_params[:format] if format.nil? && context_scope.respond_to?(:request) request = context_scope.request format = request.format.to_sym.to_s if request.respond_to?(:format) end format = "json" unless format && respond_to?("to_#{format}") format end
[ "def", "request_format", "format", "=", "request_params", "[", ":format", "]", "if", "format", ".", "nil?", "&&", "context_scope", ".", "respond_to?", "(", ":request", ")", "request", "=", "context_scope", ".", "request", "format", "=", "request", ".", "format", ".", "to_sym", ".", "to_s", "if", "request", ".", "respond_to?", "(", ":format", ")", "end", "format", "=", "\"json\"", "unless", "format", "&&", "respond_to?", "(", "\"to_#{format}\"", ")", "format", "end" ]
Returns a guess at the format in this context_scope request_format => "xml"
[ "Returns", "a", "guess", "at", "the", "format", "in", "this", "context_scope", "request_format", "=", ">", "xml" ]
a112a4dd783996dab88299bbfead3fcb3d28f0d3
https://github.com/nesquena/rabl/blob/a112a4dd783996dab88299bbfead3fcb3d28f0d3/lib/rabl/engine.rb#L312-L323
train
nesquena/rabl
lib/rabl/engine.rb
Rabl.Engine.method_missing
def method_missing(name, *args, &block) context_scope.respond_to?(name, true) ? context_scope.__send__(name, *args, &block) : super end
ruby
def method_missing(name, *args, &block) context_scope.respond_to?(name, true) ? context_scope.__send__(name, *args, &block) : super end
[ "def", "method_missing", "(", "name", ",", "*", "args", ",", "&", "block", ")", "context_scope", ".", "respond_to?", "(", "name", ",", "true", ")", "?", "context_scope", ".", "__send__", "(", "name", ",", "args", ",", "block", ")", ":", "super", "end" ]
Supports calling helpers defined for the template context_scope using method_missing hook
[ "Supports", "calling", "helpers", "defined", "for", "the", "template", "context_scope", "using", "method_missing", "hook" ]
a112a4dd783996dab88299bbfead3fcb3d28f0d3
https://github.com/nesquena/rabl/blob/a112a4dd783996dab88299bbfead3fcb3d28f0d3/lib/rabl/engine.rb#L356-L358
train
nesquena/rabl
lib/rabl/sources.rb
Rabl.Sources.fetch_padrino_source
def fetch_padrino_source(file, options = {}) view_path = Array(options[:view_path] || context_scope.settings.views) # use Padrino's own template resolution mechanism file_path, _ = context_scope.instance_eval { resolve_template(file) } # Padrino chops the extension, stitch it back on File.join(view_path.first.to_s, (file_path.to_s + ".rabl")) end
ruby
def fetch_padrino_source(file, options = {}) view_path = Array(options[:view_path] || context_scope.settings.views) # use Padrino's own template resolution mechanism file_path, _ = context_scope.instance_eval { resolve_template(file) } # Padrino chops the extension, stitch it back on File.join(view_path.first.to_s, (file_path.to_s + ".rabl")) end
[ "def", "fetch_padrino_source", "(", "file", ",", "options", "=", "{", "}", ")", "view_path", "=", "Array", "(", "options", "[", ":view_path", "]", "||", "context_scope", ".", "settings", ".", "views", ")", "# use Padrino's own template resolution mechanism", "file_path", ",", "_", "=", "context_scope", ".", "instance_eval", "{", "resolve_template", "(", "file", ")", "}", "# Padrino chops the extension, stitch it back on", "File", ".", "join", "(", "view_path", ".", "first", ".", "to_s", ",", "(", "file_path", ".", "to_s", "+", "\".rabl\"", ")", ")", "end" ]
Returns the rabl template path for padrino views using configured views
[ "Returns", "the", "rabl", "template", "path", "for", "padrino", "views", "using", "configured", "views" ]
a112a4dd783996dab88299bbfead3fcb3d28f0d3
https://github.com/nesquena/rabl/blob/a112a4dd783996dab88299bbfead3fcb3d28f0d3/lib/rabl/sources.rb#L33-L41
train
nesquena/rabl
lib/rabl/sources.rb
Rabl.Sources.fetch_rails_source
def fetch_rails_source(file, options = {}) # use Rails template resolution mechanism if possible (find_template) source_format = request_format if defined?(request_format) if source_format && context_scope.respond_to?(:lookup_context) # Rails 3 lookup_proc = lambda do |partial| if ActionPack::VERSION::MAJOR == 3 && ActionPack::VERSION::MINOR < 2 context_scope.lookup_context.find(file, [], partial) else # Rails 3.2 and higher # pull format directly from rails unless it is html request_format = context_scope.request.format.to_sym source_format = request_format unless request_format == :html context_scope.lookup_context.find(file, [], partial, [], { :formats => [source_format] }) end end template = lookup_proc.call(false) rescue nil template ||= lookup_proc.call(true) rescue nil template.identifier if template elsif source_format && context_scope.respond_to?(:view_paths) # Rails 2 template = context_scope.view_paths.find_template(file, source_format, false) template.filename if template end end
ruby
def fetch_rails_source(file, options = {}) # use Rails template resolution mechanism if possible (find_template) source_format = request_format if defined?(request_format) if source_format && context_scope.respond_to?(:lookup_context) # Rails 3 lookup_proc = lambda do |partial| if ActionPack::VERSION::MAJOR == 3 && ActionPack::VERSION::MINOR < 2 context_scope.lookup_context.find(file, [], partial) else # Rails 3.2 and higher # pull format directly from rails unless it is html request_format = context_scope.request.format.to_sym source_format = request_format unless request_format == :html context_scope.lookup_context.find(file, [], partial, [], { :formats => [source_format] }) end end template = lookup_proc.call(false) rescue nil template ||= lookup_proc.call(true) rescue nil template.identifier if template elsif source_format && context_scope.respond_to?(:view_paths) # Rails 2 template = context_scope.view_paths.find_template(file, source_format, false) template.filename if template end end
[ "def", "fetch_rails_source", "(", "file", ",", "options", "=", "{", "}", ")", "# use Rails template resolution mechanism if possible (find_template)", "source_format", "=", "request_format", "if", "defined?", "(", "request_format", ")", "if", "source_format", "&&", "context_scope", ".", "respond_to?", "(", ":lookup_context", ")", "# Rails 3", "lookup_proc", "=", "lambda", "do", "|", "partial", "|", "if", "ActionPack", "::", "VERSION", "::", "MAJOR", "==", "3", "&&", "ActionPack", "::", "VERSION", "::", "MINOR", "<", "2", "context_scope", ".", "lookup_context", ".", "find", "(", "file", ",", "[", "]", ",", "partial", ")", "else", "# Rails 3.2 and higher", "# pull format directly from rails unless it is html", "request_format", "=", "context_scope", ".", "request", ".", "format", ".", "to_sym", "source_format", "=", "request_format", "unless", "request_format", "==", ":html", "context_scope", ".", "lookup_context", ".", "find", "(", "file", ",", "[", "]", ",", "partial", ",", "[", "]", ",", "{", ":formats", "=>", "[", "source_format", "]", "}", ")", "end", "end", "template", "=", "lookup_proc", ".", "call", "(", "false", ")", "rescue", "nil", "template", "||=", "lookup_proc", ".", "call", "(", "true", ")", "rescue", "nil", "template", ".", "identifier", "if", "template", "elsif", "source_format", "&&", "context_scope", ".", "respond_to?", "(", ":view_paths", ")", "# Rails 2", "template", "=", "context_scope", ".", "view_paths", ".", "find_template", "(", "file", ",", "source_format", ",", "false", ")", "template", ".", "filename", "if", "template", "end", "end" ]
Returns the rabl template path for Rails, including special lookups for Rails 2 and 3
[ "Returns", "the", "rabl", "template", "path", "for", "Rails", "including", "special", "lookups", "for", "Rails", "2", "and", "3" ]
a112a4dd783996dab88299bbfead3fcb3d28f0d3
https://github.com/nesquena/rabl/blob/a112a4dd783996dab88299bbfead3fcb3d28f0d3/lib/rabl/sources.rb#L44-L66
train
nesquena/rabl
lib/rabl/sources.rb
Rabl.Sources.fetch_sinatra_source
def fetch_sinatra_source(file, options = {}) view_path = Array(options[:view_path] || context_scope.settings.views) fetch_manual_template(view_path, file) end
ruby
def fetch_sinatra_source(file, options = {}) view_path = Array(options[:view_path] || context_scope.settings.views) fetch_manual_template(view_path, file) end
[ "def", "fetch_sinatra_source", "(", "file", ",", "options", "=", "{", "}", ")", "view_path", "=", "Array", "(", "options", "[", ":view_path", "]", "||", "context_scope", ".", "settings", ".", "views", ")", "fetch_manual_template", "(", "view_path", ",", "file", ")", "end" ]
Returns the rabl template path for sinatra views using configured views
[ "Returns", "the", "rabl", "template", "path", "for", "sinatra", "views", "using", "configured", "views" ]
a112a4dd783996dab88299bbfead3fcb3d28f0d3
https://github.com/nesquena/rabl/blob/a112a4dd783996dab88299bbfead3fcb3d28f0d3/lib/rabl/sources.rb#L69-L72
train
nesquena/rabl
lib/rabl/builder.rb
Rabl.Builder.child
def child(data, options = {}, &block) return unless data.present? && resolve_condition(options) name = is_name_value?(options[:root]) ? options[:root] : data_name(data) object = data_object(data) engine_options = @options.slice(:child_root) engine_options[:root] = is_collection?(object) && options.fetch(:object_root, @options[:child_root]) # child @users engine_options[:object_root_name] = options[:object_root] if is_name_value?(options[:object_root]) object = { object => name } if data.is_a?(Hash) && object # child :users => :people engines << { create_key(name) => object_to_engine(object, engine_options, &block) } end
ruby
def child(data, options = {}, &block) return unless data.present? && resolve_condition(options) name = is_name_value?(options[:root]) ? options[:root] : data_name(data) object = data_object(data) engine_options = @options.slice(:child_root) engine_options[:root] = is_collection?(object) && options.fetch(:object_root, @options[:child_root]) # child @users engine_options[:object_root_name] = options[:object_root] if is_name_value?(options[:object_root]) object = { object => name } if data.is_a?(Hash) && object # child :users => :people engines << { create_key(name) => object_to_engine(object, engine_options, &block) } end
[ "def", "child", "(", "data", ",", "options", "=", "{", "}", ",", "&", "block", ")", "return", "unless", "data", ".", "present?", "&&", "resolve_condition", "(", "options", ")", "name", "=", "is_name_value?", "(", "options", "[", ":root", "]", ")", "?", "options", "[", ":root", "]", ":", "data_name", "(", "data", ")", "object", "=", "data_object", "(", "data", ")", "engine_options", "=", "@options", ".", "slice", "(", ":child_root", ")", "engine_options", "[", ":root", "]", "=", "is_collection?", "(", "object", ")", "&&", "options", ".", "fetch", "(", ":object_root", ",", "@options", "[", ":child_root", "]", ")", "# child @users", "engine_options", "[", ":object_root_name", "]", "=", "options", "[", ":object_root", "]", "if", "is_name_value?", "(", "options", "[", ":object_root", "]", ")", "object", "=", "{", "object", "=>", "name", "}", "if", "data", ".", "is_a?", "(", "Hash", ")", "&&", "object", "# child :users => :people", "engines", "<<", "{", "create_key", "(", "name", ")", "=>", "object_to_engine", "(", "object", ",", "engine_options", ",", "block", ")", "}", "end" ]
Creates a child node that is included in json output child(@user) { attribute :full_name } child(@user => :person) { ... } child(@users => :people) { ... }
[ "Creates", "a", "child", "node", "that", "is", "included", "in", "json", "output", "child", "(" ]
a112a4dd783996dab88299bbfead3fcb3d28f0d3
https://github.com/nesquena/rabl/blob/a112a4dd783996dab88299bbfead3fcb3d28f0d3/lib/rabl/builder.rb#L170-L183
train
nesquena/rabl
lib/rabl/builder.rb
Rabl.Builder.glue
def glue(data, options = {}, &block) return unless data.present? && resolve_condition(options) object = data_object(data) engine = object_to_engine(object, :root => false, &block) engines << engine if engine end
ruby
def glue(data, options = {}, &block) return unless data.present? && resolve_condition(options) object = data_object(data) engine = object_to_engine(object, :root => false, &block) engines << engine if engine end
[ "def", "glue", "(", "data", ",", "options", "=", "{", "}", ",", "&", "block", ")", "return", "unless", "data", ".", "present?", "&&", "resolve_condition", "(", "options", ")", "object", "=", "data_object", "(", "data", ")", "engine", "=", "object_to_engine", "(", "object", ",", ":root", "=>", "false", ",", "block", ")", "engines", "<<", "engine", "if", "engine", "end" ]
Glues data from a child node to the json_output glue(@user) { attribute :full_name => :user_full_name }
[ "Glues", "data", "from", "a", "child", "node", "to", "the", "json_output", "glue", "(" ]
a112a4dd783996dab88299bbfead3fcb3d28f0d3
https://github.com/nesquena/rabl/blob/a112a4dd783996dab88299bbfead3fcb3d28f0d3/lib/rabl/builder.rb#L187-L193
train
stffn/declarative_authorization
lib/declarative_authorization/authorization.rb
Authorization.Engine.permit?
def permit? (privilege, options = {}) # :yields: if permit!(privilege, options.merge(:bang=> false)) yield if block_given? true else false end end
ruby
def permit? (privilege, options = {}) # :yields: if permit!(privilege, options.merge(:bang=> false)) yield if block_given? true else false end end
[ "def", "permit?", "(", "privilege", ",", "options", "=", "{", "}", ")", "# :yields:", "if", "permit!", "(", "privilege", ",", "options", ".", "merge", "(", ":bang", "=>", "false", ")", ")", "yield", "if", "block_given?", "true", "else", "false", "end", "end" ]
Calls permit! but doesn't raise authorization errors. If no exception is raised, permit? returns true and yields to the optional block.
[ "Calls", "permit!", "but", "doesn", "t", "raise", "authorization", "errors", ".", "If", "no", "exception", "is", "raised", "permit?", "returns", "true", "and", "yields", "to", "the", "optional", "block", "." ]
45e91af20eba71b2828c5c84066bcce3ef032e8a
https://github.com/stffn/declarative_authorization/blob/45e91af20eba71b2828c5c84066bcce3ef032e8a/lib/declarative_authorization/authorization.rb#L205-L212
train
stffn/declarative_authorization
lib/declarative_authorization/authorization.rb
Authorization.Engine.roles_for
def roles_for (user) user ||= Authorization.current_user raise AuthorizationUsageError, "User object doesn't respond to roles (#{user.inspect})" \ if !user.respond_to?(:role_symbols) and !user.respond_to?(:roles) Rails.logger.info("The use of user.roles is deprecated. Please add a method " + "role_symbols to your User model.") if defined?(Rails) and Rails.respond_to?(:logger) and !user.respond_to?(:role_symbols) roles = user.respond_to?(:role_symbols) ? user.role_symbols : user.roles raise AuthorizationUsageError, "User.#{user.respond_to?(:role_symbols) ? 'role_symbols' : 'roles'} " + "doesn't return an Array of Symbols (#{roles.inspect})" \ if !roles.is_a?(Array) or (!roles.empty? and !roles[0].is_a?(Symbol)) (roles.empty? ? [Authorization.default_role] : roles) end
ruby
def roles_for (user) user ||= Authorization.current_user raise AuthorizationUsageError, "User object doesn't respond to roles (#{user.inspect})" \ if !user.respond_to?(:role_symbols) and !user.respond_to?(:roles) Rails.logger.info("The use of user.roles is deprecated. Please add a method " + "role_symbols to your User model.") if defined?(Rails) and Rails.respond_to?(:logger) and !user.respond_to?(:role_symbols) roles = user.respond_to?(:role_symbols) ? user.role_symbols : user.roles raise AuthorizationUsageError, "User.#{user.respond_to?(:role_symbols) ? 'role_symbols' : 'roles'} " + "doesn't return an Array of Symbols (#{roles.inspect})" \ if !roles.is_a?(Array) or (!roles.empty? and !roles[0].is_a?(Symbol)) (roles.empty? ? [Authorization.default_role] : roles) end
[ "def", "roles_for", "(", "user", ")", "user", "||=", "Authorization", ".", "current_user", "raise", "AuthorizationUsageError", ",", "\"User object doesn't respond to roles (#{user.inspect})\"", "if", "!", "user", ".", "respond_to?", "(", ":role_symbols", ")", "and", "!", "user", ".", "respond_to?", "(", ":roles", ")", "Rails", ".", "logger", ".", "info", "(", "\"The use of user.roles is deprecated. Please add a method \"", "+", "\"role_symbols to your User model.\"", ")", "if", "defined?", "(", "Rails", ")", "and", "Rails", ".", "respond_to?", "(", ":logger", ")", "and", "!", "user", ".", "respond_to?", "(", ":role_symbols", ")", "roles", "=", "user", ".", "respond_to?", "(", ":role_symbols", ")", "?", "user", ".", "role_symbols", ":", "user", ".", "roles", "raise", "AuthorizationUsageError", ",", "\"User.#{user.respond_to?(:role_symbols) ? 'role_symbols' : 'roles'} \"", "+", "\"doesn't return an Array of Symbols (#{roles.inspect})\"", "if", "!", "roles", ".", "is_a?", "(", "Array", ")", "or", "(", "!", "roles", ".", "empty?", "and", "!", "roles", "[", "0", "]", ".", "is_a?", "(", "Symbol", ")", ")", "(", "roles", ".", "empty?", "?", "[", "Authorization", ".", "default_role", "]", ":", "roles", ")", "end" ]
Returns the role symbols of the given user.
[ "Returns", "the", "role", "symbols", "of", "the", "given", "user", "." ]
45e91af20eba71b2828c5c84066bcce3ef032e8a
https://github.com/stffn/declarative_authorization/blob/45e91af20eba71b2828c5c84066bcce3ef032e8a/lib/declarative_authorization/authorization.rb#L259-L274
train
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
train
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
train
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
train
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
train
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
train
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
train
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
train
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
train
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
train
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
train
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
train
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
train
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
train
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
train
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
train
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
train
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
train
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
train
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
train
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
train
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
train
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
train
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
train
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
train
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
train
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
train
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
train
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
train
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
train
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
train
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
train
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
train
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
train
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
train
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
train
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
train
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
train
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
train
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
train
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
train
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
train
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
train
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
train
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
train
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
train
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
train
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
train
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
train
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
train
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
train
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
train
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
train
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
train
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
train
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
train
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
train
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
train
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
train
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
train
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
train
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
train
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
train
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
train
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
train
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
train
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
train
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
train
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
train
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
train
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
train
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
train
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
train
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
train
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
train