repo
stringlengths
5
58
path
stringlengths
9
168
func_name
stringlengths
9
130
original_string
stringlengths
66
10.5k
language
stringclasses
1 value
code
stringlengths
66
10.5k
code_tokens
list
docstring
stringlengths
8
16k
docstring_tokens
list
sha
stringlengths
40
40
url
stringlengths
94
266
partition
stringclasses
1 value
rgrove/crass
lib/crass/parser.rb
Crass.Parser.parse_component_values
def parse_component_values(input = @tokens) input = TokenScanner.new(input) unless input.is_a?(TokenScanner) tokens = [] while token = consume_component_value(input) tokens << token end tokens end
ruby
def parse_component_values(input = @tokens) input = TokenScanner.new(input) unless input.is_a?(TokenScanner) tokens = [] while token = consume_component_value(input) tokens << token end tokens end
[ "def", "parse_component_values", "(", "input", "=", "@tokens", ")", "input", "=", "TokenScanner", ".", "new", "(", "input", ")", "unless", "input", ".", "is_a?", "(", "TokenScanner", ")", "tokens", "=", "[", "]", "while", "token", "=", "consume_component_value", "(", "input", ")", "tokens", "<<", "token", "end", "tokens", "end" ]
Parses a list of component values and returns an array of parsed tokens. 5.3.8. http://dev.w3.org/csswg/css-syntax/#parse-a-list-of-component-values
[ "Parses", "a", "list", "of", "component", "values", "and", "returns", "an", "array", "of", "parsed", "tokens", "." ]
074e56f2a9f10bb873fa8e708ef58a065d4281a2
https://github.com/rgrove/crass/blob/074e56f2a9f10bb873fa8e708ef58a065d4281a2/lib/crass/parser.rb#L510-L519
train
rgrove/crass
lib/crass/parser.rb
Crass.Parser.parse_declaration
def parse_declaration(input = @tokens) input = TokenScanner.new(input) unless input.is_a?(TokenScanner) while input.peek && input.peek[:node] == :whitespace input.consume end if input.peek.nil? # Syntax error. return create_node(:error, :value => 'empty') elsif input.peek[:node] != :ident # Syntax error. return create_node(:error, :value => 'invalid') end if decl = consume_declaration(input) return decl end # Syntax error. create_node(:error, :value => 'invalid') end
ruby
def parse_declaration(input = @tokens) input = TokenScanner.new(input) unless input.is_a?(TokenScanner) while input.peek && input.peek[:node] == :whitespace input.consume end if input.peek.nil? # Syntax error. return create_node(:error, :value => 'empty') elsif input.peek[:node] != :ident # Syntax error. return create_node(:error, :value => 'invalid') end if decl = consume_declaration(input) return decl end # Syntax error. create_node(:error, :value => 'invalid') end
[ "def", "parse_declaration", "(", "input", "=", "@tokens", ")", "input", "=", "TokenScanner", ".", "new", "(", "input", ")", "unless", "input", ".", "is_a?", "(", "TokenScanner", ")", "while", "input", ".", "peek", "&&", "input", ".", "peek", "[", ":node", "]", "==", ":whitespace", "input", ".", "consume", "end", "if", "input", ".", "peek", ".", "nil?", "return", "create_node", "(", ":error", ",", ":value", "=>", "'empty'", ")", "elsif", "input", ".", "peek", "[", ":node", "]", "!=", ":ident", "return", "create_node", "(", ":error", ",", ":value", "=>", "'invalid'", ")", "end", "if", "decl", "=", "consume_declaration", "(", "input", ")", "return", "decl", "end", "create_node", "(", ":error", ",", ":value", "=>", "'invalid'", ")", "end" ]
Parses a single declaration and returns it. 5.3.5. http://dev.w3.org/csswg/css-syntax/#parse-a-declaration
[ "Parses", "a", "single", "declaration", "and", "returns", "it", "." ]
074e56f2a9f10bb873fa8e708ef58a065d4281a2
https://github.com/rgrove/crass/blob/074e56f2a9f10bb873fa8e708ef58a065d4281a2/lib/crass/parser.rb#L524-L545
train
rgrove/crass
lib/crass/parser.rb
Crass.Parser.parse_declarations
def parse_declarations(input = @tokens, options = {}) input = TokenScanner.new(input) unless input.is_a?(TokenScanner) consume_declarations(input, options) end
ruby
def parse_declarations(input = @tokens, options = {}) input = TokenScanner.new(input) unless input.is_a?(TokenScanner) consume_declarations(input, options) end
[ "def", "parse_declarations", "(", "input", "=", "@tokens", ",", "options", "=", "{", "}", ")", "input", "=", "TokenScanner", ".", "new", "(", "input", ")", "unless", "input", ".", "is_a?", "(", "TokenScanner", ")", "consume_declarations", "(", "input", ",", "options", ")", "end" ]
Parses a list of declarations and returns them. See {#consume_declarations} for _options_. 5.3.6. http://dev.w3.org/csswg/css-syntax/#parse-a-list-of-declarations
[ "Parses", "a", "list", "of", "declarations", "and", "returns", "them", "." ]
074e56f2a9f10bb873fa8e708ef58a065d4281a2
https://github.com/rgrove/crass/blob/074e56f2a9f10bb873fa8e708ef58a065d4281a2/lib/crass/parser.rb#L552-L555
train
rgrove/crass
lib/crass/parser.rb
Crass.Parser.parse_rule
def parse_rule(input = @tokens) input = TokenScanner.new(input) unless input.is_a?(TokenScanner) while input.peek && input.peek[:node] == :whitespace input.consume end if input.peek.nil? # Syntax error. return create_node(:error, :value => 'empty') elsif input.peek[:node] == :at_keyword rule = consume_at_rule(input) else rule = consume_qualified_rule(input) end while input.peek && input.peek[:node] == :whitespace input.consume end if input.peek.nil? rule else # Syntax error. create_node(:error, :value => 'extra-input') end end
ruby
def parse_rule(input = @tokens) input = TokenScanner.new(input) unless input.is_a?(TokenScanner) while input.peek && input.peek[:node] == :whitespace input.consume end if input.peek.nil? # Syntax error. return create_node(:error, :value => 'empty') elsif input.peek[:node] == :at_keyword rule = consume_at_rule(input) else rule = consume_qualified_rule(input) end while input.peek && input.peek[:node] == :whitespace input.consume end if input.peek.nil? rule else # Syntax error. create_node(:error, :value => 'extra-input') end end
[ "def", "parse_rule", "(", "input", "=", "@tokens", ")", "input", "=", "TokenScanner", ".", "new", "(", "input", ")", "unless", "input", ".", "is_a?", "(", "TokenScanner", ")", "while", "input", ".", "peek", "&&", "input", ".", "peek", "[", ":node", "]", "==", ":whitespace", "input", ".", "consume", "end", "if", "input", ".", "peek", ".", "nil?", "return", "create_node", "(", ":error", ",", ":value", "=>", "'empty'", ")", "elsif", "input", ".", "peek", "[", ":node", "]", "==", ":at_keyword", "rule", "=", "consume_at_rule", "(", "input", ")", "else", "rule", "=", "consume_qualified_rule", "(", "input", ")", "end", "while", "input", ".", "peek", "&&", "input", ".", "peek", "[", ":node", "]", "==", ":whitespace", "input", ".", "consume", "end", "if", "input", ".", "peek", ".", "nil?", "rule", "else", "create_node", "(", ":error", ",", ":value", "=>", "'extra-input'", ")", "end", "end" ]
Parses a single rule and returns it. 5.3.4. http://dev.w3.org/csswg/css-syntax-3/#parse-a-rule
[ "Parses", "a", "single", "rule", "and", "returns", "it", "." ]
074e56f2a9f10bb873fa8e708ef58a065d4281a2
https://github.com/rgrove/crass/blob/074e56f2a9f10bb873fa8e708ef58a065d4281a2/lib/crass/parser.rb#L586-L612
train
rgrove/crass
lib/crass/parser.rb
Crass.Parser.parse_value
def parse_value(nodes) nodes = [nodes] unless nodes.is_a?(Array) string = String.new nodes.each do |node| case node[:node] when :comment, :semicolon next when :at_keyword, :ident string << node[:value] when :function if node[:value].is_a?(String) string << node[:value] string << '(' else string << parse_value(node[:tokens]) end else if node.key?(:raw) string << node[:raw] elsif node.key?(:tokens) string << parse_value(node[:tokens]) end end end string.strip end
ruby
def parse_value(nodes) nodes = [nodes] unless nodes.is_a?(Array) string = String.new nodes.each do |node| case node[:node] when :comment, :semicolon next when :at_keyword, :ident string << node[:value] when :function if node[:value].is_a?(String) string << node[:value] string << '(' else string << parse_value(node[:tokens]) end else if node.key?(:raw) string << node[:raw] elsif node.key?(:tokens) string << parse_value(node[:tokens]) end end end string.strip end
[ "def", "parse_value", "(", "nodes", ")", "nodes", "=", "[", "nodes", "]", "unless", "nodes", ".", "is_a?", "(", "Array", ")", "string", "=", "String", ".", "new", "nodes", ".", "each", "do", "|", "node", "|", "case", "node", "[", ":node", "]", "when", ":comment", ",", ":semicolon", "next", "when", ":at_keyword", ",", ":ident", "string", "<<", "node", "[", ":value", "]", "when", ":function", "if", "node", "[", ":value", "]", ".", "is_a?", "(", "String", ")", "string", "<<", "node", "[", ":value", "]", "string", "<<", "'('", "else", "string", "<<", "parse_value", "(", "node", "[", ":tokens", "]", ")", "end", "else", "if", "node", ".", "key?", "(", ":raw", ")", "string", "<<", "node", "[", ":raw", "]", "elsif", "node", ".", "key?", "(", ":tokens", ")", "string", "<<", "parse_value", "(", "node", "[", ":tokens", "]", ")", "end", "end", "end", "string", ".", "strip", "end" ]
Returns the unescaped value of a selector name or property declaration.
[ "Returns", "the", "unescaped", "value", "of", "a", "selector", "name", "or", "property", "declaration", "." ]
074e56f2a9f10bb873fa8e708ef58a065d4281a2
https://github.com/rgrove/crass/blob/074e56f2a9f10bb873fa8e708ef58a065d4281a2/lib/crass/parser.rb#L615-L645
train
rgrove/crass
lib/crass/tokenizer.rb
Crass.Tokenizer.consume_bad_url
def consume_bad_url text = String.new until @s.eos? if valid_escape? text << consume_escaped elsif valid_escape?(@s.peek(2)) @s.consume text << consume_escaped else char = @s.consume if char == ')' break else text << char end end end text end
ruby
def consume_bad_url text = String.new until @s.eos? if valid_escape? text << consume_escaped elsif valid_escape?(@s.peek(2)) @s.consume text << consume_escaped else char = @s.consume if char == ')' break else text << char end end end text end
[ "def", "consume_bad_url", "text", "=", "String", ".", "new", "until", "@s", ".", "eos?", "if", "valid_escape?", "text", "<<", "consume_escaped", "elsif", "valid_escape?", "(", "@s", ".", "peek", "(", "2", ")", ")", "@s", ".", "consume", "text", "<<", "consume_escaped", "else", "char", "=", "@s", ".", "consume", "if", "char", "==", "')'", "break", "else", "text", "<<", "char", "end", "end", "end", "text", "end" ]
Consumes the remnants of a bad URL and returns the consumed text. 4.3.15. http://dev.w3.org/csswg/css-syntax/#consume-the-remnants-of-a-bad-url
[ "Consumes", "the", "remnants", "of", "a", "bad", "URL", "and", "returns", "the", "consumed", "text", "." ]
074e56f2a9f10bb873fa8e708ef58a065d4281a2
https://github.com/rgrove/crass/blob/074e56f2a9f10bb873fa8e708ef58a065d4281a2/lib/crass/tokenizer.rb#L275-L296
train
rgrove/crass
lib/crass/tokenizer.rb
Crass.Tokenizer.consume_comments
def consume_comments if @s.peek(2) == '/*' @s.consume @s.consume if text = @s.scan_until(RE_COMMENT_CLOSE) text.slice!(-2, 2) else # Parse error. text = @s.consume_rest end return create_token(:comment, :value => text) end nil end
ruby
def consume_comments if @s.peek(2) == '/*' @s.consume @s.consume if text = @s.scan_until(RE_COMMENT_CLOSE) text.slice!(-2, 2) else # Parse error. text = @s.consume_rest end return create_token(:comment, :value => text) end nil end
[ "def", "consume_comments", "if", "@s", ".", "peek", "(", "2", ")", "==", "'/*'", "@s", ".", "consume", "@s", ".", "consume", "if", "text", "=", "@s", ".", "scan_until", "(", "RE_COMMENT_CLOSE", ")", "text", ".", "slice!", "(", "-", "2", ",", "2", ")", "else", "text", "=", "@s", ".", "consume_rest", "end", "return", "create_token", "(", ":comment", ",", ":value", "=>", "text", ")", "end", "nil", "end" ]
Consumes comments and returns them, or `nil` if no comments were consumed. 4.3.2. http://dev.w3.org/csswg/css-syntax/#consume-comments
[ "Consumes", "comments", "and", "returns", "them", "or", "nil", "if", "no", "comments", "were", "consumed", "." ]
074e56f2a9f10bb873fa8e708ef58a065d4281a2
https://github.com/rgrove/crass/blob/074e56f2a9f10bb873fa8e708ef58a065d4281a2/lib/crass/tokenizer.rb#L301-L317
train
rgrove/crass
lib/crass/tokenizer.rb
Crass.Tokenizer.consume_escaped
def consume_escaped return "\ufffd" if @s.eos? if hex_str = @s.scan(RE_HEX) @s.consume if @s.peek =~ RE_WHITESPACE codepoint = hex_str.hex if codepoint == 0 || codepoint.between?(0xD800, 0xDFFF) || codepoint > 0x10FFFF return "\ufffd" else return codepoint.chr(Encoding::UTF_8) end end @s.consume end
ruby
def consume_escaped return "\ufffd" if @s.eos? if hex_str = @s.scan(RE_HEX) @s.consume if @s.peek =~ RE_WHITESPACE codepoint = hex_str.hex if codepoint == 0 || codepoint.between?(0xD800, 0xDFFF) || codepoint > 0x10FFFF return "\ufffd" else return codepoint.chr(Encoding::UTF_8) end end @s.consume end
[ "def", "consume_escaped", "return", "\"\\ufffd\"", "if", "@s", ".", "eos?", "if", "hex_str", "=", "@s", ".", "scan", "(", "RE_HEX", ")", "@s", ".", "consume", "if", "@s", ".", "peek", "=~", "RE_WHITESPACE", "codepoint", "=", "hex_str", ".", "hex", "if", "codepoint", "==", "0", "||", "codepoint", ".", "between?", "(", "0xD800", ",", "0xDFFF", ")", "||", "codepoint", ">", "0x10FFFF", "return", "\"\\ufffd\"", "else", "return", "codepoint", ".", "chr", "(", "Encoding", "::", "UTF_8", ")", "end", "end", "@s", ".", "consume", "end" ]
Consumes an escaped code point and returns its unescaped value. This method assumes that the `\` has already been consumed, and that the next character in the input has already been verified not to be a newline or EOF. 4.3.8. http://dev.w3.org/csswg/css-syntax/#consume-an-escaped-code-point
[ "Consumes", "an", "escaped", "code", "point", "and", "returns", "its", "unescaped", "value", "." ]
074e56f2a9f10bb873fa8e708ef58a065d4281a2
https://github.com/rgrove/crass/blob/074e56f2a9f10bb873fa8e708ef58a065d4281a2/lib/crass/tokenizer.rb#L326-L345
train
rgrove/crass
lib/crass/tokenizer.rb
Crass.Tokenizer.consume_ident
def consume_ident value = consume_name if @s.peek == '(' @s.consume if value.downcase == 'url' @s.consume while @s.peek(2) =~ RE_WHITESPACE_ANCHORED if @s.peek(2) =~ RE_QUOTED_URL_START create_token(:function, :value => value) else consume_url end else create_token(:function, :value => value) end else create_token(:ident, :value => value) end end
ruby
def consume_ident value = consume_name if @s.peek == '(' @s.consume if value.downcase == 'url' @s.consume while @s.peek(2) =~ RE_WHITESPACE_ANCHORED if @s.peek(2) =~ RE_QUOTED_URL_START create_token(:function, :value => value) else consume_url end else create_token(:function, :value => value) end else create_token(:ident, :value => value) end end
[ "def", "consume_ident", "value", "=", "consume_name", "if", "@s", ".", "peek", "==", "'('", "@s", ".", "consume", "if", "value", ".", "downcase", "==", "'url'", "@s", ".", "consume", "while", "@s", ".", "peek", "(", "2", ")", "=~", "RE_WHITESPACE_ANCHORED", "if", "@s", ".", "peek", "(", "2", ")", "=~", "RE_QUOTED_URL_START", "create_token", "(", ":function", ",", ":value", "=>", "value", ")", "else", "consume_url", "end", "else", "create_token", "(", ":function", ",", ":value", "=>", "value", ")", "end", "else", "create_token", "(", ":ident", ",", ":value", "=>", "value", ")", "end", "end" ]
Consumes an ident-like token and returns it. 4.3.4. http://dev.w3.org/csswg/css-syntax/#consume-an-ident-like-token
[ "Consumes", "an", "ident", "-", "like", "token", "and", "returns", "it", "." ]
074e56f2a9f10bb873fa8e708ef58a065d4281a2
https://github.com/rgrove/crass/blob/074e56f2a9f10bb873fa8e708ef58a065d4281a2/lib/crass/tokenizer.rb#L350-L370
train
rgrove/crass
lib/crass/tokenizer.rb
Crass.Tokenizer.consume_name
def consume_name result = String.new until @s.eos? if match = @s.scan(RE_NAME) result << match next end char = @s.consume if valid_escape? result << consume_escaped # Non-standard: IE * hack elsif char == '*' && @options[:preserve_hacks] result << @s.consume else @s.reconsume return result end end result end
ruby
def consume_name result = String.new until @s.eos? if match = @s.scan(RE_NAME) result << match next end char = @s.consume if valid_escape? result << consume_escaped # Non-standard: IE * hack elsif char == '*' && @options[:preserve_hacks] result << @s.consume else @s.reconsume return result end end result end
[ "def", "consume_name", "result", "=", "String", ".", "new", "until", "@s", ".", "eos?", "if", "match", "=", "@s", ".", "scan", "(", "RE_NAME", ")", "result", "<<", "match", "next", "end", "char", "=", "@s", ".", "consume", "if", "valid_escape?", "result", "<<", "consume_escaped", "elsif", "char", "==", "'*'", "&&", "@options", "[", ":preserve_hacks", "]", "result", "<<", "@s", ".", "consume", "else", "@s", ".", "reconsume", "return", "result", "end", "end", "result", "end" ]
Consumes a name and returns it. 4.3.12. http://dev.w3.org/csswg/css-syntax/#consume-a-name
[ "Consumes", "a", "name", "and", "returns", "it", "." ]
074e56f2a9f10bb873fa8e708ef58a065d4281a2
https://github.com/rgrove/crass/blob/074e56f2a9f10bb873fa8e708ef58a065d4281a2/lib/crass/tokenizer.rb#L375-L400
train
rgrove/crass
lib/crass/tokenizer.rb
Crass.Tokenizer.consume_numeric
def consume_numeric number = consume_number if start_identifier?(@s.peek(3)) create_token(:dimension, :repr => number[0], :type => number[2], :unit => consume_name, :value => number[1]) elsif @s.peek == '%' @s.consume create_token(:percentage, :repr => number[0], :type => number[2], :value => number[1]) else create_token(:number, :repr => number[0], :type => number[2], :value => number[1]) end end
ruby
def consume_numeric number = consume_number if start_identifier?(@s.peek(3)) create_token(:dimension, :repr => number[0], :type => number[2], :unit => consume_name, :value => number[1]) elsif @s.peek == '%' @s.consume create_token(:percentage, :repr => number[0], :type => number[2], :value => number[1]) else create_token(:number, :repr => number[0], :type => number[2], :value => number[1]) end end
[ "def", "consume_numeric", "number", "=", "consume_number", "if", "start_identifier?", "(", "@s", ".", "peek", "(", "3", ")", ")", "create_token", "(", ":dimension", ",", ":repr", "=>", "number", "[", "0", "]", ",", ":type", "=>", "number", "[", "2", "]", ",", ":unit", "=>", "consume_name", ",", ":value", "=>", "number", "[", "1", "]", ")", "elsif", "@s", ".", "peek", "==", "'%'", "@s", ".", "consume", "create_token", "(", ":percentage", ",", ":repr", "=>", "number", "[", "0", "]", ",", ":type", "=>", "number", "[", "2", "]", ",", ":value", "=>", "number", "[", "1", "]", ")", "else", "create_token", "(", ":number", ",", ":repr", "=>", "number", "[", "0", "]", ",", ":type", "=>", "number", "[", "2", "]", ",", ":value", "=>", "number", "[", "1", "]", ")", "end", "end" ]
Consumes a numeric token and returns it. 4.3.3. http://dev.w3.org/csswg/css-syntax/#consume-a-numeric-token
[ "Consumes", "a", "numeric", "token", "and", "returns", "it", "." ]
074e56f2a9f10bb873fa8e708ef58a065d4281a2
https://github.com/rgrove/crass/blob/074e56f2a9f10bb873fa8e708ef58a065d4281a2/lib/crass/tokenizer.rb#L430-L454
train
rgrove/crass
lib/crass/tokenizer.rb
Crass.Tokenizer.consume_string
def consume_string(ending = nil) ending = @s.current if ending.nil? value = String.new until @s.eos? case char = @s.consume when ending break when "\n" # Parse error. @s.reconsume return create_token(:bad_string, :error => true, :value => value) when '\\' case @s.peek when '' # End of the input, so do nothing. next when "\n" @s.consume else value << consume_escaped end else value << char end end create_token(:string, :value => value) end
ruby
def consume_string(ending = nil) ending = @s.current if ending.nil? value = String.new until @s.eos? case char = @s.consume when ending break when "\n" # Parse error. @s.reconsume return create_token(:bad_string, :error => true, :value => value) when '\\' case @s.peek when '' # End of the input, so do nothing. next when "\n" @s.consume else value << consume_escaped end else value << char end end create_token(:string, :value => value) end
[ "def", "consume_string", "(", "ending", "=", "nil", ")", "ending", "=", "@s", ".", "current", "if", "ending", ".", "nil?", "value", "=", "String", ".", "new", "until", "@s", ".", "eos?", "case", "char", "=", "@s", ".", "consume", "when", "ending", "break", "when", "\"\\n\"", "@s", ".", "reconsume", "return", "create_token", "(", ":bad_string", ",", ":error", "=>", "true", ",", ":value", "=>", "value", ")", "when", "'\\\\'", "case", "@s", ".", "peek", "when", "''", "next", "when", "\"\\n\"", "@s", ".", "consume", "else", "value", "<<", "consume_escaped", "end", "else", "value", "<<", "char", "end", "end", "create_token", "(", ":string", ",", ":value", "=>", "value", ")", "end" ]
Consumes a string token that ends at the given character, and returns the token. 4.3.5. http://dev.w3.org/csswg/css-syntax/#consume-a-string-token
[ "Consumes", "a", "string", "token", "that", "ends", "at", "the", "given", "character", "and", "returns", "the", "token", "." ]
074e56f2a9f10bb873fa8e708ef58a065d4281a2
https://github.com/rgrove/crass/blob/074e56f2a9f10bb873fa8e708ef58a065d4281a2/lib/crass/tokenizer.rb#L460-L495
train
rgrove/crass
lib/crass/tokenizer.rb
Crass.Tokenizer.consume_unicode_range
def consume_unicode_range value = @s.scan(RE_HEX) || String.new while value.length < 6 break unless @s.peek == '?' value << @s.consume end range = {} if value.include?('?') range[:start] = value.gsub('?', '0').hex range[:end] = value.gsub('?', 'F').hex return create_token(:unicode_range, range) end range[:start] = value.hex if @s.peek(2) =~ RE_UNICODE_RANGE_END @s.consume range[:end] = (@s.scan(RE_HEX) || '').hex else range[:end] = range[:start] end create_token(:unicode_range, range) end
ruby
def consume_unicode_range value = @s.scan(RE_HEX) || String.new while value.length < 6 break unless @s.peek == '?' value << @s.consume end range = {} if value.include?('?') range[:start] = value.gsub('?', '0').hex range[:end] = value.gsub('?', 'F').hex return create_token(:unicode_range, range) end range[:start] = value.hex if @s.peek(2) =~ RE_UNICODE_RANGE_END @s.consume range[:end] = (@s.scan(RE_HEX) || '').hex else range[:end] = range[:start] end create_token(:unicode_range, range) end
[ "def", "consume_unicode_range", "value", "=", "@s", ".", "scan", "(", "RE_HEX", ")", "||", "String", ".", "new", "while", "value", ".", "length", "<", "6", "break", "unless", "@s", ".", "peek", "==", "'?'", "value", "<<", "@s", ".", "consume", "end", "range", "=", "{", "}", "if", "value", ".", "include?", "(", "'?'", ")", "range", "[", ":start", "]", "=", "value", ".", "gsub", "(", "'?'", ",", "'0'", ")", ".", "hex", "range", "[", ":end", "]", "=", "value", ".", "gsub", "(", "'?'", ",", "'F'", ")", ".", "hex", "return", "create_token", "(", ":unicode_range", ",", "range", ")", "end", "range", "[", ":start", "]", "=", "value", ".", "hex", "if", "@s", ".", "peek", "(", "2", ")", "=~", "RE_UNICODE_RANGE_END", "@s", ".", "consume", "range", "[", ":end", "]", "=", "(", "@s", ".", "scan", "(", "RE_HEX", ")", "||", "''", ")", ".", "hex", "else", "range", "[", ":end", "]", "=", "range", "[", ":start", "]", "end", "create_token", "(", ":unicode_range", ",", "range", ")", "end" ]
Consumes a Unicode range token and returns it. Assumes the initial "u+" or "U+" has already been consumed. 4.3.7. http://dev.w3.org/csswg/css-syntax/#consume-a-unicode-range-token
[ "Consumes", "a", "Unicode", "range", "token", "and", "returns", "it", ".", "Assumes", "the", "initial", "u", "+", "or", "U", "+", "has", "already", "been", "consumed", "." ]
074e56f2a9f10bb873fa8e708ef58a065d4281a2
https://github.com/rgrove/crass/blob/074e56f2a9f10bb873fa8e708ef58a065d4281a2/lib/crass/tokenizer.rb#L501-L527
train
rgrove/crass
lib/crass/tokenizer.rb
Crass.Tokenizer.consume_url
def consume_url value = String.new @s.scan(RE_WHITESPACE) until @s.eos? case char = @s.consume when ')' break when RE_WHITESPACE @s.scan(RE_WHITESPACE) if @s.eos? || @s.peek == ')' @s.consume break else return create_token(:bad_url, :value => value + consume_bad_url) end when '"', "'", '(', RE_NON_PRINTABLE # Parse error. return create_token(:bad_url, :error => true, :value => value + consume_bad_url) when '\\' if valid_escape? value << consume_escaped else # Parse error. return create_token(:bad_url, :error => true, :value => value + consume_bad_url ) end else value << char end end create_token(:url, :value => value) end
ruby
def consume_url value = String.new @s.scan(RE_WHITESPACE) until @s.eos? case char = @s.consume when ')' break when RE_WHITESPACE @s.scan(RE_WHITESPACE) if @s.eos? || @s.peek == ')' @s.consume break else return create_token(:bad_url, :value => value + consume_bad_url) end when '"', "'", '(', RE_NON_PRINTABLE # Parse error. return create_token(:bad_url, :error => true, :value => value + consume_bad_url) when '\\' if valid_escape? value << consume_escaped else # Parse error. return create_token(:bad_url, :error => true, :value => value + consume_bad_url ) end else value << char end end create_token(:url, :value => value) end
[ "def", "consume_url", "value", "=", "String", ".", "new", "@s", ".", "scan", "(", "RE_WHITESPACE", ")", "until", "@s", ".", "eos?", "case", "char", "=", "@s", ".", "consume", "when", "')'", "break", "when", "RE_WHITESPACE", "@s", ".", "scan", "(", "RE_WHITESPACE", ")", "if", "@s", ".", "eos?", "||", "@s", ".", "peek", "==", "')'", "@s", ".", "consume", "break", "else", "return", "create_token", "(", ":bad_url", ",", ":value", "=>", "value", "+", "consume_bad_url", ")", "end", "when", "'\"'", ",", "\"'\"", ",", "'('", ",", "RE_NON_PRINTABLE", "return", "create_token", "(", ":bad_url", ",", ":error", "=>", "true", ",", ":value", "=>", "value", "+", "consume_bad_url", ")", "when", "'\\\\'", "if", "valid_escape?", "value", "<<", "consume_escaped", "else", "return", "create_token", "(", ":bad_url", ",", ":error", "=>", "true", ",", ":value", "=>", "value", "+", "consume_bad_url", ")", "end", "else", "value", "<<", "char", "end", "end", "create_token", "(", ":url", ",", ":value", "=>", "value", ")", "end" ]
Consumes a URL token and returns it. Assumes the original "url(" has already been consumed. 4.3.6. http://dev.w3.org/csswg/css-syntax/#consume-a-url-token
[ "Consumes", "a", "URL", "token", "and", "returns", "it", ".", "Assumes", "the", "original", "url", "(", "has", "already", "been", "consumed", "." ]
074e56f2a9f10bb873fa8e708ef58a065d4281a2
https://github.com/rgrove/crass/blob/074e56f2a9f10bb873fa8e708ef58a065d4281a2/lib/crass/tokenizer.rb#L533-L576
train
rgrove/crass
lib/crass/tokenizer.rb
Crass.Tokenizer.convert_string_to_number
def convert_string_to_number(str) matches = RE_NUMBER_STR.match(str) s = matches[:sign] == '-' ? -1 : 1 i = matches[:integer].to_i f = matches[:fractional].to_i d = matches[:fractional] ? matches[:fractional].length : 0 t = matches[:exponent_sign] == '-' ? -1 : 1 e = matches[:exponent].to_i # I know this looks nutty, but it's exactly what's defined in the spec, # and it works. s * (i + f * 10**-d) * 10**(t * e) end
ruby
def convert_string_to_number(str) matches = RE_NUMBER_STR.match(str) s = matches[:sign] == '-' ? -1 : 1 i = matches[:integer].to_i f = matches[:fractional].to_i d = matches[:fractional] ? matches[:fractional].length : 0 t = matches[:exponent_sign] == '-' ? -1 : 1 e = matches[:exponent].to_i # I know this looks nutty, but it's exactly what's defined in the spec, # and it works. s * (i + f * 10**-d) * 10**(t * e) end
[ "def", "convert_string_to_number", "(", "str", ")", "matches", "=", "RE_NUMBER_STR", ".", "match", "(", "str", ")", "s", "=", "matches", "[", ":sign", "]", "==", "'-'", "?", "-", "1", ":", "1", "i", "=", "matches", "[", ":integer", "]", ".", "to_i", "f", "=", "matches", "[", ":fractional", "]", ".", "to_i", "d", "=", "matches", "[", ":fractional", "]", "?", "matches", "[", ":fractional", "]", ".", "length", ":", "0", "t", "=", "matches", "[", ":exponent_sign", "]", "==", "'-'", "?", "-", "1", ":", "1", "e", "=", "matches", "[", ":exponent", "]", ".", "to_i", "s", "*", "(", "i", "+", "f", "*", "10", "**", "-", "d", ")", "*", "10", "**", "(", "t", "*", "e", ")", "end" ]
Converts a valid CSS number string into a number and returns the number. 4.3.14. http://dev.w3.org/csswg/css-syntax/#convert-a-string-to-a-number
[ "Converts", "a", "valid", "CSS", "number", "string", "into", "a", "number", "and", "returns", "the", "number", "." ]
074e56f2a9f10bb873fa8e708ef58a065d4281a2
https://github.com/rgrove/crass/blob/074e56f2a9f10bb873fa8e708ef58a065d4281a2/lib/crass/tokenizer.rb#L581-L594
train
rgrove/crass
lib/crass/tokenizer.rb
Crass.Tokenizer.preprocess
def preprocess(input) input = input.to_s.encode('UTF-8', :invalid => :replace, :undef => :replace) input.gsub!(/(?:\r\n|[\r\f])/, "\n") input.gsub!("\u0000", "\ufffd") input end
ruby
def preprocess(input) input = input.to_s.encode('UTF-8', :invalid => :replace, :undef => :replace) input.gsub!(/(?:\r\n|[\r\f])/, "\n") input.gsub!("\u0000", "\ufffd") input end
[ "def", "preprocess", "(", "input", ")", "input", "=", "input", ".", "to_s", ".", "encode", "(", "'UTF-8'", ",", ":invalid", "=>", ":replace", ",", ":undef", "=>", ":replace", ")", "input", ".", "gsub!", "(", "/", "\\r", "\\n", "\\r", "\\f", "/", ",", "\"\\n\"", ")", "input", ".", "gsub!", "(", "\"\\u0000\"", ",", "\"\\ufffd\"", ")", "input", "end" ]
Preprocesses _input_ to prepare it for the tokenizer. 3.3. http://dev.w3.org/csswg/css-syntax/#input-preprocessing
[ "Preprocesses", "_input_", "to", "prepare", "it", "for", "the", "tokenizer", "." ]
074e56f2a9f10bb873fa8e708ef58a065d4281a2
https://github.com/rgrove/crass/blob/074e56f2a9f10bb873fa8e708ef58a065d4281a2/lib/crass/tokenizer.rb#L608-L616
train
rgrove/crass
lib/crass/tokenizer.rb
Crass.Tokenizer.start_identifier?
def start_identifier?(text = nil) text = @s.current + @s.peek(2) if text.nil? case text[0] when '-' nextChar = text[1] !!(nextChar == '-' || nextChar =~ RE_NAME_START || valid_escape?(text[1, 2])) when RE_NAME_START true when '\\' valid_escape?(text[0, 2]) else false end end
ruby
def start_identifier?(text = nil) text = @s.current + @s.peek(2) if text.nil? case text[0] when '-' nextChar = text[1] !!(nextChar == '-' || nextChar =~ RE_NAME_START || valid_escape?(text[1, 2])) when RE_NAME_START true when '\\' valid_escape?(text[0, 2]) else false end end
[ "def", "start_identifier?", "(", "text", "=", "nil", ")", "text", "=", "@s", ".", "current", "+", "@s", ".", "peek", "(", "2", ")", "if", "text", ".", "nil?", "case", "text", "[", "0", "]", "when", "'-'", "nextChar", "=", "text", "[", "1", "]", "!", "!", "(", "nextChar", "==", "'-'", "||", "nextChar", "=~", "RE_NAME_START", "||", "valid_escape?", "(", "text", "[", "1", ",", "2", "]", ")", ")", "when", "RE_NAME_START", "true", "when", "'\\\\'", "valid_escape?", "(", "text", "[", "0", ",", "2", "]", ")", "else", "false", "end", "end" ]
Returns `true` if the given three-character _text_ would start an identifier. If _text_ is `nil`, the current and next two characters in the input stream will be checked, but will not be consumed. 4.3.10. http://dev.w3.org/csswg/css-syntax/#would-start-an-identifier
[ "Returns", "true", "if", "the", "given", "three", "-", "character", "_text_", "would", "start", "an", "identifier", ".", "If", "_text_", "is", "nil", "the", "current", "and", "next", "two", "characters", "in", "the", "input", "stream", "will", "be", "checked", "but", "will", "not", "be", "consumed", "." ]
074e56f2a9f10bb873fa8e708ef58a065d4281a2
https://github.com/rgrove/crass/blob/074e56f2a9f10bb873fa8e708ef58a065d4281a2/lib/crass/tokenizer.rb#L623-L640
train
rgrove/crass
lib/crass/tokenizer.rb
Crass.Tokenizer.start_number?
def start_number?(text = nil) text = @s.current + @s.peek(2) if text.nil? case text[0] when '+', '-' !!(text[1] =~ RE_DIGIT || (text[1] == '.' && text[2] =~ RE_DIGIT)) when '.' !!(text[1] =~ RE_DIGIT) when RE_DIGIT true else false end end
ruby
def start_number?(text = nil) text = @s.current + @s.peek(2) if text.nil? case text[0] when '+', '-' !!(text[1] =~ RE_DIGIT || (text[1] == '.' && text[2] =~ RE_DIGIT)) when '.' !!(text[1] =~ RE_DIGIT) when RE_DIGIT true else false end end
[ "def", "start_number?", "(", "text", "=", "nil", ")", "text", "=", "@s", ".", "current", "+", "@s", ".", "peek", "(", "2", ")", "if", "text", ".", "nil?", "case", "text", "[", "0", "]", "when", "'+'", ",", "'-'", "!", "!", "(", "text", "[", "1", "]", "=~", "RE_DIGIT", "||", "(", "text", "[", "1", "]", "==", "'.'", "&&", "text", "[", "2", "]", "=~", "RE_DIGIT", ")", ")", "when", "'.'", "!", "!", "(", "text", "[", "1", "]", "=~", "RE_DIGIT", ")", "when", "RE_DIGIT", "true", "else", "false", "end", "end" ]
Returns `true` if the given three-character _text_ would start a number. If _text_ is `nil`, the current and next two characters in the input stream will be checked, but will not be consumed. 4.3.11. http://dev.w3.org/csswg/css-syntax/#starts-with-a-number
[ "Returns", "true", "if", "the", "given", "three", "-", "character", "_text_", "would", "start", "a", "number", ".", "If", "_text_", "is", "nil", "the", "current", "and", "next", "two", "characters", "in", "the", "input", "stream", "will", "be", "checked", "but", "will", "not", "be", "consumed", "." ]
074e56f2a9f10bb873fa8e708ef58a065d4281a2
https://github.com/rgrove/crass/blob/074e56f2a9f10bb873fa8e708ef58a065d4281a2/lib/crass/tokenizer.rb#L647-L663
train
suweller/mongoid-autoinc
lib/autoinc.rb
Mongoid.Autoinc.assign!
def assign!(field) options = self.class.incrementing_fields[field] fail AutoIncrementsError if options[:auto] fail AlreadyAssignedError if send(field).present? increment!(field, options) end
ruby
def assign!(field) options = self.class.incrementing_fields[field] fail AutoIncrementsError if options[:auto] fail AlreadyAssignedError if send(field).present? increment!(field, options) end
[ "def", "assign!", "(", "field", ")", "options", "=", "self", ".", "class", ".", "incrementing_fields", "[", "field", "]", "fail", "AutoIncrementsError", "if", "options", "[", ":auto", "]", "fail", "AlreadyAssignedError", "if", "send", "(", "field", ")", ".", "present?", "increment!", "(", "field", ",", "options", ")", "end" ]
Manually assign the next number to the passed autoinc field. @raise [ Mongoid::Autoinc::AutoIncrementsError ] When `auto: true` is set in the increments call for `field` @raise [ AlreadyAssignedError ] When called more then once. @return [ Fixnum ] The assigned number
[ "Manually", "assign", "the", "next", "number", "to", "the", "passed", "autoinc", "field", "." ]
30cfe694da15ddfa2709249fdfdd5d22b93e63c1
https://github.com/suweller/mongoid-autoinc/blob/30cfe694da15ddfa2709249fdfdd5d22b93e63c1/lib/autoinc.rb#L82-L87
train
suweller/mongoid-autoinc
lib/autoinc.rb
Mongoid.Autoinc.update_auto_increments
def update_auto_increments self.class.incrementing_fields.each do |field, options| increment!(field, options) if options[:auto] end && true end
ruby
def update_auto_increments self.class.incrementing_fields.each do |field, options| increment!(field, options) if options[:auto] end && true end
[ "def", "update_auto_increments", "self", ".", "class", ".", "incrementing_fields", ".", "each", "do", "|", "field", ",", "options", "|", "increment!", "(", "field", ",", "options", ")", "if", "options", "[", ":auto", "]", "end", "&&", "true", "end" ]
Sets autoincrement values for all autoincrement fields. @return [ true ]
[ "Sets", "autoincrement", "values", "for", "all", "autoincrement", "fields", "." ]
30cfe694da15ddfa2709249fdfdd5d22b93e63c1
https://github.com/suweller/mongoid-autoinc/blob/30cfe694da15ddfa2709249fdfdd5d22b93e63c1/lib/autoinc.rb#L92-L96
train
suweller/mongoid-autoinc
lib/autoinc.rb
Mongoid.Autoinc.increment!
def increment!(field, options) options = options.dup model_name = (options.delete(:model_name) || self.class.model_name).to_s options[:scope] = evaluate_scope(options[:scope]) if options[:scope] options[:step] = evaluate_step(options[:step]) if options[:step] write_attribute( field.to_sym, Mongoid::Autoinc::Incrementor.new(model_name, field, options).inc ) end
ruby
def increment!(field, options) options = options.dup model_name = (options.delete(:model_name) || self.class.model_name).to_s options[:scope] = evaluate_scope(options[:scope]) if options[:scope] options[:step] = evaluate_step(options[:step]) if options[:step] write_attribute( field.to_sym, Mongoid::Autoinc::Incrementor.new(model_name, field, options).inc ) end
[ "def", "increment!", "(", "field", ",", "options", ")", "options", "=", "options", ".", "dup", "model_name", "=", "(", "options", ".", "delete", "(", ":model_name", ")", "||", "self", ".", "class", ".", "model_name", ")", ".", "to_s", "options", "[", ":scope", "]", "=", "evaluate_scope", "(", "options", "[", ":scope", "]", ")", "if", "options", "[", ":scope", "]", "options", "[", ":step", "]", "=", "evaluate_step", "(", "options", "[", ":step", "]", ")", "if", "options", "[", ":step", "]", "write_attribute", "(", "field", ".", "to_sym", ",", "Mongoid", "::", "Autoinc", "::", "Incrementor", ".", "new", "(", "model_name", ",", "field", ",", "options", ")", ".", "inc", ")", "end" ]
Set autoincrement value for the passed autoincrement field, using the passed options @param [ Symbol ] field Field to set the autoincrement value for. @param [ Hash ] options Options to pass through to the serializer. @return [ true ] The value of `write_attribute`
[ "Set", "autoincrement", "value", "for", "the", "passed", "autoincrement", "field", "using", "the", "passed", "options" ]
30cfe694da15ddfa2709249fdfdd5d22b93e63c1
https://github.com/suweller/mongoid-autoinc/blob/30cfe694da15ddfa2709249fdfdd5d22b93e63c1/lib/autoinc.rb#L105-L114
train
suweller/mongoid-autoinc
lib/autoinc.rb
Mongoid.Autoinc.evaluate_scope
def evaluate_scope(scope) return send(scope) if scope.is_a? Symbol return instance_exec(&scope) if scope.is_a? Proc fail ArgumentError, 'scope is not a Symbol or a Proc' end
ruby
def evaluate_scope(scope) return send(scope) if scope.is_a? Symbol return instance_exec(&scope) if scope.is_a? Proc fail ArgumentError, 'scope is not a Symbol or a Proc' end
[ "def", "evaluate_scope", "(", "scope", ")", "return", "send", "(", "scope", ")", "if", "scope", ".", "is_a?", "Symbol", "return", "instance_exec", "(", "&", "scope", ")", "if", "scope", ".", "is_a?", "Proc", "fail", "ArgumentError", ",", "'scope is not a Symbol or a Proc'", "end" ]
Asserts the validity of the passed scope @param [ Object ] scope The +Symbol+ or +Proc+ to evaluate @raise [ ArgumentError ] When +scope+ is not a +Symbol+ or +Proc+ @return [ Object ] The scope of the autoincrement call
[ "Asserts", "the", "validity", "of", "the", "passed", "scope" ]
30cfe694da15ddfa2709249fdfdd5d22b93e63c1
https://github.com/suweller/mongoid-autoinc/blob/30cfe694da15ddfa2709249fdfdd5d22b93e63c1/lib/autoinc.rb#L123-L127
train
suweller/mongoid-autoinc
lib/autoinc.rb
Mongoid.Autoinc.evaluate_step
def evaluate_step(step) return step if step.is_a? Integer return evaluate_step_proc(step) if step.is_a? Proc fail ArgumentError, 'step is not an Integer or a Proc' end
ruby
def evaluate_step(step) return step if step.is_a? Integer return evaluate_step_proc(step) if step.is_a? Proc fail ArgumentError, 'step is not an Integer or a Proc' end
[ "def", "evaluate_step", "(", "step", ")", "return", "step", "if", "step", ".", "is_a?", "Integer", "return", "evaluate_step_proc", "(", "step", ")", "if", "step", ".", "is_a?", "Proc", "fail", "ArgumentError", ",", "'step is not an Integer or a Proc'", "end" ]
Returns the number to add to the current increment @param [ Object ] step The +Integer+ to be returned or +Proc+ to be evaluated @raise [ ArgumentError ] When +step+ is not an +Integer+ or +Proc+ @return [ Integer ] The number to add to the current increment
[ "Returns", "the", "number", "to", "add", "to", "the", "current", "increment" ]
30cfe694da15ddfa2709249fdfdd5d22b93e63c1
https://github.com/suweller/mongoid-autoinc/blob/30cfe694da15ddfa2709249fdfdd5d22b93e63c1/lib/autoinc.rb#L137-L141
train
suweller/mongoid-autoinc
lib/autoinc.rb
Mongoid.Autoinc.evaluate_step_proc
def evaluate_step_proc(step_proc) result = instance_exec(&step_proc) return result if result.is_a? Integer fail 'step Proc does not evaluate to an Integer' end
ruby
def evaluate_step_proc(step_proc) result = instance_exec(&step_proc) return result if result.is_a? Integer fail 'step Proc does not evaluate to an Integer' end
[ "def", "evaluate_step_proc", "(", "step_proc", ")", "result", "=", "instance_exec", "(", "&", "step_proc", ")", "return", "result", "if", "result", ".", "is_a?", "Integer", "fail", "'step Proc does not evaluate to an Integer'", "end" ]
Executes a proc and returns its +Integer+ value @param [ Proc ] step_proc The +Proc+ to call @raise [ ArgumentError ] When +step_proc+ does not evaluate to +Integer+ @return [ Integer ] The number to add to the current increment
[ "Executes", "a", "proc", "and", "returns", "its", "+", "Integer", "+", "value" ]
30cfe694da15ddfa2709249fdfdd5d22b93e63c1
https://github.com/suweller/mongoid-autoinc/blob/30cfe694da15ddfa2709249fdfdd5d22b93e63c1/lib/autoinc.rb#L150-L154
train
mbklein/equivalent-xml
lib/equivalent-xml.rb
EquivalentXml.Processor.same_namespace?
def same_namespace?(node_1, node_2) args = [node_1,node_2] # CharacterData nodes shouldn't have namespaces. But in Nokogiri, # they do. And they're invisible. And they get corrupted easily. # So let's wilfully ignore them. And while we're at it, let's # ignore any class that doesn't know it has a namespace. if args.all? { |node| not node.is_namespaced? } or args.any? { |node| node.is_character_data? } return true end href1 = node_1.namespace_uri || '' href2 = node_2.namespace_uri || '' return href1 == href2 end
ruby
def same_namespace?(node_1, node_2) args = [node_1,node_2] # CharacterData nodes shouldn't have namespaces. But in Nokogiri, # they do. And they're invisible. And they get corrupted easily. # So let's wilfully ignore them. And while we're at it, let's # ignore any class that doesn't know it has a namespace. if args.all? { |node| not node.is_namespaced? } or args.any? { |node| node.is_character_data? } return true end href1 = node_1.namespace_uri || '' href2 = node_2.namespace_uri || '' return href1 == href2 end
[ "def", "same_namespace?", "(", "node_1", ",", "node_2", ")", "args", "=", "[", "node_1", ",", "node_2", "]", "if", "args", ".", "all?", "{", "|", "node", "|", "not", "node", ".", "is_namespaced?", "}", "or", "args", ".", "any?", "{", "|", "node", "|", "node", ".", "is_character_data?", "}", "return", "true", "end", "href1", "=", "node_1", ".", "namespace_uri", "||", "''", "href2", "=", "node_2", ".", "namespace_uri", "||", "''", "return", "href1", "==", "href2", "end" ]
Determine if two nodes are in the same effective Namespace @param [Node OR String] node_1 The first node to test @param [Node OR String] node_2 The second node to test
[ "Determine", "if", "two", "nodes", "are", "in", "the", "same", "effective", "Namespace" ]
47de39c006636eaeea2eb153e0a346470e0ec693
https://github.com/mbklein/equivalent-xml/blob/47de39c006636eaeea2eb153e0a346470e0ec693/lib/equivalent-xml.rb#L181-L196
train
phatworx/easy_captcha
lib/easy_captcha/controller_helpers.rb
EasyCaptcha.ControllerHelpers.generate_captcha
def generate_captcha if EasyCaptcha.cache # create cache dir FileUtils.mkdir_p(EasyCaptcha.cache_temp_dir) # select all generated captchas from cache files = Dir.glob(EasyCaptcha.cache_temp_dir + "*.png") unless files.size < EasyCaptcha.cache_size file = File.open(files.at(Kernel.rand(files.size))) session[:captcha] = File.basename(file.path, '.*') if file.mtime < EasyCaptcha.cache_expire.ago File.unlink(file.path) # remove speech version File.unlink(file.path.gsub(/png\z/, "wav")) if File.exists?(file.path.gsub(/png\z/, "wav")) else return file.readlines.join end end generated_code = generate_captcha_code image = Captcha.new(generated_code).image # write captcha for caching File.open(captcha_cache_path(generated_code), 'w') { |f| f.write image } # write speech file if u create a new captcha image EasyCaptcha.espeak.generate(generated_code, speech_captcha_cache_path(generated_code)) if EasyCaptcha.espeak? # return image image else Captcha.new(generate_captcha_code).image end end
ruby
def generate_captcha if EasyCaptcha.cache # create cache dir FileUtils.mkdir_p(EasyCaptcha.cache_temp_dir) # select all generated captchas from cache files = Dir.glob(EasyCaptcha.cache_temp_dir + "*.png") unless files.size < EasyCaptcha.cache_size file = File.open(files.at(Kernel.rand(files.size))) session[:captcha] = File.basename(file.path, '.*') if file.mtime < EasyCaptcha.cache_expire.ago File.unlink(file.path) # remove speech version File.unlink(file.path.gsub(/png\z/, "wav")) if File.exists?(file.path.gsub(/png\z/, "wav")) else return file.readlines.join end end generated_code = generate_captcha_code image = Captcha.new(generated_code).image # write captcha for caching File.open(captcha_cache_path(generated_code), 'w') { |f| f.write image } # write speech file if u create a new captcha image EasyCaptcha.espeak.generate(generated_code, speech_captcha_cache_path(generated_code)) if EasyCaptcha.espeak? # return image image else Captcha.new(generate_captcha_code).image end end
[ "def", "generate_captcha", "if", "EasyCaptcha", ".", "cache", "FileUtils", ".", "mkdir_p", "(", "EasyCaptcha", ".", "cache_temp_dir", ")", "files", "=", "Dir", ".", "glob", "(", "EasyCaptcha", ".", "cache_temp_dir", "+", "\"*.png\"", ")", "unless", "files", ".", "size", "<", "EasyCaptcha", ".", "cache_size", "file", "=", "File", ".", "open", "(", "files", ".", "at", "(", "Kernel", ".", "rand", "(", "files", ".", "size", ")", ")", ")", "session", "[", ":captcha", "]", "=", "File", ".", "basename", "(", "file", ".", "path", ",", "'.*'", ")", "if", "file", ".", "mtime", "<", "EasyCaptcha", ".", "cache_expire", ".", "ago", "File", ".", "unlink", "(", "file", ".", "path", ")", "File", ".", "unlink", "(", "file", ".", "path", ".", "gsub", "(", "/", "\\z", "/", ",", "\"wav\"", ")", ")", "if", "File", ".", "exists?", "(", "file", ".", "path", ".", "gsub", "(", "/", "\\z", "/", ",", "\"wav\"", ")", ")", "else", "return", "file", ".", "readlines", ".", "join", "end", "end", "generated_code", "=", "generate_captcha_code", "image", "=", "Captcha", ".", "new", "(", "generated_code", ")", ".", "image", "File", ".", "open", "(", "captcha_cache_path", "(", "generated_code", ")", ",", "'w'", ")", "{", "|", "f", "|", "f", ".", "write", "image", "}", "EasyCaptcha", ".", "espeak", ".", "generate", "(", "generated_code", ",", "speech_captcha_cache_path", "(", "generated_code", ")", ")", "if", "EasyCaptcha", ".", "espeak?", "image", "else", "Captcha", ".", "new", "(", "generate_captcha_code", ")", ".", "image", "end", "end" ]
generate captcha image and return it as blob
[ "generate", "captcha", "image", "and", "return", "it", "as", "blob" ]
d3a0281b00bd8fc67caf15a0380e185809f12252
https://github.com/phatworx/easy_captcha/blob/d3a0281b00bd8fc67caf15a0380e185809f12252/lib/easy_captcha/controller_helpers.rb#L12-L46
train
phatworx/easy_captcha
lib/easy_captcha/controller_helpers.rb
EasyCaptcha.ControllerHelpers.generate_speech_captcha
def generate_speech_captcha raise RuntimeError, "espeak disabled" unless EasyCaptcha.espeak? if EasyCaptcha.cache File.read(speech_captcha_cache_path(current_captcha_code)) else wav_file = Tempfile.new("#{current_captcha_code}.wav") EasyCaptcha.espeak.generate(current_captcha_code, wav_file.path) File.read(wav_file.path) end end
ruby
def generate_speech_captcha raise RuntimeError, "espeak disabled" unless EasyCaptcha.espeak? if EasyCaptcha.cache File.read(speech_captcha_cache_path(current_captcha_code)) else wav_file = Tempfile.new("#{current_captcha_code}.wav") EasyCaptcha.espeak.generate(current_captcha_code, wav_file.path) File.read(wav_file.path) end end
[ "def", "generate_speech_captcha", "raise", "RuntimeError", ",", "\"espeak disabled\"", "unless", "EasyCaptcha", ".", "espeak?", "if", "EasyCaptcha", ".", "cache", "File", ".", "read", "(", "speech_captcha_cache_path", "(", "current_captcha_code", ")", ")", "else", "wav_file", "=", "Tempfile", ".", "new", "(", "\"#{current_captcha_code}.wav\"", ")", "EasyCaptcha", ".", "espeak", ".", "generate", "(", "current_captcha_code", ",", "wav_file", ".", "path", ")", "File", ".", "read", "(", "wav_file", ".", "path", ")", "end", "end" ]
generate speech by captcha from session
[ "generate", "speech", "by", "captcha", "from", "session" ]
d3a0281b00bd8fc67caf15a0380e185809f12252
https://github.com/phatworx/easy_captcha/blob/d3a0281b00bd8fc67caf15a0380e185809f12252/lib/easy_captcha/controller_helpers.rb#L49-L58
train
phatworx/easy_captcha
lib/easy_captcha/controller_helpers.rb
EasyCaptcha.ControllerHelpers.generate_captcha_code
def generate_captcha_code session[:captcha] = EasyCaptcha.length.times.collect { EasyCaptcha.chars[rand(EasyCaptcha.chars.size)] }.join end
ruby
def generate_captcha_code session[:captcha] = EasyCaptcha.length.times.collect { EasyCaptcha.chars[rand(EasyCaptcha.chars.size)] }.join end
[ "def", "generate_captcha_code", "session", "[", ":captcha", "]", "=", "EasyCaptcha", ".", "length", ".", "times", ".", "collect", "{", "EasyCaptcha", ".", "chars", "[", "rand", "(", "EasyCaptcha", ".", "chars", ".", "size", ")", "]", "}", ".", "join", "end" ]
generate captcha code, save in session and return
[ "generate", "captcha", "code", "save", "in", "session", "and", "return" ]
d3a0281b00bd8fc67caf15a0380e185809f12252
https://github.com/phatworx/easy_captcha/blob/d3a0281b00bd8fc67caf15a0380e185809f12252/lib/easy_captcha/controller_helpers.rb#L76-L78
train
phatworx/easy_captcha
lib/easy_captcha/controller_helpers.rb
EasyCaptcha.ControllerHelpers.captcha_valid?
def captcha_valid?(code) return false if session[:captcha].blank? or code.blank? session[:captcha].to_s.upcase == code.to_s.upcase end
ruby
def captcha_valid?(code) return false if session[:captcha].blank? or code.blank? session[:captcha].to_s.upcase == code.to_s.upcase end
[ "def", "captcha_valid?", "(", "code", ")", "return", "false", "if", "session", "[", ":captcha", "]", ".", "blank?", "or", "code", ".", "blank?", "session", "[", ":captcha", "]", ".", "to_s", ".", "upcase", "==", "code", ".", "to_s", ".", "upcase", "end" ]
validate given captcha code and re
[ "validate", "given", "captcha", "code", "and", "re" ]
d3a0281b00bd8fc67caf15a0380e185809f12252
https://github.com/phatworx/easy_captcha/blob/d3a0281b00bd8fc67caf15a0380e185809f12252/lib/easy_captcha/controller_helpers.rb#L81-L84
train
phatworx/easy_captcha
lib/easy_captcha/view_helpers.rb
EasyCaptcha.ViewHelpers.captcha_tag
def captcha_tag(*args) options = { :alt => 'captcha', :width => EasyCaptcha.image_width, :height => EasyCaptcha.image_height } options.merge! args.extract_options! image_tag(captcha_url(:i => Time.now.to_i), options) end
ruby
def captcha_tag(*args) options = { :alt => 'captcha', :width => EasyCaptcha.image_width, :height => EasyCaptcha.image_height } options.merge! args.extract_options! image_tag(captcha_url(:i => Time.now.to_i), options) end
[ "def", "captcha_tag", "(", "*", "args", ")", "options", "=", "{", ":alt", "=>", "'captcha'", ",", ":width", "=>", "EasyCaptcha", ".", "image_width", ",", ":height", "=>", "EasyCaptcha", ".", "image_height", "}", "options", ".", "merge!", "args", ".", "extract_options!", "image_tag", "(", "captcha_url", "(", ":i", "=>", "Time", ".", "now", ".", "to_i", ")", ",", "options", ")", "end" ]
generate an image_tag for captcha image
[ "generate", "an", "image_tag", "for", "captcha", "image" ]
d3a0281b00bd8fc67caf15a0380e185809f12252
https://github.com/phatworx/easy_captcha/blob/d3a0281b00bd8fc67caf15a0380e185809f12252/lib/easy_captcha/view_helpers.rb#L5-L9
train
kristianmandrup/rails-gallery
lib/rails-gallery/rgallery/photo.rb
RGallery.Photo.source_photos
def source_photos return [] unless sources.kind_of? Array @source_photos ||= sources.map do |source| RGallery::Photo.new source.src, options.merge(:sizing => source.sizing) end end
ruby
def source_photos return [] unless sources.kind_of? Array @source_photos ||= sources.map do |source| RGallery::Photo.new source.src, options.merge(:sizing => source.sizing) end end
[ "def", "source_photos", "return", "[", "]", "unless", "sources", ".", "kind_of?", "Array", "@source_photos", "||=", "sources", ".", "map", "do", "|", "source", "|", "RGallery", "::", "Photo", ".", "new", "source", ".", "src", ",", "options", ".", "merge", "(", ":sizing", "=>", "source", ".", "sizing", ")", "end", "end" ]
A photo can contain a source set of other photos!
[ "A", "photo", "can", "contain", "a", "source", "set", "of", "other", "photos!" ]
cf02ca751ad1e51ed2f4b370baf4e34601c6f897
https://github.com/kristianmandrup/rails-gallery/blob/cf02ca751ad1e51ed2f4b370baf4e34601c6f897/lib/rails-gallery/rgallery/photo.rb#L28-L33
train
kristianmandrup/rails-gallery
lib/rails-gallery/rgallery/photo.rb
RGallery.Photo.sources=
def sources= sources = [] return unless sources.kind_of? Array @sources = sources.map{|source| Hashie::Mash.new source } end
ruby
def sources= sources = [] return unless sources.kind_of? Array @sources = sources.map{|source| Hashie::Mash.new source } end
[ "def", "sources", "=", "sources", "=", "[", "]", "return", "unless", "sources", ".", "kind_of?", "Array", "@sources", "=", "sources", ".", "map", "{", "|", "source", "|", "Hashie", "::", "Mash", ".", "new", "source", "}", "end" ]
make sure that sources are wrapped as Hashies to allow method access
[ "make", "sure", "that", "sources", "are", "wrapped", "as", "Hashies", "to", "allow", "method", "access" ]
cf02ca751ad1e51ed2f4b370baf4e34601c6f897
https://github.com/kristianmandrup/rails-gallery/blob/cf02ca751ad1e51ed2f4b370baf4e34601c6f897/lib/rails-gallery/rgallery/photo.rb#L36-L39
train
tomichj/authenticate
lib/authenticate/configuration.rb
Authenticate.Configuration.modules
def modules modules = @modules.dup # in case the user pushes any on modules << @authentication_strategy modules << :db_password modules << :password_reset modules << :trackable # needs configuration modules << :timeoutable if @timeout_in modules << :lifetimed if @max_session_lifetime modules << :brute_force if @max_consecutive_bad_logins_allowed modules end
ruby
def modules modules = @modules.dup # in case the user pushes any on modules << @authentication_strategy modules << :db_password modules << :password_reset modules << :trackable # needs configuration modules << :timeoutable if @timeout_in modules << :lifetimed if @max_session_lifetime modules << :brute_force if @max_consecutive_bad_logins_allowed modules end
[ "def", "modules", "modules", "=", "@modules", ".", "dup", "modules", "<<", "@authentication_strategy", "modules", "<<", ":db_password", "modules", "<<", ":password_reset", "modules", "<<", ":trackable", "modules", "<<", ":timeoutable", "if", "@timeout_in", "modules", "<<", ":lifetimed", "if", "@max_session_lifetime", "modules", "<<", ":brute_force", "if", "@max_consecutive_bad_logins_allowed", "modules", "end" ]
List of symbols naming modules to load.
[ "List", "of", "symbols", "naming", "modules", "to", "load", "." ]
f4cdcbc6e42886394a440182f84ce7fa80cd714a
https://github.com/tomichj/authenticate/blob/f4cdcbc6e42886394a440182f84ce7fa80cd714a/lib/authenticate/configuration.rb#L302-L312
train
tomichj/authenticate
lib/authenticate/session.rb
Authenticate.Session.login
def login(user) @current_user = user @current_user.generate_session_token if user.present? message = catch(:failure) do Authenticate.lifecycle.run_callbacks(:after_set_user, @current_user, self, event: :authentication) Authenticate.lifecycle.run_callbacks(:after_authentication, @current_user, self, event: :authentication) end status = message.present? ? Failure.new(message) : Success.new if status.success? @current_user.save write_cookie if @current_user.session_token else @current_user = nil end yield(status) if block_given? end
ruby
def login(user) @current_user = user @current_user.generate_session_token if user.present? message = catch(:failure) do Authenticate.lifecycle.run_callbacks(:after_set_user, @current_user, self, event: :authentication) Authenticate.lifecycle.run_callbacks(:after_authentication, @current_user, self, event: :authentication) end status = message.present? ? Failure.new(message) : Success.new if status.success? @current_user.save write_cookie if @current_user.session_token else @current_user = nil end yield(status) if block_given? end
[ "def", "login", "(", "user", ")", "@current_user", "=", "user", "@current_user", ".", "generate_session_token", "if", "user", ".", "present?", "message", "=", "catch", "(", ":failure", ")", "do", "Authenticate", ".", "lifecycle", ".", "run_callbacks", "(", ":after_set_user", ",", "@current_user", ",", "self", ",", "event", ":", ":authentication", ")", "Authenticate", ".", "lifecycle", ".", "run_callbacks", "(", ":after_authentication", ",", "@current_user", ",", "self", ",", "event", ":", ":authentication", ")", "end", "status", "=", "message", ".", "present?", "?", "Failure", ".", "new", "(", "message", ")", ":", "Success", ".", "new", "if", "status", ".", "success?", "@current_user", ".", "save", "write_cookie", "if", "@current_user", ".", "session_token", "else", "@current_user", "=", "nil", "end", "yield", "(", "status", ")", "if", "block_given?", "end" ]
Initialize an Authenticate session. The presence of a session does NOT mean the user is logged in; call #logged_in? to determine login status. Finish user login process, *after* the user has been authenticated. The user is authenticated by Authenticate::Controller#authenticate. Called when user creates an account or signs back into the app. Runs all configured callbacks, checking for login failure. If login is successful, @current_user is set and a session token is generated and returned to the client browser. If login fails, the user is NOT logged in. No session token is set, and @current_user will not be set. After callbacks are finished, a {LoginStatus} is yielded to the provided block, if one is provided. @param [User] user login completed for this user @yieldparam [Success,Failure] status result of the sign in operation. @return [User]
[ "Initialize", "an", "Authenticate", "session", "." ]
f4cdcbc6e42886394a440182f84ce7fa80cd714a
https://github.com/tomichj/authenticate/blob/f4cdcbc6e42886394a440182f84ce7fa80cd714a/lib/authenticate/session.rb#L38-L56
train
tomichj/authenticate
lib/authenticate/controller.rb
Authenticate.Controller.require_login
def require_login debug "!!!!!!!!!!!!!!!!!! controller#require_login " # logged_in? #{logged_in?}" unauthorized unless logged_in? message = catch(:failure) do current_user = authenticate_session.current_user Authenticate.lifecycle.run_callbacks(:after_set_user, current_user, authenticate_session, event: :set_user) end unauthorized(message) if message end
ruby
def require_login debug "!!!!!!!!!!!!!!!!!! controller#require_login " # logged_in? #{logged_in?}" unauthorized unless logged_in? message = catch(:failure) do current_user = authenticate_session.current_user Authenticate.lifecycle.run_callbacks(:after_set_user, current_user, authenticate_session, event: :set_user) end unauthorized(message) if message end
[ "def", "require_login", "debug", "\"!!!!!!!!!!!!!!!!!! controller#require_login \"", "unauthorized", "unless", "logged_in?", "message", "=", "catch", "(", ":failure", ")", "do", "current_user", "=", "authenticate_session", ".", "current_user", "Authenticate", ".", "lifecycle", ".", "run_callbacks", "(", ":after_set_user", ",", "current_user", ",", "authenticate_session", ",", "event", ":", ":set_user", ")", "end", "unauthorized", "(", "message", ")", "if", "message", "end" ]
Use this filter as a before_action to control access to controller actions, limiting to logged in users. Placing in application_controller will control access to all controllers. Example: class ApplicationController < ActionController::Base before_action :require_login def index # ... end end
[ "Use", "this", "filter", "as", "a", "before_action", "to", "control", "access", "to", "controller", "actions", "limiting", "to", "logged", "in", "users", "." ]
f4cdcbc6e42886394a440182f84ce7fa80cd714a
https://github.com/tomichj/authenticate/blob/f4cdcbc6e42886394a440182f84ce7fa80cd714a/lib/authenticate/controller.rb#L81-L89
train
tomichj/authenticate
lib/authenticate/controller.rb
Authenticate.Controller.unauthorized
def unauthorized(msg = t('flashes.failure_when_not_signed_in')) authenticate_session.logout respond_to do |format| format.any(:js, :json, :xml) { head :unauthorized } format.any { redirect_unauthorized(msg) } end end
ruby
def unauthorized(msg = t('flashes.failure_when_not_signed_in')) authenticate_session.logout respond_to do |format| format.any(:js, :json, :xml) { head :unauthorized } format.any { redirect_unauthorized(msg) } end end
[ "def", "unauthorized", "(", "msg", "=", "t", "(", "'flashes.failure_when_not_signed_in'", ")", ")", "authenticate_session", ".", "logout", "respond_to", "do", "|", "format", "|", "format", ".", "any", "(", ":js", ",", ":json", ",", ":xml", ")", "{", "head", ":unauthorized", "}", "format", ".", "any", "{", "redirect_unauthorized", "(", "msg", ")", "}", "end", "end" ]
User is not authorized, bounce 'em to sign in
[ "User", "is", "not", "authorized", "bounce", "em", "to", "sign", "in" ]
f4cdcbc6e42886394a440182f84ce7fa80cd714a
https://github.com/tomichj/authenticate/blob/f4cdcbc6e42886394a440182f84ce7fa80cd714a/lib/authenticate/controller.rb#L153-L159
train
yivo/pug-ruby
lib/jade-pug/config.rb
JadePug.Config.method_missing
def method_missing(name, *args, &block) return super if block case args.size when 0 # config.client? if name =~ /\A(\w+)\?\z/ !!(respond_to?($1) ? send($1) : instance_variable_get("@#{ $1 }")) # config.client elsif name =~ /\A(\w+)\z/ instance_variable_get("@#{ $1 }") else super end when 1 # config.client= if name =~ /\A(\w+)=\z/ instance_variable_set("@#{ $1 }", args.first) else super end else super end end
ruby
def method_missing(name, *args, &block) return super if block case args.size when 0 # config.client? if name =~ /\A(\w+)\?\z/ !!(respond_to?($1) ? send($1) : instance_variable_get("@#{ $1 }")) # config.client elsif name =~ /\A(\w+)\z/ instance_variable_get("@#{ $1 }") else super end when 1 # config.client= if name =~ /\A(\w+)=\z/ instance_variable_set("@#{ $1 }", args.first) else super end else super end end
[ "def", "method_missing", "(", "name", ",", "*", "args", ",", "&", "block", ")", "return", "super", "if", "block", "case", "args", ".", "size", "when", "0", "if", "name", "=~", "/", "\\A", "\\w", "\\?", "\\z", "/", "!", "!", "(", "respond_to?", "(", "$1", ")", "?", "send", "(", "$1", ")", ":", "instance_variable_get", "(", "\"@#{ $1 }\"", ")", ")", "elsif", "name", "=~", "/", "\\A", "\\w", "\\z", "/", "instance_variable_get", "(", "\"@#{ $1 }\"", ")", "else", "super", "end", "when", "1", "if", "name", "=~", "/", "\\A", "\\w", "\\z", "/", "instance_variable_set", "(", "\"@#{ $1 }\"", ",", "args", ".", "first", ")", "else", "super", "end", "else", "super", "end", "end" ]
Allows to dynamically set config attributes.
[ "Allows", "to", "dynamically", "set", "config", "attributes", "." ]
73489d9c6854e22b8ca648e02a68bb6baa410804
https://github.com/yivo/pug-ruby/blob/73489d9c6854e22b8ca648e02a68bb6baa410804/lib/jade-pug/config.rb#L14-L42
train
yivo/pug-ruby
lib/jade-pug/config.rb
JadePug.Config.to_hash
def to_hash instance_variables.each_with_object({}) do |var, h| h[var[1..-1].to_sym] = instance_variable_get(var) end end
ruby
def to_hash instance_variables.each_with_object({}) do |var, h| h[var[1..-1].to_sym] = instance_variable_get(var) end end
[ "def", "to_hash", "instance_variables", ".", "each_with_object", "(", "{", "}", ")", "do", "|", "var", ",", "h", "|", "h", "[", "var", "[", "1", "..", "-", "1", "]", ".", "to_sym", "]", "=", "instance_variable_get", "(", "var", ")", "end", "end" ]
Transforms config to the hash with all keys symbolized. @return [Hash]
[ "Transforms", "config", "to", "the", "hash", "with", "all", "keys", "symbolized", "." ]
73489d9c6854e22b8ca648e02a68bb6baa410804
https://github.com/yivo/pug-ruby/blob/73489d9c6854e22b8ca648e02a68bb6baa410804/lib/jade-pug/config.rb#L52-L56
train
yivo/pug-ruby
lib/jade-pug/compiler.rb
JadePug.Compiler.prepare_options
def prepare_options(options) options = engine.config.to_hash.merge(options) options.keys.each { |k| options[k.to_s.gsub(/_([a-z])/) { $1.upcase }.to_sym] = options[k] } options.delete_if { |k, v| v.nil? } end
ruby
def prepare_options(options) options = engine.config.to_hash.merge(options) options.keys.each { |k| options[k.to_s.gsub(/_([a-z])/) { $1.upcase }.to_sym] = options[k] } options.delete_if { |k, v| v.nil? } end
[ "def", "prepare_options", "(", "options", ")", "options", "=", "engine", ".", "config", ".", "to_hash", ".", "merge", "(", "options", ")", "options", ".", "keys", ".", "each", "{", "|", "k", "|", "options", "[", "k", ".", "to_s", ".", "gsub", "(", "/", "/", ")", "{", "$1", ".", "upcase", "}", ".", "to_sym", "]", "=", "options", "[", "k", "]", "}", "options", ".", "delete_if", "{", "|", "k", ",", "v", "|", "v", ".", "nil?", "}", "end" ]
Responds for preparing compilation options. The next steps are executed: - is merges options into the engine config - it camelizes and symbolizes every option key - it removes nil values from the options @param options [Hash] @return [Hash]
[ "Responds", "for", "preparing", "compilation", "options", "." ]
73489d9c6854e22b8ca648e02a68bb6baa410804
https://github.com/yivo/pug-ruby/blob/73489d9c6854e22b8ca648e02a68bb6baa410804/lib/jade-pug/compiler.rb#L94-L98
train
yivo/pug-ruby
lib/jade-pug/shipped-compiler.rb
JadePug.ShippedCompiler.read_compiler_source
def read_compiler_source(path) raise engine::CompilerError, "Couldn't read compiler source: #{ path }" unless File.readable?(path) File.read(path) end
ruby
def read_compiler_source(path) raise engine::CompilerError, "Couldn't read compiler source: #{ path }" unless File.readable?(path) File.read(path) end
[ "def", "read_compiler_source", "(", "path", ")", "raise", "engine", "::", "CompilerError", ",", "\"Couldn't read compiler source: #{ path }\"", "unless", "File", ".", "readable?", "(", "path", ")", "File", ".", "read", "(", "path", ")", "end" ]
Reads the compiler source from a file and returns it. @param path [String] @return [String]
[ "Reads", "the", "compiler", "source", "from", "a", "file", "and", "returns", "it", "." ]
73489d9c6854e22b8ca648e02a68bb6baa410804
https://github.com/yivo/pug-ruby/blob/73489d9c6854e22b8ca648e02a68bb6baa410804/lib/jade-pug/shipped-compiler.rb#L54-L57
train
yivo/pug-ruby
lib/jade-pug/system-compiler.rb
JadePug.SystemCompiler.version
def version stdout, exit_status = Open3.capture2 "node", "--eval", \ "console.log(require(#{ JSON.dump(File.join(npm_package_path, "package.json")) }).version)" if exit_status.success? stdout.strip else raise engine::CompilerError, \ %{Failed to get #{ engine.name } version. Perhaps, the problem with Node.js runtime.} end end
ruby
def version stdout, exit_status = Open3.capture2 "node", "--eval", \ "console.log(require(#{ JSON.dump(File.join(npm_package_path, "package.json")) }).version)" if exit_status.success? stdout.strip else raise engine::CompilerError, \ %{Failed to get #{ engine.name } version. Perhaps, the problem with Node.js runtime.} end end
[ "def", "version", "stdout", ",", "exit_status", "=", "Open3", ".", "capture2", "\"node\"", ",", "\"--eval\"", ",", "\"console.log(require(#{ JSON.dump(File.join(npm_package_path, \"package.json\")) }).version)\"", "if", "exit_status", ".", "success?", "stdout", ".", "strip", "else", "raise", "engine", "::", "CompilerError", ",", "%{Failed to get #{ engine.name } version. Perhaps, the problem with Node.js runtime.}", "end", "end" ]
Returns version of engine installed system-wide. @return [String]
[ "Returns", "version", "of", "engine", "installed", "system", "-", "wide", "." ]
73489d9c6854e22b8ca648e02a68bb6baa410804
https://github.com/yivo/pug-ruby/blob/73489d9c6854e22b8ca648e02a68bb6baa410804/lib/jade-pug/system-compiler.rb#L47-L57
train
yivo/pug-ruby
lib/jade-pug/system-compiler.rb
JadePug.SystemCompiler.check_npm_package!
def check_npm_package! exit_status = Open3.capture2("node", "--eval", npm_package_require_snippet)[1] unless exit_status.success? raise engine::CompilerError, \ %{No #{ engine.name } NPM package has been found in your system. } + %{Have you forgotten to "npm install --global #{ npm_package_name }"?} end nil end
ruby
def check_npm_package! exit_status = Open3.capture2("node", "--eval", npm_package_require_snippet)[1] unless exit_status.success? raise engine::CompilerError, \ %{No #{ engine.name } NPM package has been found in your system. } + %{Have you forgotten to "npm install --global #{ npm_package_name }"?} end nil end
[ "def", "check_npm_package!", "exit_status", "=", "Open3", ".", "capture2", "(", "\"node\"", ",", "\"--eval\"", ",", "npm_package_require_snippet", ")", "[", "1", "]", "unless", "exit_status", ".", "success?", "raise", "engine", "::", "CompilerError", ",", "%{No #{ engine.name } NPM package has been found in your system. }", "+", "%{Have you forgotten to \"npm install --global #{ npm_package_name }\"?}", "end", "nil", "end" ]
Checks if engine NPM package is installed. @raise {JadePug::CompilerError} If engine NPM package is not installed. @return [nil]
[ "Checks", "if", "engine", "NPM", "package", "is", "installed", "." ]
73489d9c6854e22b8ca648e02a68bb6baa410804
https://github.com/yivo/pug-ruby/blob/73489d9c6854e22b8ca648e02a68bb6baa410804/lib/jade-pug/system-compiler.rb#L127-L136
train
jmettraux/rufus-lua
lib/rufus/lua/state.rb
Rufus::Lua.StateMixin.loadstring_and_call
def loadstring_and_call(s, bndng, filename, lineno) bottom = stack_top chunk = filename ? "#{filename}:#{lineno}" : 'line' err = Lib.luaL_loadbuffer(@pointer, s, s.bytesize, chunk) fail_if_error('eval:compile', err, bndng, filename, lineno) pcall(bottom, 0, bndng, filename, lineno) # arg_count is set to 0 end
ruby
def loadstring_and_call(s, bndng, filename, lineno) bottom = stack_top chunk = filename ? "#{filename}:#{lineno}" : 'line' err = Lib.luaL_loadbuffer(@pointer, s, s.bytesize, chunk) fail_if_error('eval:compile', err, bndng, filename, lineno) pcall(bottom, 0, bndng, filename, lineno) # arg_count is set to 0 end
[ "def", "loadstring_and_call", "(", "s", ",", "bndng", ",", "filename", ",", "lineno", ")", "bottom", "=", "stack_top", "chunk", "=", "filename", "?", "\"#{filename}:#{lineno}\"", ":", "'line'", "err", "=", "Lib", ".", "luaL_loadbuffer", "(", "@pointer", ",", "s", ",", "s", ".", "bytesize", ",", "chunk", ")", "fail_if_error", "(", "'eval:compile'", ",", "err", ",", "bndng", ",", "filename", ",", "lineno", ")", "pcall", "(", "bottom", ",", "0", ",", "bndng", ",", "filename", ",", "lineno", ")", "end" ]
This method holds the 'eval' mechanism.
[ "This", "method", "holds", "the", "eval", "mechanism", "." ]
7bf215d9222c27895f17bc128b32362caee6dd62
https://github.com/jmettraux/rufus-lua/blob/7bf215d9222c27895f17bc128b32362caee6dd62/lib/rufus/lua/state.rb#L65-L74
train
jmettraux/rufus-lua
lib/rufus/lua/state.rb
Rufus::Lua.StateMixin.stack_to_s
def stack_to_s # warning : don't touch at stack[0] s = (1..stack_top).inject([]) { |a, i| type, tname = stack_type_at(i) val = if type == TSTRING "\"#{stack_fetch(i)}\"" elsif SIMPLE_TYPES.include?(type) stack_fetch(i).to_s elsif type == TTABLE "(# is #{Lib.lua_objlen(@pointer, i)})" else '' end a << "#{i} : #{tname} (#{type}) #{val}" a }.reverse.join("\n") s += "\n" if s.length > 0 s end
ruby
def stack_to_s # warning : don't touch at stack[0] s = (1..stack_top).inject([]) { |a, i| type, tname = stack_type_at(i) val = if type == TSTRING "\"#{stack_fetch(i)}\"" elsif SIMPLE_TYPES.include?(type) stack_fetch(i).to_s elsif type == TTABLE "(# is #{Lib.lua_objlen(@pointer, i)})" else '' end a << "#{i} : #{tname} (#{type}) #{val}" a }.reverse.join("\n") s += "\n" if s.length > 0 s end
[ "def", "stack_to_s", "s", "=", "(", "1", "..", "stack_top", ")", ".", "inject", "(", "[", "]", ")", "{", "|", "a", ",", "i", "|", "type", ",", "tname", "=", "stack_type_at", "(", "i", ")", "val", "=", "if", "type", "==", "TSTRING", "\"\\\"#{stack_fetch(i)}\\\"\"", "elsif", "SIMPLE_TYPES", ".", "include?", "(", "type", ")", "stack_fetch", "(", "i", ")", ".", "to_s", "elsif", "type", "==", "TTABLE", "\"(# is #{Lib.lua_objlen(@pointer, i)})\"", "else", "''", "end", "a", "<<", "\"#{i} : #{tname} (#{type}) #{val}\"", "a", "}", ".", "reverse", ".", "join", "(", "\"\\n\"", ")", "s", "+=", "\"\\n\"", "if", "s", ".", "length", ">", "0", "s", "end" ]
Returns a string representation of the state's stack.
[ "Returns", "a", "string", "representation", "of", "the", "state", "s", "stack", "." ]
7bf215d9222c27895f17bc128b32362caee6dd62
https://github.com/jmettraux/rufus-lua/blob/7bf215d9222c27895f17bc128b32362caee6dd62/lib/rufus/lua/state.rb#L78-L104
train
jmettraux/rufus-lua
lib/rufus/lua/state.rb
Rufus::Lua.StateMixin.stack_push
def stack_push(o) return stack_push(o.to_lua) if o.respond_to?(:to_lua) case o when NilClass then Lib.lua_pushnil(@pointer) when TrueClass then Lib.lua_pushboolean(@pointer, 1) when FalseClass then Lib.lua_pushboolean(@pointer, 0) when Integer then Lib.lua_pushinteger(@pointer, o) when Float then Lib.lua_pushnumber(@pointer, o) when String then Lib.lua_pushlstring(@pointer, o, o.bytesize) when Symbol then Lib.lua_pushlstring(@pointer, o.to_s, o.to_s.bytesize) when Hash then stack_push_hash(o) when Array then stack_push_array(o) else raise( ArgumentError.new( "don't know how to pass Ruby instance of #{o.class} to Lua")) end end
ruby
def stack_push(o) return stack_push(o.to_lua) if o.respond_to?(:to_lua) case o when NilClass then Lib.lua_pushnil(@pointer) when TrueClass then Lib.lua_pushboolean(@pointer, 1) when FalseClass then Lib.lua_pushboolean(@pointer, 0) when Integer then Lib.lua_pushinteger(@pointer, o) when Float then Lib.lua_pushnumber(@pointer, o) when String then Lib.lua_pushlstring(@pointer, o, o.bytesize) when Symbol then Lib.lua_pushlstring(@pointer, o.to_s, o.to_s.bytesize) when Hash then stack_push_hash(o) when Array then stack_push_array(o) else raise( ArgumentError.new( "don't know how to pass Ruby instance of #{o.class} to Lua")) end end
[ "def", "stack_push", "(", "o", ")", "return", "stack_push", "(", "o", ".", "to_lua", ")", "if", "o", ".", "respond_to?", "(", ":to_lua", ")", "case", "o", "when", "NilClass", "then", "Lib", ".", "lua_pushnil", "(", "@pointer", ")", "when", "TrueClass", "then", "Lib", ".", "lua_pushboolean", "(", "@pointer", ",", "1", ")", "when", "FalseClass", "then", "Lib", ".", "lua_pushboolean", "(", "@pointer", ",", "0", ")", "when", "Integer", "then", "Lib", ".", "lua_pushinteger", "(", "@pointer", ",", "o", ")", "when", "Float", "then", "Lib", ".", "lua_pushnumber", "(", "@pointer", ",", "o", ")", "when", "String", "then", "Lib", ".", "lua_pushlstring", "(", "@pointer", ",", "o", ",", "o", ".", "bytesize", ")", "when", "Symbol", "then", "Lib", ".", "lua_pushlstring", "(", "@pointer", ",", "o", ".", "to_s", ",", "o", ".", "to_s", ".", "bytesize", ")", "when", "Hash", "then", "stack_push_hash", "(", "o", ")", "when", "Array", "then", "stack_push_array", "(", "o", ")", "else", "raise", "(", "ArgumentError", ".", "new", "(", "\"don't know how to pass Ruby instance of #{o.class} to Lua\"", ")", ")", "end", "end" ]
Given a Ruby instance, will attempt to push it on the Lua stack.
[ "Given", "a", "Ruby", "instance", "will", "attempt", "to", "push", "it", "on", "the", "Lua", "stack", "." ]
7bf215d9222c27895f17bc128b32362caee6dd62
https://github.com/jmettraux/rufus-lua/blob/7bf215d9222c27895f17bc128b32362caee6dd62/lib/rufus/lua/state.rb#L190-L214
train
jmettraux/rufus-lua
lib/rufus/lua/state.rb
Rufus::Lua.StateMixin.stack_push_hash
def stack_push_hash(h) Lib.lua_createtable(@pointer, 0, h.size) # since we already know the size of the table... h.each do |k, v| stack_push(k) stack_push(v) Lib.lua_settable(@pointer, -3) end end
ruby
def stack_push_hash(h) Lib.lua_createtable(@pointer, 0, h.size) # since we already know the size of the table... h.each do |k, v| stack_push(k) stack_push(v) Lib.lua_settable(@pointer, -3) end end
[ "def", "stack_push_hash", "(", "h", ")", "Lib", ".", "lua_createtable", "(", "@pointer", ",", "0", ",", "h", ".", "size", ")", "h", ".", "each", "do", "|", "k", ",", "v", "|", "stack_push", "(", "k", ")", "stack_push", "(", "v", ")", "Lib", ".", "lua_settable", "(", "@pointer", ",", "-", "3", ")", "end", "end" ]
Pushes a hash on top of the Lua stack.
[ "Pushes", "a", "hash", "on", "top", "of", "the", "Lua", "stack", "." ]
7bf215d9222c27895f17bc128b32362caee6dd62
https://github.com/jmettraux/rufus-lua/blob/7bf215d9222c27895f17bc128b32362caee6dd62/lib/rufus/lua/state.rb#L218-L228
train
jmettraux/rufus-lua
lib/rufus/lua/state.rb
Rufus::Lua.StateMixin.stack_push_array
def stack_push_array(a) Lib.lua_createtable(@pointer, a.size, 0) # since we already know the size of the table... a.each_with_index do |e, i| stack_push(i + 1) stack_push(e) Lib.lua_settable(@pointer, -3) end end
ruby
def stack_push_array(a) Lib.lua_createtable(@pointer, a.size, 0) # since we already know the size of the table... a.each_with_index do |e, i| stack_push(i + 1) stack_push(e) Lib.lua_settable(@pointer, -3) end end
[ "def", "stack_push_array", "(", "a", ")", "Lib", ".", "lua_createtable", "(", "@pointer", ",", "a", ".", "size", ",", "0", ")", "a", ".", "each_with_index", "do", "|", "e", ",", "i", "|", "stack_push", "(", "i", "+", "1", ")", "stack_push", "(", "e", ")", "Lib", ".", "lua_settable", "(", "@pointer", ",", "-", "3", ")", "end", "end" ]
Pushes an array on top of the Lua stack.
[ "Pushes", "an", "array", "on", "top", "of", "the", "Lua", "stack", "." ]
7bf215d9222c27895f17bc128b32362caee6dd62
https://github.com/jmettraux/rufus-lua/blob/7bf215d9222c27895f17bc128b32362caee6dd62/lib/rufus/lua/state.rb#L232-L242
train
bdurand/seamless_database_pool
lib/seamless_database_pool/controller_filter.rb
SeamlessDatabasePool.ControllerFilter.set_read_only_connection_for_block
def set_read_only_connection_for_block(action) read_pool_method = nil if session read_pool_method = session[:next_request_db_connection] session.delete(:next_request_db_connection) if session[:next_request_db_connection] end read_pool_method ||= seamless_database_pool_options[action.to_sym] || seamless_database_pool_options[:all] if read_pool_method SeamlessDatabasePool.set_read_only_connection_type(read_pool_method) do yield end else yield end end
ruby
def set_read_only_connection_for_block(action) read_pool_method = nil if session read_pool_method = session[:next_request_db_connection] session.delete(:next_request_db_connection) if session[:next_request_db_connection] end read_pool_method ||= seamless_database_pool_options[action.to_sym] || seamless_database_pool_options[:all] if read_pool_method SeamlessDatabasePool.set_read_only_connection_type(read_pool_method) do yield end else yield end end
[ "def", "set_read_only_connection_for_block", "(", "action", ")", "read_pool_method", "=", "nil", "if", "session", "read_pool_method", "=", "session", "[", ":next_request_db_connection", "]", "session", ".", "delete", "(", ":next_request_db_connection", ")", "if", "session", "[", ":next_request_db_connection", "]", "end", "read_pool_method", "||=", "seamless_database_pool_options", "[", "action", ".", "to_sym", "]", "||", "seamless_database_pool_options", "[", ":all", "]", "if", "read_pool_method", "SeamlessDatabasePool", ".", "set_read_only_connection_type", "(", "read_pool_method", ")", "do", "yield", "end", "else", "yield", "end", "end" ]
Set the read only connection for a block. Used to set the connection for a controller action.
[ "Set", "the", "read", "only", "connection", "for", "a", "block", ".", "Used", "to", "set", "the", "connection", "for", "a", "controller", "action", "." ]
529c1d49b2c6029de7444830bce72917de79ebff
https://github.com/bdurand/seamless_database_pool/blob/529c1d49b2c6029de7444830bce72917de79ebff/lib/seamless_database_pool/controller_filter.rb#L72-L87
train
jmettraux/rufus-lua
lib/rufus/lua/objects.rb
Rufus::Lua.Function.call
def call(*args) bottom = stack_top load_onto_stack # load function on stack args.each { |arg| stack_push(arg) } # push arguments on stack pcall(bottom, args.length, nil, nil, nil) end
ruby
def call(*args) bottom = stack_top load_onto_stack # load function on stack args.each { |arg| stack_push(arg) } # push arguments on stack pcall(bottom, args.length, nil, nil, nil) end
[ "def", "call", "(", "*", "args", ")", "bottom", "=", "stack_top", "load_onto_stack", "args", ".", "each", "{", "|", "arg", "|", "stack_push", "(", "arg", ")", "}", "pcall", "(", "bottom", ",", "args", ".", "length", ",", "nil", ",", "nil", ",", "nil", ")", "end" ]
Calls the Lua function.
[ "Calls", "the", "Lua", "function", "." ]
7bf215d9222c27895f17bc128b32362caee6dd62
https://github.com/jmettraux/rufus-lua/blob/7bf215d9222c27895f17bc128b32362caee6dd62/lib/rufus/lua/objects.rb#L67-L78
train
jmettraux/rufus-lua
lib/rufus/lua/objects.rb
Rufus::Lua.Coroutine.resume
def resume(*args) bottom = stack_top fetch_library_method('coroutine.resume').load_onto_stack load_onto_stack args.each { |arg| stack_push(arg) } pcall(bottom, args.length + 1, nil, nil, nil) end
ruby
def resume(*args) bottom = stack_top fetch_library_method('coroutine.resume').load_onto_stack load_onto_stack args.each { |arg| stack_push(arg) } pcall(bottom, args.length + 1, nil, nil, nil) end
[ "def", "resume", "(", "*", "args", ")", "bottom", "=", "stack_top", "fetch_library_method", "(", "'coroutine.resume'", ")", ".", "load_onto_stack", "load_onto_stack", "args", ".", "each", "{", "|", "arg", "|", "stack_push", "(", "arg", ")", "}", "pcall", "(", "bottom", ",", "args", ".", "length", "+", "1", ",", "nil", ",", "nil", ",", "nil", ")", "end" ]
Resumes the coroutine
[ "Resumes", "the", "coroutine" ]
7bf215d9222c27895f17bc128b32362caee6dd62
https://github.com/jmettraux/rufus-lua/blob/7bf215d9222c27895f17bc128b32362caee6dd62/lib/rufus/lua/objects.rb#L88-L98
train
jmettraux/rufus-lua
lib/rufus/lua/objects.rb
Rufus::Lua.Table.[]=
def []=(k, v) load_onto_stack stack_push(k) stack_push(v) Lib.lua_settable(@pointer, -3) v end
ruby
def []=(k, v) load_onto_stack stack_push(k) stack_push(v) Lib.lua_settable(@pointer, -3) v end
[ "def", "[]=", "(", "k", ",", "v", ")", "load_onto_stack", "stack_push", "(", "k", ")", "stack_push", "(", "v", ")", "Lib", ".", "lua_settable", "(", "@pointer", ",", "-", "3", ")", "v", "end" ]
Sets a value in the table TODO : have something for adding in the array part...
[ "Sets", "a", "value", "in", "the", "table" ]
7bf215d9222c27895f17bc128b32362caee6dd62
https://github.com/jmettraux/rufus-lua/blob/7bf215d9222c27895f17bc128b32362caee6dd62/lib/rufus/lua/objects.rb#L166-L175
train
jmettraux/rufus-lua
lib/rufus/lua/objects.rb
Rufus::Lua.Table.to_h
def to_h load_onto_stack table_pos = stack_top Lib.lua_pushnil(@pointer) h = {} while Lib.lua_next(@pointer, table_pos) != 0 do value = stack_fetch(-1) value.load_onto_stack if value.is_a?(Ref) key = stack_fetch(-2) key.load_onto_stack if key.is_a?(Ref) stack_unstack # leave key on top h[key] = value end h end
ruby
def to_h load_onto_stack table_pos = stack_top Lib.lua_pushnil(@pointer) h = {} while Lib.lua_next(@pointer, table_pos) != 0 do value = stack_fetch(-1) value.load_onto_stack if value.is_a?(Ref) key = stack_fetch(-2) key.load_onto_stack if key.is_a?(Ref) stack_unstack # leave key on top h[key] = value end h end
[ "def", "to_h", "load_onto_stack", "table_pos", "=", "stack_top", "Lib", ".", "lua_pushnil", "(", "@pointer", ")", "h", "=", "{", "}", "while", "Lib", ".", "lua_next", "(", "@pointer", ",", "table_pos", ")", "!=", "0", "do", "value", "=", "stack_fetch", "(", "-", "1", ")", "value", ".", "load_onto_stack", "if", "value", ".", "is_a?", "(", "Ref", ")", "key", "=", "stack_fetch", "(", "-", "2", ")", "key", ".", "load_onto_stack", "if", "key", ".", "is_a?", "(", "Ref", ")", "stack_unstack", "h", "[", "key", "]", "=", "value", "end", "h", "end" ]
Returns a Ruby Hash instance representing this Lua table.
[ "Returns", "a", "Ruby", "Hash", "instance", "representing", "this", "Lua", "table", "." ]
7bf215d9222c27895f17bc128b32362caee6dd62
https://github.com/jmettraux/rufus-lua/blob/7bf215d9222c27895f17bc128b32362caee6dd62/lib/rufus/lua/objects.rb#L199-L223
train
jmettraux/rufus-lua
lib/rufus/lua/objects.rb
Rufus::Lua.Table.to_a
def to_a(pure=true) h = self.to_h pure && h.keys.find { |k| not [ Float ].include?(k.class) } && fail('cannot turn hash into array, some keys are not numbers') a_keys = (1..objlen).to_a.collect { |k| k.to_f } keys = a_keys + (h.keys - a_keys) keys.inject([]) { |a, k| a << (a_keys.include?(k) ? h[k] : [ k, h[k] ]) a } end
ruby
def to_a(pure=true) h = self.to_h pure && h.keys.find { |k| not [ Float ].include?(k.class) } && fail('cannot turn hash into array, some keys are not numbers') a_keys = (1..objlen).to_a.collect { |k| k.to_f } keys = a_keys + (h.keys - a_keys) keys.inject([]) { |a, k| a << (a_keys.include?(k) ? h[k] : [ k, h[k] ]) a } end
[ "def", "to_a", "(", "pure", "=", "true", ")", "h", "=", "self", ".", "to_h", "pure", "&&", "h", ".", "keys", ".", "find", "{", "|", "k", "|", "not", "[", "Float", "]", ".", "include?", "(", "k", ".", "class", ")", "}", "&&", "fail", "(", "'cannot turn hash into array, some keys are not numbers'", ")", "a_keys", "=", "(", "1", "..", "objlen", ")", ".", "to_a", ".", "collect", "{", "|", "k", "|", "k", ".", "to_f", "}", "keys", "=", "a_keys", "+", "(", "h", ".", "keys", "-", "a_keys", ")", "keys", ".", "inject", "(", "[", "]", ")", "{", "|", "a", ",", "k", "|", "a", "<<", "(", "a_keys", ".", "include?", "(", "k", ")", "?", "h", "[", "k", "]", ":", "[", "k", ",", "h", "[", "k", "]", "]", ")", "a", "}", "end" ]
Returns a Ruby Array instance representing this Lua table. Will raise an error if the 'rendering' is not possible. s = Rufus::Lua::State.new @s.eval("return { a = 'A', b = 'B', c = 3 }").to_a # => error ! @s.eval("return { 1, 2 }").to_a # => [ 1.0, 2.0 ] @s.eval("return {}").to_a # => [] @s.eval("return { 1, 2, car = 'benz' }").to_a # => error ! == to_a(false) Setting the optional argument 'pure' to false will manage any table : s = Rufus::Lua::State.new @s.eval("return { a = 'A', b = 'B', c = 3 }").to_a(false) # => [["a", "A"], ["b", "B"], ["c", 3.0]] @s.eval("return { 1, 2 }").to_a(false) # => [1.0, 2.0] @s.eval("return {}").to_a(false) # => [] @s.eval("return { 1, 2, car = 'benz' }").to_a(false) # => [1.0, 2.0, ["car", "benz"]]
[ "Returns", "a", "Ruby", "Array", "instance", "representing", "this", "Lua", "table", "." ]
7bf215d9222c27895f17bc128b32362caee6dd62
https://github.com/jmettraux/rufus-lua/blob/7bf215d9222c27895f17bc128b32362caee6dd62/lib/rufus/lua/objects.rb#L261-L275
train
Atrox/sweetify
lib/sweetify/sweetalert.rb
Sweetify.SweetAlert.sweetalert
def sweetalert(text, title = '', opts = {}) opts = { showConfirmButton: false, timer: 2000, allowOutsideClick: true, confirmButtonText: 'OK' }.merge(opts) opts[:text] = text opts[:title] = title if opts[:button] opts[:showConfirmButton] = true opts[:confirmButtonText] = opts[:button] if opts[:button].is_a?(String) opts.delete(:button) end if opts[:persistent] opts[:showConfirmButton] = true opts[:allowOutsideClick] = false opts[:timer] = nil opts[:confirmButtonText] = opts[:persistent] if opts[:persistent].is_a?(String) opts.delete(:persistent) end flash_config(opts) end
ruby
def sweetalert(text, title = '', opts = {}) opts = { showConfirmButton: false, timer: 2000, allowOutsideClick: true, confirmButtonText: 'OK' }.merge(opts) opts[:text] = text opts[:title] = title if opts[:button] opts[:showConfirmButton] = true opts[:confirmButtonText] = opts[:button] if opts[:button].is_a?(String) opts.delete(:button) end if opts[:persistent] opts[:showConfirmButton] = true opts[:allowOutsideClick] = false opts[:timer] = nil opts[:confirmButtonText] = opts[:persistent] if opts[:persistent].is_a?(String) opts.delete(:persistent) end flash_config(opts) end
[ "def", "sweetalert", "(", "text", ",", "title", "=", "''", ",", "opts", "=", "{", "}", ")", "opts", "=", "{", "showConfirmButton", ":", "false", ",", "timer", ":", "2000", ",", "allowOutsideClick", ":", "true", ",", "confirmButtonText", ":", "'OK'", "}", ".", "merge", "(", "opts", ")", "opts", "[", ":text", "]", "=", "text", "opts", "[", ":title", "]", "=", "title", "if", "opts", "[", ":button", "]", "opts", "[", ":showConfirmButton", "]", "=", "true", "opts", "[", ":confirmButtonText", "]", "=", "opts", "[", ":button", "]", "if", "opts", "[", ":button", "]", ".", "is_a?", "(", "String", ")", "opts", ".", "delete", "(", ":button", ")", "end", "if", "opts", "[", ":persistent", "]", "opts", "[", ":showConfirmButton", "]", "=", "true", "opts", "[", ":allowOutsideClick", "]", "=", "false", "opts", "[", ":timer", "]", "=", "nil", "opts", "[", ":confirmButtonText", "]", "=", "opts", "[", ":persistent", "]", "if", "opts", "[", ":persistent", "]", ".", "is_a?", "(", "String", ")", "opts", ".", "delete", "(", ":persistent", ")", "end", "flash_config", "(", "opts", ")", "end" ]
Display an alert with a text and an optional title Default without an specific type @param [String] text Body of the alert (gets automatically the title if no title is specified) @param [String] title Title of the alert @param [Hash] opts Optional Parameters
[ "Display", "an", "alert", "with", "a", "text", "and", "an", "optional", "title", "Default", "without", "an", "specific", "type" ]
299e91e6407f17912f351f9492d42a4eb44c063f
https://github.com/Atrox/sweetify/blob/299e91e6407f17912f351f9492d42a4eb44c063f/lib/sweetify/sweetalert.rb#L9-L37
train
Atrox/sweetify
lib/sweetify/sweetalert.rb
Sweetify.SweetAlert.flash_config
def flash_config(opts) if opts[:title].blank? opts[:title] = opts[:text] opts.delete(:text) end flash[:sweetify] = opts.to_json end
ruby
def flash_config(opts) if opts[:title].blank? opts[:title] = opts[:text] opts.delete(:text) end flash[:sweetify] = opts.to_json end
[ "def", "flash_config", "(", "opts", ")", "if", "opts", "[", ":title", "]", ".", "blank?", "opts", "[", ":title", "]", "=", "opts", "[", ":text", "]", "opts", ".", "delete", "(", ":text", ")", "end", "flash", "[", ":sweetify", "]", "=", "opts", ".", "to_json", "end" ]
Flash the configuration as json If no title is specified, use the text as the title @param [Hash] opts @return [Void]
[ "Flash", "the", "configuration", "as", "json", "If", "no", "title", "is", "specified", "use", "the", "text", "as", "the", "title" ]
299e91e6407f17912f351f9492d42a4eb44c063f
https://github.com/Atrox/sweetify/blob/299e91e6407f17912f351f9492d42a4eb44c063f/lib/sweetify/sweetalert.rb#L86-L93
train
ebeigarts/exchanger
lib/exchanger/element.rb
Exchanger.Element.to_xml
def to_xml(options = {}) doc = Nokogiri::XML::Document.new root = doc.create_element(tag_name) self.class.keys.each do |name| value = read_attribute(name) next if value.blank? root[name.to_s.camelize] = value end self.class.elements.each do |name, field| next if options[:only] && !options[:only].include?(name) next if field.options[:readonly] value = read_attribute(name) next if field.type.is_a?(Array) && value.blank? next if new_record? && field.type == Identifier next if new_record? && value.blank? if name == :text root << value.to_s else root << field.to_xml(value) end end root end
ruby
def to_xml(options = {}) doc = Nokogiri::XML::Document.new root = doc.create_element(tag_name) self.class.keys.each do |name| value = read_attribute(name) next if value.blank? root[name.to_s.camelize] = value end self.class.elements.each do |name, field| next if options[:only] && !options[:only].include?(name) next if field.options[:readonly] value = read_attribute(name) next if field.type.is_a?(Array) && value.blank? next if new_record? && field.type == Identifier next if new_record? && value.blank? if name == :text root << value.to_s else root << field.to_xml(value) end end root end
[ "def", "to_xml", "(", "options", "=", "{", "}", ")", "doc", "=", "Nokogiri", "::", "XML", "::", "Document", ".", "new", "root", "=", "doc", ".", "create_element", "(", "tag_name", ")", "self", ".", "class", ".", "keys", ".", "each", "do", "|", "name", "|", "value", "=", "read_attribute", "(", "name", ")", "next", "if", "value", ".", "blank?", "root", "[", "name", ".", "to_s", ".", "camelize", "]", "=", "value", "end", "self", ".", "class", ".", "elements", ".", "each", "do", "|", "name", ",", "field", "|", "next", "if", "options", "[", ":only", "]", "&&", "!", "options", "[", ":only", "]", ".", "include?", "(", "name", ")", "next", "if", "field", ".", "options", "[", ":readonly", "]", "value", "=", "read_attribute", "(", "name", ")", "next", "if", "field", ".", "type", ".", "is_a?", "(", "Array", ")", "&&", "value", ".", "blank?", "next", "if", "new_record?", "&&", "field", ".", "type", "==", "Identifier", "next", "if", "new_record?", "&&", "value", ".", "blank?", "if", "name", "==", ":text", "root", "<<", "value", ".", "to_s", "else", "root", "<<", "field", ".", "to_xml", "(", "value", ")", "end", "end", "root", "end" ]
Builds XML from elements and attributes
[ "Builds", "XML", "from", "elements", "and", "attributes" ]
10f24ffaaa69881bebb9823b1756cb18ca96e2f8
https://github.com/ebeigarts/exchanger/blob/10f24ffaaa69881bebb9823b1756cb18ca96e2f8/lib/exchanger/element.rb#L97-L119
train
mitchellh/middleware
lib/middleware/builder.rb
Middleware.Builder.insert
def insert(index, middleware, *args, &block) index = self.index(index) unless index.is_a?(Integer) raise "no such middleware to insert before: #{index.inspect}" unless index stack.insert(index, [middleware, args, block]) end
ruby
def insert(index, middleware, *args, &block) index = self.index(index) unless index.is_a?(Integer) raise "no such middleware to insert before: #{index.inspect}" unless index stack.insert(index, [middleware, args, block]) end
[ "def", "insert", "(", "index", ",", "middleware", ",", "*", "args", ",", "&", "block", ")", "index", "=", "self", ".", "index", "(", "index", ")", "unless", "index", ".", "is_a?", "(", "Integer", ")", "raise", "\"no such middleware to insert before: #{index.inspect}\"", "unless", "index", "stack", ".", "insert", "(", "index", ",", "[", "middleware", ",", "args", ",", "block", "]", ")", "end" ]
Inserts a middleware at the given index or directly before the given middleware object.
[ "Inserts", "a", "middleware", "at", "the", "given", "index", "or", "directly", "before", "the", "given", "middleware", "object", "." ]
23d4741d15c5999d81493ec43448f72032119bee
https://github.com/mitchellh/middleware/blob/23d4741d15c5999d81493ec43448f72032119bee/lib/middleware/builder.rb#L68-L72
train
mitchellh/middleware
lib/middleware/builder.rb
Middleware.Builder.replace
def replace(index, middleware, *args, &block) if index.is_a?(Integer) delete(index) insert(index, middleware, *args, &block) else insert_before(index, middleware, *args, &block) delete(index) end end
ruby
def replace(index, middleware, *args, &block) if index.is_a?(Integer) delete(index) insert(index, middleware, *args, &block) else insert_before(index, middleware, *args, &block) delete(index) end end
[ "def", "replace", "(", "index", ",", "middleware", ",", "*", "args", ",", "&", "block", ")", "if", "index", ".", "is_a?", "(", "Integer", ")", "delete", "(", "index", ")", "insert", "(", "index", ",", "middleware", ",", "*", "args", ",", "&", "block", ")", "else", "insert_before", "(", "index", ",", "middleware", ",", "*", "args", ",", "&", "block", ")", "delete", "(", "index", ")", "end", "end" ]
Replaces the given middleware object or index with the new middleware.
[ "Replaces", "the", "given", "middleware", "object", "or", "index", "with", "the", "new", "middleware", "." ]
23d4741d15c5999d81493ec43448f72032119bee
https://github.com/mitchellh/middleware/blob/23d4741d15c5999d81493ec43448f72032119bee/lib/middleware/builder.rb#L85-L93
train
ebeigarts/exchanger
lib/exchanger/persistence.rb
Exchanger.Persistence.reload
def reload if new_record? false else reloaded_element = self.class.find(self.id) @attributes = reloaded_element.attributes reset_modifications true end end
ruby
def reload if new_record? false else reloaded_element = self.class.find(self.id) @attributes = reloaded_element.attributes reset_modifications true end end
[ "def", "reload", "if", "new_record?", "false", "else", "reloaded_element", "=", "self", ".", "class", ".", "find", "(", "self", ".", "id", ")", "@attributes", "=", "reloaded_element", ".", "attributes", "reset_modifications", "true", "end", "end" ]
Reloads the +Element+ attributes from Exchanger.
[ "Reloads", "the", "+", "Element", "+", "attributes", "from", "Exchanger", "." ]
10f24ffaaa69881bebb9823b1756cb18ca96e2f8
https://github.com/ebeigarts/exchanger/blob/10f24ffaaa69881bebb9823b1756cb18ca96e2f8/lib/exchanger/persistence.rb#L28-L37
train
ebeigarts/exchanger
lib/exchanger/field.rb
Exchanger.Field.to_xml
def to_xml(value, options = {}) if value.is_a?(Exchanger::Element) value.tag_name = tag_name value.to_xml(options) else doc = Nokogiri::XML::Document.new root = doc.create_element(tag_name) case value when Array value.each do |sub_value| root << sub_field.to_xml(sub_value, options) end when Boolean root << doc.create_text_node(value == true) when Time root << doc.create_text_node(value.xmlschema) else # String, Integer, etc root << doc.create_text_node(value.to_s) end root end end
ruby
def to_xml(value, options = {}) if value.is_a?(Exchanger::Element) value.tag_name = tag_name value.to_xml(options) else doc = Nokogiri::XML::Document.new root = doc.create_element(tag_name) case value when Array value.each do |sub_value| root << sub_field.to_xml(sub_value, options) end when Boolean root << doc.create_text_node(value == true) when Time root << doc.create_text_node(value.xmlschema) else # String, Integer, etc root << doc.create_text_node(value.to_s) end root end end
[ "def", "to_xml", "(", "value", ",", "options", "=", "{", "}", ")", "if", "value", ".", "is_a?", "(", "Exchanger", "::", "Element", ")", "value", ".", "tag_name", "=", "tag_name", "value", ".", "to_xml", "(", "options", ")", "else", "doc", "=", "Nokogiri", "::", "XML", "::", "Document", ".", "new", "root", "=", "doc", ".", "create_element", "(", "tag_name", ")", "case", "value", "when", "Array", "value", ".", "each", "do", "|", "sub_value", "|", "root", "<<", "sub_field", ".", "to_xml", "(", "sub_value", ",", "options", ")", "end", "when", "Boolean", "root", "<<", "doc", ".", "create_text_node", "(", "value", "==", "true", ")", "when", "Time", "root", "<<", "doc", ".", "create_text_node", "(", "value", ".", "xmlschema", ")", "else", "root", "<<", "doc", ".", "create_text_node", "(", "value", ".", "to_s", ")", "end", "root", "end", "end" ]
Convert Ruby value to XML
[ "Convert", "Ruby", "value", "to", "XML" ]
10f24ffaaa69881bebb9823b1756cb18ca96e2f8
https://github.com/ebeigarts/exchanger/blob/10f24ffaaa69881bebb9823b1756cb18ca96e2f8/lib/exchanger/field.rb#L97-L118
train
ebeigarts/exchanger
lib/exchanger/field.rb
Exchanger.Field.value_from_xml
def value_from_xml(node) if type.respond_to?(:new_from_xml) type.new_from_xml(node) elsif type.is_a?(Array) node.children.map do |sub_node| sub_field.value_from_xml(sub_node) end elsif type == Boolean node.text == "true" elsif type == Integer node.text.to_i unless node.text.empty? elsif type == Time Time.xmlschema(node.text) unless node.text.empty? else node.text end end
ruby
def value_from_xml(node) if type.respond_to?(:new_from_xml) type.new_from_xml(node) elsif type.is_a?(Array) node.children.map do |sub_node| sub_field.value_from_xml(sub_node) end elsif type == Boolean node.text == "true" elsif type == Integer node.text.to_i unless node.text.empty? elsif type == Time Time.xmlschema(node.text) unless node.text.empty? else node.text end end
[ "def", "value_from_xml", "(", "node", ")", "if", "type", ".", "respond_to?", "(", ":new_from_xml", ")", "type", ".", "new_from_xml", "(", "node", ")", "elsif", "type", ".", "is_a?", "(", "Array", ")", "node", ".", "children", ".", "map", "do", "|", "sub_node", "|", "sub_field", ".", "value_from_xml", "(", "sub_node", ")", "end", "elsif", "type", "==", "Boolean", "node", ".", "text", "==", "\"true\"", "elsif", "type", "==", "Integer", "node", ".", "text", ".", "to_i", "unless", "node", ".", "text", ".", "empty?", "elsif", "type", "==", "Time", "Time", ".", "xmlschema", "(", "node", ".", "text", ")", "unless", "node", ".", "text", ".", "empty?", "else", "node", ".", "text", "end", "end" ]
Convert XML to Ruby value
[ "Convert", "XML", "to", "Ruby", "value" ]
10f24ffaaa69881bebb9823b1756cb18ca96e2f8
https://github.com/ebeigarts/exchanger/blob/10f24ffaaa69881bebb9823b1756cb18ca96e2f8/lib/exchanger/field.rb#L121-L137
train
ebeigarts/exchanger
lib/exchanger/dirty.rb
Exchanger.Dirty.reset_attribute!
def reset_attribute!(name) value = attribute_was(name) if value @attributes[name] = value modifications.delete(name) end end
ruby
def reset_attribute!(name) value = attribute_was(name) if value @attributes[name] = value modifications.delete(name) end end
[ "def", "reset_attribute!", "(", "name", ")", "value", "=", "attribute_was", "(", "name", ")", "if", "value", "@attributes", "[", "name", "]", "=", "value", "modifications", ".", "delete", "(", "name", ")", "end", "end" ]
Resets a changed field back to its old value. Example: person = Person.new(:title => "Sir") person.title = "Madam" person.reset_attribute!("title") person.title # "Sir" Returns: The old field value.
[ "Resets", "a", "changed", "field", "back", "to", "its", "old", "value", "." ]
10f24ffaaa69881bebb9823b1756cb18ca96e2f8
https://github.com/ebeigarts/exchanger/blob/10f24ffaaa69881bebb9823b1756cb18ca96e2f8/lib/exchanger/dirty.rb#L139-L145
train
ebeigarts/exchanger
lib/exchanger/dirty.rb
Exchanger.Dirty.accessed
def accessed(name, value) @accessed ||= {} @accessed[name] = value.dup if (value.is_a?(Array) || value.is_a?(Hash)) && [email protected]_key?(name) value end
ruby
def accessed(name, value) @accessed ||= {} @accessed[name] = value.dup if (value.is_a?(Array) || value.is_a?(Hash)) && [email protected]_key?(name) value end
[ "def", "accessed", "(", "name", ",", "value", ")", "@accessed", "||=", "{", "}", "@accessed", "[", "name", "]", "=", "value", ".", "dup", "if", "(", "value", ".", "is_a?", "(", "Array", ")", "||", "value", ".", "is_a?", "(", "Hash", ")", ")", "&&", "!", "@accessed", ".", "has_key?", "(", "name", ")", "value", "end" ]
Audit the original value for a field that can be modified in place. Example: <tt>person.accessed("aliases", [ "007" ])</tt>
[ "Audit", "the", "original", "value", "for", "a", "field", "that", "can", "be", "modified", "in", "place", "." ]
10f24ffaaa69881bebb9823b1756cb18ca96e2f8
https://github.com/ebeigarts/exchanger/blob/10f24ffaaa69881bebb9823b1756cb18ca96e2f8/lib/exchanger/dirty.rb#L177-L181
train
ebeigarts/exchanger
lib/exchanger/dirty.rb
Exchanger.Dirty.modifications
def modifications @accessed.each_pair do |field, value| current = @attributes[field] if current != value || (current.is_a?(Array) && current.any? { |v| v.respond_to?(:changed?) && v.changed? }) @modifications[field] = [ value, current ] end end @accessed.clear @modifications end
ruby
def modifications @accessed.each_pair do |field, value| current = @attributes[field] if current != value || (current.is_a?(Array) && current.any? { |v| v.respond_to?(:changed?) && v.changed? }) @modifications[field] = [ value, current ] end end @accessed.clear @modifications end
[ "def", "modifications", "@accessed", ".", "each_pair", "do", "|", "field", ",", "value", "|", "current", "=", "@attributes", "[", "field", "]", "if", "current", "!=", "value", "||", "(", "current", ".", "is_a?", "(", "Array", ")", "&&", "current", ".", "any?", "{", "|", "v", "|", "v", ".", "respond_to?", "(", ":changed?", ")", "&&", "v", ".", "changed?", "}", ")", "@modifications", "[", "field", "]", "=", "[", "value", ",", "current", "]", "end", "end", "@accessed", ".", "clear", "@modifications", "end" ]
Get all normal modifications plus in place potential changes. Also checks changes in array attributes with +Element+ objects. Example: <tt>person.modifications</tt> Returns: All changes to the document.
[ "Get", "all", "normal", "modifications", "plus", "in", "place", "potential", "changes", ".", "Also", "checks", "changes", "in", "array", "attributes", "with", "+", "Element", "+", "objects", "." ]
10f24ffaaa69881bebb9823b1756cb18ca96e2f8
https://github.com/ebeigarts/exchanger/blob/10f24ffaaa69881bebb9823b1756cb18ca96e2f8/lib/exchanger/dirty.rb#L193-L203
train
ebeigarts/exchanger
lib/exchanger/dirty.rb
Exchanger.Dirty.modify
def modify(name, old_value, new_value) @attributes[name] = new_value if @modifications && (old_value != new_value) original = @modifications[name].first if @modifications[name] @modifications[name] = [ (original || old_value), new_value ] end end
ruby
def modify(name, old_value, new_value) @attributes[name] = new_value if @modifications && (old_value != new_value) original = @modifications[name].first if @modifications[name] @modifications[name] = [ (original || old_value), new_value ] end end
[ "def", "modify", "(", "name", ",", "old_value", ",", "new_value", ")", "@attributes", "[", "name", "]", "=", "new_value", "if", "@modifications", "&&", "(", "old_value", "!=", "new_value", ")", "original", "=", "@modifications", "[", "name", "]", ".", "first", "if", "@modifications", "[", "name", "]", "@modifications", "[", "name", "]", "=", "[", "(", "original", "||", "old_value", ")", ",", "new_value", "]", "end", "end" ]
Audit the change of a field's value. Example: <tt>person.modify("name", "Jack", "John")</tt>
[ "Audit", "the", "change", "of", "a", "field", "s", "value", "." ]
10f24ffaaa69881bebb9823b1756cb18ca96e2f8
https://github.com/ebeigarts/exchanger/blob/10f24ffaaa69881bebb9823b1756cb18ca96e2f8/lib/exchanger/dirty.rb#L210-L216
train
ebeigarts/exchanger
lib/exchanger/attributes.rb
Exchanger.Attributes.method_missing
def method_missing(name, *args) attr = name.to_s.sub("=", "") return super unless attributes.has_key?(attr) if name.to_s.ends_with?("=") write_attribute(attr, *args) else read_attribute(attr) end end
ruby
def method_missing(name, *args) attr = name.to_s.sub("=", "") return super unless attributes.has_key?(attr) if name.to_s.ends_with?("=") write_attribute(attr, *args) else read_attribute(attr) end end
[ "def", "method_missing", "(", "name", ",", "*", "args", ")", "attr", "=", "name", ".", "to_s", ".", "sub", "(", "\"=\"", ",", "\"\"", ")", "return", "super", "unless", "attributes", ".", "has_key?", "(", "attr", ")", "if", "name", ".", "to_s", ".", "ends_with?", "(", "\"=\"", ")", "write_attribute", "(", "attr", ",", "*", "args", ")", "else", "read_attribute", "(", "attr", ")", "end", "end" ]
Used for allowing accessor methods for dynamic attributes
[ "Used", "for", "allowing", "accessor", "methods", "for", "dynamic", "attributes" ]
10f24ffaaa69881bebb9823b1756cb18ca96e2f8
https://github.com/ebeigarts/exchanger/blob/10f24ffaaa69881bebb9823b1756cb18ca96e2f8/lib/exchanger/attributes.rb#L51-L59
train
ebeigarts/exchanger
lib/exchanger/client.rb
Exchanger.Client.request
def request(post_body, headers) response = @client.post(endpoint, post_body, headers) return { :status => response.status, :body => response.content, :content_type => response.contenttype } end
ruby
def request(post_body, headers) response = @client.post(endpoint, post_body, headers) return { :status => response.status, :body => response.content, :content_type => response.contenttype } end
[ "def", "request", "(", "post_body", ",", "headers", ")", "response", "=", "@client", ".", "post", "(", "endpoint", ",", "post_body", ",", "headers", ")", "return", "{", ":status", "=>", "response", ".", "status", ",", ":body", "=>", "response", ".", "content", ",", ":content_type", "=>", "response", ".", "contenttype", "}", "end" ]
Does the actual HTTP level interaction.
[ "Does", "the", "actual", "HTTP", "level", "interaction", "." ]
10f24ffaaa69881bebb9823b1756cb18ca96e2f8
https://github.com/ebeigarts/exchanger/blob/10f24ffaaa69881bebb9823b1756cb18ca96e2f8/lib/exchanger/client.rb#L15-L18
train
Arcath/Adauth
lib/adauth/connection.rb
Adauth.Connection.bind
def bind conn = Net::LDAP.new :host => @config[:server], :port => @config[:port], :base => @config[:base] if @config[:encryption] conn.encryption @config[:encryption] end raise "Anonymous Bind is disabled" if @config[:password] == "" && !(@config[:anonymous_bind]) conn.auth "#{@config[:username]}@#{@config[:domain]}", @config[:password] begin Timeout::timeout(10){ if conn.bind return conn else raise 'Query User Rejected' end } rescue Timeout::Error raise 'Unable to connect to LDAP Server' rescue Errno::ECONNRESET if @config[:allow_fallback] @config[:port] = @config[:allow_fallback] @config[:encryption] = false return Adauth::Connection.new(@config).bind end end end
ruby
def bind conn = Net::LDAP.new :host => @config[:server], :port => @config[:port], :base => @config[:base] if @config[:encryption] conn.encryption @config[:encryption] end raise "Anonymous Bind is disabled" if @config[:password] == "" && !(@config[:anonymous_bind]) conn.auth "#{@config[:username]}@#{@config[:domain]}", @config[:password] begin Timeout::timeout(10){ if conn.bind return conn else raise 'Query User Rejected' end } rescue Timeout::Error raise 'Unable to connect to LDAP Server' rescue Errno::ECONNRESET if @config[:allow_fallback] @config[:port] = @config[:allow_fallback] @config[:encryption] = false return Adauth::Connection.new(@config).bind end end end
[ "def", "bind", "conn", "=", "Net", "::", "LDAP", ".", "new", ":host", "=>", "@config", "[", ":server", "]", ",", ":port", "=>", "@config", "[", ":port", "]", ",", ":base", "=>", "@config", "[", ":base", "]", "if", "@config", "[", ":encryption", "]", "conn", ".", "encryption", "@config", "[", ":encryption", "]", "end", "raise", "\"Anonymous Bind is disabled\"", "if", "@config", "[", ":password", "]", "==", "\"\"", "&&", "!", "(", "@config", "[", ":anonymous_bind", "]", ")", "conn", ".", "auth", "\"#{@config[:username]}@#{@config[:domain]}\"", ",", "@config", "[", ":password", "]", "begin", "Timeout", "::", "timeout", "(", "10", ")", "{", "if", "conn", ".", "bind", "return", "conn", "else", "raise", "'Query User Rejected'", "end", "}", "rescue", "Timeout", "::", "Error", "raise", "'Unable to connect to LDAP Server'", "rescue", "Errno", "::", "ECONNRESET", "if", "@config", "[", ":allow_fallback", "]", "@config", "[", ":port", "]", "=", "@config", "[", ":allow_fallback", "]", "@config", "[", ":encryption", "]", "=", "false", "return", "Adauth", "::", "Connection", ".", "new", "(", "@config", ")", ".", "bind", "end", "end", "end" ]
Attempts to bind to Active Directory If it works it returns the connection If it fails it raises and exception
[ "Attempts", "to", "bind", "to", "Active", "Directory" ]
5017ceded89d8927fd3d772c9046395706b39570
https://github.com/Arcath/Adauth/blob/5017ceded89d8927fd3d772c9046395706b39570/lib/adauth/connection.rb#L18-L47
train
dachinat/nextcloud
lib/nextcloud/api.rb
Nextcloud.Api.request
def request(method, path, params = nil, body = nil, depth = nil, destination = nil, raw = false) response = Net::HTTP.start(@url.host, @url.port, use_ssl: @url.scheme == "https") do |http| req = Kernel.const_get("Net::HTTP::#{method.capitalize}").new(@url.request_uri + path) req["OCS-APIRequest"] = true req.basic_auth @username, @password req["Content-Type"] = "application/x-www-form-urlencoded" req["Depth"] = 0 if depth req["Destination"] = destination if destination req.set_form_data(params) if params req.body = body if body http.request(req) end # if ![201, 204, 207].include? response.code # raise Errors::Error.new("Nextcloud received invalid status code") # end raw ? response.body : Nokogiri::XML.parse(response.body) end
ruby
def request(method, path, params = nil, body = nil, depth = nil, destination = nil, raw = false) response = Net::HTTP.start(@url.host, @url.port, use_ssl: @url.scheme == "https") do |http| req = Kernel.const_get("Net::HTTP::#{method.capitalize}").new(@url.request_uri + path) req["OCS-APIRequest"] = true req.basic_auth @username, @password req["Content-Type"] = "application/x-www-form-urlencoded" req["Depth"] = 0 if depth req["Destination"] = destination if destination req.set_form_data(params) if params req.body = body if body http.request(req) end # if ![201, 204, 207].include? response.code # raise Errors::Error.new("Nextcloud received invalid status code") # end raw ? response.body : Nokogiri::XML.parse(response.body) end
[ "def", "request", "(", "method", ",", "path", ",", "params", "=", "nil", ",", "body", "=", "nil", ",", "depth", "=", "nil", ",", "destination", "=", "nil", ",", "raw", "=", "false", ")", "response", "=", "Net", "::", "HTTP", ".", "start", "(", "@url", ".", "host", ",", "@url", ".", "port", ",", "use_ssl", ":", "@url", ".", "scheme", "==", "\"https\"", ")", "do", "|", "http", "|", "req", "=", "Kernel", ".", "const_get", "(", "\"Net::HTTP::#{method.capitalize}\"", ")", ".", "new", "(", "@url", ".", "request_uri", "+", "path", ")", "req", "[", "\"OCS-APIRequest\"", "]", "=", "true", "req", ".", "basic_auth", "@username", ",", "@password", "req", "[", "\"Content-Type\"", "]", "=", "\"application/x-www-form-urlencoded\"", "req", "[", "\"Depth\"", "]", "=", "0", "if", "depth", "req", "[", "\"Destination\"", "]", "=", "destination", "if", "destination", "req", ".", "set_form_data", "(", "params", ")", "if", "params", "req", ".", "body", "=", "body", "if", "body", "http", ".", "request", "(", "req", ")", "end", "raw", "?", "response", ".", "body", ":", "Nokogiri", "::", "XML", ".", "parse", "(", "response", ".", "body", ")", "end" ]
Gathers credentials for communicating with Nextcloud instance @param [Hash] args authentication credentials. @option args [String] :url Nextcloud instance URL @option args [String] :username Nextcloud instance administrator username @option args [String] :password Nextcloud instance administrator password Sends API request to Nextcloud @param method [Symbol] Request type. Can be :get, :post, :put, etc. @param path [String] Nextcloud OCS API request path @param params [Hash, nil] Parameters to send @return [Object] Nokogiri::XML::Document
[ "Gathers", "credentials", "for", "communicating", "with", "Nextcloud", "instance" ]
717e5a0f5971fdd35210f256125234ce6b92006a
https://github.com/dachinat/nextcloud/blob/717e5a0f5971fdd35210f256125234ce6b92006a/lib/nextcloud/api.rb#L26-L47
train
dachinat/nextcloud
lib/nextcloud/helpers/nextcloud.rb
Nextcloud.Helpers.parse_with_meta
def parse_with_meta(doc, xpath) groups = [] doc.xpath(xpath).each do |prop| groups << prop.text end meta = get_meta(doc) groups.send(:define_singleton_method, :meta) do meta end groups end
ruby
def parse_with_meta(doc, xpath) groups = [] doc.xpath(xpath).each do |prop| groups << prop.text end meta = get_meta(doc) groups.send(:define_singleton_method, :meta) do meta end groups end
[ "def", "parse_with_meta", "(", "doc", ",", "xpath", ")", "groups", "=", "[", "]", "doc", ".", "xpath", "(", "xpath", ")", ".", "each", "do", "|", "prop", "|", "groups", "<<", "prop", ".", "text", "end", "meta", "=", "get_meta", "(", "doc", ")", "groups", ".", "send", "(", ":define_singleton_method", ",", ":meta", ")", "do", "meta", "end", "groups", "end" ]
Makes an array out of repeated elements @param doc [Object] Nokogiri::XML::Document @param xpath [String] Path to element that is being repeated @return [Array] Parsed array
[ "Makes", "an", "array", "out", "of", "repeated", "elements" ]
717e5a0f5971fdd35210f256125234ce6b92006a
https://github.com/dachinat/nextcloud/blob/717e5a0f5971fdd35210f256125234ce6b92006a/lib/nextcloud/helpers/nextcloud.rb#L12-L22
train
dachinat/nextcloud
lib/nextcloud/helpers/nextcloud.rb
Nextcloud.Helpers.get_meta
def get_meta(doc) meta = doc.xpath("//meta/*").each_with_object({}) do |node, meta| meta[node.name] = node.text end end
ruby
def get_meta(doc) meta = doc.xpath("//meta/*").each_with_object({}) do |node, meta| meta[node.name] = node.text end end
[ "def", "get_meta", "(", "doc", ")", "meta", "=", "doc", ".", "xpath", "(", "\"//meta/*\"", ")", ".", "each_with_object", "(", "{", "}", ")", "do", "|", "node", ",", "meta", "|", "meta", "[", "node", ".", "name", "]", "=", "node", ".", "text", "end", "end" ]
Parses meta information returned by API, may include a status, status code and a message @param doc [Object] Nokogiri::XML::Document @return [Hash] Parsed hash
[ "Parses", "meta", "information", "returned", "by", "API", "may", "include", "a", "status", "status", "code", "and", "a", "message" ]
717e5a0f5971fdd35210f256125234ce6b92006a
https://github.com/dachinat/nextcloud/blob/717e5a0f5971fdd35210f256125234ce6b92006a/lib/nextcloud/helpers/nextcloud.rb#L28-L32
train
dachinat/nextcloud
lib/nextcloud/helpers/nextcloud.rb
Nextcloud.Helpers.doc_to_hash
def doc_to_hash(doc, xpath = "/") h = Hash.from_xml(doc.xpath(xpath).to_xml) h end
ruby
def doc_to_hash(doc, xpath = "/") h = Hash.from_xml(doc.xpath(xpath).to_xml) h end
[ "def", "doc_to_hash", "(", "doc", ",", "xpath", "=", "\"/\"", ")", "h", "=", "Hash", ".", "from_xml", "(", "doc", ".", "xpath", "(", "xpath", ")", ".", "to_xml", ")", "h", "end" ]
Converts document to hash @param doc [Object] Nokogiri::XML::Document @param xpath [String] Document path to convert to hash @return [Hash] Hash that was produced from XML document
[ "Converts", "document", "to", "hash" ]
717e5a0f5971fdd35210f256125234ce6b92006a
https://github.com/dachinat/nextcloud/blob/717e5a0f5971fdd35210f256125234ce6b92006a/lib/nextcloud/helpers/nextcloud.rb#L39-L42
train
dachinat/nextcloud
lib/nextcloud/helpers/nextcloud.rb
Nextcloud.Helpers.add_meta
def add_meta(doc, obj) meta = get_meta(doc) obj.define_singleton_method(:meta) { meta } && obj end
ruby
def add_meta(doc, obj) meta = get_meta(doc) obj.define_singleton_method(:meta) { meta } && obj end
[ "def", "add_meta", "(", "doc", ",", "obj", ")", "meta", "=", "get_meta", "(", "doc", ")", "obj", ".", "define_singleton_method", "(", ":meta", ")", "{", "meta", "}", "&&", "obj", "end" ]
Adds meta method to an object @param doc [Object] Nokogiri::XML::Document to take meta information from @param obj [#define_singleton_method] Object to add meta method to @return [#define_singleton_method] Object with meta method defined
[ "Adds", "meta", "method", "to", "an", "object" ]
717e5a0f5971fdd35210f256125234ce6b92006a
https://github.com/dachinat/nextcloud/blob/717e5a0f5971fdd35210f256125234ce6b92006a/lib/nextcloud/helpers/nextcloud.rb#L49-L52
train
dachinat/nextcloud
lib/nextcloud/helpers/nextcloud.rb
Nextcloud.Helpers.parse_dav_response
def parse_dav_response(doc) doc.remove_namespaces! if doc.at_xpath("//error") { exception: doc.xpath("//exception").text, message: doc.xpath("//message").text } elsif doc.at_xpath("//status") { status: doc.xpath("//status").text } else { status: "ok" } end end
ruby
def parse_dav_response(doc) doc.remove_namespaces! if doc.at_xpath("//error") { exception: doc.xpath("//exception").text, message: doc.xpath("//message").text } elsif doc.at_xpath("//status") { status: doc.xpath("//status").text } else { status: "ok" } end end
[ "def", "parse_dav_response", "(", "doc", ")", "doc", ".", "remove_namespaces!", "if", "doc", ".", "at_xpath", "(", "\"//error\"", ")", "{", "exception", ":", "doc", ".", "xpath", "(", "\"//exception\"", ")", ".", "text", ",", "message", ":", "doc", ".", "xpath", "(", "\"//message\"", ")", ".", "text", "}", "elsif", "doc", ".", "at_xpath", "(", "\"//status\"", ")", "{", "status", ":", "doc", ".", "xpath", "(", "\"//status\"", ")", ".", "text", "}", "else", "{", "status", ":", "\"ok\"", "}", "end", "end" ]
Shows errors, or success message @param doc [Object] Nokogiri::XML::Document @return [Hash] State response
[ "Shows", "errors", "or", "success", "message" ]
717e5a0f5971fdd35210f256125234ce6b92006a
https://github.com/dachinat/nextcloud/blob/717e5a0f5971fdd35210f256125234ce6b92006a/lib/nextcloud/helpers/nextcloud.rb#L67-L83
train
dachinat/nextcloud
lib/nextcloud/helpers/nextcloud.rb
Nextcloud.Helpers.has_dav_errors
def has_dav_errors(doc) doc.remove_namespaces! if doc.at_xpath("//error") { exception: doc.xpath("//exception").text, message: doc.xpath("//message").text } else false end end
ruby
def has_dav_errors(doc) doc.remove_namespaces! if doc.at_xpath("//error") { exception: doc.xpath("//exception").text, message: doc.xpath("//message").text } else false end end
[ "def", "has_dav_errors", "(", "doc", ")", "doc", ".", "remove_namespaces!", "if", "doc", ".", "at_xpath", "(", "\"//error\"", ")", "{", "exception", ":", "doc", ".", "xpath", "(", "\"//exception\"", ")", ".", "text", ",", "message", ":", "doc", ".", "xpath", "(", "\"//message\"", ")", ".", "text", "}", "else", "false", "end", "end" ]
Shows error or returns false @param doc [Object] Nokogiri::XML::Document @return [Hash,Boolean] Returns error message if found, false otherwise
[ "Shows", "error", "or", "returns", "false" ]
717e5a0f5971fdd35210f256125234ce6b92006a
https://github.com/dachinat/nextcloud/blob/717e5a0f5971fdd35210f256125234ce6b92006a/lib/nextcloud/helpers/nextcloud.rb#L89-L99
train
Arcath/Adauth
lib/adauth/ad_object.rb
Adauth.AdObject.handle_field
def handle_field(field) case field when Symbol then return return_symbol_value(field) when Array then return @ldap_object.try(field.first).try(:collect, &field.last) end end
ruby
def handle_field(field) case field when Symbol then return return_symbol_value(field) when Array then return @ldap_object.try(field.first).try(:collect, &field.last) end end
[ "def", "handle_field", "(", "field", ")", "case", "field", "when", "Symbol", "then", "return", "return_symbol_value", "(", "field", ")", "when", "Array", "then", "return", "@ldap_object", ".", "try", "(", "field", ".", "first", ")", ".", "try", "(", ":collect", ",", "&", "field", ".", "last", ")", "end", "end" ]
Handle the output for the given field
[ "Handle", "the", "output", "for", "the", "given", "field" ]
5017ceded89d8927fd3d772c9046395706b39570
https://github.com/Arcath/Adauth/blob/5017ceded89d8927fd3d772c9046395706b39570/lib/adauth/ad_object.rb#L93-L98
train
Arcath/Adauth
lib/adauth/ad_object.rb
Adauth.AdObject.cn_groups_nested
def cn_groups_nested @cn_groups_nested = cn_groups cn_groups.each do |group| ado = Adauth::AdObjects::Group.where('name', group).first if ado groups = convert_to_objects ado.cn_groups groups.each do |g| @cn_groups_nested.push g if !(@cn_groups_nested.include?(g)) end end end return @cn_groups_nested end
ruby
def cn_groups_nested @cn_groups_nested = cn_groups cn_groups.each do |group| ado = Adauth::AdObjects::Group.where('name', group).first if ado groups = convert_to_objects ado.cn_groups groups.each do |g| @cn_groups_nested.push g if !(@cn_groups_nested.include?(g)) end end end return @cn_groups_nested end
[ "def", "cn_groups_nested", "@cn_groups_nested", "=", "cn_groups", "cn_groups", ".", "each", "do", "|", "group", "|", "ado", "=", "Adauth", "::", "AdObjects", "::", "Group", ".", "where", "(", "'name'", ",", "group", ")", ".", "first", "if", "ado", "groups", "=", "convert_to_objects", "ado", ".", "cn_groups", "groups", ".", "each", "do", "|", "g", "|", "@cn_groups_nested", ".", "push", "g", "if", "!", "(", "@cn_groups_nested", ".", "include?", "(", "g", ")", ")", "end", "end", "end", "return", "@cn_groups_nested", "end" ]
The same as cn_groups, but with the parent groups included
[ "The", "same", "as", "cn_groups", "but", "with", "the", "parent", "groups", "included" ]
5017ceded89d8927fd3d772c9046395706b39570
https://github.com/Arcath/Adauth/blob/5017ceded89d8927fd3d772c9046395706b39570/lib/adauth/ad_object.rb#L109-L121
train
Arcath/Adauth
lib/adauth/ad_object.rb
Adauth.AdObject.ous
def ous unless @ous @ous = [] @ldap_object.dn.split(/,/).each do |entry| @ous.push Adauth::AdObjects::OU.where('name', entry.gsub(/OU=/, '')).first if entry =~ /OU=/ end end @ous end
ruby
def ous unless @ous @ous = [] @ldap_object.dn.split(/,/).each do |entry| @ous.push Adauth::AdObjects::OU.where('name', entry.gsub(/OU=/, '')).first if entry =~ /OU=/ end end @ous end
[ "def", "ous", "unless", "@ous", "@ous", "=", "[", "]", "@ldap_object", ".", "dn", ".", "split", "(", "/", "/", ")", ".", "each", "do", "|", "entry", "|", "@ous", ".", "push", "Adauth", "::", "AdObjects", "::", "OU", ".", "where", "(", "'name'", ",", "entry", ".", "gsub", "(", "/", "/", ",", "''", ")", ")", ".", "first", "if", "entry", "=~", "/", "/", "end", "end", "@ous", "end" ]
Returns all the ous the object is in
[ "Returns", "all", "the", "ous", "the", "object", "is", "in" ]
5017ceded89d8927fd3d772c9046395706b39570
https://github.com/Arcath/Adauth/blob/5017ceded89d8927fd3d772c9046395706b39570/lib/adauth/ad_object.rb#L124-L132
train
Arcath/Adauth
lib/adauth/ad_object.rb
Adauth.AdObject.modify
def modify(operations) Adauth.logger.info(self.class.inspect) { "Attempting modify operation" } unless Adauth.connection.modify :dn => @ldap_object.dn, :operations => operations Adauth.logger.fatal(self.class.inspect) { "Modify Operation Failed! Code: #{Adauth.connection.get_operation_result.code} Message: #{Adauth.connection.get_operation_result.message}" } raise 'Modify Operation Failed (see log for details)' end end
ruby
def modify(operations) Adauth.logger.info(self.class.inspect) { "Attempting modify operation" } unless Adauth.connection.modify :dn => @ldap_object.dn, :operations => operations Adauth.logger.fatal(self.class.inspect) { "Modify Operation Failed! Code: #{Adauth.connection.get_operation_result.code} Message: #{Adauth.connection.get_operation_result.message}" } raise 'Modify Operation Failed (see log for details)' end end
[ "def", "modify", "(", "operations", ")", "Adauth", ".", "logger", ".", "info", "(", "self", ".", "class", ".", "inspect", ")", "{", "\"Attempting modify operation\"", "}", "unless", "Adauth", ".", "connection", ".", "modify", ":dn", "=>", "@ldap_object", ".", "dn", ",", ":operations", "=>", "operations", "Adauth", ".", "logger", ".", "fatal", "(", "self", ".", "class", ".", "inspect", ")", "{", "\"Modify Operation Failed! Code: #{Adauth.connection.get_operation_result.code} Message: #{Adauth.connection.get_operation_result.message}\"", "}", "raise", "'Modify Operation Failed (see log for details)'", "end", "end" ]
Runs a modify action on the current object, takes an aray of operations
[ "Runs", "a", "modify", "action", "on", "the", "current", "object", "takes", "an", "aray", "of", "operations" ]
5017ceded89d8927fd3d772c9046395706b39570
https://github.com/Arcath/Adauth/blob/5017ceded89d8927fd3d772c9046395706b39570/lib/adauth/ad_object.rb#L146-L152
train
Arcath/Adauth
lib/adauth/ad_object.rb
Adauth.AdObject.members
def members unless @members @members = [] [Adauth::AdObjects::Computer, Adauth::AdObjects::OU, Adauth::AdObjects::User, Adauth::AdObjects::Group].each do |object| object.all.each do |entity| @members.push entity if entity.is_a_member?(self) end end end @members end
ruby
def members unless @members @members = [] [Adauth::AdObjects::Computer, Adauth::AdObjects::OU, Adauth::AdObjects::User, Adauth::AdObjects::Group].each do |object| object.all.each do |entity| @members.push entity if entity.is_a_member?(self) end end end @members end
[ "def", "members", "unless", "@members", "@members", "=", "[", "]", "[", "Adauth", "::", "AdObjects", "::", "Computer", ",", "Adauth", "::", "AdObjects", "::", "OU", ",", "Adauth", "::", "AdObjects", "::", "User", ",", "Adauth", "::", "AdObjects", "::", "Group", "]", ".", "each", "do", "|", "object", "|", "object", ".", "all", ".", "each", "do", "|", "entity", "|", "@members", ".", "push", "entity", "if", "entity", ".", "is_a_member?", "(", "self", ")", "end", "end", "end", "@members", "end" ]
Returns an array of member objects for this object
[ "Returns", "an", "array", "of", "member", "objects", "for", "this", "object" ]
5017ceded89d8927fd3d772c9046395706b39570
https://github.com/Arcath/Adauth/blob/5017ceded89d8927fd3d772c9046395706b39570/lib/adauth/ad_object.rb#L155-L165
train
Maher4Ever/wdm
spec/support/monitor_helper.rb
WDM.SpecSupport.run_and_collect_multiple_changes
def run_and_collect_multiple_changes(monitor, times, directory, *flags, &block) watch_and_run(monitor, times, false, directory, *flags, &block) end
ruby
def run_and_collect_multiple_changes(monitor, times, directory, *flags, &block) watch_and_run(monitor, times, false, directory, *flags, &block) end
[ "def", "run_and_collect_multiple_changes", "(", "monitor", ",", "times", ",", "directory", ",", "*", "flags", ",", "&", "block", ")", "watch_and_run", "(", "monitor", ",", "times", ",", "false", ",", "directory", ",", "*", "flags", ",", "&", "block", ")", "end" ]
Runs the monitor and collects changes for the specified amount of times on the given directory. It stops the monitor afterwards. @yield
[ "Runs", "the", "monitor", "and", "collects", "changes", "for", "the", "specified", "amount", "of", "times", "on", "the", "given", "directory", ".", "It", "stops", "the", "monitor", "afterwards", "." ]
41aaa6d7bb228e0721a36681b789295467494fb6
https://github.com/Maher4Ever/wdm/blob/41aaa6d7bb228e0721a36681b789295467494fb6/spec/support/monitor_helper.rb#L12-L14
train
Maher4Ever/wdm
spec/support/monitor_helper.rb
WDM.SpecSupport.run
def run(monitor, directory, *flags, &block) result = watch_and_run(monitor, 1, false, directory, *flags, &block) result.changes[0].directory = result.directory result.changes[0] end
ruby
def run(monitor, directory, *flags, &block) result = watch_and_run(monitor, 1, false, directory, *flags, &block) result.changes[0].directory = result.directory result.changes[0] end
[ "def", "run", "(", "monitor", ",", "directory", ",", "*", "flags", ",", "&", "block", ")", "result", "=", "watch_and_run", "(", "monitor", ",", "1", ",", "false", ",", "directory", ",", "*", "flags", ",", "&", "block", ")", "result", ".", "changes", "[", "0", "]", ".", "directory", "=", "result", ".", "directory", "result", ".", "changes", "[", "0", "]", "end" ]
Helper method for running the monitor one time. @yield
[ "Helper", "method", "for", "running", "the", "monitor", "one", "time", "." ]
41aaa6d7bb228e0721a36681b789295467494fb6
https://github.com/Maher4Ever/wdm/blob/41aaa6d7bb228e0721a36681b789295467494fb6/spec/support/monitor_helper.rb#L20-L24
train
Maher4Ever/wdm
spec/support/monitor_helper.rb
WDM.SpecSupport.run_with_fixture
def run_with_fixture(monitor, *flags, &block) fixture do |f| run(monitor, f, *flags, &block) end end
ruby
def run_with_fixture(monitor, *flags, &block) fixture do |f| run(monitor, f, *flags, &block) end end
[ "def", "run_with_fixture", "(", "monitor", ",", "*", "flags", ",", "&", "block", ")", "fixture", "do", "|", "f", "|", "run", "(", "monitor", ",", "f", ",", "*", "flags", ",", "&", "block", ")", "end", "end" ]
Helper method for using the run method with the fixture helper. @yield
[ "Helper", "method", "for", "using", "the", "run", "method", "with", "the", "fixture", "helper", "." ]
41aaa6d7bb228e0721a36681b789295467494fb6
https://github.com/Maher4Ever/wdm/blob/41aaa6d7bb228e0721a36681b789295467494fb6/spec/support/monitor_helper.rb#L30-L34
train
Maher4Ever/wdm
spec/support/monitor_helper.rb
WDM.SpecSupport.run_recursively_and_collect_multiple_changes
def run_recursively_and_collect_multiple_changes(monitor, times, directory, *flags, &block) watch_and_run(monitor, times, true, directory, *flags, &block) end
ruby
def run_recursively_and_collect_multiple_changes(monitor, times, directory, *flags, &block) watch_and_run(monitor, times, true, directory, *flags, &block) end
[ "def", "run_recursively_and_collect_multiple_changes", "(", "monitor", ",", "times", ",", "directory", ",", "*", "flags", ",", "&", "block", ")", "watch_and_run", "(", "monitor", ",", "times", ",", "true", ",", "directory", ",", "*", "flags", ",", "&", "block", ")", "end" ]
Runs the monitor recursively and collects changes for the specified amount of times on the given directory. It stops the monitor afterwards. @yield
[ "Runs", "the", "monitor", "recursively", "and", "collects", "changes", "for", "the", "specified", "amount", "of", "times", "on", "the", "given", "directory", ".", "It", "stops", "the", "monitor", "afterwards", "." ]
41aaa6d7bb228e0721a36681b789295467494fb6
https://github.com/Maher4Ever/wdm/blob/41aaa6d7bb228e0721a36681b789295467494fb6/spec/support/monitor_helper.rb#L41-L43
train
Maher4Ever/wdm
spec/support/monitor_helper.rb
WDM.SpecSupport.run_recursively
def run_recursively(monitor, directory, *flags, &block) result = watch_and_run(monitor, 1, true, directory, *flags, &block) result.changes[0].directory = result.directory result.changes[0] end
ruby
def run_recursively(monitor, directory, *flags, &block) result = watch_and_run(monitor, 1, true, directory, *flags, &block) result.changes[0].directory = result.directory result.changes[0] end
[ "def", "run_recursively", "(", "monitor", ",", "directory", ",", "*", "flags", ",", "&", "block", ")", "result", "=", "watch_and_run", "(", "monitor", ",", "1", ",", "true", ",", "directory", ",", "*", "flags", ",", "&", "block", ")", "result", ".", "changes", "[", "0", "]", ".", "directory", "=", "result", ".", "directory", "result", ".", "changes", "[", "0", "]", "end" ]
Helper method for running the monitor recursively one time. @yield
[ "Helper", "method", "for", "running", "the", "monitor", "recursively", "one", "time", "." ]
41aaa6d7bb228e0721a36681b789295467494fb6
https://github.com/Maher4Ever/wdm/blob/41aaa6d7bb228e0721a36681b789295467494fb6/spec/support/monitor_helper.rb#L49-L53
train
Maher4Ever/wdm
spec/support/monitor_helper.rb
WDM.SpecSupport.run_recursively_with_fixture
def run_recursively_with_fixture(monitor, *flags, &block) fixture do |f| run_recursively(monitor, f, *flags, &block) end end
ruby
def run_recursively_with_fixture(monitor, *flags, &block) fixture do |f| run_recursively(monitor, f, *flags, &block) end end
[ "def", "run_recursively_with_fixture", "(", "monitor", ",", "*", "flags", ",", "&", "block", ")", "fixture", "do", "|", "f", "|", "run_recursively", "(", "monitor", ",", "f", ",", "*", "flags", ",", "&", "block", ")", "end", "end" ]
Helper method for using the run method recursively with the fixture helper. @yield
[ "Helper", "method", "for", "using", "the", "run", "method", "recursively", "with", "the", "fixture", "helper", "." ]
41aaa6d7bb228e0721a36681b789295467494fb6
https://github.com/Maher4Ever/wdm/blob/41aaa6d7bb228e0721a36681b789295467494fb6/spec/support/monitor_helper.rb#L59-L63
train
Maher4Ever/wdm
spec/support/monitor_helper.rb
WDM.SpecSupport.watch_and_run
def watch_and_run(monitor, times, recursively, directory, *flags) result = OpenStruct.new(directory: directory, changes: []) i = 0 result.changes[i] = OpenStruct.new(called: false) can_return = false callback = Proc.new do |change| next if can_return result.changes[i].called = true; result.changes[i].change = change i += 1 if i < times result.changes[i] = OpenStruct.new(called: false) else can_return = true end end if recursively monitor.watch_recursively(directory, *flags, &callback) else monitor.watch(directory, *flags, &callback) end thread = Thread.new(monitor) { |m| m.run! } sleep(0.2) # give time for the monitor to bootup yield # So much boilerplate code to get here :S sleep(0.2) # allow the monitor to run the callbacks # Nothing can change after the callback if there is only one of them, # so never wait for one callback if times > 1 until can_return sleep(0.1) end end return result ensure monitor.stop thread.join if thread end
ruby
def watch_and_run(monitor, times, recursively, directory, *flags) result = OpenStruct.new(directory: directory, changes: []) i = 0 result.changes[i] = OpenStruct.new(called: false) can_return = false callback = Proc.new do |change| next if can_return result.changes[i].called = true; result.changes[i].change = change i += 1 if i < times result.changes[i] = OpenStruct.new(called: false) else can_return = true end end if recursively monitor.watch_recursively(directory, *flags, &callback) else monitor.watch(directory, *flags, &callback) end thread = Thread.new(monitor) { |m| m.run! } sleep(0.2) # give time for the monitor to bootup yield # So much boilerplate code to get here :S sleep(0.2) # allow the monitor to run the callbacks # Nothing can change after the callback if there is only one of them, # so never wait for one callback if times > 1 until can_return sleep(0.1) end end return result ensure monitor.stop thread.join if thread end
[ "def", "watch_and_run", "(", "monitor", ",", "times", ",", "recursively", ",", "directory", ",", "*", "flags", ")", "result", "=", "OpenStruct", ".", "new", "(", "directory", ":", "directory", ",", "changes", ":", "[", "]", ")", "i", "=", "0", "result", ".", "changes", "[", "i", "]", "=", "OpenStruct", ".", "new", "(", "called", ":", "false", ")", "can_return", "=", "false", "callback", "=", "Proc", ".", "new", "do", "|", "change", "|", "next", "if", "can_return", "result", ".", "changes", "[", "i", "]", ".", "called", "=", "true", ";", "result", ".", "changes", "[", "i", "]", ".", "change", "=", "change", "i", "+=", "1", "if", "i", "<", "times", "result", ".", "changes", "[", "i", "]", "=", "OpenStruct", ".", "new", "(", "called", ":", "false", ")", "else", "can_return", "=", "true", "end", "end", "if", "recursively", "monitor", ".", "watch_recursively", "(", "directory", ",", "*", "flags", ",", "&", "callback", ")", "else", "monitor", ".", "watch", "(", "directory", ",", "*", "flags", ",", "&", "callback", ")", "end", "thread", "=", "Thread", ".", "new", "(", "monitor", ")", "{", "|", "m", "|", "m", ".", "run!", "}", "sleep", "(", "0.2", ")", "yield", "sleep", "(", "0.2", ")", "if", "times", ">", "1", "until", "can_return", "sleep", "(", "0.1", ")", "end", "end", "return", "result", "ensure", "monitor", ".", "stop", "thread", ".", "join", "if", "thread", "end" ]
Very customizable method to watch directories and then run the monitor @yield
[ "Very", "customizable", "method", "to", "watch", "directories", "and", "then", "run", "the", "monitor" ]
41aaa6d7bb228e0721a36681b789295467494fb6
https://github.com/Maher4Ever/wdm/blob/41aaa6d7bb228e0721a36681b789295467494fb6/spec/support/monitor_helper.rb#L71-L116
train
Maher4Ever/wdm
spec/support/fixture_helper.rb
WDM.SpecSupport.fixture
def fixture pwd = FileUtils.pwd path = File.expand_path(File.join(pwd, "spec/.fixtures/#{rand(99999)}")) FileUtils.mkdir_p(path) FileUtils.cd(path) yield(path) ensure FileUtils.cd pwd FileUtils.rm_rf(path) if File.exists?(path) end
ruby
def fixture pwd = FileUtils.pwd path = File.expand_path(File.join(pwd, "spec/.fixtures/#{rand(99999)}")) FileUtils.mkdir_p(path) FileUtils.cd(path) yield(path) ensure FileUtils.cd pwd FileUtils.rm_rf(path) if File.exists?(path) end
[ "def", "fixture", "pwd", "=", "FileUtils", ".", "pwd", "path", "=", "File", ".", "expand_path", "(", "File", ".", "join", "(", "pwd", ",", "\"spec/.fixtures/#{rand(99999)}\"", ")", ")", "FileUtils", ".", "mkdir_p", "(", "path", ")", "FileUtils", ".", "cd", "(", "path", ")", "yield", "(", "path", ")", "ensure", "FileUtils", ".", "cd", "pwd", "FileUtils", ".", "rm_rf", "(", "path", ")", "if", "File", ".", "exists?", "(", "path", ")", "end" ]
Prepares the temporary fixture directory and cleans it afterwards. @yield [path] an empty fixture directory @yieldparam [String] path the path to the fixture directory
[ "Prepares", "the", "temporary", "fixture", "directory", "and", "cleans", "it", "afterwards", "." ]
41aaa6d7bb228e0721a36681b789295467494fb6
https://github.com/Maher4Ever/wdm/blob/41aaa6d7bb228e0721a36681b789295467494fb6/spec/support/fixture_helper.rb#L13-L25
train
kyrylo/pry-theme
lib/pry-theme/rgb.rb
PryTheme.RGB.to_term
def to_term(color_model = 256) term = case color_model when 256 then PryTheme::RGB::TABLE.index(@value) when 16 then PryTheme::RGB::SYSTEM.index(@value) when 8 then PryTheme::RGB::LINUX.index(@value) else raise ArgumentError, "invalid value for PryTheme::HEX#to_term(): #{ @value }" end term = find_among_term_colors(term, color_model) if term.nil? PryTheme::TERM.new(term, color_model) end
ruby
def to_term(color_model = 256) term = case color_model when 256 then PryTheme::RGB::TABLE.index(@value) when 16 then PryTheme::RGB::SYSTEM.index(@value) when 8 then PryTheme::RGB::LINUX.index(@value) else raise ArgumentError, "invalid value for PryTheme::HEX#to_term(): #{ @value }" end term = find_among_term_colors(term, color_model) if term.nil? PryTheme::TERM.new(term, color_model) end
[ "def", "to_term", "(", "color_model", "=", "256", ")", "term", "=", "case", "color_model", "when", "256", "then", "PryTheme", "::", "RGB", "::", "TABLE", ".", "index", "(", "@value", ")", "when", "16", "then", "PryTheme", "::", "RGB", "::", "SYSTEM", ".", "index", "(", "@value", ")", "when", "8", "then", "PryTheme", "::", "RGB", "::", "LINUX", ".", "index", "(", "@value", ")", "else", "raise", "ArgumentError", ",", "\"invalid value for PryTheme::HEX#to_term(): #{ @value }\"", "end", "term", "=", "find_among_term_colors", "(", "term", ",", "color_model", ")", "if", "term", ".", "nil?", "PryTheme", "::", "TERM", ".", "new", "(", "term", ",", "color_model", ")", "end" ]
Converts the RGB to a terminal colour equivalent. @note Accepts the following numbers: 256, 16, 8. @param [Integer] color_model @raise [ArgumentError] if +color_model+ parameter is incorrect @return [TERM] a TERM representation of the RGB
[ "Converts", "the", "RGB", "to", "a", "terminal", "colour", "equivalent", "." ]
db99825ff4438b04ce8b808b0303200350fe551b
https://github.com/kyrylo/pry-theme/blob/db99825ff4438b04ce8b808b0303200350fe551b/lib/pry-theme/rgb.rb#L128-L138
train
kyrylo/pry-theme
lib/pry-theme/rgb.rb
PryTheme.RGB.validate_array
def validate_array(ary) correct_size = ary.size.equal?(3) correct_vals = ary.all?{ |val| val.is_a?(Integer) && val.between?(0, 255) } return true if correct_size && correct_vals raise ArgumentError, %|invalid value for PryTheme::RGB#validate_array(): "#{ ary }"| end
ruby
def validate_array(ary) correct_size = ary.size.equal?(3) correct_vals = ary.all?{ |val| val.is_a?(Integer) && val.between?(0, 255) } return true if correct_size && correct_vals raise ArgumentError, %|invalid value for PryTheme::RGB#validate_array(): "#{ ary }"| end
[ "def", "validate_array", "(", "ary", ")", "correct_size", "=", "ary", ".", "size", ".", "equal?", "(", "3", ")", "correct_vals", "=", "ary", ".", "all?", "{", "|", "val", "|", "val", ".", "is_a?", "(", "Integer", ")", "&&", "val", ".", "between?", "(", "0", ",", "255", ")", "}", "return", "true", "if", "correct_size", "&&", "correct_vals", "raise", "ArgumentError", ",", "%|invalid value for PryTheme::RGB#validate_array(): \"#{ ary }\"|", "end" ]
Checks whether the +ary+ has correct number of elements and these elements are valid RGB numbers. @param [Array<Integer>] ary @raise [ArgumentError] if the +ary+ is invalid @return [void]
[ "Checks", "whether", "the", "+", "ary", "+", "has", "correct", "number", "of", "elements", "and", "these", "elements", "are", "valid", "RGB", "numbers", "." ]
db99825ff4438b04ce8b808b0303200350fe551b
https://github.com/kyrylo/pry-theme/blob/db99825ff4438b04ce8b808b0303200350fe551b/lib/pry-theme/rgb.rb#L175-L181
train
kyrylo/pry-theme
lib/pry-theme/rgb.rb
PryTheme.RGB.nearest_term_256
def nearest_term_256(byte) for i in 0..4 lower, upper = BYTEPOINTS_256[i], BYTEPOINTS_256[i + 1] next unless byte.between?(lower, upper) distance_from_lower = (lower - byte).abs distance_from_upper = (upper - byte).abs closest = distance_from_lower < distance_from_upper ? lower : upper end closest end
ruby
def nearest_term_256(byte) for i in 0..4 lower, upper = BYTEPOINTS_256[i], BYTEPOINTS_256[i + 1] next unless byte.between?(lower, upper) distance_from_lower = (lower - byte).abs distance_from_upper = (upper - byte).abs closest = distance_from_lower < distance_from_upper ? lower : upper end closest end
[ "def", "nearest_term_256", "(", "byte", ")", "for", "i", "in", "0", "..", "4", "lower", ",", "upper", "=", "BYTEPOINTS_256", "[", "i", "]", ",", "BYTEPOINTS_256", "[", "i", "+", "1", "]", "next", "unless", "byte", ".", "between?", "(", "lower", ",", "upper", ")", "distance_from_lower", "=", "(", "lower", "-", "byte", ")", ".", "abs", "distance_from_upper", "=", "(", "upper", "-", "byte", ")", ".", "abs", "closest", "=", "distance_from_lower", "<", "distance_from_upper", "?", "lower", ":", "upper", "end", "closest", "end" ]
Approximates the given +byte+ to a terminal colour value within range of 256 colours. @param [Integer] byte a number between 0 and 255 @return [Integer] approximated number
[ "Approximates", "the", "given", "+", "byte", "+", "to", "a", "terminal", "colour", "value", "within", "range", "of", "256", "colours", "." ]
db99825ff4438b04ce8b808b0303200350fe551b
https://github.com/kyrylo/pry-theme/blob/db99825ff4438b04ce8b808b0303200350fe551b/lib/pry-theme/rgb.rb#L188-L198
train
kyrylo/pry-theme
lib/pry-theme/rgb.rb
PryTheme.RGB.find_among_term_colors
def find_among_term_colors(term, color_model) rgb = @value.map { |byte| nearest_term_256(byte) } term = PryTheme::RGB::TABLE.index(rgb) approximate(term, color_model) end
ruby
def find_among_term_colors(term, color_model) rgb = @value.map { |byte| nearest_term_256(byte) } term = PryTheme::RGB::TABLE.index(rgb) approximate(term, color_model) end
[ "def", "find_among_term_colors", "(", "term", ",", "color_model", ")", "rgb", "=", "@value", ".", "map", "{", "|", "byte", "|", "nearest_term_256", "(", "byte", ")", "}", "term", "=", "PryTheme", "::", "RGB", "::", "TABLE", ".", "index", "(", "rgb", ")", "approximate", "(", "term", ",", "color_model", ")", "end" ]
Finds an approximated +term+ colour among the colour numbers within the given +color_model+. @param [Integer] term a colour to be approximated @param [Integer] color_model possible values {#to_term} @return [Integer] approximated number, which fits in range of color_model
[ "Finds", "an", "approximated", "+", "term", "+", "colour", "among", "the", "colour", "numbers", "within", "the", "given", "+", "color_model", "+", "." ]
db99825ff4438b04ce8b808b0303200350fe551b
https://github.com/kyrylo/pry-theme/blob/db99825ff4438b04ce8b808b0303200350fe551b/lib/pry-theme/rgb.rb#L222-L226
train
kyrylo/pry-theme
lib/pry-theme/rgb.rb
PryTheme.RGB.approximate
def approximate(term, color_model) needs_approximation = (term > color_model - 1) if needs_approximation case color_model when 16 then nearest_term_16(term) when 8 then nearest_term_8(term) end else term end end
ruby
def approximate(term, color_model) needs_approximation = (term > color_model - 1) if needs_approximation case color_model when 16 then nearest_term_16(term) when 8 then nearest_term_8(term) end else term end end
[ "def", "approximate", "(", "term", ",", "color_model", ")", "needs_approximation", "=", "(", "term", ">", "color_model", "-", "1", ")", "if", "needs_approximation", "case", "color_model", "when", "16", "then", "nearest_term_16", "(", "term", ")", "when", "8", "then", "nearest_term_8", "(", "term", ")", "end", "else", "term", "end", "end" ]
Approximates +term+ in correspondence with +color_model+ @see #nearest_term_16 @see #nearest_term_8 @param [Integer] term a colour to be approximated @param [Integer] color_model possible values {#to_term} @return [Integer] approximated number, which fits in range of color_model
[ "Approximates", "+", "term", "+", "in", "correspondence", "with", "+", "color_model", "+" ]
db99825ff4438b04ce8b808b0303200350fe551b
https://github.com/kyrylo/pry-theme/blob/db99825ff4438b04ce8b808b0303200350fe551b/lib/pry-theme/rgb.rb#L235-L246
train
archiloque/sinatra-swagger-exposer
lib/sinatra/swagger-exposer/swagger-exposer.rb
Sinatra.SwaggerExposer.endpoint_parameter
def endpoint_parameter(name, description, how_to_pass, required, type, params = {}) parameters = settings.swagger_current_endpoint_parameters check_if_not_duplicate(name, parameters, 'Parameter') parameters[name] = Sinatra::SwaggerExposer::Configuration::SwaggerEndpointParameter.new( name, description, how_to_pass, required, type, params, settings.swagger_types.types_names) end
ruby
def endpoint_parameter(name, description, how_to_pass, required, type, params = {}) parameters = settings.swagger_current_endpoint_parameters check_if_not_duplicate(name, parameters, 'Parameter') parameters[name] = Sinatra::SwaggerExposer::Configuration::SwaggerEndpointParameter.new( name, description, how_to_pass, required, type, params, settings.swagger_types.types_names) end
[ "def", "endpoint_parameter", "(", "name", ",", "description", ",", "how_to_pass", ",", "required", ",", "type", ",", "params", "=", "{", "}", ")", "parameters", "=", "settings", ".", "swagger_current_endpoint_parameters", "check_if_not_duplicate", "(", "name", ",", "parameters", ",", "'Parameter'", ")", "parameters", "[", "name", "]", "=", "Sinatra", "::", "SwaggerExposer", "::", "Configuration", "::", "SwaggerEndpointParameter", ".", "new", "(", "name", ",", "description", ",", "how_to_pass", ",", "required", ",", "type", ",", "params", ",", "settings", ".", "swagger_types", ".", "types_names", ")", "end" ]
Define parameter for the endpoint
[ "Define", "parameter", "for", "the", "endpoint" ]
375fcb432e901815562d94b64208753faaed7cdb
https://github.com/archiloque/sinatra-swagger-exposer/blob/375fcb432e901815562d94b64208753faaed7cdb/lib/sinatra/swagger-exposer/swagger-exposer.rb#L95-L106
train
archiloque/sinatra-swagger-exposer
lib/sinatra/swagger-exposer/swagger-exposer.rb
Sinatra.SwaggerExposer.endpoint
def endpoint(params) params.each_pair do |param_name, param_value| case param_name when :summary endpoint_summary param_value when :description endpoint_description param_value when :tags endpoint_tags *param_value when :produces endpoint_produces *param_value when :path endpoint_path param_value when :parameters param_value.each do |param, args_param| endpoint_parameter param, *args_param end when :responses param_value.each do |code, args_response| endpoint_response code, *args_response end else raise SwaggerInvalidException.new("Invalid endpoint parameter [#{param_name}]") end end end
ruby
def endpoint(params) params.each_pair do |param_name, param_value| case param_name when :summary endpoint_summary param_value when :description endpoint_description param_value when :tags endpoint_tags *param_value when :produces endpoint_produces *param_value when :path endpoint_path param_value when :parameters param_value.each do |param, args_param| endpoint_parameter param, *args_param end when :responses param_value.each do |code, args_response| endpoint_response code, *args_response end else raise SwaggerInvalidException.new("Invalid endpoint parameter [#{param_name}]") end end end
[ "def", "endpoint", "(", "params", ")", "params", ".", "each_pair", "do", "|", "param_name", ",", "param_value", "|", "case", "param_name", "when", ":summary", "endpoint_summary", "param_value", "when", ":description", "endpoint_description", "param_value", "when", ":tags", "endpoint_tags", "*", "param_value", "when", ":produces", "endpoint_produces", "*", "param_value", "when", ":path", "endpoint_path", "param_value", "when", ":parameters", "param_value", ".", "each", "do", "|", "param", ",", "args_param", "|", "endpoint_parameter", "param", ",", "*", "args_param", "end", "when", ":responses", "param_value", ".", "each", "do", "|", "code", ",", "args_response", "|", "endpoint_response", "code", ",", "*", "args_response", "end", "else", "raise", "SwaggerInvalidException", ".", "new", "(", "\"Invalid endpoint parameter [#{param_name}]\"", ")", "end", "end", "end" ]
Define fluent endpoint dispatcher @param params [Hash] the parameters
[ "Define", "fluent", "endpoint", "dispatcher" ]
375fcb432e901815562d94b64208753faaed7cdb
https://github.com/archiloque/sinatra-swagger-exposer/blob/375fcb432e901815562d94b64208753faaed7cdb/lib/sinatra/swagger-exposer/swagger-exposer.rb#L110-L135
train
archiloque/sinatra-swagger-exposer
lib/sinatra/swagger-exposer/swagger-exposer.rb
Sinatra.SwaggerExposer.response_header
def response_header(name, type, description) settings.swagger_response_headers.add_response_header(name, type, description) end
ruby
def response_header(name, type, description) settings.swagger_response_headers.add_response_header(name, type, description) end
[ "def", "response_header", "(", "name", ",", "type", ",", "description", ")", "settings", ".", "swagger_response_headers", ".", "add_response_header", "(", "name", ",", "type", ",", "description", ")", "end" ]
Declare a response header
[ "Declare", "a", "response", "header" ]
375fcb432e901815562d94b64208753faaed7cdb
https://github.com/archiloque/sinatra-swagger-exposer/blob/375fcb432e901815562d94b64208753faaed7cdb/lib/sinatra/swagger-exposer/swagger-exposer.rb#L148-L150
train
archiloque/sinatra-swagger-exposer
lib/sinatra/swagger-exposer/swagger-exposer.rb
Sinatra.SwaggerExposer.endpoint_response
def endpoint_response(code, type = nil, description = nil, headers = []) responses = settings.swagger_current_endpoint_responses check_if_not_duplicate(code, responses, 'Response') responses[code] = Sinatra::SwaggerExposer::Configuration::SwaggerEndpointResponse.new( type, description, settings.swagger_types.types_names, headers, settings.swagger_response_headers ) end
ruby
def endpoint_response(code, type = nil, description = nil, headers = []) responses = settings.swagger_current_endpoint_responses check_if_not_duplicate(code, responses, 'Response') responses[code] = Sinatra::SwaggerExposer::Configuration::SwaggerEndpointResponse.new( type, description, settings.swagger_types.types_names, headers, settings.swagger_response_headers ) end
[ "def", "endpoint_response", "(", "code", ",", "type", "=", "nil", ",", "description", "=", "nil", ",", "headers", "=", "[", "]", ")", "responses", "=", "settings", ".", "swagger_current_endpoint_responses", "check_if_not_duplicate", "(", "code", ",", "responses", ",", "'Response'", ")", "responses", "[", "code", "]", "=", "Sinatra", "::", "SwaggerExposer", "::", "Configuration", "::", "SwaggerEndpointResponse", ".", "new", "(", "type", ",", "description", ",", "settings", ".", "swagger_types", ".", "types_names", ",", "headers", ",", "settings", ".", "swagger_response_headers", ")", "end" ]
Declare a response @param code [Integer] the response code @param type the type @param description [String] the description @param headers [Array<String>] the headers names
[ "Declare", "a", "response" ]
375fcb432e901815562d94b64208753faaed7cdb
https://github.com/archiloque/sinatra-swagger-exposer/blob/375fcb432e901815562d94b64208753faaed7cdb/lib/sinatra/swagger-exposer/swagger-exposer.rb#L157-L167
train
archiloque/sinatra-swagger-exposer
lib/sinatra/swagger-exposer/swagger-exposer.rb
Sinatra.SwaggerExposer.route
def route(verb, path, options = {}, &block) no_swagger = options[:no_swagger] options.delete(:no_swagger) if (verb == 'HEAD') || no_swagger super(verb, path, options, &block) else request_processor = create_request_processor(verb.downcase, path, options) super(verb, path, options) do |*params| response = catch(:halt) do request_processor.run(self, params, &block) end if settings.result_validation begin # Inspired from Sinatra#invoke if (Fixnum === response) or (String === response) response = [response] end if (Array === response) and (Fixnum === response.first) response_for_validation = response.dup response_status = response_for_validation.shift response_body = response_for_validation.pop response_headers = (response_for_validation.pop || {}).merge(self.response.header) response_content_type = response_headers['Content-Type'] request_processor.validate_response(response_body, response_content_type, response_status) elsif response.respond_to? :each request_processor.validate_response(response.first.dup, self.response.header['Content-Type'], 200) end rescue Sinatra::SwaggerExposer::SwaggerInvalidException => e content_type :json throw :halt, [400, {:code => 400, :message => e.message}.to_json] end end throw :halt, response end end end
ruby
def route(verb, path, options = {}, &block) no_swagger = options[:no_swagger] options.delete(:no_swagger) if (verb == 'HEAD') || no_swagger super(verb, path, options, &block) else request_processor = create_request_processor(verb.downcase, path, options) super(verb, path, options) do |*params| response = catch(:halt) do request_processor.run(self, params, &block) end if settings.result_validation begin # Inspired from Sinatra#invoke if (Fixnum === response) or (String === response) response = [response] end if (Array === response) and (Fixnum === response.first) response_for_validation = response.dup response_status = response_for_validation.shift response_body = response_for_validation.pop response_headers = (response_for_validation.pop || {}).merge(self.response.header) response_content_type = response_headers['Content-Type'] request_processor.validate_response(response_body, response_content_type, response_status) elsif response.respond_to? :each request_processor.validate_response(response.first.dup, self.response.header['Content-Type'], 200) end rescue Sinatra::SwaggerExposer::SwaggerInvalidException => e content_type :json throw :halt, [400, {:code => 400, :message => e.message}.to_json] end end throw :halt, response end end end
[ "def", "route", "(", "verb", ",", "path", ",", "options", "=", "{", "}", ",", "&", "block", ")", "no_swagger", "=", "options", "[", ":no_swagger", "]", "options", ".", "delete", "(", ":no_swagger", ")", "if", "(", "verb", "==", "'HEAD'", ")", "||", "no_swagger", "super", "(", "verb", ",", "path", ",", "options", ",", "&", "block", ")", "else", "request_processor", "=", "create_request_processor", "(", "verb", ".", "downcase", ",", "path", ",", "options", ")", "super", "(", "verb", ",", "path", ",", "options", ")", "do", "|", "*", "params", "|", "response", "=", "catch", "(", ":halt", ")", "do", "request_processor", ".", "run", "(", "self", ",", "params", ",", "&", "block", ")", "end", "if", "settings", ".", "result_validation", "begin", "if", "(", "Fixnum", "===", "response", ")", "or", "(", "String", "===", "response", ")", "response", "=", "[", "response", "]", "end", "if", "(", "Array", "===", "response", ")", "and", "(", "Fixnum", "===", "response", ".", "first", ")", "response_for_validation", "=", "response", ".", "dup", "response_status", "=", "response_for_validation", ".", "shift", "response_body", "=", "response_for_validation", ".", "pop", "response_headers", "=", "(", "response_for_validation", ".", "pop", "||", "{", "}", ")", ".", "merge", "(", "self", ".", "response", ".", "header", ")", "response_content_type", "=", "response_headers", "[", "'Content-Type'", "]", "request_processor", ".", "validate_response", "(", "response_body", ",", "response_content_type", ",", "response_status", ")", "elsif", "response", ".", "respond_to?", ":each", "request_processor", ".", "validate_response", "(", "response", ".", "first", ".", "dup", ",", "self", ".", "response", ".", "header", "[", "'Content-Type'", "]", ",", "200", ")", "end", "rescue", "Sinatra", "::", "SwaggerExposer", "::", "SwaggerInvalidException", "=>", "e", "content_type", ":json", "throw", ":halt", ",", "[", "400", ",", "{", ":code", "=>", "400", ",", ":message", "=>", "e", ".", "message", "}", ".", "to_json", "]", "end", "end", "throw", ":halt", ",", "response", "end", "end", "end" ]
Override Sinatra route method
[ "Override", "Sinatra", "route", "method" ]
375fcb432e901815562d94b64208753faaed7cdb
https://github.com/archiloque/sinatra-swagger-exposer/blob/375fcb432e901815562d94b64208753faaed7cdb/lib/sinatra/swagger-exposer/swagger-exposer.rb#L170-L205
train
archiloque/sinatra-swagger-exposer
lib/sinatra/swagger-exposer/swagger-exposer.rb
Sinatra.SwaggerExposer.create_request_processor
def create_request_processor(type, path, opts) current_endpoint_info = settings.swagger_current_endpoint_info current_endpoint_parameters = settings.swagger_current_endpoint_parameters current_endpoint_responses = settings.swagger_current_endpoint_responses endpoint = Sinatra::SwaggerExposer::Configuration::SwaggerEndpoint.new( type, path, current_endpoint_parameters.values, current_endpoint_responses.clone, current_endpoint_info[:summary], current_endpoint_info[:description], current_endpoint_info[:tags], current_endpoint_info[:path], current_endpoint_info[:produces]) settings.swagger_endpoints << endpoint current_endpoint_info.clear current_endpoint_parameters.clear current_endpoint_responses.clear settings.swagger_processor_creator.create_request_processor(endpoint) end
ruby
def create_request_processor(type, path, opts) current_endpoint_info = settings.swagger_current_endpoint_info current_endpoint_parameters = settings.swagger_current_endpoint_parameters current_endpoint_responses = settings.swagger_current_endpoint_responses endpoint = Sinatra::SwaggerExposer::Configuration::SwaggerEndpoint.new( type, path, current_endpoint_parameters.values, current_endpoint_responses.clone, current_endpoint_info[:summary], current_endpoint_info[:description], current_endpoint_info[:tags], current_endpoint_info[:path], current_endpoint_info[:produces]) settings.swagger_endpoints << endpoint current_endpoint_info.clear current_endpoint_parameters.clear current_endpoint_responses.clear settings.swagger_processor_creator.create_request_processor(endpoint) end
[ "def", "create_request_processor", "(", "type", ",", "path", ",", "opts", ")", "current_endpoint_info", "=", "settings", ".", "swagger_current_endpoint_info", "current_endpoint_parameters", "=", "settings", ".", "swagger_current_endpoint_parameters", "current_endpoint_responses", "=", "settings", ".", "swagger_current_endpoint_responses", "endpoint", "=", "Sinatra", "::", "SwaggerExposer", "::", "Configuration", "::", "SwaggerEndpoint", ".", "new", "(", "type", ",", "path", ",", "current_endpoint_parameters", ".", "values", ",", "current_endpoint_responses", ".", "clone", ",", "current_endpoint_info", "[", ":summary", "]", ",", "current_endpoint_info", "[", ":description", "]", ",", "current_endpoint_info", "[", ":tags", "]", ",", "current_endpoint_info", "[", ":path", "]", ",", "current_endpoint_info", "[", ":produces", "]", ")", "settings", ".", "swagger_endpoints", "<<", "endpoint", "current_endpoint_info", ".", "clear", "current_endpoint_parameters", ".", "clear", "current_endpoint_responses", ".", "clear", "settings", ".", "swagger_processor_creator", ".", "create_request_processor", "(", "endpoint", ")", "end" ]
Call for each endpoint declaration @return [Sinatra::SwaggerExposer::Processing::SwaggerRequestProcessor]
[ "Call", "for", "each", "endpoint", "declaration" ]
375fcb432e901815562d94b64208753faaed7cdb
https://github.com/archiloque/sinatra-swagger-exposer/blob/375fcb432e901815562d94b64208753faaed7cdb/lib/sinatra/swagger-exposer/swagger-exposer.rb#L211-L230
train
archiloque/sinatra-swagger-exposer
lib/sinatra/swagger-exposer/swagger-exposer.rb
Sinatra.SwaggerExposer.check_if_not_duplicate
def check_if_not_duplicate(key, values, name) if values.key? key raise SwaggerInvalidException.new("#{name} already exist for #{key} with value [#{values[key]}]") end end
ruby
def check_if_not_duplicate(key, values, name) if values.key? key raise SwaggerInvalidException.new("#{name} already exist for #{key} with value [#{values[key]}]") end end
[ "def", "check_if_not_duplicate", "(", "key", ",", "values", ",", "name", ")", "if", "values", ".", "key?", "key", "raise", "SwaggerInvalidException", ".", "new", "(", "\"#{name} already exist for #{key} with value [#{values[key]}]\"", ")", "end", "end" ]
Check if a value does not exist in a hash and throw an Exception @param key the key to validate @param values [Hash] the existing keys @param name [String] the valud name for the error message
[ "Check", "if", "a", "value", "does", "not", "exist", "in", "a", "hash", "and", "throw", "an", "Exception" ]
375fcb432e901815562d94b64208753faaed7cdb
https://github.com/archiloque/sinatra-swagger-exposer/blob/375fcb432e901815562d94b64208753faaed7cdb/lib/sinatra/swagger-exposer/swagger-exposer.rb#L250-L254
train