id
int32
0
24.9k
repo
stringlengths
5
58
path
stringlengths
9
168
func_name
stringlengths
9
130
original_string
stringlengths
66
10.5k
language
stringclasses
1 value
code
stringlengths
66
10.5k
code_tokens
sequence
docstring
stringlengths
8
16k
docstring_tokens
sequence
sha
stringlengths
40
40
url
stringlengths
94
266
22,700
kevindew/openapi3_parser
lib/openapi3_parser/document.rb
Openapi3Parser.Document.errors
def errors reference_factories.inject(factory.errors) do |memo, f| Validation::ErrorCollection.combine(memo, f.errors) end end
ruby
def errors reference_factories.inject(factory.errors) do |memo, f| Validation::ErrorCollection.combine(memo, f.errors) end end
[ "def", "errors", "reference_factories", ".", "inject", "(", "factory", ".", "errors", ")", "do", "|", "memo", ",", "f", "|", "Validation", "::", "ErrorCollection", ".", "combine", "(", "memo", ",", "f", ".", "errors", ")", "end", "end" ]
Any validation errors that are present on the OpenAPI document @return [Validation::ErrorCollection]
[ "Any", "validation", "errors", "that", "are", "present", "on", "the", "OpenAPI", "document" ]
70c599f03bb6c26726bed200907cabf5ceec225d
https://github.com/kevindew/openapi3_parser/blob/70c599f03bb6c26726bed200907cabf5ceec225d/lib/openapi3_parser/document.rb#L115-L119
22,701
kevindew/openapi3_parser
lib/openapi3_parser/source.rb
Openapi3Parser.Source.register_reference
def register_reference(given_reference, factory, context) reference = Reference.new(given_reference) ReferenceResolver.new( reference, factory, context ).tap do |resolver| next if resolver.in_root_source? reference_register.register(resolver.reference_factory) end end
ruby
def register_reference(given_reference, factory, context) reference = Reference.new(given_reference) ReferenceResolver.new( reference, factory, context ).tap do |resolver| next if resolver.in_root_source? reference_register.register(resolver.reference_factory) end end
[ "def", "register_reference", "(", "given_reference", ",", "factory", ",", "context", ")", "reference", "=", "Reference", ".", "new", "(", "given_reference", ")", "ReferenceResolver", ".", "new", "(", "reference", ",", "factory", ",", "context", ")", ".", "tap", "do", "|", "resolver", "|", "next", "if", "resolver", ".", "in_root_source?", "reference_register", ".", "register", "(", "resolver", ".", "reference_factory", ")", "end", "end" ]
Used to register a reference with the underlying document and return a reference resolver to access the object referenced @param [String] given_reference The reference as text @param [NodeFactory] factory Factory class for the expected eventual resource @param [Context] context The context of the object calling this reference @return [ReferenceResolver]
[ "Used", "to", "register", "a", "reference", "with", "the", "underlying", "document", "and", "return", "a", "reference", "resolver", "to", "access", "the", "object", "referenced" ]
70c599f03bb6c26726bed200907cabf5ceec225d
https://github.com/kevindew/openapi3_parser/blob/70c599f03bb6c26726bed200907cabf5ceec225d/lib/openapi3_parser/source.rb#L55-L63
22,702
kevindew/openapi3_parser
lib/openapi3_parser/source.rb
Openapi3Parser.Source.data_at_pointer
def data_at_pointer(json_pointer) return data if json_pointer.empty? data.dig(*json_pointer) if data.respond_to?(:dig) end
ruby
def data_at_pointer(json_pointer) return data if json_pointer.empty? data.dig(*json_pointer) if data.respond_to?(:dig) end
[ "def", "data_at_pointer", "(", "json_pointer", ")", "return", "data", "if", "json_pointer", ".", "empty?", "data", ".", "dig", "(", "json_pointer", ")", "if", "data", ".", "respond_to?", "(", ":dig", ")", "end" ]
Access the data in a source at a particular pointer @param [Array] json_pointer An array of segments of a JSON pointer @return [Object]
[ "Access", "the", "data", "in", "a", "source", "at", "a", "particular", "pointer" ]
70c599f03bb6c26726bed200907cabf5ceec225d
https://github.com/kevindew/openapi3_parser/blob/70c599f03bb6c26726bed200907cabf5ceec225d/lib/openapi3_parser/source.rb#L91-L94
22,703
greyblake/blogo
lib/blogo/paginator.rb
Blogo.Paginator.pages
def pages @pages ||= begin from = @page - (@size / 2).ceil from = 1 if from < 1 upto = from + @size - 1 # Correct +from+ and +to+ if +to+ is more than number of pages if upto > pages_count from -= (upto - pages_count) from = 1 if from < 1 upto = pages_count end (from..upto).to_a end end
ruby
def pages @pages ||= begin from = @page - (@size / 2).ceil from = 1 if from < 1 upto = from + @size - 1 # Correct +from+ and +to+ if +to+ is more than number of pages if upto > pages_count from -= (upto - pages_count) from = 1 if from < 1 upto = pages_count end (from..upto).to_a end end
[ "def", "pages", "@pages", "||=", "begin", "from", "=", "@page", "-", "(", "@size", "/", "2", ")", ".", "ceil", "from", "=", "1", "if", "from", "<", "1", "upto", "=", "from", "+", "@size", "-", "1", "# Correct +from+ and +to+ if +to+ is more than number of pages", "if", "upto", ">", "pages_count", "from", "-=", "(", "upto", "-", "pages_count", ")", "from", "=", "1", "if", "from", "<", "1", "upto", "=", "pages_count", "end", "(", "from", "..", "upto", ")", ".", "to_a", "end", "end" ]
Number of pages to display. @return [Array<Integer>]
[ "Number", "of", "pages", "to", "display", "." ]
eee0a8854cfdc309763197e3ef9b295008be85f6
https://github.com/greyblake/blogo/blob/eee0a8854cfdc309763197e3ef9b295008be85f6/lib/blogo/paginator.rb#L57-L72
22,704
danger/danger-mention
lib/danger_plugin.rb
Danger.DangerMention.run
def run(max_reviewers = 3, file_blacklist = [], user_blacklist = []) files = select_files(file_blacklist) return if files.empty? authors = {} compose_urls(files).each do |url| result = parse_blame(url) authors.merge!(result) { |_, m, n| m + n } end reviewers = find_reviewers(authors, user_blacklist, max_reviewers) if reviewers.count > 0 reviewers = reviewers.map { |r| '@' + r } result = format('By analyzing the blame information on this pull '\ 'request, we identified %s to be potential reviewer%s.', reviewers.join(', '), reviewers.count > 1 ? 's' : '') markdown result end end
ruby
def run(max_reviewers = 3, file_blacklist = [], user_blacklist = []) files = select_files(file_blacklist) return if files.empty? authors = {} compose_urls(files).each do |url| result = parse_blame(url) authors.merge!(result) { |_, m, n| m + n } end reviewers = find_reviewers(authors, user_blacklist, max_reviewers) if reviewers.count > 0 reviewers = reviewers.map { |r| '@' + r } result = format('By analyzing the blame information on this pull '\ 'request, we identified %s to be potential reviewer%s.', reviewers.join(', '), reviewers.count > 1 ? 's' : '') markdown result end end
[ "def", "run", "(", "max_reviewers", "=", "3", ",", "file_blacklist", "=", "[", "]", ",", "user_blacklist", "=", "[", "]", ")", "files", "=", "select_files", "(", "file_blacklist", ")", "return", "if", "files", ".", "empty?", "authors", "=", "{", "}", "compose_urls", "(", "files", ")", ".", "each", "do", "|", "url", "|", "result", "=", "parse_blame", "(", "url", ")", "authors", ".", "merge!", "(", "result", ")", "{", "|", "_", ",", "m", ",", "n", "|", "m", "+", "n", "}", "end", "reviewers", "=", "find_reviewers", "(", "authors", ",", "user_blacklist", ",", "max_reviewers", ")", "if", "reviewers", ".", "count", ">", "0", "reviewers", "=", "reviewers", ".", "map", "{", "|", "r", "|", "'@'", "+", "r", "}", "result", "=", "format", "(", "'By analyzing the blame information on this pull '", "'request, we identified %s to be potential reviewer%s.'", ",", "reviewers", ".", "join", "(", "', '", ")", ",", "reviewers", ".", "count", ">", "1", "?", "'s'", ":", "''", ")", "markdown", "result", "end", "end" ]
Mention potential reviewers. @param [Integer] max_reviewers Maximum number of people to ping in the PR message, default is 3. @param [Array<String>] file_blacklist Regexes of ignored files. @param [Array<String>] user_blacklist List of users that will never be mentioned. @return [void]
[ "Mention", "potential", "reviewers", "." ]
3b2d07363409b28c2ca707cfde89abccd3ea839a
https://github.com/danger/danger-mention/blob/3b2d07363409b28c2ca707cfde89abccd3ea839a/lib/danger_plugin.rb#L40-L61
22,705
spectator/linked-list
lib/linked-list/list.rb
LinkedList.List.push
def push(node) node = Node(node) @head ||= node if @tail @tail.next = node node.prev = @tail end @tail = node @length += 1 self end
ruby
def push(node) node = Node(node) @head ||= node if @tail @tail.next = node node.prev = @tail end @tail = node @length += 1 self end
[ "def", "push", "(", "node", ")", "node", "=", "Node", "(", "node", ")", "@head", "||=", "node", "if", "@tail", "@tail", ".", "next", "=", "node", "node", ".", "prev", "=", "@tail", "end", "@tail", "=", "node", "@length", "+=", "1", "self", "end" ]
Pushes new nodes to the end of the list. == Parameters: node:: Any object, including +Node+ objects. == Returns: +self+ of +List+ object.
[ "Pushes", "new", "nodes", "to", "the", "end", "of", "the", "list", "." ]
f4e0d62fbc129282374f91d4fbcc699f7c330bd4
https://github.com/spectator/linked-list/blob/f4e0d62fbc129282374f91d4fbcc699f7c330bd4/lib/linked-list/list.rb#L36-L49
22,706
spectator/linked-list
lib/linked-list/list.rb
LinkedList.List.unshift
def unshift(node) node = Node(node) @tail ||= node node.next = @head @head.prev = node if @head @head = node @length += 1 self end
ruby
def unshift(node) node = Node(node) @tail ||= node node.next = @head @head.prev = node if @head @head = node @length += 1 self end
[ "def", "unshift", "(", "node", ")", "node", "=", "Node", "(", "node", ")", "@tail", "||=", "node", "node", ".", "next", "=", "@head", "@head", ".", "prev", "=", "node", "if", "@head", "@head", "=", "node", "@length", "+=", "1", "self", "end" ]
Pushes new nodes on top of the list. == Parameters: node:: Any object, including +Node+ objects. == Returns: +self+ of +List+ object.
[ "Pushes", "new", "nodes", "on", "top", "of", "the", "list", "." ]
f4e0d62fbc129282374f91d4fbcc699f7c330bd4
https://github.com/spectator/linked-list/blob/f4e0d62fbc129282374f91d4fbcc699f7c330bd4/lib/linked-list/list.rb#L60-L70
22,707
spectator/linked-list
lib/linked-list/list.rb
LinkedList.List.insert
def insert(to_add, after: nil, before: nil) if after && before || !after && !before raise ArgumentError, 'either :after or :before keys should be passed' end matcher = after || before matcher_proc = if matcher.is_a?(Proc) __to_matcher(&matcher) else __to_matcher(matcher) end node = each_node.find(&matcher_proc) return unless node new_node = after ? insert_after_node(to_add, node) : insert_before_node(to_add, node) new_node.data end
ruby
def insert(to_add, after: nil, before: nil) if after && before || !after && !before raise ArgumentError, 'either :after or :before keys should be passed' end matcher = after || before matcher_proc = if matcher.is_a?(Proc) __to_matcher(&matcher) else __to_matcher(matcher) end node = each_node.find(&matcher_proc) return unless node new_node = after ? insert_after_node(to_add, node) : insert_before_node(to_add, node) new_node.data end
[ "def", "insert", "(", "to_add", ",", "after", ":", "nil", ",", "before", ":", "nil", ")", "if", "after", "&&", "before", "||", "!", "after", "&&", "!", "before", "raise", "ArgumentError", ",", "'either :after or :before keys should be passed'", "end", "matcher", "=", "after", "||", "before", "matcher_proc", "=", "if", "matcher", ".", "is_a?", "(", "Proc", ")", "__to_matcher", "(", "matcher", ")", "else", "__to_matcher", "(", "matcher", ")", "end", "node", "=", "each_node", ".", "find", "(", "matcher_proc", ")", "return", "unless", "node", "new_node", "=", "after", "?", "insert_after_node", "(", "to_add", ",", "node", ")", ":", "insert_before_node", "(", "to_add", ",", "node", ")", "new_node", ".", "data", "end" ]
Inserts after or before first matched node.data from the the list by passed block or value. == Returns: Inserted node data
[ "Inserts", "after", "or", "before", "first", "matched", "node", ".", "data", "from", "the", "the", "list", "by", "passed", "block", "or", "value", "." ]
f4e0d62fbc129282374f91d4fbcc699f7c330bd4
https://github.com/spectator/linked-list/blob/f4e0d62fbc129282374f91d4fbcc699f7c330bd4/lib/linked-list/list.rb#L77-L91
22,708
spectator/linked-list
lib/linked-list/list.rb
LinkedList.List.insert_after_node
def insert_after_node(data, node) Node(data).tap do |new_node| new_node.prev = node new_node.next = node.next if node.next node.next.prev = new_node else @tail = new_node end node.next = new_node @length += 1 end end
ruby
def insert_after_node(data, node) Node(data).tap do |new_node| new_node.prev = node new_node.next = node.next if node.next node.next.prev = new_node else @tail = new_node end node.next = new_node @length += 1 end end
[ "def", "insert_after_node", "(", "data", ",", "node", ")", "Node", "(", "data", ")", ".", "tap", "do", "|", "new_node", "|", "new_node", ".", "prev", "=", "node", "new_node", ".", "next", "=", "node", ".", "next", "if", "node", ".", "next", "node", ".", "next", ".", "prev", "=", "new_node", "else", "@tail", "=", "new_node", "end", "node", ".", "next", "=", "new_node", "@length", "+=", "1", "end", "end" ]
Inserts data after first matched node.data. == Returns: Inserted node
[ "Inserts", "data", "after", "first", "matched", "node", ".", "data", "." ]
f4e0d62fbc129282374f91d4fbcc699f7c330bd4
https://github.com/spectator/linked-list/blob/f4e0d62fbc129282374f91d4fbcc699f7c330bd4/lib/linked-list/list.rb#L98-L110
22,709
spectator/linked-list
lib/linked-list/list.rb
LinkedList.List.insert_before_node
def insert_before_node(data, node) Node(data).tap do |new_node| new_node.next = node new_node.prev = node.prev if node.prev node.prev.next = new_node else @head = new_node end node.prev = new_node @length += 1 end end
ruby
def insert_before_node(data, node) Node(data).tap do |new_node| new_node.next = node new_node.prev = node.prev if node.prev node.prev.next = new_node else @head = new_node end node.prev = new_node @length += 1 end end
[ "def", "insert_before_node", "(", "data", ",", "node", ")", "Node", "(", "data", ")", ".", "tap", "do", "|", "new_node", "|", "new_node", ".", "next", "=", "node", "new_node", ".", "prev", "=", "node", ".", "prev", "if", "node", ".", "prev", "node", ".", "prev", ".", "next", "=", "new_node", "else", "@head", "=", "new_node", "end", "node", ".", "prev", "=", "new_node", "@length", "+=", "1", "end", "end" ]
Inserts data before first matched node.data. == Returns: Inserted node
[ "Inserts", "data", "before", "first", "matched", "node", ".", "data", "." ]
f4e0d62fbc129282374f91d4fbcc699f7c330bd4
https://github.com/spectator/linked-list/blob/f4e0d62fbc129282374f91d4fbcc699f7c330bd4/lib/linked-list/list.rb#L117-L129
22,710
spectator/linked-list
lib/linked-list/list.rb
LinkedList.List.delete
def delete(val = nil, &block) if val.respond_to?(:to_node) node = val.to_node __unlink_node(node) return node.data end each_node.find(&__to_matcher(val, &block)).tap do |node_to_delete| return unless node_to_delete __unlink_node(node_to_delete) end.data end
ruby
def delete(val = nil, &block) if val.respond_to?(:to_node) node = val.to_node __unlink_node(node) return node.data end each_node.find(&__to_matcher(val, &block)).tap do |node_to_delete| return unless node_to_delete __unlink_node(node_to_delete) end.data end
[ "def", "delete", "(", "val", "=", "nil", ",", "&", "block", ")", "if", "val", ".", "respond_to?", "(", ":to_node", ")", "node", "=", "val", ".", "to_node", "__unlink_node", "(", "node", ")", "return", "node", ".", "data", "end", "each_node", ".", "find", "(", "__to_matcher", "(", "val", ",", "block", ")", ")", ".", "tap", "do", "|", "node_to_delete", "|", "return", "unless", "node_to_delete", "__unlink_node", "(", "node_to_delete", ")", "end", ".", "data", "end" ]
Removes first matched node.data from the the list by passed block or value. If +val+ is a +Node+, removes that node from the list. Behavior is undefined if +val+ is a +Node+ that's not a member of this list. == Returns: Deleted node's data
[ "Removes", "first", "matched", "node", ".", "data", "from", "the", "the", "list", "by", "passed", "block", "or", "value", "." ]
f4e0d62fbc129282374f91d4fbcc699f7c330bd4
https://github.com/spectator/linked-list/blob/f4e0d62fbc129282374f91d4fbcc699f7c330bd4/lib/linked-list/list.rb#L139-L150
22,711
spectator/linked-list
lib/linked-list/list.rb
LinkedList.List.delete_all
def delete_all(val = nil, &block) each_node.select(&__to_matcher(val, &block)).each do |node_to_delete| next unless node_to_delete __unlink_node(node_to_delete) end.map(&:data) end
ruby
def delete_all(val = nil, &block) each_node.select(&__to_matcher(val, &block)).each do |node_to_delete| next unless node_to_delete __unlink_node(node_to_delete) end.map(&:data) end
[ "def", "delete_all", "(", "val", "=", "nil", ",", "&", "block", ")", "each_node", ".", "select", "(", "__to_matcher", "(", "val", ",", "block", ")", ")", ".", "each", "do", "|", "node_to_delete", "|", "next", "unless", "node_to_delete", "__unlink_node", "(", "node_to_delete", ")", "end", ".", "map", "(", ":data", ")", "end" ]
Removes all matched data.data from the the list by passed block or value. == Returns: Array of deleted nodes
[ "Removes", "all", "matched", "data", ".", "data", "from", "the", "the", "list", "by", "passed", "block", "or", "value", "." ]
f4e0d62fbc129282374f91d4fbcc699f7c330bd4
https://github.com/spectator/linked-list/blob/f4e0d62fbc129282374f91d4fbcc699f7c330bd4/lib/linked-list/list.rb#L157-L162
22,712
wycats/merb
merb-core/lib/merb-core/dispatch/session/store_container.rb
Merb.SessionStoreContainer.regenerate
def regenerate store.delete_session(self.session_id) self.session_id = Merb::SessionMixin.rand_uuid store.store_session(self.session_id, self) end
ruby
def regenerate store.delete_session(self.session_id) self.session_id = Merb::SessionMixin.rand_uuid store.store_session(self.session_id, self) end
[ "def", "regenerate", "store", ".", "delete_session", "(", "self", ".", "session_id", ")", "self", ".", "session_id", "=", "Merb", "::", "SessionMixin", ".", "rand_uuid", "store", ".", "store_session", "(", "self", ".", "session_id", ",", "self", ")", "end" ]
Regenerate the session ID. :api: private
[ "Regenerate", "the", "session", "ID", "." ]
b34d3d4fb6da70c2e9e9e56ddccc73f8a3e55e39
https://github.com/wycats/merb/blob/b34d3d4fb6da70c2e9e9e56ddccc73f8a3e55e39/merb-core/lib/merb-core/dispatch/session/store_container.rb#L156-L160
22,713
wycats/merb
merb-gen/lib/generators/templates/application/merb_core/doc/rdoc/generators/merb_generator.rb
Generators.ContextUser.collect_methods
def collect_methods list = @context.method_list unless @options.show_all list = list.find_all {|m| m.visibility == :public || m.visibility == :protected || m.force_documentation } end @methods = list.collect {|m| HtmlMethod.new(m, self, @options) } end
ruby
def collect_methods list = @context.method_list unless @options.show_all list = list.find_all {|m| m.visibility == :public || m.visibility == :protected || m.force_documentation } end @methods = list.collect {|m| HtmlMethod.new(m, self, @options) } end
[ "def", "collect_methods", "list", "=", "@context", ".", "method_list", "unless", "@options", ".", "show_all", "list", "=", "list", ".", "find_all", "{", "|", "m", "|", "m", ".", "visibility", "==", ":public", "||", "m", ".", "visibility", "==", ":protected", "||", "m", ".", "force_documentation", "}", "end", "@methods", "=", "list", ".", "collect", "{", "|", "m", "|", "HtmlMethod", ".", "new", "(", "m", ",", "self", ",", "@options", ")", "}", "end" ]
Create a list of HtmlMethod objects for each method in the corresponding context object. If the @options.show_all variable is set (corresponding to the <tt>--all</tt> option, we include all methods, otherwise just the public ones.
[ "Create", "a", "list", "of", "HtmlMethod", "objects", "for", "each", "method", "in", "the", "corresponding", "context", "object", ".", "If", "the" ]
b34d3d4fb6da70c2e9e9e56ddccc73f8a3e55e39
https://github.com/wycats/merb/blob/b34d3d4fb6da70c2e9e9e56ddccc73f8a3e55e39/merb-gen/lib/generators/templates/application/merb_core/doc/rdoc/generators/merb_generator.rb#L286-L292
22,714
wycats/merb
merb-gen/lib/generators/templates/application/merb_core/doc/rdoc/generators/merb_generator.rb
Generators.HtmlMethod.markup_code
def markup_code(tokens) src = "" tokens.each do |t| next unless t # p t.class # style = STYLE_MAP[t.class] style = case t when RubyToken::TkCONSTANT then "ruby-constant" when RubyToken::TkKW then "ruby-keyword kw" when RubyToken::TkIVAR then "ruby-ivar" when RubyToken::TkOp then "ruby-operator" when RubyToken::TkId then "ruby-identifier" when RubyToken::TkNode then "ruby-node" when RubyToken::TkCOMMENT then "ruby-comment cmt" when RubyToken::TkREGEXP then "ruby-regexp re" when RubyToken::TkSTRING then "ruby-value str" when RubyToken::TkVal then "ruby-value" else nil end text = CGI.escapeHTML(t.text) if style src << "<span class=\"#{style}\">#{text}</span>" else src << text end end add_line_numbers(src) src end
ruby
def markup_code(tokens) src = "" tokens.each do |t| next unless t # p t.class # style = STYLE_MAP[t.class] style = case t when RubyToken::TkCONSTANT then "ruby-constant" when RubyToken::TkKW then "ruby-keyword kw" when RubyToken::TkIVAR then "ruby-ivar" when RubyToken::TkOp then "ruby-operator" when RubyToken::TkId then "ruby-identifier" when RubyToken::TkNode then "ruby-node" when RubyToken::TkCOMMENT then "ruby-comment cmt" when RubyToken::TkREGEXP then "ruby-regexp re" when RubyToken::TkSTRING then "ruby-value str" when RubyToken::TkVal then "ruby-value" else nil end text = CGI.escapeHTML(t.text) if style src << "<span class=\"#{style}\">#{text}</span>" else src << text end end add_line_numbers(src) src end
[ "def", "markup_code", "(", "tokens", ")", "src", "=", "\"\"", "tokens", ".", "each", "do", "|", "t", "|", "next", "unless", "t", "# p t.class", "# style = STYLE_MAP[t.class]", "style", "=", "case", "t", "when", "RubyToken", "::", "TkCONSTANT", "then", "\"ruby-constant\"", "when", "RubyToken", "::", "TkKW", "then", "\"ruby-keyword kw\"", "when", "RubyToken", "::", "TkIVAR", "then", "\"ruby-ivar\"", "when", "RubyToken", "::", "TkOp", "then", "\"ruby-operator\"", "when", "RubyToken", "::", "TkId", "then", "\"ruby-identifier\"", "when", "RubyToken", "::", "TkNode", "then", "\"ruby-node\"", "when", "RubyToken", "::", "TkCOMMENT", "then", "\"ruby-comment cmt\"", "when", "RubyToken", "::", "TkREGEXP", "then", "\"ruby-regexp re\"", "when", "RubyToken", "::", "TkSTRING", "then", "\"ruby-value str\"", "when", "RubyToken", "::", "TkVal", "then", "\"ruby-value\"", "else", "nil", "end", "text", "=", "CGI", ".", "escapeHTML", "(", "t", ".", "text", ")", "if", "style", "src", "<<", "\"<span class=\\\"#{style}\\\">#{text}</span>\"", "else", "src", "<<", "text", "end", "end", "add_line_numbers", "(", "src", ")", "src", "end" ]
Given a sequence of source tokens, mark up the source code to make it look purty.
[ "Given", "a", "sequence", "of", "source", "tokens", "mark", "up", "the", "source", "code", "to", "make", "it", "look", "purty", "." ]
b34d3d4fb6da70c2e9e9e56ddccc73f8a3e55e39
https://github.com/wycats/merb/blob/b34d3d4fb6da70c2e9e9e56ddccc73f8a3e55e39/merb-gen/lib/generators/templates/application/merb_core/doc/rdoc/generators/merb_generator.rb#L1056-L1088
22,715
wycats/merb
merb-mailer/lib/merb-mailer/mailer.rb
Merb.Mailer.net_smtp
def net_smtp smtp = Net::SMTP.new(config[:host], config[:port].to_i) if config[:tls] if smtp.respond_to?(:enable_starttls) # 1.9.x smtp.enable_starttls elsif smtp.respond_to?(:enable_tls) && smtp.respond_to?(:use_tls?) smtp.enable_tls(OpenSSL::SSL::VERIFY_NONE) # 1.8.x with tlsmail else raise 'Unable to enable TLS, for Ruby 1.8.x install tlsmail' end end smtp.start(config[:domain], config[:user], config[:pass], config[:auth]) { |smtp| to = @mail.to.is_a?(String) ? @mail.to.split(/[,;]/) : @mail.to smtp.send_message(@mail.to_s, @mail.from.first, to) } end
ruby
def net_smtp smtp = Net::SMTP.new(config[:host], config[:port].to_i) if config[:tls] if smtp.respond_to?(:enable_starttls) # 1.9.x smtp.enable_starttls elsif smtp.respond_to?(:enable_tls) && smtp.respond_to?(:use_tls?) smtp.enable_tls(OpenSSL::SSL::VERIFY_NONE) # 1.8.x with tlsmail else raise 'Unable to enable TLS, for Ruby 1.8.x install tlsmail' end end smtp.start(config[:domain], config[:user], config[:pass], config[:auth]) { |smtp| to = @mail.to.is_a?(String) ? @mail.to.split(/[,;]/) : @mail.to smtp.send_message(@mail.to_s, @mail.from.first, to) } end
[ "def", "net_smtp", "smtp", "=", "Net", "::", "SMTP", ".", "new", "(", "config", "[", ":host", "]", ",", "config", "[", ":port", "]", ".", "to_i", ")", "if", "config", "[", ":tls", "]", "if", "smtp", ".", "respond_to?", "(", ":enable_starttls", ")", "# 1.9.x", "smtp", ".", "enable_starttls", "elsif", "smtp", ".", "respond_to?", "(", ":enable_tls", ")", "&&", "smtp", ".", "respond_to?", "(", ":use_tls?", ")", "smtp", ".", "enable_tls", "(", "OpenSSL", "::", "SSL", "::", "VERIFY_NONE", ")", "# 1.8.x with tlsmail", "else", "raise", "'Unable to enable TLS, for Ruby 1.8.x install tlsmail'", "end", "end", "smtp", ".", "start", "(", "config", "[", ":domain", "]", ",", "config", "[", ":user", "]", ",", "config", "[", ":pass", "]", ",", "config", "[", ":auth", "]", ")", "{", "|", "smtp", "|", "to", "=", "@mail", ".", "to", ".", "is_a?", "(", "String", ")", "?", "@mail", ".", "to", ".", "split", "(", "/", "/", ")", ":", "@mail", ".", "to", "smtp", ".", "send_message", "(", "@mail", ".", "to_s", ",", "@mail", ".", "from", ".", "first", ",", "to", ")", "}", "end" ]
Sends the mail using SMTP.
[ "Sends", "the", "mail", "using", "SMTP", "." ]
b34d3d4fb6da70c2e9e9e56ddccc73f8a3e55e39
https://github.com/wycats/merb/blob/b34d3d4fb6da70c2e9e9e56ddccc73f8a3e55e39/merb-mailer/lib/merb-mailer/mailer.rb#L57-L72
22,716
wycats/merb
merb-core/lib/merb-core/dispatch/worker.rb
Merb.Worker.process_queue
def process_queue begin while blk = Merb::Dispatcher.work_queue.pop # we've been blocking on the queue waiting for an item sleeping. # when someone pushes an item it wakes up this thread so we # immediately pass execution to the scheduler so we don't # accidentally run this block before the action finishes # it's own processing Thread.pass blk.call break if Merb::Dispatcher.work_queue.empty? && Merb.exiting end rescue Exception => e Merb.logger.warn! %Q!Worker Thread Crashed with Exception:\n#{Merb.exception(e)}\nRestarting Worker Thread! retry end end
ruby
def process_queue begin while blk = Merb::Dispatcher.work_queue.pop # we've been blocking on the queue waiting for an item sleeping. # when someone pushes an item it wakes up this thread so we # immediately pass execution to the scheduler so we don't # accidentally run this block before the action finishes # it's own processing Thread.pass blk.call break if Merb::Dispatcher.work_queue.empty? && Merb.exiting end rescue Exception => e Merb.logger.warn! %Q!Worker Thread Crashed with Exception:\n#{Merb.exception(e)}\nRestarting Worker Thread! retry end end
[ "def", "process_queue", "begin", "while", "blk", "=", "Merb", "::", "Dispatcher", ".", "work_queue", ".", "pop", "# we've been blocking on the queue waiting for an item sleeping.", "# when someone pushes an item it wakes up this thread so we ", "# immediately pass execution to the scheduler so we don't ", "# accidentally run this block before the action finishes ", "# it's own processing", "Thread", ".", "pass", "blk", ".", "call", "break", "if", "Merb", "::", "Dispatcher", ".", "work_queue", ".", "empty?", "&&", "Merb", ".", "exiting", "end", "rescue", "Exception", "=>", "e", "Merb", ".", "logger", ".", "warn!", "%Q!Worker Thread Crashed with Exception:\\n#{Merb.exception(e)}\\nRestarting Worker Thread!", "retry", "end", "end" ]
Creates a new worker thread that loops over the work queue. :api: private Processes tasks in the Merb::Dispatcher.work_queue. :api: private
[ "Creates", "a", "new", "worker", "thread", "that", "loops", "over", "the", "work", "queue", "." ]
b34d3d4fb6da70c2e9e9e56ddccc73f8a3e55e39
https://github.com/wycats/merb/blob/b34d3d4fb6da70c2e9e9e56ddccc73f8a3e55e39/merb-core/lib/merb-core/dispatch/worker.rb#L49-L65
22,717
wycats/merb
merb-core/lib/merb-core/dispatch/dispatcher.rb
Merb.Request.handle
def handle @start = env["merb.request_start"] = Time.now Merb.logger.info { "Started request handling: #{start.to_s}" } find_route! return rack_response if handled? klass = controller Merb.logger.debug { "Routed to: #{klass::_filter_params(params).inspect}" } unless klass < Controller raise NotFound, "Controller '#{klass}' not found.\n" \ "If Merb tries to find a controller for static files, " \ "you may need to check your Rackup file, see the Problems " \ "section at: http://wiki.merbivore.com/pages/rack-middleware" end if klass.abstract? raise NotFound, "The '#{klass}' controller has no public actions" end dispatch_action(klass, params[:action]) rescue Object => exception dispatch_exception(exception) end
ruby
def handle @start = env["merb.request_start"] = Time.now Merb.logger.info { "Started request handling: #{start.to_s}" } find_route! return rack_response if handled? klass = controller Merb.logger.debug { "Routed to: #{klass::_filter_params(params).inspect}" } unless klass < Controller raise NotFound, "Controller '#{klass}' not found.\n" \ "If Merb tries to find a controller for static files, " \ "you may need to check your Rackup file, see the Problems " \ "section at: http://wiki.merbivore.com/pages/rack-middleware" end if klass.abstract? raise NotFound, "The '#{klass}' controller has no public actions" end dispatch_action(klass, params[:action]) rescue Object => exception dispatch_exception(exception) end
[ "def", "handle", "@start", "=", "env", "[", "\"merb.request_start\"", "]", "=", "Time", ".", "now", "Merb", ".", "logger", ".", "info", "{", "\"Started request handling: #{start.to_s}\"", "}", "find_route!", "return", "rack_response", "if", "handled?", "klass", "=", "controller", "Merb", ".", "logger", ".", "debug", "{", "\"Routed to: #{klass::_filter_params(params).inspect}\"", "}", "unless", "klass", "<", "Controller", "raise", "NotFound", ",", "\"Controller '#{klass}' not found.\\n\"", "\"If Merb tries to find a controller for static files, \"", "\"you may need to check your Rackup file, see the Problems \"", "\"section at: http://wiki.merbivore.com/pages/rack-middleware\"", "end", "if", "klass", ".", "abstract?", "raise", "NotFound", ",", "\"The '#{klass}' controller has no public actions\"", "end", "dispatch_action", "(", "klass", ",", "params", "[", ":action", "]", ")", "rescue", "Object", "=>", "exception", "dispatch_exception", "(", "exception", ")", "end" ]
Handles request routing and action dispatch. ==== Returns Array[Integer, Hash, #each]:: A Rack response :api: private
[ "Handles", "request", "routing", "and", "action", "dispatch", "." ]
b34d3d4fb6da70c2e9e9e56ddccc73f8a3e55e39
https://github.com/wycats/merb/blob/b34d3d4fb6da70c2e9e9e56ddccc73f8a3e55e39/merb-core/lib/merb-core/dispatch/dispatcher.rb#L54-L79
22,718
wycats/merb
merb-core/lib/merb-core/dispatch/dispatcher.rb
Merb.Request.dispatch_action
def dispatch_action(klass, action_name, status=200) @env["merb.status"] = status @env["merb.action_name"] = action_name if Dispatcher.use_mutex @@mutex.synchronize { klass.call(env) } else klass.call(env) end end
ruby
def dispatch_action(klass, action_name, status=200) @env["merb.status"] = status @env["merb.action_name"] = action_name if Dispatcher.use_mutex @@mutex.synchronize { klass.call(env) } else klass.call(env) end end
[ "def", "dispatch_action", "(", "klass", ",", "action_name", ",", "status", "=", "200", ")", "@env", "[", "\"merb.status\"", "]", "=", "status", "@env", "[", "\"merb.action_name\"", "]", "=", "action_name", "if", "Dispatcher", ".", "use_mutex", "@@mutex", ".", "synchronize", "{", "klass", ".", "call", "(", "env", ")", "}", "else", "klass", ".", "call", "(", "env", ")", "end", "end" ]
Setup the controller and call the chosen action ==== Parameters klass<Merb::Controller>:: The controller class to dispatch to. action<Symbol>:: The action to dispatch. status<Integer>:: The status code to respond with. ==== Returns Array[Integer, Hash, #each]:: A Rack response :api: private
[ "Setup", "the", "controller", "and", "call", "the", "chosen", "action" ]
b34d3d4fb6da70c2e9e9e56ddccc73f8a3e55e39
https://github.com/wycats/merb/blob/b34d3d4fb6da70c2e9e9e56ddccc73f8a3e55e39/merb-core/lib/merb-core/dispatch/dispatcher.rb#L93-L102
22,719
wycats/merb
merb-core/lib/merb-core/dispatch/dispatcher.rb
Merb.Request.dispatch_exception
def dispatch_exception(exception) if(exception.is_a?(Merb::ControllerExceptions::Base) && !exception.is_a?(Merb::ControllerExceptions::ServerError)) Merb.logger.info(Merb.exception(exception)) else Merb.logger.error(Merb.exception(exception)) end exceptions = env["merb.exceptions"] = [exception] begin e = exceptions.first if action_name = e.action_name dispatch_action(Exceptions, action_name, e.class.status) else dispatch_action(Dispatcher::DefaultException, :index, e.class.status) end rescue Object => dispatch_issue if e.same?(dispatch_issue) || exceptions.size > 5 dispatch_action(Dispatcher::DefaultException, :index, e.class.status) else Merb.logger.error("Dispatching #{e.class} raised another error.") Merb.logger.error(Merb.exception(dispatch_issue)) exceptions.unshift dispatch_issue retry end end end
ruby
def dispatch_exception(exception) if(exception.is_a?(Merb::ControllerExceptions::Base) && !exception.is_a?(Merb::ControllerExceptions::ServerError)) Merb.logger.info(Merb.exception(exception)) else Merb.logger.error(Merb.exception(exception)) end exceptions = env["merb.exceptions"] = [exception] begin e = exceptions.first if action_name = e.action_name dispatch_action(Exceptions, action_name, e.class.status) else dispatch_action(Dispatcher::DefaultException, :index, e.class.status) end rescue Object => dispatch_issue if e.same?(dispatch_issue) || exceptions.size > 5 dispatch_action(Dispatcher::DefaultException, :index, e.class.status) else Merb.logger.error("Dispatching #{e.class} raised another error.") Merb.logger.error(Merb.exception(dispatch_issue)) exceptions.unshift dispatch_issue retry end end end
[ "def", "dispatch_exception", "(", "exception", ")", "if", "(", "exception", ".", "is_a?", "(", "Merb", "::", "ControllerExceptions", "::", "Base", ")", "&&", "!", "exception", ".", "is_a?", "(", "Merb", "::", "ControllerExceptions", "::", "ServerError", ")", ")", "Merb", ".", "logger", ".", "info", "(", "Merb", ".", "exception", "(", "exception", ")", ")", "else", "Merb", ".", "logger", ".", "error", "(", "Merb", ".", "exception", "(", "exception", ")", ")", "end", "exceptions", "=", "env", "[", "\"merb.exceptions\"", "]", "=", "[", "exception", "]", "begin", "e", "=", "exceptions", ".", "first", "if", "action_name", "=", "e", ".", "action_name", "dispatch_action", "(", "Exceptions", ",", "action_name", ",", "e", ".", "class", ".", "status", ")", "else", "dispatch_action", "(", "Dispatcher", "::", "DefaultException", ",", ":index", ",", "e", ".", "class", ".", "status", ")", "end", "rescue", "Object", "=>", "dispatch_issue", "if", "e", ".", "same?", "(", "dispatch_issue", ")", "||", "exceptions", ".", "size", ">", "5", "dispatch_action", "(", "Dispatcher", "::", "DefaultException", ",", ":index", ",", "e", ".", "class", ".", "status", ")", "else", "Merb", ".", "logger", ".", "error", "(", "\"Dispatching #{e.class} raised another error.\"", ")", "Merb", ".", "logger", ".", "error", "(", "Merb", ".", "exception", "(", "dispatch_issue", ")", ")", "exceptions", ".", "unshift", "dispatch_issue", "retry", "end", "end", "end" ]
Re-route the current request to the Exception controller if it is available, and try to render the exception nicely. You can handle exceptions by implementing actions for specific exceptions such as not_found or for entire classes of exceptions such as client_error. You can also implement handlers for exceptions outside the Merb exception hierarchy (e.g. StandardError is caught in standard_error). ==== Parameters exception<Object>:: The exception object that was created when trying to dispatch the original controller. ==== Returns Array[Integer, Hash, #each]:: A Rack response :api: private
[ "Re", "-", "route", "the", "current", "request", "to", "the", "Exception", "controller", "if", "it", "is", "available", "and", "try", "to", "render", "the", "exception", "nicely", "." ]
b34d3d4fb6da70c2e9e9e56ddccc73f8a3e55e39
https://github.com/wycats/merb/blob/b34d3d4fb6da70c2e9e9e56ddccc73f8a3e55e39/merb-core/lib/merb-core/dispatch/dispatcher.rb#L122-L151
22,720
wycats/merb
merb-core/lib/merb-core/controller/mixins/controller.rb
Merb.ControllerMixin.render_chunked
def render_chunked(&blk) must_support_streaming! headers['Transfer-Encoding'] = 'chunked' Proc.new { |response| @response = response response.send_status_no_connection_close('') response.send_header blk.call response.write("0\r\n\r\n") } end
ruby
def render_chunked(&blk) must_support_streaming! headers['Transfer-Encoding'] = 'chunked' Proc.new { |response| @response = response response.send_status_no_connection_close('') response.send_header blk.call response.write("0\r\n\r\n") } end
[ "def", "render_chunked", "(", "&", "blk", ")", "must_support_streaming!", "headers", "[", "'Transfer-Encoding'", "]", "=", "'chunked'", "Proc", ".", "new", "{", "|", "response", "|", "@response", "=", "response", "response", ".", "send_status_no_connection_close", "(", "''", ")", "response", ".", "send_header", "blk", ".", "call", "response", ".", "write", "(", "\"0\\r\\n\\r\\n\"", ")", "}", "end" ]
Renders the block given as a parameter using chunked encoding. ==== Parameters &blk:: A block that, when called, will use send_chunks to send chunks of data down to the server. The chunking will terminate once the block returns. ==== Examples def stream prefix = '<p>' suffix = "</p>\r\n" render_chunked do IO.popen("cat /tmp/test.log") do |io| done = false until done sleep 0.3 line = io.gets.chomp if line == 'EOF' done = true else send_chunk(prefix + line + suffix) end end end end end :api: public
[ "Renders", "the", "block", "given", "as", "a", "parameter", "using", "chunked", "encoding", "." ]
b34d3d4fb6da70c2e9e9e56ddccc73f8a3e55e39
https://github.com/wycats/merb/blob/b34d3d4fb6da70c2e9e9e56ddccc73f8a3e55e39/merb-core/lib/merb-core/controller/mixins/controller.rb#L50-L60
22,721
wycats/merb
merb-core/lib/merb-core/controller/mixins/controller.rb
Merb.ControllerMixin.render_then_call
def render_then_call(str, &blk) Proc.new do |response| response.write(str) blk.call end end
ruby
def render_then_call(str, &blk) Proc.new do |response| response.write(str) blk.call end end
[ "def", "render_then_call", "(", "str", ",", "&", "blk", ")", "Proc", ".", "new", "do", "|", "response", "|", "response", ".", "write", "(", "str", ")", "blk", ".", "call", "end", "end" ]
Renders the passed in string, then calls the block outside the mutex and after the string has been returned to the client. ==== Parameters str<String>:: A +String+ to return to the client. &blk:: A block that should get called once the string has been returned. ==== Returns Proc:: A block that Mongrel can call after returning the string to the user. :api: public
[ "Renders", "the", "passed", "in", "string", "then", "calls", "the", "block", "outside", "the", "mutex", "and", "after", "the", "string", "has", "been", "returned", "to", "the", "client", "." ]
b34d3d4fb6da70c2e9e9e56ddccc73f8a3e55e39
https://github.com/wycats/merb/blob/b34d3d4fb6da70c2e9e9e56ddccc73f8a3e55e39/merb-core/lib/merb-core/controller/mixins/controller.rb#L104-L109
22,722
wycats/merb
merb-core/lib/merb-core/controller/mixins/controller.rb
Merb.ControllerMixin.send_file
def send_file(file, opts={}) opts.update(Merb::Const::DEFAULT_SEND_FILE_OPTIONS.merge(opts)) disposition = opts[:disposition].dup || 'attachment' disposition << %(; filename="#{opts[:filename] ? opts[:filename] : File.basename(file)}") headers.update( 'Content-Type' => opts[:type].strip, # fixes a problem with extra '\r' with some browsers 'Content-Disposition' => disposition, 'Content-Transfer-Encoding' => 'binary' ) Proc.new do |response| file = File.open(file, 'rb') while chunk = file.read(16384) response.write chunk end file.close end end
ruby
def send_file(file, opts={}) opts.update(Merb::Const::DEFAULT_SEND_FILE_OPTIONS.merge(opts)) disposition = opts[:disposition].dup || 'attachment' disposition << %(; filename="#{opts[:filename] ? opts[:filename] : File.basename(file)}") headers.update( 'Content-Type' => opts[:type].strip, # fixes a problem with extra '\r' with some browsers 'Content-Disposition' => disposition, 'Content-Transfer-Encoding' => 'binary' ) Proc.new do |response| file = File.open(file, 'rb') while chunk = file.read(16384) response.write chunk end file.close end end
[ "def", "send_file", "(", "file", ",", "opts", "=", "{", "}", ")", "opts", ".", "update", "(", "Merb", "::", "Const", "::", "DEFAULT_SEND_FILE_OPTIONS", ".", "merge", "(", "opts", ")", ")", "disposition", "=", "opts", "[", ":disposition", "]", ".", "dup", "||", "'attachment'", "disposition", "<<", "%(; filename=\"#{opts[:filename] ? opts[:filename] : File.basename(file)}\")", "headers", ".", "update", "(", "'Content-Type'", "=>", "opts", "[", ":type", "]", ".", "strip", ",", "# fixes a problem with extra '\\r' with some browsers", "'Content-Disposition'", "=>", "disposition", ",", "'Content-Transfer-Encoding'", "=>", "'binary'", ")", "Proc", ".", "new", "do", "|", "response", "|", "file", "=", "File", ".", "open", "(", "file", ",", "'rb'", ")", "while", "chunk", "=", "file", ".", "read", "(", "16384", ")", "response", ".", "write", "chunk", "end", "file", ".", "close", "end", "end" ]
Sends a file over HTTP. When given a path to a file, it will set the right headers so that the static file is served directly. ==== Parameters file<String>:: Path to file to send to the client. opts<Hash>:: Options for sending the file (see below). ==== Options (opts) :disposition<String>:: The disposition of the file send. Defaults to "attachment". :filename<String>:: The name to use for the file. Defaults to the filename of file. :type<String>:: The content type. ==== Returns IO:: An I/O stream for the file. :api: public
[ "Sends", "a", "file", "over", "HTTP", ".", "When", "given", "a", "path", "to", "a", "file", "it", "will", "set", "the", "right", "headers", "so", "that", "the", "static", "file", "is", "served", "directly", "." ]
b34d3d4fb6da70c2e9e9e56ddccc73f8a3e55e39
https://github.com/wycats/merb/blob/b34d3d4fb6da70c2e9e9e56ddccc73f8a3e55e39/merb-core/lib/merb-core/controller/mixins/controller.rb#L175-L191
22,723
wycats/merb
merb-core/lib/merb-core/controller/mixins/controller.rb
Merb.ControllerMixin.send_data
def send_data(data, opts={}) opts.update(Merb::Const::DEFAULT_SEND_FILE_OPTIONS.merge(opts)) disposition = opts[:disposition].dup || 'attachment' disposition << %(; filename="#{opts[:filename]}") if opts[:filename] headers.update( 'Content-Type' => opts[:type].strip, # fixes a problem with extra '\r' with some browsers 'Content-Disposition' => disposition, 'Content-Transfer-Encoding' => 'binary' ) data end
ruby
def send_data(data, opts={}) opts.update(Merb::Const::DEFAULT_SEND_FILE_OPTIONS.merge(opts)) disposition = opts[:disposition].dup || 'attachment' disposition << %(; filename="#{opts[:filename]}") if opts[:filename] headers.update( 'Content-Type' => opts[:type].strip, # fixes a problem with extra '\r' with some browsers 'Content-Disposition' => disposition, 'Content-Transfer-Encoding' => 'binary' ) data end
[ "def", "send_data", "(", "data", ",", "opts", "=", "{", "}", ")", "opts", ".", "update", "(", "Merb", "::", "Const", "::", "DEFAULT_SEND_FILE_OPTIONS", ".", "merge", "(", "opts", ")", ")", "disposition", "=", "opts", "[", ":disposition", "]", ".", "dup", "||", "'attachment'", "disposition", "<<", "%(; filename=\"#{opts[:filename]}\")", "if", "opts", "[", ":filename", "]", "headers", ".", "update", "(", "'Content-Type'", "=>", "opts", "[", ":type", "]", ".", "strip", ",", "# fixes a problem with extra '\\r' with some browsers", "'Content-Disposition'", "=>", "disposition", ",", "'Content-Transfer-Encoding'", "=>", "'binary'", ")", "data", "end" ]
Send binary data over HTTP to the user as a file download. May set content type, apparent file name, and specify whether to show data inline or download as an attachment. ==== Parameters data<String>:: Path to file to send to the client. opts<Hash>:: Options for sending the data (see below). ==== Options (opts) :disposition<String>:: The disposition of the file send. Defaults to "attachment". :filename<String>:: The name to use for the file. Defaults to the filename of file. :type<String>:: The content type. :api: public
[ "Send", "binary", "data", "over", "HTTP", "to", "the", "user", "as", "a", "file", "download", ".", "May", "set", "content", "type", "apparent", "file", "name", "and", "specify", "whether", "to", "show", "data", "inline", "or", "download", "as", "an", "attachment", "." ]
b34d3d4fb6da70c2e9e9e56ddccc73f8a3e55e39
https://github.com/wycats/merb/blob/b34d3d4fb6da70c2e9e9e56ddccc73f8a3e55e39/merb-core/lib/merb-core/controller/mixins/controller.rb#L208-L218
22,724
wycats/merb
merb-core/lib/merb-core/controller/mixins/controller.rb
Merb.ControllerMixin.stream_file
def stream_file(opts={}, &stream) opts.update(Merb::Const::DEFAULT_SEND_FILE_OPTIONS.merge(opts)) disposition = opts[:disposition].dup || 'attachment' disposition << %(; filename="#{opts[:filename]}") headers.update( 'Content-Type' => opts[:type].strip, # fixes a problem with extra '\r' with some browsers 'Content-Disposition' => disposition, 'Content-Transfer-Encoding' => 'binary', # Rack specification requires header values to respond to :each 'CONTENT-LENGTH' => opts[:content_length].to_s ) Proc.new do |response| stream.call(response) end end
ruby
def stream_file(opts={}, &stream) opts.update(Merb::Const::DEFAULT_SEND_FILE_OPTIONS.merge(opts)) disposition = opts[:disposition].dup || 'attachment' disposition << %(; filename="#{opts[:filename]}") headers.update( 'Content-Type' => opts[:type].strip, # fixes a problem with extra '\r' with some browsers 'Content-Disposition' => disposition, 'Content-Transfer-Encoding' => 'binary', # Rack specification requires header values to respond to :each 'CONTENT-LENGTH' => opts[:content_length].to_s ) Proc.new do |response| stream.call(response) end end
[ "def", "stream_file", "(", "opts", "=", "{", "}", ",", "&", "stream", ")", "opts", ".", "update", "(", "Merb", "::", "Const", "::", "DEFAULT_SEND_FILE_OPTIONS", ".", "merge", "(", "opts", ")", ")", "disposition", "=", "opts", "[", ":disposition", "]", ".", "dup", "||", "'attachment'", "disposition", "<<", "%(; filename=\"#{opts[:filename]}\")", "headers", ".", "update", "(", "'Content-Type'", "=>", "opts", "[", ":type", "]", ".", "strip", ",", "# fixes a problem with extra '\\r' with some browsers", "'Content-Disposition'", "=>", "disposition", ",", "'Content-Transfer-Encoding'", "=>", "'binary'", ",", "# Rack specification requires header values to respond to :each", "'CONTENT-LENGTH'", "=>", "opts", "[", ":content_length", "]", ".", "to_s", ")", "Proc", ".", "new", "do", "|", "response", "|", "stream", ".", "call", "(", "response", ")", "end", "end" ]
Streams a file over HTTP. ==== Parameters opts<Hash>:: Options for the file streaming (see below). &stream:: A block that, when called, will return an object that responds to +get_lines+ for streaming. ==== Options :disposition<String>:: The disposition of the file send. Defaults to "attachment". :type<String>:: The content type. :content_length<Numeric>:: The length of the content to send. :filename<String>:: The name to use for the streamed file. ==== Examples stream_file({ :filename => file_name, :type => content_type, :content_length => content_length }) do |response| AWS::S3::S3Object.stream(user.folder_name + "-" + user_file.unique_id, bucket_name) do |chunk| response.write chunk end end :api: public
[ "Streams", "a", "file", "over", "HTTP", "." ]
b34d3d4fb6da70c2e9e9e56ddccc73f8a3e55e39
https://github.com/wycats/merb/blob/b34d3d4fb6da70c2e9e9e56ddccc73f8a3e55e39/merb-core/lib/merb-core/controller/mixins/controller.rb#L244-L258
22,725
wycats/merb
merb-core/lib/merb-core/controller/mixins/controller.rb
Merb.ControllerMixin.set_cookie
def set_cookie(name, value, expires) options = expires.is_a?(Hash) ? expires : {:expires => expires} cookies.set_cookie(name, value, options) end
ruby
def set_cookie(name, value, expires) options = expires.is_a?(Hash) ? expires : {:expires => expires} cookies.set_cookie(name, value, options) end
[ "def", "set_cookie", "(", "name", ",", "value", ",", "expires", ")", "options", "=", "expires", ".", "is_a?", "(", "Hash", ")", "?", "expires", ":", "{", ":expires", "=>", "expires", "}", "cookies", ".", "set_cookie", "(", "name", ",", "value", ",", "options", ")", "end" ]
Sets a cookie to be included in the response. If you need to set a cookie, then use the +cookies+ hash. ==== Parameters name<~to_s>:: A name for the cookie. value<~to_s>:: A value for the cookie. expires<~gmtime:~strftime, Hash>:: An expiration time for the cookie, or a hash of cookie options. :api: public
[ "Sets", "a", "cookie", "to", "be", "included", "in", "the", "response", "." ]
b34d3d4fb6da70c2e9e9e56ddccc73f8a3e55e39
https://github.com/wycats/merb/blob/b34d3d4fb6da70c2e9e9e56ddccc73f8a3e55e39/merb-core/lib/merb-core/controller/mixins/controller.rb#L306-L309
22,726
wycats/merb
merb-core/lib/merb-core/controller/mixins/controller.rb
Merb.ControllerMixin.handle_redirect_messages
def handle_redirect_messages(url, opts={}) opts = opts.dup # check opts for message shortcut keys (and assign them to message) [:notice, :error, :success].each do |message_key| if opts[message_key] opts[:message] ||= {} opts[:message][message_key] = opts[message_key] end end # append message query param if message is passed if opts[:message] notice = Merb::Parse.escape([Marshal.dump(opts[:message])].pack("m")) u = ::URI.parse(url) u.query = u.query ? "#{u.query}&_message=#{notice}" : "_message=#{notice}" url = u.to_s end url end
ruby
def handle_redirect_messages(url, opts={}) opts = opts.dup # check opts for message shortcut keys (and assign them to message) [:notice, :error, :success].each do |message_key| if opts[message_key] opts[:message] ||= {} opts[:message][message_key] = opts[message_key] end end # append message query param if message is passed if opts[:message] notice = Merb::Parse.escape([Marshal.dump(opts[:message])].pack("m")) u = ::URI.parse(url) u.query = u.query ? "#{u.query}&_message=#{notice}" : "_message=#{notice}" url = u.to_s end url end
[ "def", "handle_redirect_messages", "(", "url", ",", "opts", "=", "{", "}", ")", "opts", "=", "opts", ".", "dup", "# check opts for message shortcut keys (and assign them to message)", "[", ":notice", ",", ":error", ",", ":success", "]", ".", "each", "do", "|", "message_key", "|", "if", "opts", "[", "message_key", "]", "opts", "[", ":message", "]", "||=", "{", "}", "opts", "[", ":message", "]", "[", "message_key", "]", "=", "opts", "[", "message_key", "]", "end", "end", "# append message query param if message is passed", "if", "opts", "[", ":message", "]", "notice", "=", "Merb", "::", "Parse", ".", "escape", "(", "[", "Marshal", ".", "dump", "(", "opts", "[", ":message", "]", ")", "]", ".", "pack", "(", "\"m\"", ")", ")", "u", "=", "::", "URI", ".", "parse", "(", "url", ")", "u", ".", "query", "=", "u", ".", "query", "?", "\"#{u.query}&_message=#{notice}\"", ":", "\"_message=#{notice}\"", "url", "=", "u", ".", "to_s", "end", "url", "end" ]
Process a redirect url with options, appending messages onto the url as query params ==== Parameter url<String>:: the url being redirected to ==== Options (opts) :message<Hash>:: A hash of key/value strings to be passed along within the redirect query params. :notice<String>:: A shortcut to passing :message => {:notice => "..."} :error<String>:: A shortcut to passing :message => {:error => "..."} :success<String>:: A shortcut to passing :message => {:success => "..."} ==== Returns String:: the new url with messages attached :api: private
[ "Process", "a", "redirect", "url", "with", "options", "appending", "messages", "onto", "the", "url", "as", "query", "params" ]
b34d3d4fb6da70c2e9e9e56ddccc73f8a3e55e39
https://github.com/wycats/merb/blob/b34d3d4fb6da70c2e9e9e56ddccc73f8a3e55e39/merb-core/lib/merb-core/controller/mixins/controller.rb#L372-L392
22,727
wycats/merb
merb-core/lib/merb-core/controller/abstract_controller.rb
Merb.AbstractController._call_filters
def _call_filters(filter_set) (filter_set || []).each do |filter, rule| if _call_filter_for_action?(rule, action_name) && _filter_condition_met?(rule) case filter when Symbol, String if rule.key?(:with) args = rule[:with] send(filter, *args) else send(filter) end when Proc then self.instance_eval(&filter) end end end return :filter_chain_completed end
ruby
def _call_filters(filter_set) (filter_set || []).each do |filter, rule| if _call_filter_for_action?(rule, action_name) && _filter_condition_met?(rule) case filter when Symbol, String if rule.key?(:with) args = rule[:with] send(filter, *args) else send(filter) end when Proc then self.instance_eval(&filter) end end end return :filter_chain_completed end
[ "def", "_call_filters", "(", "filter_set", ")", "(", "filter_set", "||", "[", "]", ")", ".", "each", "do", "|", "filter", ",", "rule", "|", "if", "_call_filter_for_action?", "(", "rule", ",", "action_name", ")", "&&", "_filter_condition_met?", "(", "rule", ")", "case", "filter", "when", "Symbol", ",", "String", "if", "rule", ".", "key?", "(", ":with", ")", "args", "=", "rule", "[", ":with", "]", "send", "(", "filter", ",", "args", ")", "else", "send", "(", "filter", ")", "end", "when", "Proc", "then", "self", ".", "instance_eval", "(", "filter", ")", "end", "end", "end", "return", ":filter_chain_completed", "end" ]
Calls a filter chain. ==== Parameters filter_set<Array[Filter]>:: A set of filters in the form [[:filter, rule], [:filter, rule]] ==== Returns Symbol:: :filter_chain_completed. ==== Notes Filter rules can be Symbols, Strings, or Procs. Symbols or Strings:: Call the method represented by the +Symbol+ or +String+. Procs:: Execute the +Proc+, in the context of the controller (self will be the controller) :api: private
[ "Calls", "a", "filter", "chain", "." ]
b34d3d4fb6da70c2e9e9e56ddccc73f8a3e55e39
https://github.com/wycats/merb/blob/b34d3d4fb6da70c2e9e9e56ddccc73f8a3e55e39/merb-core/lib/merb-core/controller/abstract_controller.rb#L343-L359
22,728
wycats/merb
merb-core/lib/merb-core/controller/abstract_controller.rb
Merb.AbstractController.absolute_url
def absolute_url(*args) # FIXME: arrgh, why request.protocol returns http://? # :// is not part of protocol name options = extract_options_from_args!(args) || {} protocol = options.delete(:protocol) host = options.delete(:host) raise ArgumentError, "The :protocol option must be specified" unless protocol raise ArgumentError, "The :host option must be specified" unless host args << options protocol + "://" + host + url(*args) end
ruby
def absolute_url(*args) # FIXME: arrgh, why request.protocol returns http://? # :// is not part of protocol name options = extract_options_from_args!(args) || {} protocol = options.delete(:protocol) host = options.delete(:host) raise ArgumentError, "The :protocol option must be specified" unless protocol raise ArgumentError, "The :host option must be specified" unless host args << options protocol + "://" + host + url(*args) end
[ "def", "absolute_url", "(", "*", "args", ")", "# FIXME: arrgh, why request.protocol returns http://?", "# :// is not part of protocol name", "options", "=", "extract_options_from_args!", "(", "args", ")", "||", "{", "}", "protocol", "=", "options", ".", "delete", "(", ":protocol", ")", "host", "=", "options", ".", "delete", "(", ":host", ")", "raise", "ArgumentError", ",", "\"The :protocol option must be specified\"", "unless", "protocol", "raise", "ArgumentError", ",", "\"The :host option must be specified\"", "unless", "host", "args", "<<", "options", "protocol", "+", "\"://\"", "+", "host", "+", "url", "(", "args", ")", "end" ]
Returns the absolute url including the passed protocol and host. This uses the same arguments as the url method, with added requirements of protocol and host options. :api: public
[ "Returns", "the", "absolute", "url", "including", "the", "passed", "protocol", "and", "host", "." ]
b34d3d4fb6da70c2e9e9e56ddccc73f8a3e55e39
https://github.com/wycats/merb/blob/b34d3d4fb6da70c2e9e9e56ddccc73f8a3e55e39/merb-core/lib/merb-core/controller/abstract_controller.rb#L557-L570
22,729
wycats/merb
merb-core/lib/merb-core/controller/abstract_controller.rb
Merb.AbstractController.capture
def capture(*args, &block) ret = nil captured = send("capture_#{@_engine}", *args) do |*args| ret = yield *args end # return captured value only if it is not empty captured.empty? ? ret.to_s : captured end
ruby
def capture(*args, &block) ret = nil captured = send("capture_#{@_engine}", *args) do |*args| ret = yield *args end # return captured value only if it is not empty captured.empty? ? ret.to_s : captured end
[ "def", "capture", "(", "*", "args", ",", "&", "block", ")", "ret", "=", "nil", "captured", "=", "send", "(", "\"capture_#{@_engine}\"", ",", "args", ")", "do", "|", "*", "args", "|", "ret", "=", "yield", "args", "end", "# return captured value only if it is not empty", "captured", ".", "empty?", "?", "ret", ".", "to_s", ":", "captured", "end" ]
Calls the capture method for the selected template engine. ==== Parameters *args:: Arguments to pass to the block. &block:: The block to call. ==== Returns String:: The output of a template block or the return value of a non-template block converted to a string. :api: public
[ "Calls", "the", "capture", "method", "for", "the", "selected", "template", "engine", "." ]
b34d3d4fb6da70c2e9e9e56ddccc73f8a3e55e39
https://github.com/wycats/merb/blob/b34d3d4fb6da70c2e9e9e56ddccc73f8a3e55e39/merb-core/lib/merb-core/controller/abstract_controller.rb#L616-L625
22,730
wycats/merb
merb-exceptions/lib/merb-exceptions/exceptions_helper.rb
MerbExceptions.ExceptionsHelper.notify_of_exceptions
def notify_of_exceptions if Merb::Plugins.config[:exceptions][:environments].include?(Merb.env) begin request = self.request details = {} details['exceptions'] = request.exceptions details['params'] = params details['params'] = self.class._filter_params(params) details['environment'] = request.env.merge( 'process' => $$ ) details['url'] = "#{request.protocol}#{request.env["HTTP_HOST"]}#{request.uri}" MerbExceptions::Notification.new(details).deliver! rescue Exception => e exceptions = request.exceptions << e Merb.logger.fatal!("Exception Notification Failed:\n" + (exceptions).inspect) File.open(Merb.root / 'log' / 'notification_errors.log', 'a') do |log| log.puts("Exception Notification Failed:") exceptions.each do |e| log.puts(Merb.exception(e)) end end end end end
ruby
def notify_of_exceptions if Merb::Plugins.config[:exceptions][:environments].include?(Merb.env) begin request = self.request details = {} details['exceptions'] = request.exceptions details['params'] = params details['params'] = self.class._filter_params(params) details['environment'] = request.env.merge( 'process' => $$ ) details['url'] = "#{request.protocol}#{request.env["HTTP_HOST"]}#{request.uri}" MerbExceptions::Notification.new(details).deliver! rescue Exception => e exceptions = request.exceptions << e Merb.logger.fatal!("Exception Notification Failed:\n" + (exceptions).inspect) File.open(Merb.root / 'log' / 'notification_errors.log', 'a') do |log| log.puts("Exception Notification Failed:") exceptions.each do |e| log.puts(Merb.exception(e)) end end end end end
[ "def", "notify_of_exceptions", "if", "Merb", "::", "Plugins", ".", "config", "[", ":exceptions", "]", "[", ":environments", "]", ".", "include?", "(", "Merb", ".", "env", ")", "begin", "request", "=", "self", ".", "request", "details", "=", "{", "}", "details", "[", "'exceptions'", "]", "=", "request", ".", "exceptions", "details", "[", "'params'", "]", "=", "params", "details", "[", "'params'", "]", "=", "self", ".", "class", ".", "_filter_params", "(", "params", ")", "details", "[", "'environment'", "]", "=", "request", ".", "env", ".", "merge", "(", "'process'", "=>", "$$", ")", "details", "[", "'url'", "]", "=", "\"#{request.protocol}#{request.env[\"HTTP_HOST\"]}#{request.uri}\"", "MerbExceptions", "::", "Notification", ".", "new", "(", "details", ")", ".", "deliver!", "rescue", "Exception", "=>", "e", "exceptions", "=", "request", ".", "exceptions", "<<", "e", "Merb", ".", "logger", ".", "fatal!", "(", "\"Exception Notification Failed:\\n\"", "+", "(", "exceptions", ")", ".", "inspect", ")", "File", ".", "open", "(", "Merb", ".", "root", "/", "'log'", "/", "'notification_errors.log'", ",", "'a'", ")", "do", "|", "log", "|", "log", ".", "puts", "(", "\"Exception Notification Failed:\"", ")", "exceptions", ".", "each", "do", "|", "e", "|", "log", ".", "puts", "(", "Merb", ".", "exception", "(", "e", ")", ")", "end", "end", "end", "end", "end" ]
if you need to handle the render yourself for some reason, you can call this method directly. It sends notifications without any rendering logic. Note though that if you are sending lots of notifications this could delay sending a response back to the user so try to avoid using it where possible.
[ "if", "you", "need", "to", "handle", "the", "render", "yourself", "for", "some", "reason", "you", "can", "call", "this", "method", "directly", ".", "It", "sends", "notifications", "without", "any", "rendering", "logic", ".", "Note", "though", "that", "if", "you", "are", "sending", "lots", "of", "notifications", "this", "could", "delay", "sending", "a", "response", "back", "to", "the", "user", "so", "try", "to", "avoid", "using", "it", "where", "possible", "." ]
b34d3d4fb6da70c2e9e9e56ddccc73f8a3e55e39
https://github.com/wycats/merb/blob/b34d3d4fb6da70c2e9e9e56ddccc73f8a3e55e39/merb-exceptions/lib/merb-exceptions/exceptions_helper.rb#L9-L32
22,731
wycats/merb
merb-cache/lib/merb-cache/stores/fundamental/file_store.rb
Merb::Cache.FileStore.writable?
def writable?(key, parameters = {}, conditions = {}) case key when String, Numeric, Symbol !conditions.has_key?(:expire_in) else nil end end
ruby
def writable?(key, parameters = {}, conditions = {}) case key when String, Numeric, Symbol !conditions.has_key?(:expire_in) else nil end end
[ "def", "writable?", "(", "key", ",", "parameters", "=", "{", "}", ",", "conditions", "=", "{", "}", ")", "case", "key", "when", "String", ",", "Numeric", ",", "Symbol", "!", "conditions", ".", "has_key?", "(", ":expire_in", ")", "else", "nil", "end", "end" ]
Creates directory for cached files unless it exists. File caching does not support expiration time.
[ "Creates", "directory", "for", "cached", "files", "unless", "it", "exists", ".", "File", "caching", "does", "not", "support", "expiration", "time", "." ]
b34d3d4fb6da70c2e9e9e56ddccc73f8a3e55e39
https://github.com/wycats/merb/blob/b34d3d4fb6da70c2e9e9e56ddccc73f8a3e55e39/merb-cache/lib/merb-cache/stores/fundamental/file_store.rb#L20-L26
22,732
wycats/merb
merb-cache/lib/merb-cache/stores/fundamental/file_store.rb
Merb::Cache.FileStore.read
def read(key, parameters = {}) if exists?(key, parameters) read_file(pathify(key, parameters)) end end
ruby
def read(key, parameters = {}) if exists?(key, parameters) read_file(pathify(key, parameters)) end end
[ "def", "read", "(", "key", ",", "parameters", "=", "{", "}", ")", "if", "exists?", "(", "key", ",", "parameters", ")", "read_file", "(", "pathify", "(", "key", ",", "parameters", ")", ")", "end", "end" ]
Reads cached template from disk if it exists.
[ "Reads", "cached", "template", "from", "disk", "if", "it", "exists", "." ]
b34d3d4fb6da70c2e9e9e56ddccc73f8a3e55e39
https://github.com/wycats/merb/blob/b34d3d4fb6da70c2e9e9e56ddccc73f8a3e55e39/merb-cache/lib/merb-cache/stores/fundamental/file_store.rb#L29-L33
22,733
wycats/merb
merb-cache/lib/merb-cache/stores/fundamental/file_store.rb
Merb::Cache.FileStore.write
def write(key, data = nil, parameters = {}, conditions = {}) if writable?(key, parameters, conditions) if File.file?(path = pathify(key, parameters)) write_file(path, data) else create_path(path) && write_file(path, data) end end end
ruby
def write(key, data = nil, parameters = {}, conditions = {}) if writable?(key, parameters, conditions) if File.file?(path = pathify(key, parameters)) write_file(path, data) else create_path(path) && write_file(path, data) end end end
[ "def", "write", "(", "key", ",", "data", "=", "nil", ",", "parameters", "=", "{", "}", ",", "conditions", "=", "{", "}", ")", "if", "writable?", "(", "key", ",", "parameters", ",", "conditions", ")", "if", "File", ".", "file?", "(", "path", "=", "pathify", "(", "key", ",", "parameters", ")", ")", "write_file", "(", "path", ",", "data", ")", "else", "create_path", "(", "path", ")", "&&", "write_file", "(", "path", ",", "data", ")", "end", "end", "end" ]
Writes cached template to disk, creating cache directory if it does not exist.
[ "Writes", "cached", "template", "to", "disk", "creating", "cache", "directory", "if", "it", "does", "not", "exist", "." ]
b34d3d4fb6da70c2e9e9e56ddccc73f8a3e55e39
https://github.com/wycats/merb/blob/b34d3d4fb6da70c2e9e9e56ddccc73f8a3e55e39/merb-cache/lib/merb-cache/stores/fundamental/file_store.rb#L37-L45
22,734
wycats/merb
merb-cache/lib/merb-cache/stores/fundamental/file_store.rb
Merb::Cache.FileStore.fetch
def fetch(key, parameters = {}, conditions = {}, &blk) read(key, parameters) || (writable?(key, parameters, conditions) && write(key, value = blk.call, parameters, conditions) && value) end
ruby
def fetch(key, parameters = {}, conditions = {}, &blk) read(key, parameters) || (writable?(key, parameters, conditions) && write(key, value = blk.call, parameters, conditions) && value) end
[ "def", "fetch", "(", "key", ",", "parameters", "=", "{", "}", ",", "conditions", "=", "{", "}", ",", "&", "blk", ")", "read", "(", "key", ",", "parameters", ")", "||", "(", "writable?", "(", "key", ",", "parameters", ",", "conditions", ")", "&&", "write", "(", "key", ",", "value", "=", "blk", ".", "call", ",", "parameters", ",", "conditions", ")", "&&", "value", ")", "end" ]
Fetches cached data by key if it exists. If it does not, uses passed block to get new cached value and writes it using given key.
[ "Fetches", "cached", "data", "by", "key", "if", "it", "exists", ".", "If", "it", "does", "not", "uses", "passed", "block", "to", "get", "new", "cached", "value", "and", "writes", "it", "using", "given", "key", "." ]
b34d3d4fb6da70c2e9e9e56ddccc73f8a3e55e39
https://github.com/wycats/merb/blob/b34d3d4fb6da70c2e9e9e56ddccc73f8a3e55e39/merb-cache/lib/merb-cache/stores/fundamental/file_store.rb#L50-L52
22,735
wycats/merb
merb-cache/lib/merb-cache/stores/fundamental/file_store.rb
Merb::Cache.FileStore.read_file
def read_file(path) data = nil File.open(path, "r") do |file| file.flock(File::LOCK_EX) data = file.read file.flock(File::LOCK_UN) end data end
ruby
def read_file(path) data = nil File.open(path, "r") do |file| file.flock(File::LOCK_EX) data = file.read file.flock(File::LOCK_UN) end data end
[ "def", "read_file", "(", "path", ")", "data", "=", "nil", "File", ".", "open", "(", "path", ",", "\"r\"", ")", "do", "|", "file", "|", "file", ".", "flock", "(", "File", "::", "LOCK_EX", ")", "data", "=", "file", ".", "read", "file", ".", "flock", "(", "File", "::", "LOCK_UN", ")", "end", "data", "end" ]
Reads file content. Access to the file uses file locking.
[ "Reads", "file", "content", ".", "Access", "to", "the", "file", "uses", "file", "locking", "." ]
b34d3d4fb6da70c2e9e9e56ddccc73f8a3e55e39
https://github.com/wycats/merb/blob/b34d3d4fb6da70c2e9e9e56ddccc73f8a3e55e39/merb-cache/lib/merb-cache/stores/fundamental/file_store.rb#L89-L98
22,736
wycats/merb
merb-cache/lib/merb-cache/stores/fundamental/file_store.rb
Merb::Cache.FileStore.write_file
def write_file(path, data) File.open(path, "w+") do |file| file.flock(File::LOCK_EX) file.write(data) file.flock(File::LOCK_UN) end true end
ruby
def write_file(path, data) File.open(path, "w+") do |file| file.flock(File::LOCK_EX) file.write(data) file.flock(File::LOCK_UN) end true end
[ "def", "write_file", "(", "path", ",", "data", ")", "File", ".", "open", "(", "path", ",", "\"w+\"", ")", "do", "|", "file", "|", "file", ".", "flock", "(", "File", "::", "LOCK_EX", ")", "file", ".", "write", "(", "data", ")", "file", ".", "flock", "(", "File", "::", "LOCK_UN", ")", "end", "true", "end" ]
Writes file content. Access to the file uses file locking.
[ "Writes", "file", "content", ".", "Access", "to", "the", "file", "uses", "file", "locking", "." ]
b34d3d4fb6da70c2e9e9e56ddccc73f8a3e55e39
https://github.com/wycats/merb/blob/b34d3d4fb6da70c2e9e9e56ddccc73f8a3e55e39/merb-cache/lib/merb-cache/stores/fundamental/file_store.rb#L102-L110
22,737
wycats/merb
merb-cache/lib/merb-cache/stores/strategy/adhoc_store.rb
Merb::Cache.AdhocStore.write
def write(key, data = nil, parameters = {}, conditions = {}) @stores.capture_first {|s| s.write(key, data, parameters, conditions)} end
ruby
def write(key, data = nil, parameters = {}, conditions = {}) @stores.capture_first {|s| s.write(key, data, parameters, conditions)} end
[ "def", "write", "(", "key", ",", "data", "=", "nil", ",", "parameters", "=", "{", "}", ",", "conditions", "=", "{", "}", ")", "@stores", ".", "capture_first", "{", "|", "s", "|", "s", ".", "write", "(", "key", ",", "data", ",", "parameters", ",", "conditions", ")", "}", "end" ]
persists the data so that it can be retrieved by the key & parameters. returns nil if it is unable to persist the data. returns true if successful.
[ "persists", "the", "data", "so", "that", "it", "can", "be", "retrieved", "by", "the", "key", "&", "parameters", ".", "returns", "nil", "if", "it", "is", "unable", "to", "persist", "the", "data", ".", "returns", "true", "if", "successful", "." ]
b34d3d4fb6da70c2e9e9e56ddccc73f8a3e55e39
https://github.com/wycats/merb/blob/b34d3d4fb6da70c2e9e9e56ddccc73f8a3e55e39/merb-cache/lib/merb-cache/stores/strategy/adhoc_store.rb#L31-L33
22,738
wycats/merb
merb-cache/lib/merb-cache/stores/strategy/adhoc_store.rb
Merb::Cache.AdhocStore.write_all
def write_all(key, data = nil, parameters = {}, conditions = {}) @stores.map {|s| s.write_all(key, data, parameters, conditions)}.all? end
ruby
def write_all(key, data = nil, parameters = {}, conditions = {}) @stores.map {|s| s.write_all(key, data, parameters, conditions)}.all? end
[ "def", "write_all", "(", "key", ",", "data", "=", "nil", ",", "parameters", "=", "{", "}", ",", "conditions", "=", "{", "}", ")", "@stores", ".", "map", "{", "|", "s", "|", "s", ".", "write_all", "(", "key", ",", "data", ",", "parameters", ",", "conditions", ")", "}", ".", "all?", "end" ]
persists the data to all context stores. returns nil if none of the stores were able to persist the data. returns true if at least one write was successful.
[ "persists", "the", "data", "to", "all", "context", "stores", ".", "returns", "nil", "if", "none", "of", "the", "stores", "were", "able", "to", "persist", "the", "data", ".", "returns", "true", "if", "at", "least", "one", "write", "was", "successful", "." ]
b34d3d4fb6da70c2e9e9e56ddccc73f8a3e55e39
https://github.com/wycats/merb/blob/b34d3d4fb6da70c2e9e9e56ddccc73f8a3e55e39/merb-cache/lib/merb-cache/stores/strategy/adhoc_store.rb#L38-L40
22,739
wycats/merb
merb-cache/lib/merb-cache/stores/strategy/adhoc_store.rb
Merb::Cache.AdhocStore.fetch
def fetch(key, parameters = {}, conditions = {}, &blk) read(key, parameters) || @stores.capture_first {|s| s.fetch(key, parameters, conditions, &blk)} || blk.call end
ruby
def fetch(key, parameters = {}, conditions = {}, &blk) read(key, parameters) || @stores.capture_first {|s| s.fetch(key, parameters, conditions, &blk)} || blk.call end
[ "def", "fetch", "(", "key", ",", "parameters", "=", "{", "}", ",", "conditions", "=", "{", "}", ",", "&", "blk", ")", "read", "(", "key", ",", "parameters", ")", "||", "@stores", ".", "capture_first", "{", "|", "s", "|", "s", ".", "fetch", "(", "key", ",", "parameters", ",", "conditions", ",", "blk", ")", "}", "||", "blk", ".", "call", "end" ]
tries to read the data from the store. If that fails, it calls the block parameter and persists the result. If it cannot be fetched, the block call is returned.
[ "tries", "to", "read", "the", "data", "from", "the", "store", ".", "If", "that", "fails", "it", "calls", "the", "block", "parameter", "and", "persists", "the", "result", ".", "If", "it", "cannot", "be", "fetched", "the", "block", "call", "is", "returned", "." ]
b34d3d4fb6da70c2e9e9e56ddccc73f8a3e55e39
https://github.com/wycats/merb/blob/b34d3d4fb6da70c2e9e9e56ddccc73f8a3e55e39/merb-cache/lib/merb-cache/stores/strategy/adhoc_store.rb#L45-L49
22,740
wycats/merb
merb-cache/lib/merb-cache/stores/strategy/adhoc_store.rb
Merb::Cache.AdhocStore.delete
def delete(key, parameters = {}) @stores.map {|s| s.delete(key, parameters)}.any? end
ruby
def delete(key, parameters = {}) @stores.map {|s| s.delete(key, parameters)}.any? end
[ "def", "delete", "(", "key", ",", "parameters", "=", "{", "}", ")", "@stores", ".", "map", "{", "|", "s", "|", "s", ".", "delete", "(", "key", ",", "parameters", ")", "}", ".", "any?", "end" ]
deletes the entry for the key & parameter from the store.
[ "deletes", "the", "entry", "for", "the", "key", "&", "parameter", "from", "the", "store", "." ]
b34d3d4fb6da70c2e9e9e56ddccc73f8a3e55e39
https://github.com/wycats/merb/blob/b34d3d4fb6da70c2e9e9e56ddccc73f8a3e55e39/merb-cache/lib/merb-cache/stores/strategy/adhoc_store.rb#L58-L60
22,741
wycats/merb
merb-auth/merb-auth-core/lib/merb-auth-core/authentication.rb
Merb.Authentication.user=
def user=(user) session[:user] = nil && return if user.nil? session[:user] = store_user(user) @user = session[:user] ? user : session[:user] end
ruby
def user=(user) session[:user] = nil && return if user.nil? session[:user] = store_user(user) @user = session[:user] ? user : session[:user] end
[ "def", "user", "=", "(", "user", ")", "session", "[", ":user", "]", "=", "nil", "&&", "return", "if", "user", ".", "nil?", "session", "[", ":user", "]", "=", "store_user", "(", "user", ")", "@user", "=", "session", "[", ":user", "]", "?", "user", ":", "session", "[", ":user", "]", "end" ]
This method will store the user provided into the session and set the user as the currently logged in user @return <User Class>|NilClass
[ "This", "method", "will", "store", "the", "user", "provided", "into", "the", "session", "and", "set", "the", "user", "as", "the", "currently", "logged", "in", "user" ]
b34d3d4fb6da70c2e9e9e56ddccc73f8a3e55e39
https://github.com/wycats/merb/blob/b34d3d4fb6da70c2e9e9e56ddccc73f8a3e55e39/merb-auth/merb-auth-core/lib/merb-auth-core/authentication.rb#L48-L52
22,742
wycats/merb
merb-auth/merb-auth-core/lib/merb-auth-core/authentication.rb
Merb.Authentication.authenticate!
def authenticate!(request, params, *rest) opts = rest.last.kind_of?(Hash) ? rest.pop : {} rest = rest.flatten strategies = if rest.empty? if request.session[:authentication_strategies] request.session[:authentication_strategies] else Merb::Authentication.default_strategy_order end else request.session[:authentication_strategies] ||= [] request.session[:authentication_strategies] << rest request.session[:authentication_strategies].flatten!.uniq! request.session[:authentication_strategies] end msg = opts[:message] || error_message user = nil # This one should find the first one that matches. It should not run antother strategies.detect do |s| s = Merb::Authentication.lookup_strategy[s] # Get the strategy from string or class unless s.abstract? strategy = s.new(request, params) user = strategy.run! if strategy.halted? self.headers, self.status, self.body = [strategy.headers, strategy.status, strategy.body] halt! return end user end end # Check after callbacks to make sure the user is still cool user = run_after_authentication_callbacks(user, request, params) if user # Finally, Raise an error if there is no user found, or set it in the session if there is. raise Merb::Controller::Unauthenticated, msg unless user session[:authentication_strategies] = nil # clear the session of Failed Strategies if login is successful self.user = user end
ruby
def authenticate!(request, params, *rest) opts = rest.last.kind_of?(Hash) ? rest.pop : {} rest = rest.flatten strategies = if rest.empty? if request.session[:authentication_strategies] request.session[:authentication_strategies] else Merb::Authentication.default_strategy_order end else request.session[:authentication_strategies] ||= [] request.session[:authentication_strategies] << rest request.session[:authentication_strategies].flatten!.uniq! request.session[:authentication_strategies] end msg = opts[:message] || error_message user = nil # This one should find the first one that matches. It should not run antother strategies.detect do |s| s = Merb::Authentication.lookup_strategy[s] # Get the strategy from string or class unless s.abstract? strategy = s.new(request, params) user = strategy.run! if strategy.halted? self.headers, self.status, self.body = [strategy.headers, strategy.status, strategy.body] halt! return end user end end # Check after callbacks to make sure the user is still cool user = run_after_authentication_callbacks(user, request, params) if user # Finally, Raise an error if there is no user found, or set it in the session if there is. raise Merb::Controller::Unauthenticated, msg unless user session[:authentication_strategies] = nil # clear the session of Failed Strategies if login is successful self.user = user end
[ "def", "authenticate!", "(", "request", ",", "params", ",", "*", "rest", ")", "opts", "=", "rest", ".", "last", ".", "kind_of?", "(", "Hash", ")", "?", "rest", ".", "pop", ":", "{", "}", "rest", "=", "rest", ".", "flatten", "strategies", "=", "if", "rest", ".", "empty?", "if", "request", ".", "session", "[", ":authentication_strategies", "]", "request", ".", "session", "[", ":authentication_strategies", "]", "else", "Merb", "::", "Authentication", ".", "default_strategy_order", "end", "else", "request", ".", "session", "[", ":authentication_strategies", "]", "||=", "[", "]", "request", ".", "session", "[", ":authentication_strategies", "]", "<<", "rest", "request", ".", "session", "[", ":authentication_strategies", "]", ".", "flatten!", ".", "uniq!", "request", ".", "session", "[", ":authentication_strategies", "]", "end", "msg", "=", "opts", "[", ":message", "]", "||", "error_message", "user", "=", "nil", "# This one should find the first one that matches. It should not run antother", "strategies", ".", "detect", "do", "|", "s", "|", "s", "=", "Merb", "::", "Authentication", ".", "lookup_strategy", "[", "s", "]", "# Get the strategy from string or class", "unless", "s", ".", "abstract?", "strategy", "=", "s", ".", "new", "(", "request", ",", "params", ")", "user", "=", "strategy", ".", "run!", "if", "strategy", ".", "halted?", "self", ".", "headers", ",", "self", ".", "status", ",", "self", ".", "body", "=", "[", "strategy", ".", "headers", ",", "strategy", ".", "status", ",", "strategy", ".", "body", "]", "halt!", "return", "end", "user", "end", "end", "# Check after callbacks to make sure the user is still cool", "user", "=", "run_after_authentication_callbacks", "(", "user", ",", "request", ",", "params", ")", "if", "user", "# Finally, Raise an error if there is no user found, or set it in the session if there is.", "raise", "Merb", "::", "Controller", "::", "Unauthenticated", ",", "msg", "unless", "user", "session", "[", ":authentication_strategies", "]", "=", "nil", "# clear the session of Failed Strategies if login is successful ", "self", ".", "user", "=", "user", "end" ]
The workhorse of the framework. The authentiate! method is where the work is done. authenticate! will try each strategy in order either passed in, or in the default_strategy_order. If a strategy returns some kind of user object, this will be stored in the session, otherwise a Merb::Controller::Unauthenticated exception is raised @params Merb::Request, [List,Of,Strategies, optional_options_hash] Pass in a list of strategy objects to have this list take precedence over the normal defaults Use an options hash to provide an error message to be passed into the exception. @return user object of the verified user. An exception is raised if no user is found
[ "The", "workhorse", "of", "the", "framework", ".", "The", "authentiate!", "method", "is", "where", "the", "work", "is", "done", ".", "authenticate!", "will", "try", "each", "strategy", "in", "order", "either", "passed", "in", "or", "in", "the", "default_strategy_order", "." ]
b34d3d4fb6da70c2e9e9e56ddccc73f8a3e55e39
https://github.com/wycats/merb/blob/b34d3d4fb6da70c2e9e9e56ddccc73f8a3e55e39/merb-auth/merb-auth-core/lib/merb-auth-core/authentication.rb#L69-L110
22,743
wycats/merb
merb-core/lib/merb-core/dispatch/cookies.rb
Merb.Cookies.extract_headers
def extract_headers(controller_defaults = {}) defaults = @_cookie_defaults.merge(controller_defaults) cookies = [] self.each do |name, value| # Only set cookies that marked for inclusion in the response header. next unless @_options_lookup[name] options = defaults.merge(@_options_lookup[name]) if (expiry = options["expires"]).respond_to?(:gmtime) options["expires"] = expiry.gmtime.strftime(Merb::Const::COOKIE_EXPIRATION_FORMAT) end secure = options.delete("secure") http_only = options.delete("http_only") kookie = "#{name}=#{Merb::Parse.escape(value)}; " # WebKit in particular doens't like empty cookie options - skip them. options.each { |k, v| kookie << "#{k}=#{v}; " unless v.blank? } kookie << 'secure; ' if secure kookie << 'HttpOnly; ' if http_only cookies << kookie.rstrip end cookies.empty? ? {} : { 'Set-Cookie' => cookies } end
ruby
def extract_headers(controller_defaults = {}) defaults = @_cookie_defaults.merge(controller_defaults) cookies = [] self.each do |name, value| # Only set cookies that marked for inclusion in the response header. next unless @_options_lookup[name] options = defaults.merge(@_options_lookup[name]) if (expiry = options["expires"]).respond_to?(:gmtime) options["expires"] = expiry.gmtime.strftime(Merb::Const::COOKIE_EXPIRATION_FORMAT) end secure = options.delete("secure") http_only = options.delete("http_only") kookie = "#{name}=#{Merb::Parse.escape(value)}; " # WebKit in particular doens't like empty cookie options - skip them. options.each { |k, v| kookie << "#{k}=#{v}; " unless v.blank? } kookie << 'secure; ' if secure kookie << 'HttpOnly; ' if http_only cookies << kookie.rstrip end cookies.empty? ? {} : { 'Set-Cookie' => cookies } end
[ "def", "extract_headers", "(", "controller_defaults", "=", "{", "}", ")", "defaults", "=", "@_cookie_defaults", ".", "merge", "(", "controller_defaults", ")", "cookies", "=", "[", "]", "self", ".", "each", "do", "|", "name", ",", "value", "|", "# Only set cookies that marked for inclusion in the response header. ", "next", "unless", "@_options_lookup", "[", "name", "]", "options", "=", "defaults", ".", "merge", "(", "@_options_lookup", "[", "name", "]", ")", "if", "(", "expiry", "=", "options", "[", "\"expires\"", "]", ")", ".", "respond_to?", "(", ":gmtime", ")", "options", "[", "\"expires\"", "]", "=", "expiry", ".", "gmtime", ".", "strftime", "(", "Merb", "::", "Const", "::", "COOKIE_EXPIRATION_FORMAT", ")", "end", "secure", "=", "options", ".", "delete", "(", "\"secure\"", ")", "http_only", "=", "options", ".", "delete", "(", "\"http_only\"", ")", "kookie", "=", "\"#{name}=#{Merb::Parse.escape(value)}; \"", "# WebKit in particular doens't like empty cookie options - skip them.", "options", ".", "each", "{", "|", "k", ",", "v", "|", "kookie", "<<", "\"#{k}=#{v}; \"", "unless", "v", ".", "blank?", "}", "kookie", "<<", "'secure; '", "if", "secure", "kookie", "<<", "'HttpOnly; '", "if", "http_only", "cookies", "<<", "kookie", ".", "rstrip", "end", "cookies", ".", "empty?", "?", "{", "}", ":", "{", "'Set-Cookie'", "=>", "cookies", "}", "end" ]
Generate any necessary headers. ==== Returns Hash:: The headers to set, or an empty array if no cookies are set. :api: private
[ "Generate", "any", "necessary", "headers", "." ]
b34d3d4fb6da70c2e9e9e56ddccc73f8a3e55e39
https://github.com/wycats/merb/blob/b34d3d4fb6da70c2e9e9e56ddccc73f8a3e55e39/merb-core/lib/merb-core/dispatch/cookies.rb#L70-L90
22,744
wycats/merb
merb-cache/lib/merb-cache/stores/fundamental/memcached_store.rb
Merb::Cache.MemcachedStore.read
def read(key, parameters = {}) begin @memcached.get(normalize(key, parameters)) rescue Memcached::NotFound, Memcached::Stored nil end end
ruby
def read(key, parameters = {}) begin @memcached.get(normalize(key, parameters)) rescue Memcached::NotFound, Memcached::Stored nil end end
[ "def", "read", "(", "key", ",", "parameters", "=", "{", "}", ")", "begin", "@memcached", ".", "get", "(", "normalize", "(", "key", ",", "parameters", ")", ")", "rescue", "Memcached", "::", "NotFound", ",", "Memcached", "::", "Stored", "nil", "end", "end" ]
Reads key from the cache.
[ "Reads", "key", "from", "the", "cache", "." ]
b34d3d4fb6da70c2e9e9e56ddccc73f8a3e55e39
https://github.com/wycats/merb/blob/b34d3d4fb6da70c2e9e9e56ddccc73f8a3e55e39/merb-cache/lib/merb-cache/stores/fundamental/memcached_store.rb#L25-L31
22,745
wycats/merb
merb-cache/lib/merb-cache/stores/fundamental/memcached_store.rb
Merb::Cache.MemcachedStore.write
def write(key, data = nil, parameters = {}, conditions = {}) if writable?(key, parameters, conditions) begin @memcached.set(normalize(key, parameters), data, expire_time(conditions)) true rescue nil end end end
ruby
def write(key, data = nil, parameters = {}, conditions = {}) if writable?(key, parameters, conditions) begin @memcached.set(normalize(key, parameters), data, expire_time(conditions)) true rescue nil end end end
[ "def", "write", "(", "key", ",", "data", "=", "nil", ",", "parameters", "=", "{", "}", ",", "conditions", "=", "{", "}", ")", "if", "writable?", "(", "key", ",", "parameters", ",", "conditions", ")", "begin", "@memcached", ".", "set", "(", "normalize", "(", "key", ",", "parameters", ")", ",", "data", ",", "expire_time", "(", "conditions", ")", ")", "true", "rescue", "nil", "end", "end", "end" ]
Writes data to the cache using key, parameters and conditions.
[ "Writes", "data", "to", "the", "cache", "using", "key", "parameters", "and", "conditions", "." ]
b34d3d4fb6da70c2e9e9e56ddccc73f8a3e55e39
https://github.com/wycats/merb/blob/b34d3d4fb6da70c2e9e9e56ddccc73f8a3e55e39/merb-cache/lib/merb-cache/stores/fundamental/memcached_store.rb#L34-L43
22,746
wycats/merb
merb-assets/lib/merb-assets/assets_mixin.rb
Merb.AssetsMixin.extract_required_files
def extract_required_files(files, options = {}) return [] if files.nil? || files.empty? seen = [] files.inject([]) do |extracted, req_js| include_files, include_options = if req_js.last.is_a?(Hash) [req_js[0..-2], options.merge(req_js.last)] else [req_js, options] end seen += (includes = include_files - seen) extracted << (includes + [include_options]) unless includes.empty? extracted end end
ruby
def extract_required_files(files, options = {}) return [] if files.nil? || files.empty? seen = [] files.inject([]) do |extracted, req_js| include_files, include_options = if req_js.last.is_a?(Hash) [req_js[0..-2], options.merge(req_js.last)] else [req_js, options] end seen += (includes = include_files - seen) extracted << (includes + [include_options]) unless includes.empty? extracted end end
[ "def", "extract_required_files", "(", "files", ",", "options", "=", "{", "}", ")", "return", "[", "]", "if", "files", ".", "nil?", "||", "files", ".", "empty?", "seen", "=", "[", "]", "files", ".", "inject", "(", "[", "]", ")", "do", "|", "extracted", ",", "req_js", "|", "include_files", ",", "include_options", "=", "if", "req_js", ".", "last", ".", "is_a?", "(", "Hash", ")", "[", "req_js", "[", "0", "..", "-", "2", "]", ",", "options", ".", "merge", "(", "req_js", ".", "last", ")", "]", "else", "[", "req_js", ",", "options", "]", "end", "seen", "+=", "(", "includes", "=", "include_files", "-", "seen", ")", "extracted", "<<", "(", "includes", "+", "[", "include_options", "]", ")", "unless", "includes", ".", "empty?", "extracted", "end", "end" ]
Helper method to filter out duplicate files. ==== Parameters options<Hash>:: Options to pass to include tag methods.
[ "Helper", "method", "to", "filter", "out", "duplicate", "files", "." ]
b34d3d4fb6da70c2e9e9e56ddccc73f8a3e55e39
https://github.com/wycats/merb/blob/b34d3d4fb6da70c2e9e9e56ddccc73f8a3e55e39/merb-assets/lib/merb-assets/assets_mixin.rb#L742-L755
22,747
wycats/merb
merb-core/lib/merb-core/dispatch/session/memory.rb
Merb.MemorySessionStore.reap_expired_sessions
def reap_expired_sessions @timestamps.each do |session_id,stamp| delete_session(session_id) if (stamp + @session_ttl) < Time.now end GC.start end
ruby
def reap_expired_sessions @timestamps.each do |session_id,stamp| delete_session(session_id) if (stamp + @session_ttl) < Time.now end GC.start end
[ "def", "reap_expired_sessions", "@timestamps", ".", "each", "do", "|", "session_id", ",", "stamp", "|", "delete_session", "(", "session_id", ")", "if", "(", "stamp", "+", "@session_ttl", ")", "<", "Time", ".", "now", "end", "GC", ".", "start", "end" ]
Deletes any sessions that have reached their maximum validity. :api: private
[ "Deletes", "any", "sessions", "that", "have", "reached", "their", "maximum", "validity", "." ]
b34d3d4fb6da70c2e9e9e56ddccc73f8a3e55e39
https://github.com/wycats/merb/blob/b34d3d4fb6da70c2e9e9e56ddccc73f8a3e55e39/merb-core/lib/merb-core/dispatch/session/memory.rb#L92-L97
22,748
wycats/merb
merb-core/lib/merb-core/dispatch/session/cookie.rb
Merb.CookieSession.to_cookie
def to_cookie unless self.empty? data = self.serialize value = Merb::Parse.escape "#{data}--#{generate_digest(data)}" if value.size > MAX msg = "Cookies have limit of 4K. Session contents: #{data.inspect}" Merb.logger.error!(msg) raise CookieOverflow, msg end value end end
ruby
def to_cookie unless self.empty? data = self.serialize value = Merb::Parse.escape "#{data}--#{generate_digest(data)}" if value.size > MAX msg = "Cookies have limit of 4K. Session contents: #{data.inspect}" Merb.logger.error!(msg) raise CookieOverflow, msg end value end end
[ "def", "to_cookie", "unless", "self", ".", "empty?", "data", "=", "self", ".", "serialize", "value", "=", "Merb", "::", "Parse", ".", "escape", "\"#{data}--#{generate_digest(data)}\"", "if", "value", ".", "size", ">", "MAX", "msg", "=", "\"Cookies have limit of 4K. Session contents: #{data.inspect}\"", "Merb", ".", "logger", ".", "error!", "(", "msg", ")", "raise", "CookieOverflow", ",", "msg", "end", "value", "end", "end" ]
Create the raw cookie string; includes an HMAC keyed message digest. ==== Returns String:: Cookie value. ==== Raises CookieOverflow:: More than 4K of data put into session. ==== Notes Session data is converted to a Hash first, since a container might choose to marshal it, which would make it persist attributes like 'needs_new_cookie', which it shouldn't. :api: private
[ "Create", "the", "raw", "cookie", "string", ";", "includes", "an", "HMAC", "keyed", "message", "digest", "." ]
b34d3d4fb6da70c2e9e9e56ddccc73f8a3e55e39
https://github.com/wycats/merb/blob/b34d3d4fb6da70c2e9e9e56ddccc73f8a3e55e39/merb-core/lib/merb-core/dispatch/session/cookie.rb#L127-L138
22,749
wycats/merb
merb-core/lib/merb-core/dispatch/session/cookie.rb
Merb.CookieSession.secure_compare
def secure_compare(a, b) if a.length == b.length # unpack to forty characters. # needed for 1.8 and 1.9 compat a_bytes = a.unpack('C*') b_bytes = b.unpack('C*') result = 0 for i in 0..(a_bytes.length - 1) result |= a_bytes[i] ^ b_bytes[i] end result == 0 else false end end
ruby
def secure_compare(a, b) if a.length == b.length # unpack to forty characters. # needed for 1.8 and 1.9 compat a_bytes = a.unpack('C*') b_bytes = b.unpack('C*') result = 0 for i in 0..(a_bytes.length - 1) result |= a_bytes[i] ^ b_bytes[i] end result == 0 else false end end
[ "def", "secure_compare", "(", "a", ",", "b", ")", "if", "a", ".", "length", "==", "b", ".", "length", "# unpack to forty characters.", "# needed for 1.8 and 1.9 compat", "a_bytes", "=", "a", ".", "unpack", "(", "'C*'", ")", "b_bytes", "=", "b", ".", "unpack", "(", "'C*'", ")", "result", "=", "0", "for", "i", "in", "0", "..", "(", "a_bytes", ".", "length", "-", "1", ")", "result", "|=", "a_bytes", "[", "i", "]", "^", "b_bytes", "[", "i", "]", "end", "result", "==", "0", "else", "false", "end", "end" ]
Securely compare two digests using a constant time algorithm. This avoids leaking information about the calculated HMAC Based on code by Michael Koziarski <[email protected]> http://github.com/rails/rails/commit/674f780d59a5a7ec0301755d43a7b277a3ad2978 ==== Parameters a, b<~to_s>:: digests to compare. ==== Returns Boolean:: Do the digests validate?
[ "Securely", "compare", "two", "digests", "using", "a", "constant", "time", "algorithm", ".", "This", "avoids", "leaking", "information", "about", "the", "calculated", "HMAC" ]
b34d3d4fb6da70c2e9e9e56ddccc73f8a3e55e39
https://github.com/wycats/merb/blob/b34d3d4fb6da70c2e9e9e56ddccc73f8a3e55e39/merb-core/lib/merb-core/dispatch/session/cookie.rb#L163-L179
22,750
wycats/merb
merb-core/lib/merb-core/dispatch/session/cookie.rb
Merb.CookieSession.unmarshal
def unmarshal(cookie) if cookie.blank? {} else data, digest = Merb::Parse.unescape(cookie).split('--') return {} if data.blank? || digest.blank? unless secure_compare(generate_digest(data), digest) clear unless Merb::Config[:ignore_tampered_cookies] raise TamperedWithCookie, "Maybe the site's session_secret_key has changed?" end end unserialize(data) end end
ruby
def unmarshal(cookie) if cookie.blank? {} else data, digest = Merb::Parse.unescape(cookie).split('--') return {} if data.blank? || digest.blank? unless secure_compare(generate_digest(data), digest) clear unless Merb::Config[:ignore_tampered_cookies] raise TamperedWithCookie, "Maybe the site's session_secret_key has changed?" end end unserialize(data) end end
[ "def", "unmarshal", "(", "cookie", ")", "if", "cookie", ".", "blank?", "{", "}", "else", "data", ",", "digest", "=", "Merb", "::", "Parse", ".", "unescape", "(", "cookie", ")", ".", "split", "(", "'--'", ")", "return", "{", "}", "if", "data", ".", "blank?", "||", "digest", ".", "blank?", "unless", "secure_compare", "(", "generate_digest", "(", "data", ")", ",", "digest", ")", "clear", "unless", "Merb", "::", "Config", "[", ":ignore_tampered_cookies", "]", "raise", "TamperedWithCookie", ",", "\"Maybe the site's session_secret_key has changed?\"", "end", "end", "unserialize", "(", "data", ")", "end", "end" ]
Unmarshal cookie data to a hash and verify its integrity. ==== Parameters cookie<~to_s>:: The cookie to unmarshal. ==== Raises TamperedWithCookie:: The digests don't match. ==== Returns Hash:: The stored session data. :api: private
[ "Unmarshal", "cookie", "data", "to", "a", "hash", "and", "verify", "its", "integrity", "." ]
b34d3d4fb6da70c2e9e9e56ddccc73f8a3e55e39
https://github.com/wycats/merb/blob/b34d3d4fb6da70c2e9e9e56ddccc73f8a3e55e39/merb-core/lib/merb-core/dispatch/session/cookie.rb#L194-L208
22,751
wycats/merb
merb-core/lib/merb-core/dispatch/request.rb
Merb.Request.controller
def controller unless params[:controller] raise ControllerExceptions::NotFound, "Route matched, but route did not specify a controller.\n" + "Did you forgot to add :controller => \"people\" or :controller " + "segment to route definition?\nHere is what's specified:\n" + route.inspect end path = [params[:namespace], params[:controller]].compact.join(Merb::Const::SLASH) controller = path.snake_case.to_const_string begin Object.full_const_get(controller) rescue NameError => e msg = "Controller class not found for controller `#{path}'" Merb.logger.warn!(msg) raise ControllerExceptions::NotFound, msg end end
ruby
def controller unless params[:controller] raise ControllerExceptions::NotFound, "Route matched, but route did not specify a controller.\n" + "Did you forgot to add :controller => \"people\" or :controller " + "segment to route definition?\nHere is what's specified:\n" + route.inspect end path = [params[:namespace], params[:controller]].compact.join(Merb::Const::SLASH) controller = path.snake_case.to_const_string begin Object.full_const_get(controller) rescue NameError => e msg = "Controller class not found for controller `#{path}'" Merb.logger.warn!(msg) raise ControllerExceptions::NotFound, msg end end
[ "def", "controller", "unless", "params", "[", ":controller", "]", "raise", "ControllerExceptions", "::", "NotFound", ",", "\"Route matched, but route did not specify a controller.\\n\"", "+", "\"Did you forgot to add :controller => \\\"people\\\" or :controller \"", "+", "\"segment to route definition?\\nHere is what's specified:\\n\"", "+", "route", ".", "inspect", "end", "path", "=", "[", "params", "[", ":namespace", "]", ",", "params", "[", ":controller", "]", "]", ".", "compact", ".", "join", "(", "Merb", "::", "Const", "::", "SLASH", ")", "controller", "=", "path", ".", "snake_case", ".", "to_const_string", "begin", "Object", ".", "full_const_get", "(", "controller", ")", "rescue", "NameError", "=>", "e", "msg", "=", "\"Controller class not found for controller `#{path}'\"", "Merb", ".", "logger", ".", "warn!", "(", "msg", ")", "raise", "ControllerExceptions", "::", "NotFound", ",", "msg", "end", "end" ]
Returns the controller object for initialization and dispatching the request. ==== Returns Class:: The controller class matching the routed request, e.g. Posts. :api: private
[ "Returns", "the", "controller", "object", "for", "initialization", "and", "dispatching", "the", "request", "." ]
b34d3d4fb6da70c2e9e9e56ddccc73f8a3e55e39
https://github.com/wycats/merb/blob/b34d3d4fb6da70c2e9e9e56ddccc73f8a3e55e39/merb-core/lib/merb-core/dispatch/request.rb#L69-L87
22,752
wycats/merb
merb-core/lib/merb-core/dispatch/request.rb
Merb.Request.body_params
def body_params @body_params ||= begin if content_type && content_type.match(Merb::Const::FORM_URL_ENCODED_REGEXP) # or content_type.nil? Merb::Parse.query(raw_post) end end end
ruby
def body_params @body_params ||= begin if content_type && content_type.match(Merb::Const::FORM_URL_ENCODED_REGEXP) # or content_type.nil? Merb::Parse.query(raw_post) end end end
[ "def", "body_params", "@body_params", "||=", "begin", "if", "content_type", "&&", "content_type", ".", "match", "(", "Merb", "::", "Const", "::", "FORM_URL_ENCODED_REGEXP", ")", "# or content_type.nil?", "Merb", "::", "Parse", ".", "query", "(", "raw_post", ")", "end", "end", "end" ]
Parameters passed in the body of the request. Ajax calls from prototype.js and other libraries pass content this way. ==== Returns Hash:: The parameters passed in the body. :api: private
[ "Parameters", "passed", "in", "the", "body", "of", "the", "request", ".", "Ajax", "calls", "from", "prototype", ".", "js", "and", "other", "libraries", "pass", "content", "this", "way", "." ]
b34d3d4fb6da70c2e9e9e56ddccc73f8a3e55e39
https://github.com/wycats/merb/blob/b34d3d4fb6da70c2e9e9e56ddccc73f8a3e55e39/merb-core/lib/merb-core/dispatch/request.rb#L217-L223
22,753
wycats/merb
merb-auth/merb-auth-core/lib/merb-auth-core/authenticated_helper.rb
Merb.AuthenticatedHelper.ensure_authenticated
def ensure_authenticated(*strategies) session.authenticate!(request, params, *strategies) unless session.authenticated? auth = session.authentication if auth.halted? self.headers.merge!(auth.headers) self.status = auth.status throw :halt, auth.body end session.user end
ruby
def ensure_authenticated(*strategies) session.authenticate!(request, params, *strategies) unless session.authenticated? auth = session.authentication if auth.halted? self.headers.merge!(auth.headers) self.status = auth.status throw :halt, auth.body end session.user end
[ "def", "ensure_authenticated", "(", "*", "strategies", ")", "session", ".", "authenticate!", "(", "request", ",", "params", ",", "strategies", ")", "unless", "session", ".", "authenticated?", "auth", "=", "session", ".", "authentication", "if", "auth", ".", "halted?", "self", ".", "headers", ".", "merge!", "(", "auth", ".", "headers", ")", "self", ".", "status", "=", "auth", ".", "status", "throw", ":halt", ",", "auth", ".", "body", "end", "session", ".", "user", "end" ]
This is the main method to use as a before filter. You can call it with options and strategies to use. It will check if a user is logged in, and failing that will run through either specified. @params all are optional. A list of strategies, optionally followed by a options hash. If used with no options, or only the hash, the default strategies will be used see Authentictaion.default_strategy_order. If a list of strategies is passed in, the default strategies are ignored, and the passed in strategies are used in order until either one is found, or all fail. A failed login will result in an Unauthenticated exception being raised. Use the :message key in the options hash to pass in a failure message to the exception. === Example class MyController < Application before :ensure_authenticated, :with => [OpenID,FormPassword, :message => "Failz!"] #... <snip> end
[ "This", "is", "the", "main", "method", "to", "use", "as", "a", "before", "filter", ".", "You", "can", "call", "it", "with", "options", "and", "strategies", "to", "use", ".", "It", "will", "check", "if", "a", "user", "is", "logged", "in", "and", "failing", "that", "will", "run", "through", "either", "specified", "." ]
b34d3d4fb6da70c2e9e9e56ddccc73f8a3e55e39
https://github.com/wycats/merb/blob/b34d3d4fb6da70c2e9e9e56ddccc73f8a3e55e39/merb-auth/merb-auth-core/lib/merb-auth-core/authenticated_helper.rb#L31-L40
22,754
danabr/multipart-parser
lib/multipart_parser/parser.rb
MultipartParser.Parser.callback
def callback(event, buffer = nil, start = nil, the_end = nil) return if !start.nil? && start == the_end if @callbacks.has_key? event @callbacks[event].call(buffer, start, the_end) end end
ruby
def callback(event, buffer = nil, start = nil, the_end = nil) return if !start.nil? && start == the_end if @callbacks.has_key? event @callbacks[event].call(buffer, start, the_end) end end
[ "def", "callback", "(", "event", ",", "buffer", "=", "nil", ",", "start", "=", "nil", ",", "the_end", "=", "nil", ")", "return", "if", "!", "start", ".", "nil?", "&&", "start", "==", "the_end", "if", "@callbacks", ".", "has_key?", "event", "@callbacks", "[", "event", "]", ".", "call", "(", "buffer", ",", "start", ",", "the_end", ")", "end", "end" ]
Issues a callback.
[ "Issues", "a", "callback", "." ]
b93890bb58de80d16c68bbb9131fcc140ca289fe
https://github.com/danabr/multipart-parser/blob/b93890bb58de80d16c68bbb9131fcc140ca289fe/lib/multipart_parser/parser.rb#L225-L230
22,755
wycats/merb
merb-core/lib/merb-core/controller/mixins/responder.rb
Merb.ResponderMixin.content_type=
def content_type=(type) unless Merb.available_mime_types.has_key?(type) raise Merb::ControllerExceptions::NotAcceptable.new("Unknown content_type for response: #{type}") end @_content_type = type mime = Merb.available_mime_types[type] headers["Content-Type"] = mime[:content_type] # merge any format specific response headers mime[:response_headers].each { |k,v| headers[k] ||= v } # if given, use a block to finetune any runtime headers mime[:response_block].call(self) if mime[:response_block] @_content_type end
ruby
def content_type=(type) unless Merb.available_mime_types.has_key?(type) raise Merb::ControllerExceptions::NotAcceptable.new("Unknown content_type for response: #{type}") end @_content_type = type mime = Merb.available_mime_types[type] headers["Content-Type"] = mime[:content_type] # merge any format specific response headers mime[:response_headers].each { |k,v| headers[k] ||= v } # if given, use a block to finetune any runtime headers mime[:response_block].call(self) if mime[:response_block] @_content_type end
[ "def", "content_type", "=", "(", "type", ")", "unless", "Merb", ".", "available_mime_types", ".", "has_key?", "(", "type", ")", "raise", "Merb", "::", "ControllerExceptions", "::", "NotAcceptable", ".", "new", "(", "\"Unknown content_type for response: #{type}\"", ")", "end", "@_content_type", "=", "type", "mime", "=", "Merb", ".", "available_mime_types", "[", "type", "]", "headers", "[", "\"Content-Type\"", "]", "=", "mime", "[", ":content_type", "]", "# merge any format specific response headers", "mime", "[", ":response_headers", "]", ".", "each", "{", "|", "k", ",", "v", "|", "headers", "[", "k", "]", "||=", "v", "}", "# if given, use a block to finetune any runtime headers", "mime", "[", ":response_block", "]", ".", "call", "(", "self", ")", "if", "mime", "[", ":response_block", "]", "@_content_type", "end" ]
Sets the content type of the current response to a value based on a passed in key. The Content-Type header will be set to the first registered header for the mime-type. ==== Parameters type<Symbol>:: The content type. ==== Raises ArgumentError:: type is not in the list of registered mime-types. ==== Returns Symbol:: The content-type that was passed in. :api: plugin
[ "Sets", "the", "content", "type", "of", "the", "current", "response", "to", "a", "value", "based", "on", "a", "passed", "in", "key", ".", "The", "Content", "-", "Type", "header", "will", "be", "set", "to", "the", "first", "registered", "header", "for", "the", "mime", "-", "type", "." ]
b34d3d4fb6da70c2e9e9e56ddccc73f8a3e55e39
https://github.com/wycats/merb/blob/b34d3d4fb6da70c2e9e9e56ddccc73f8a3e55e39/merb-core/lib/merb-core/controller/mixins/responder.rb#L364-L382
22,756
wycats/merb
merb-mailer/lib/merb-mailer/mail_controller.rb
Merb.MailController.render_mail
def render_mail(options = @method) @_missing_templates = false # used to make sure that at least one template was found # If the options are not a hash, normalize to an action hash options = {:action => {:html => options, :text => options}} if !options.is_a?(Hash) # Take care of the options opts_hash = {} opts = options.dup actions = opts.delete(:action) if opts[:action].is_a?(Hash) templates = opts.delete(:template) if opts[:template].is_a?(Hash) # Prepare the options hash for each format # We need to delete anything relating to the other format here # before we try to render the template. [:html, :text].each do |fmt| opts_hash[fmt] = opts.delete(fmt) opts_hash[fmt] ||= actions[fmt] if actions && actions[fmt] opts_hash[:template] = templates[fmt] if templates && templates[fmt] end # Send the result to the mailer { :html => "rawhtml=", :text => "text="}.each do |fmt,meth| begin local_opts = opts.merge(:format => fmt) local_opts.merge!(:layout => false) if opts_hash[fmt].is_a?(String) clear_content value = render opts_hash[fmt], local_opts @mail.send(meth,value) unless value.nil? || value.empty? rescue Merb::ControllerExceptions::TemplateNotFound => e # An error should be logged if no template is found instead of an error raised if @_missing_templates Merb.logger.error(e.message) else @_missing_templates = true end end end @mail end
ruby
def render_mail(options = @method) @_missing_templates = false # used to make sure that at least one template was found # If the options are not a hash, normalize to an action hash options = {:action => {:html => options, :text => options}} if !options.is_a?(Hash) # Take care of the options opts_hash = {} opts = options.dup actions = opts.delete(:action) if opts[:action].is_a?(Hash) templates = opts.delete(:template) if opts[:template].is_a?(Hash) # Prepare the options hash for each format # We need to delete anything relating to the other format here # before we try to render the template. [:html, :text].each do |fmt| opts_hash[fmt] = opts.delete(fmt) opts_hash[fmt] ||= actions[fmt] if actions && actions[fmt] opts_hash[:template] = templates[fmt] if templates && templates[fmt] end # Send the result to the mailer { :html => "rawhtml=", :text => "text="}.each do |fmt,meth| begin local_opts = opts.merge(:format => fmt) local_opts.merge!(:layout => false) if opts_hash[fmt].is_a?(String) clear_content value = render opts_hash[fmt], local_opts @mail.send(meth,value) unless value.nil? || value.empty? rescue Merb::ControllerExceptions::TemplateNotFound => e # An error should be logged if no template is found instead of an error raised if @_missing_templates Merb.logger.error(e.message) else @_missing_templates = true end end end @mail end
[ "def", "render_mail", "(", "options", "=", "@method", ")", "@_missing_templates", "=", "false", "# used to make sure that at least one template was found", "# If the options are not a hash, normalize to an action hash", "options", "=", "{", ":action", "=>", "{", ":html", "=>", "options", ",", ":text", "=>", "options", "}", "}", "if", "!", "options", ".", "is_a?", "(", "Hash", ")", "# Take care of the options", "opts_hash", "=", "{", "}", "opts", "=", "options", ".", "dup", "actions", "=", "opts", ".", "delete", "(", ":action", ")", "if", "opts", "[", ":action", "]", ".", "is_a?", "(", "Hash", ")", "templates", "=", "opts", ".", "delete", "(", ":template", ")", "if", "opts", "[", ":template", "]", ".", "is_a?", "(", "Hash", ")", "# Prepare the options hash for each format", "# We need to delete anything relating to the other format here", "# before we try to render the template.", "[", ":html", ",", ":text", "]", ".", "each", "do", "|", "fmt", "|", "opts_hash", "[", "fmt", "]", "=", "opts", ".", "delete", "(", "fmt", ")", "opts_hash", "[", "fmt", "]", "||=", "actions", "[", "fmt", "]", "if", "actions", "&&", "actions", "[", "fmt", "]", "opts_hash", "[", ":template", "]", "=", "templates", "[", "fmt", "]", "if", "templates", "&&", "templates", "[", "fmt", "]", "end", "# Send the result to the mailer", "{", ":html", "=>", "\"rawhtml=\"", ",", ":text", "=>", "\"text=\"", "}", ".", "each", "do", "|", "fmt", ",", "meth", "|", "begin", "local_opts", "=", "opts", ".", "merge", "(", ":format", "=>", "fmt", ")", "local_opts", ".", "merge!", "(", ":layout", "=>", "false", ")", "if", "opts_hash", "[", "fmt", "]", ".", "is_a?", "(", "String", ")", "clear_content", "value", "=", "render", "opts_hash", "[", "fmt", "]", ",", "local_opts", "@mail", ".", "send", "(", "meth", ",", "value", ")", "unless", "value", ".", "nil?", "||", "value", ".", "empty?", "rescue", "Merb", "::", "ControllerExceptions", "::", "TemplateNotFound", "=>", "e", "# An error should be logged if no template is found instead of an error raised", "if", "@_missing_templates", "Merb", ".", "logger", ".", "error", "(", "e", ".", "message", ")", "else", "@_missing_templates", "=", "true", "end", "end", "end", "@mail", "end" ]
Allows you to render various types of things into the text and HTML parts of an email If you include just text, the email will be sent as plain-text. If you include HTML, the email will be sent as a multi-part email. ==== Parameters options<~to_s, Hash>:: Options for rendering the email or an action name. See examples below for usage. ==== Examples There are a lot of ways to use render_mail, but it works similarly to the default Merb render method. First of all, you'll need to store email files in your app/mailers/views directory. They should be under a directory that matches the name of your mailer (e.g. TestMailer's views would be stored under test_mailer). The files themselves should be named action_name.mime_type.extension. For example, an erb template that should be the HTML part of the email, and rendered from the "foo" action would be named foo.html.erb. The only mime-types currently supported are "html" and "text", which correspond to text/html and text/plain respectively. All template systems supported by your app are available to MailController, and the extensions are the same as they are throughout the rest of Merb. render_mail can take any of the following option patterns: render_mail will attempt to render the current action. If the current action is "foo", this is identical to render_mail :foo. render_mail :foo checks for foo.html.ext and foo.text.ext and applies them as appropriate. render_mail :action => {:html => :foo, :text => :bar} checks for foo.html.ext and bar.text.ext in the view directory of the current controller and adds them to the mail object if found render_mail :template => {:html => "foo/bar", :text => "foo/baz"} checks for bar.html.ext and baz.text.ext in the foo directory and adds them to the mail object if found. render_mail :html => :foo, :text => :bar the same as render_mail :action => {html => :foo, :text => :bar } render_mail :html => "FOO", :text => "BAR" adds the text "FOO" as the html part of the email and the text "BAR" as the text part of the email. The difference between the last two examples is that symbols represent actions to render, while string represent the literal text to render. Note that you can use regular render methods instead of literal strings here, like: render_mail :html => render(:action => :foo) but you're probably better off just using render_mail :action at that point. You can also mix and match: render_mail :action => {:html => :foo}, :text => "BAR" which would be identical to: render_mail :html => :foo, :text => "BAR"
[ "Allows", "you", "to", "render", "various", "types", "of", "things", "into", "the", "text", "and", "HTML", "parts", "of", "an", "email", "If", "you", "include", "just", "text", "the", "email", "will", "be", "sent", "as", "plain", "-", "text", ".", "If", "you", "include", "HTML", "the", "email", "will", "be", "sent", "as", "a", "multi", "-", "part", "email", "." ]
b34d3d4fb6da70c2e9e9e56ddccc73f8a3e55e39
https://github.com/wycats/merb/blob/b34d3d4fb6da70c2e9e9e56ddccc73f8a3e55e39/merb-mailer/lib/merb-mailer/mail_controller.rb#L212-L251
22,757
leonhartX/danger-lgtm
lib/lgtm/plugin.rb
Danger.DangerLgtm.check_lgtm
def check_lgtm(image_url: nil, https_image_only: false) return unless status_report[:errors].length.zero? && status_report[:warnings].length.zero? image_url ||= fetch_image_url(https_image_only: https_image_only) markdown( markdown_template(image_url) ) end
ruby
def check_lgtm(image_url: nil, https_image_only: false) return unless status_report[:errors].length.zero? && status_report[:warnings].length.zero? image_url ||= fetch_image_url(https_image_only: https_image_only) markdown( markdown_template(image_url) ) end
[ "def", "check_lgtm", "(", "image_url", ":", "nil", ",", "https_image_only", ":", "false", ")", "return", "unless", "status_report", "[", ":errors", "]", ".", "length", ".", "zero?", "&&", "status_report", "[", ":warnings", "]", ".", "length", ".", "zero?", "image_url", "||=", "fetch_image_url", "(", "https_image_only", ":", "https_image_only", ")", "markdown", "(", "markdown_template", "(", "image_url", ")", ")", "end" ]
Check status report, say lgtm if no violations Generates a `markdown` of a lgtm image. @param [String] image_url lgtm image url @param [Boolean] https_image_only https image only if true @return [void]
[ "Check", "status", "report", "say", "lgtm", "if", "no", "violations", "Generates", "a", "markdown", "of", "a", "lgtm", "image", "." ]
f45b3a588dd14906c590fd2fd28922b39f272088
https://github.com/leonhartX/danger-lgtm/blob/f45b3a588dd14906c590fd2fd28922b39f272088/lib/lgtm/plugin.rb#L32-L41
22,758
ruby-marc/ruby-marc
lib/marc/xml_parsers.rb
MARC.REXMLReader.each
def each unless block_given? return self.enum_for(:each) else while @parser.has_next? event = @parser.pull # if it's the start of a record element if event.start_element? and strip_ns(event[0]) == 'record' yield build_record end end end end
ruby
def each unless block_given? return self.enum_for(:each) else while @parser.has_next? event = @parser.pull # if it's the start of a record element if event.start_element? and strip_ns(event[0]) == 'record' yield build_record end end end end
[ "def", "each", "unless", "block_given?", "return", "self", ".", "enum_for", "(", ":each", ")", "else", "while", "@parser", ".", "has_next?", "event", "=", "@parser", ".", "pull", "# if it's the start of a record element ", "if", "event", ".", "start_element?", "and", "strip_ns", "(", "event", "[", "0", "]", ")", "==", "'record'", "yield", "build_record", "end", "end", "end", "end" ]
Loop through the MARC records in the XML document
[ "Loop", "through", "the", "MARC", "records", "in", "the", "XML", "document" ]
5b06242c2a4eb5d5ce1665713181debed94ed8a0
https://github.com/ruby-marc/ruby-marc/blob/5b06242c2a4eb5d5ce1665713181debed94ed8a0/lib/marc/xml_parsers.rb#L179-L191
22,759
ruby-marc/ruby-marc
lib/marc/xml_parsers.rb
MARC.REXMLReader.build_record
def build_record record = MARC::Record.new data_field = nil control_field = nil subfield = nil text = '' attrs = nil if Module.constants.index('Nokogiri') and @parser.is_a?(Nokogiri::XML::Reader) datafield = nil cursor = nil open_elements = [] @parser.each do | node | if node.value? && cursor if cursor.is_a?(Symbol) and cursor == :leader record.leader = node.value else cursor.value = node.value end cursor = nil end next unless node.namespace_uri == @ns if open_elements.index(node.local_name.downcase) open_elements.delete(node.local_name.downcase) next else open_elements << node.local_name.downcase end case node.local_name.downcase when "leader" cursor = :leader when "controlfield" record << datafield if datafield datafield = nil control_field = MARC::ControlField.new(node.attribute('tag')) record << control_field cursor = control_field when "datafield" record << datafield if datafield datafield = nil data_field = MARC::DataField.new(node.attribute('tag'), node.attribute('ind1'), node.attribute('ind2')) datafield = data_field when "subfield" raise "No datafield to add to" unless datafield subfield = MARC::Subfield.new(node.attribute('code')) datafield.append(subfield) cursor = subfield when "record" record << datafield if datafield return record end #puts node.name end else while @parser.has_next? event = @parser.pull if event.text? text += REXML::Text::unnormalize(event[0]) next end if event.start_element? text = '' attrs = event[1] case strip_ns(event[0]) when 'controlfield' text = '' control_field = MARC::ControlField.new(attrs['tag']) when 'datafield' text = '' data_field = MARC::DataField.new(attrs['tag'], attrs['ind1'], attrs['ind2']) when 'subfield' text = '' subfield = MARC::Subfield.new(attrs['code']) end end if event.end_element? case strip_ns(event[0]) when 'leader' record.leader = text when 'record' return record when 'controlfield' control_field.value = text record.append(control_field) when 'datafield' record.append(data_field) when 'subfield' subfield.value = text data_field.append(subfield) end end end end end
ruby
def build_record record = MARC::Record.new data_field = nil control_field = nil subfield = nil text = '' attrs = nil if Module.constants.index('Nokogiri') and @parser.is_a?(Nokogiri::XML::Reader) datafield = nil cursor = nil open_elements = [] @parser.each do | node | if node.value? && cursor if cursor.is_a?(Symbol) and cursor == :leader record.leader = node.value else cursor.value = node.value end cursor = nil end next unless node.namespace_uri == @ns if open_elements.index(node.local_name.downcase) open_elements.delete(node.local_name.downcase) next else open_elements << node.local_name.downcase end case node.local_name.downcase when "leader" cursor = :leader when "controlfield" record << datafield if datafield datafield = nil control_field = MARC::ControlField.new(node.attribute('tag')) record << control_field cursor = control_field when "datafield" record << datafield if datafield datafield = nil data_field = MARC::DataField.new(node.attribute('tag'), node.attribute('ind1'), node.attribute('ind2')) datafield = data_field when "subfield" raise "No datafield to add to" unless datafield subfield = MARC::Subfield.new(node.attribute('code')) datafield.append(subfield) cursor = subfield when "record" record << datafield if datafield return record end #puts node.name end else while @parser.has_next? event = @parser.pull if event.text? text += REXML::Text::unnormalize(event[0]) next end if event.start_element? text = '' attrs = event[1] case strip_ns(event[0]) when 'controlfield' text = '' control_field = MARC::ControlField.new(attrs['tag']) when 'datafield' text = '' data_field = MARC::DataField.new(attrs['tag'], attrs['ind1'], attrs['ind2']) when 'subfield' text = '' subfield = MARC::Subfield.new(attrs['code']) end end if event.end_element? case strip_ns(event[0]) when 'leader' record.leader = text when 'record' return record when 'controlfield' control_field.value = text record.append(control_field) when 'datafield' record.append(data_field) when 'subfield' subfield.value = text data_field.append(subfield) end end end end end
[ "def", "build_record", "record", "=", "MARC", "::", "Record", ".", "new", "data_field", "=", "nil", "control_field", "=", "nil", "subfield", "=", "nil", "text", "=", "''", "attrs", "=", "nil", "if", "Module", ".", "constants", ".", "index", "(", "'Nokogiri'", ")", "and", "@parser", ".", "is_a?", "(", "Nokogiri", "::", "XML", "::", "Reader", ")", "datafield", "=", "nil", "cursor", "=", "nil", "open_elements", "=", "[", "]", "@parser", ".", "each", "do", "|", "node", "|", "if", "node", ".", "value?", "&&", "cursor", "if", "cursor", ".", "is_a?", "(", "Symbol", ")", "and", "cursor", "==", ":leader", "record", ".", "leader", "=", "node", ".", "value", "else", "cursor", ".", "value", "=", "node", ".", "value", "end", "cursor", "=", "nil", "end", "next", "unless", "node", ".", "namespace_uri", "==", "@ns", "if", "open_elements", ".", "index", "(", "node", ".", "local_name", ".", "downcase", ")", "open_elements", ".", "delete", "(", "node", ".", "local_name", ".", "downcase", ")", "next", "else", "open_elements", "<<", "node", ".", "local_name", ".", "downcase", "end", "case", "node", ".", "local_name", ".", "downcase", "when", "\"leader\"", "cursor", "=", ":leader", "when", "\"controlfield\"", "record", "<<", "datafield", "if", "datafield", "datafield", "=", "nil", "control_field", "=", "MARC", "::", "ControlField", ".", "new", "(", "node", ".", "attribute", "(", "'tag'", ")", ")", "record", "<<", "control_field", "cursor", "=", "control_field", "when", "\"datafield\"", "record", "<<", "datafield", "if", "datafield", "datafield", "=", "nil", "data_field", "=", "MARC", "::", "DataField", ".", "new", "(", "node", ".", "attribute", "(", "'tag'", ")", ",", "node", ".", "attribute", "(", "'ind1'", ")", ",", "node", ".", "attribute", "(", "'ind2'", ")", ")", "datafield", "=", "data_field", "when", "\"subfield\"", "raise", "\"No datafield to add to\"", "unless", "datafield", "subfield", "=", "MARC", "::", "Subfield", ".", "new", "(", "node", ".", "attribute", "(", "'code'", ")", ")", "datafield", ".", "append", "(", "subfield", ")", "cursor", "=", "subfield", "when", "\"record\"", "record", "<<", "datafield", "if", "datafield", "return", "record", "end", "#puts node.name", "end", "else", "while", "@parser", ".", "has_next?", "event", "=", "@parser", ".", "pull", "if", "event", ".", "text?", "text", "+=", "REXML", "::", "Text", "::", "unnormalize", "(", "event", "[", "0", "]", ")", "next", "end", "if", "event", ".", "start_element?", "text", "=", "''", "attrs", "=", "event", "[", "1", "]", "case", "strip_ns", "(", "event", "[", "0", "]", ")", "when", "'controlfield'", "text", "=", "''", "control_field", "=", "MARC", "::", "ControlField", ".", "new", "(", "attrs", "[", "'tag'", "]", ")", "when", "'datafield'", "text", "=", "''", "data_field", "=", "MARC", "::", "DataField", ".", "new", "(", "attrs", "[", "'tag'", "]", ",", "attrs", "[", "'ind1'", "]", ",", "attrs", "[", "'ind2'", "]", ")", "when", "'subfield'", "text", "=", "''", "subfield", "=", "MARC", "::", "Subfield", ".", "new", "(", "attrs", "[", "'code'", "]", ")", "end", "end", "if", "event", ".", "end_element?", "case", "strip_ns", "(", "event", "[", "0", "]", ")", "when", "'leader'", "record", ".", "leader", "=", "text", "when", "'record'", "return", "record", "when", "'controlfield'", "control_field", ".", "value", "=", "text", "record", ".", "append", "(", "control_field", ")", "when", "'datafield'", "record", ".", "append", "(", "data_field", ")", "when", "'subfield'", "subfield", ".", "value", "=", "text", "data_field", ".", "append", "(", "subfield", ")", "end", "end", "end", "end", "end" ]
will accept parse events until a record has been built up
[ "will", "accept", "parse", "events", "until", "a", "record", "has", "been", "built", "up" ]
5b06242c2a4eb5d5ce1665713181debed94ed8a0
https://github.com/ruby-marc/ruby-marc/blob/5b06242c2a4eb5d5ce1665713181debed94ed8a0/lib/marc/xml_parsers.rb#L200-L297
22,760
leonhartX/danger-lgtm
lib/lgtm/error_handleable.rb
Lgtm.ErrorHandleable.validate_response
def validate_response(response) case response when *SERVER_ERRORS raise ::Lgtm::Errors::UnexpectedError when *CLIENT_ERRORS raise ::Lgtm::Errors::UnexpectedError end end
ruby
def validate_response(response) case response when *SERVER_ERRORS raise ::Lgtm::Errors::UnexpectedError when *CLIENT_ERRORS raise ::Lgtm::Errors::UnexpectedError end end
[ "def", "validate_response", "(", "response", ")", "case", "response", "when", "SERVER_ERRORS", "raise", "::", "Lgtm", "::", "Errors", "::", "UnexpectedError", "when", "CLIENT_ERRORS", "raise", "::", "Lgtm", "::", "Errors", "::", "UnexpectedError", "end", "end" ]
validate_response is response validating @param [Net::HTTPxxx] response Net::HTTP responses @raise ::Lgtm::Errors::UnexpectedError @return [void]
[ "validate_response", "is", "response", "validating" ]
f45b3a588dd14906c590fd2fd28922b39f272088
https://github.com/leonhartX/danger-lgtm/blob/f45b3a588dd14906c590fd2fd28922b39f272088/lib/lgtm/error_handleable.rb#L24-L31
22,761
ruby-marc/ruby-marc
lib/marc/record.rb
MARC.FieldMap.reindex
def reindex @tags = {} self.each_with_index do |field, i| @tags[field.tag] ||= [] @tags[field.tag] << i end @clean = true end
ruby
def reindex @tags = {} self.each_with_index do |field, i| @tags[field.tag] ||= [] @tags[field.tag] << i end @clean = true end
[ "def", "reindex", "@tags", "=", "{", "}", "self", ".", "each_with_index", "do", "|", "field", ",", "i", "|", "@tags", "[", "field", ".", "tag", "]", "||=", "[", "]", "@tags", "[", "field", ".", "tag", "]", "<<", "i", "end", "@clean", "=", "true", "end" ]
Rebuild the HashWithChecksumAttribute with the current values of the fields Array
[ "Rebuild", "the", "HashWithChecksumAttribute", "with", "the", "current", "values", "of", "the", "fields", "Array" ]
5b06242c2a4eb5d5ce1665713181debed94ed8a0
https://github.com/ruby-marc/ruby-marc/blob/5b06242c2a4eb5d5ce1665713181debed94ed8a0/lib/marc/record.rb#L17-L24
22,762
ruby-marc/ruby-marc
lib/marc/record.rb
MARC.Record.fields
def fields(filter=nil) unless filter # Since we're returning the FieldMap object, which the caller # may mutate, we precautionarily mark dirty -- unless it's frozen # immutable. @fields.clean = false unless @fields.frozen? return @fields end @fields.reindex unless @fields.clean flds = [] if filter.is_a?(String) && @fields.tags[filter] @fields.tags[filter].each do |idx| flds << @fields[idx] end elsif filter.is_a?(Array) || filter.is_a?(Range) @fields.each_by_tag(filter) do |tag| flds << tag end end flds end
ruby
def fields(filter=nil) unless filter # Since we're returning the FieldMap object, which the caller # may mutate, we precautionarily mark dirty -- unless it's frozen # immutable. @fields.clean = false unless @fields.frozen? return @fields end @fields.reindex unless @fields.clean flds = [] if filter.is_a?(String) && @fields.tags[filter] @fields.tags[filter].each do |idx| flds << @fields[idx] end elsif filter.is_a?(Array) || filter.is_a?(Range) @fields.each_by_tag(filter) do |tag| flds << tag end end flds end
[ "def", "fields", "(", "filter", "=", "nil", ")", "unless", "filter", "# Since we're returning the FieldMap object, which the caller", "# may mutate, we precautionarily mark dirty -- unless it's frozen", "# immutable.", "@fields", ".", "clean", "=", "false", "unless", "@fields", ".", "frozen?", "return", "@fields", "end", "@fields", ".", "reindex", "unless", "@fields", ".", "clean", "flds", "=", "[", "]", "if", "filter", ".", "is_a?", "(", "String", ")", "&&", "@fields", ".", "tags", "[", "filter", "]", "@fields", ".", "tags", "[", "filter", "]", ".", "each", "do", "|", "idx", "|", "flds", "<<", "@fields", "[", "idx", "]", "end", "elsif", "filter", ".", "is_a?", "(", "Array", ")", "||", "filter", ".", "is_a?", "(", "Range", ")", "@fields", ".", "each_by_tag", "(", "filter", ")", "do", "|", "tag", "|", "flds", "<<", "tag", "end", "end", "flds", "end" ]
Provides a backwards compatible means to access the FieldMap. No argument returns the FieldMap array in entirety. Providing a string, array or range of tags will return an array of fields in the order they appear in the record.
[ "Provides", "a", "backwards", "compatible", "means", "to", "access", "the", "FieldMap", ".", "No", "argument", "returns", "the", "FieldMap", "array", "in", "entirety", ".", "Providing", "a", "string", "array", "or", "range", "of", "tags", "will", "return", "an", "array", "of", "fields", "in", "the", "order", "they", "appear", "in", "the", "record", "." ]
5b06242c2a4eb5d5ce1665713181debed94ed8a0
https://github.com/ruby-marc/ruby-marc/blob/5b06242c2a4eb5d5ce1665713181debed94ed8a0/lib/marc/record.rb#L177-L197
22,763
riboseinc/ribose-ruby
lib/ribose/file_uploader.rb
Ribose.FileUploader.create
def create upload_meta = prepare_to_upload response = upload_to_aws_s3(upload_meta) notify_ribose_file_upload_endpoint(response, upload_meta.fields.key) end
ruby
def create upload_meta = prepare_to_upload response = upload_to_aws_s3(upload_meta) notify_ribose_file_upload_endpoint(response, upload_meta.fields.key) end
[ "def", "create", "upload_meta", "=", "prepare_to_upload", "response", "=", "upload_to_aws_s3", "(", "upload_meta", ")", "notify_ribose_file_upload_endpoint", "(", "response", ",", "upload_meta", ".", "fields", ".", "key", ")", "end" ]
Initialize the file uploader @param space_id [String] The Space UUID @param file [File] The complete path for file @param attributes [Hash] Attributes as a Hash Create a file upload @return [Sawyer::Resource] File upload response.
[ "Initialize", "the", "file", "uploader" ]
3f6ef9060876d17b3c0efd3f0cefdfe3841cece9
https://github.com/riboseinc/ribose-ruby/blob/3f6ef9060876d17b3c0efd3f0cefdfe3841cece9/lib/ribose/file_uploader.rb#L21-L25
22,764
riboseinc/ribose-ruby
lib/ribose/request.rb
Ribose.Request.request
def request(options = {}) parsable = extract_config_option(:parse) != false options[:query] = extract_config_option(:query) || {} response = agent.call(http_method, api_endpoint, data, options) parsable == true ? response.data : response end
ruby
def request(options = {}) parsable = extract_config_option(:parse) != false options[:query] = extract_config_option(:query) || {} response = agent.call(http_method, api_endpoint, data, options) parsable == true ? response.data : response end
[ "def", "request", "(", "options", "=", "{", "}", ")", "parsable", "=", "extract_config_option", "(", ":parse", ")", "!=", "false", "options", "[", ":query", "]", "=", "extract_config_option", "(", ":query", ")", "||", "{", "}", "response", "=", "agent", ".", "call", "(", "http_method", ",", "api_endpoint", ",", "data", ",", "options", ")", "parsable", "==", "true", "?", "response", ".", "data", ":", "response", "end" ]
Initialize a Request @param http_method [Symbol] HTTP verb as sysmbol @param endpoint [String] The relative API endpoint @param data [Hash] Attributes / Options as a Hash @return [Ribose::Request] Make a HTTP Request @param options [Hash] Additonal options hash @return [Sawyer::Resource]
[ "Initialize", "a", "Request" ]
3f6ef9060876d17b3c0efd3f0cefdfe3841cece9
https://github.com/riboseinc/ribose-ruby/blob/3f6ef9060876d17b3c0efd3f0cefdfe3841cece9/lib/ribose/request.rb#L22-L28
22,765
ruby-marc/ruby-marc
lib/marc/datafield.rb
MARC.DataField.to_hash
def to_hash field_hash = {@tag=>{'ind1'=>@indicator1,'ind2'=>@indicator2,'subfields'=>[]}} self.each do |subfield| field_hash[@tag]['subfields'] << {subfield.code=>subfield.value} end field_hash end
ruby
def to_hash field_hash = {@tag=>{'ind1'=>@indicator1,'ind2'=>@indicator2,'subfields'=>[]}} self.each do |subfield| field_hash[@tag]['subfields'] << {subfield.code=>subfield.value} end field_hash end
[ "def", "to_hash", "field_hash", "=", "{", "@tag", "=>", "{", "'ind1'", "=>", "@indicator1", ",", "'ind2'", "=>", "@indicator2", ",", "'subfields'", "=>", "[", "]", "}", "}", "self", ".", "each", "do", "|", "subfield", "|", "field_hash", "[", "@tag", "]", "[", "'subfields'", "]", "<<", "{", "subfield", ".", "code", "=>", "subfield", ".", "value", "}", "end", "field_hash", "end" ]
Turn the variable field and subfields into a hash for MARC-in-JSON
[ "Turn", "the", "variable", "field", "and", "subfields", "into", "a", "hash", "for", "MARC", "-", "in", "-", "JSON" ]
5b06242c2a4eb5d5ce1665713181debed94ed8a0
https://github.com/ruby-marc/ruby-marc/blob/5b06242c2a4eb5d5ce1665713181debed94ed8a0/lib/marc/datafield.rb#L111-L117
22,766
chatterbugapp/cacheql
lib/cacheql/resolve_wrapper.rb
CacheQL.ResolveWrapper.call
def call(obj, args, ctx) cache_key = [CacheQL::Railtie.config.global_key, obj.cache_key, ctx.field.name] CacheQL::Railtie.config.cache.fetch(cache_key, expires_in: CacheQL::Railtie.config.expires_range.sample.minutes) do @resolver_func.call(obj, args, ctx) end end
ruby
def call(obj, args, ctx) cache_key = [CacheQL::Railtie.config.global_key, obj.cache_key, ctx.field.name] CacheQL::Railtie.config.cache.fetch(cache_key, expires_in: CacheQL::Railtie.config.expires_range.sample.minutes) do @resolver_func.call(obj, args, ctx) end end
[ "def", "call", "(", "obj", ",", "args", ",", "ctx", ")", "cache_key", "=", "[", "CacheQL", "::", "Railtie", ".", "config", ".", "global_key", ",", "obj", ".", "cache_key", ",", "ctx", ".", "field", ".", "name", "]", "CacheQL", "::", "Railtie", ".", "config", ".", "cache", ".", "fetch", "(", "cache_key", ",", "expires_in", ":", "CacheQL", "::", "Railtie", ".", "config", ".", "expires_range", ".", "sample", ".", "minutes", ")", "do", "@resolver_func", ".", "call", "(", "obj", ",", "args", ",", "ctx", ")", "end", "end" ]
Resolve function level caching!
[ "Resolve", "function", "level", "caching!" ]
c22f56292e18e11d2483a9afca38bae31b7d7535
https://github.com/chatterbugapp/cacheql/blob/c22f56292e18e11d2483a9afca38bae31b7d7535/lib/cacheql/resolve_wrapper.rb#L12-L18
22,767
solnic/transflow
lib/transflow/transaction.rb
Transflow.Transaction.call
def call(input, options = {}) handler = handler_steps(options).map(&method(:step)).reduce(:>>) handler.call(input) rescue StepError => err raise TransactionFailedError.new(self, err) end
ruby
def call(input, options = {}) handler = handler_steps(options).map(&method(:step)).reduce(:>>) handler.call(input) rescue StepError => err raise TransactionFailedError.new(self, err) end
[ "def", "call", "(", "input", ",", "options", "=", "{", "}", ")", "handler", "=", "handler_steps", "(", "options", ")", ".", "map", "(", "method", "(", ":step", ")", ")", ".", "reduce", "(", ":>>", ")", "handler", ".", "call", "(", "input", ")", "rescue", "StepError", "=>", "err", "raise", "TransactionFailedError", ".", "new", "(", "self", ",", "err", ")", "end" ]
Call the transaction Once transaction is called it will call the first step and its result will be passed to the second step and so on. @example my_container = { add_one: -> i { i + 1 }, add_two: -> j { j + 2 } } transaction = Transflow(container: my_container) { step(:one, with: :add_one) { step(:two, with: :add_two) } } transaction.call(1) # 4 @param [Object] input The input for the first step @param [Hash] options The curry-args map, optional @return [Object] @raises TransactionFailedError @api public
[ "Call", "the", "transaction" ]
725eaa8e24f6077b07d7c4c47ddab1d78ceb5577
https://github.com/solnic/transflow/blob/725eaa8e24f6077b07d7c4c47ddab1d78ceb5577/lib/transflow/transaction.rb#L107-L112
22,768
muffinista/namey
lib/namey/parser.rb
Namey.Parser.create_table
def create_table(name) if ! db.tables.include?(name.to_sym) db.create_table name do String :name, :size => 15 Float :freq index :freq end end end
ruby
def create_table(name) if ! db.tables.include?(name.to_sym) db.create_table name do String :name, :size => 15 Float :freq index :freq end end end
[ "def", "create_table", "(", "name", ")", "if", "!", "db", ".", "tables", ".", "include?", "(", "name", ".", "to_sym", ")", "db", ".", "create_table", "name", "do", "String", ":name", ",", ":size", "=>", "15", "Float", ":freq", "index", ":freq", "end", "end", "end" ]
create a name table
[ "create", "a", "name", "table" ]
10e62cba0bab2603f95ad454f752c1dc93685461
https://github.com/muffinista/namey/blob/10e62cba0bab2603f95ad454f752c1dc93685461/lib/namey/parser.rb#L95-L103
22,769
muffinista/namey
lib/namey/parser.rb
Namey.Parser.cleanup_surname
def cleanup_surname(name) if name.length > 4 name.gsub!(/^Mc(\w+)/) { |s| "Mc#{$1.capitalize}" } name.gsub!(/^Mac(\w+)/) { |s| "Mac#{$1.capitalize}" } name.gsub!(/^Mac(\w+)/) { |s| "Mac#{$1.capitalize}" } name.gsub!(/^Osh(\w+)/) { |s| "O'sh#{$1}" } name.gsub!(/^Van(\w+)/) { |s| "Van#{$1.capitalize}" } name.gsub!(/^Von(\w+)/) { |s| "Von#{$1.capitalize}" } # name.gsub!(/^Dev(\w+)/) { |s| "DeV#{$1}" } end name end
ruby
def cleanup_surname(name) if name.length > 4 name.gsub!(/^Mc(\w+)/) { |s| "Mc#{$1.capitalize}" } name.gsub!(/^Mac(\w+)/) { |s| "Mac#{$1.capitalize}" } name.gsub!(/^Mac(\w+)/) { |s| "Mac#{$1.capitalize}" } name.gsub!(/^Osh(\w+)/) { |s| "O'sh#{$1}" } name.gsub!(/^Van(\w+)/) { |s| "Van#{$1.capitalize}" } name.gsub!(/^Von(\w+)/) { |s| "Von#{$1.capitalize}" } # name.gsub!(/^Dev(\w+)/) { |s| "DeV#{$1}" } end name end
[ "def", "cleanup_surname", "(", "name", ")", "if", "name", ".", "length", ">", "4", "name", ".", "gsub!", "(", "/", "\\w", "/", ")", "{", "|", "s", "|", "\"Mc#{$1.capitalize}\"", "}", "name", ".", "gsub!", "(", "/", "\\w", "/", ")", "{", "|", "s", "|", "\"Mac#{$1.capitalize}\"", "}", "name", ".", "gsub!", "(", "/", "\\w", "/", ")", "{", "|", "s", "|", "\"Mac#{$1.capitalize}\"", "}", "name", ".", "gsub!", "(", "/", "\\w", "/", ")", "{", "|", "s", "|", "\"O'sh#{$1}\"", "}", "name", ".", "gsub!", "(", "/", "\\w", "/", ")", "{", "|", "s", "|", "\"Van#{$1.capitalize}\"", "}", "name", ".", "gsub!", "(", "/", "\\w", "/", ")", "{", "|", "s", "|", "\"Von#{$1.capitalize}\"", "}", "# name.gsub!(/^Dev(\\w+)/) { |s| \"DeV#{$1}\" } ", "end", "name", "end" ]
apply some simple regexps to clean up surnames
[ "apply", "some", "simple", "regexps", "to", "clean", "up", "surnames" ]
10e62cba0bab2603f95ad454f752c1dc93685461
https://github.com/muffinista/namey/blob/10e62cba0bab2603f95ad454f752c1dc93685461/lib/namey/parser.rb#L115-L126
22,770
postmodern/hexdump
lib/hexdump/dumper.rb
Hexdump.Dumper.each_word
def each_word(data,&block) return enum_for(:each_word,data) unless block unless data.respond_to?(:each_byte) raise(ArgumentError,"the data to hexdump must define #each_byte") end if @word_size > 1 word = 0 count = 0 init_shift = if @endian == :big ((@word_size - 1) * 8) else 0 end shift = init_shift data.each_byte do |b| word |= (b << shift) if @endian == :big shift -= 8 else shift += 8 end count += 1 if count >= @word_size yield word word = 0 count = 0 shift = init_shift end end # yield the remaining word yield word if count > 0 else data.each_byte(&block) end end
ruby
def each_word(data,&block) return enum_for(:each_word,data) unless block unless data.respond_to?(:each_byte) raise(ArgumentError,"the data to hexdump must define #each_byte") end if @word_size > 1 word = 0 count = 0 init_shift = if @endian == :big ((@word_size - 1) * 8) else 0 end shift = init_shift data.each_byte do |b| word |= (b << shift) if @endian == :big shift -= 8 else shift += 8 end count += 1 if count >= @word_size yield word word = 0 count = 0 shift = init_shift end end # yield the remaining word yield word if count > 0 else data.each_byte(&block) end end
[ "def", "each_word", "(", "data", ",", "&", "block", ")", "return", "enum_for", "(", ":each_word", ",", "data", ")", "unless", "block", "unless", "data", ".", "respond_to?", "(", ":each_byte", ")", "raise", "(", "ArgumentError", ",", "\"the data to hexdump must define #each_byte\"", ")", "end", "if", "@word_size", ">", "1", "word", "=", "0", "count", "=", "0", "init_shift", "=", "if", "@endian", "==", ":big", "(", "(", "@word_size", "-", "1", ")", "*", "8", ")", "else", "0", "end", "shift", "=", "init_shift", "data", ".", "each_byte", "do", "|", "b", "|", "word", "|=", "(", "b", "<<", "shift", ")", "if", "@endian", "==", ":big", "shift", "-=", "8", "else", "shift", "+=", "8", "end", "count", "+=", "1", "if", "count", ">=", "@word_size", "yield", "word", "word", "=", "0", "count", "=", "0", "shift", "=", "init_shift", "end", "end", "# yield the remaining word", "yield", "word", "if", "count", ">", "0", "else", "data", ".", "each_byte", "(", "block", ")", "end", "end" ]
Creates a new Hexdump dumper. @param [Hash] options Additional options. @option options [Integer] :width (16) The number of bytes to dump for each line. @option options [Integer] :endian (:little) The endianness that the bytes are organized in. Supported endianness include `:little` and `:big`. @option options [Integer] :word_size (1) The number of bytes within a word. @option options [Symbol, Integer] :base (:hexadecimal) The base to print bytes in. Supported bases include, `:hexadecimal`, `:hex`, `16, `:decimal`, `:dec`, `10, `:octal`, `:oct`, `8`, `:binary`, `:bin` and `2`. @option options [Boolean] :ascii (false) Print ascii characters when possible. @raise [ArgumentError] The values for `:base` or `:endian` were unknown. @since 0.2.0 Iterates over every word within the data. @param [#each_byte] data The data containing bytes. @yield [word] The given block will be passed each word within the data. @yieldparam [Integer] An unpacked word from the data. @return [Enumerator] If no block is given, an Enumerator will be returned. @raise [ArgumentError] The given data does not define the `#each_byte` method. @since 0.2.0
[ "Creates", "a", "new", "Hexdump", "dumper", "." ]
e9138798b7e23ca2b9588cc3b254bd54fc334edf
https://github.com/postmodern/hexdump/blob/e9138798b7e23ca2b9588cc3b254bd54fc334edf/lib/hexdump/dumper.rb#L244-L287
22,771
postmodern/hexdump
lib/hexdump/dumper.rb
Hexdump.Dumper.each
def each(data) return enum_for(:each,data) unless block_given? index = 0 count = 0 numeric = [] printable = [] each_word(data) do |word| numeric << format_numeric(word) printable << format_printable(word) count += 1 if count >= @width yield index, numeric, printable numeric.clear printable.clear index += (@width * @word_size) count = 0 end end if count > 0 # yield the remaining data yield index, numeric, printable end end
ruby
def each(data) return enum_for(:each,data) unless block_given? index = 0 count = 0 numeric = [] printable = [] each_word(data) do |word| numeric << format_numeric(word) printable << format_printable(word) count += 1 if count >= @width yield index, numeric, printable numeric.clear printable.clear index += (@width * @word_size) count = 0 end end if count > 0 # yield the remaining data yield index, numeric, printable end end
[ "def", "each", "(", "data", ")", "return", "enum_for", "(", ":each", ",", "data", ")", "unless", "block_given?", "index", "=", "0", "count", "=", "0", "numeric", "=", "[", "]", "printable", "=", "[", "]", "each_word", "(", "data", ")", "do", "|", "word", "|", "numeric", "<<", "format_numeric", "(", "word", ")", "printable", "<<", "format_printable", "(", "word", ")", "count", "+=", "1", "if", "count", ">=", "@width", "yield", "index", ",", "numeric", ",", "printable", "numeric", ".", "clear", "printable", ".", "clear", "index", "+=", "(", "@width", "*", "@word_size", ")", "count", "=", "0", "end", "end", "if", "count", ">", "0", "# yield the remaining data", "yield", "index", ",", "numeric", ",", "printable", "end", "end" ]
Iterates over the hexdump. @param [#each_byte] data The data to be hexdumped. @yield [index,numeric,printable] The given block will be passed the hexdump break-down of each segment. @yieldparam [Integer] index The index of the hexdumped segment. @yieldparam [Array<String>] numeric The numeric representation of the segment. @yieldparam [Array<String>] printable The printable representation of the segment. @return [Enumerator] If no block is given, an Enumerator will be returned. @since 0.2.0
[ "Iterates", "over", "the", "hexdump", "." ]
e9138798b7e23ca2b9588cc3b254bd54fc334edf
https://github.com/postmodern/hexdump/blob/e9138798b7e23ca2b9588cc3b254bd54fc334edf/lib/hexdump/dumper.rb#L313-L343
22,772
postmodern/hexdump
lib/hexdump/dumper.rb
Hexdump.Dumper.dump
def dump(data,output=$stdout) unless output.respond_to?(:<<) raise(ArgumentError,"output must support the #<< method") end bytes_segment_width = ((@width * @format_width) + @width) line_format = "%.8x %-#{bytes_segment_width}s |%s|\n" index = 0 count = 0 numeric = '' printable = '' each_word(data) do |word| numeric << format_numeric(word) << ' ' printable << format_printable(word) count += 1 if count >= @width output << sprintf(line_format,index,numeric,printable) numeric = '' printable = '' index += (@width * @word_size) count = 0 end end if count > 0 # output the remaining line output << sprintf(line_format,index,numeric,printable) end end
ruby
def dump(data,output=$stdout) unless output.respond_to?(:<<) raise(ArgumentError,"output must support the #<< method") end bytes_segment_width = ((@width * @format_width) + @width) line_format = "%.8x %-#{bytes_segment_width}s |%s|\n" index = 0 count = 0 numeric = '' printable = '' each_word(data) do |word| numeric << format_numeric(word) << ' ' printable << format_printable(word) count += 1 if count >= @width output << sprintf(line_format,index,numeric,printable) numeric = '' printable = '' index += (@width * @word_size) count = 0 end end if count > 0 # output the remaining line output << sprintf(line_format,index,numeric,printable) end end
[ "def", "dump", "(", "data", ",", "output", "=", "$stdout", ")", "unless", "output", ".", "respond_to?", "(", ":<<", ")", "raise", "(", "ArgumentError", ",", "\"output must support the #<< method\"", ")", "end", "bytes_segment_width", "=", "(", "(", "@width", "*", "@format_width", ")", "+", "@width", ")", "line_format", "=", "\"%.8x %-#{bytes_segment_width}s |%s|\\n\"", "index", "=", "0", "count", "=", "0", "numeric", "=", "''", "printable", "=", "''", "each_word", "(", "data", ")", "do", "|", "word", "|", "numeric", "<<", "format_numeric", "(", "word", ")", "<<", "' '", "printable", "<<", "format_printable", "(", "word", ")", "count", "+=", "1", "if", "count", ">=", "@width", "output", "<<", "sprintf", "(", "line_format", ",", "index", ",", "numeric", ",", "printable", ")", "numeric", "=", "''", "printable", "=", "''", "index", "+=", "(", "@width", "*", "@word_size", ")", "count", "=", "0", "end", "end", "if", "count", ">", "0", "# output the remaining line", "output", "<<", "sprintf", "(", "line_format", ",", "index", ",", "numeric", ",", "printable", ")", "end", "end" ]
Dumps the hexdump. @param [#each_byte] data The data to be hexdumped. @param [#<<] output The output to dump the hexdump to. @return [nil] @raise [ArgumentError] The output value does not support the `#<<` method. @since 0.2.0
[ "Dumps", "the", "hexdump", "." ]
e9138798b7e23ca2b9588cc3b254bd54fc334edf
https://github.com/postmodern/hexdump/blob/e9138798b7e23ca2b9588cc3b254bd54fc334edf/lib/hexdump/dumper.rb#L361-L396
22,773
postmodern/hexdump
lib/hexdump/dumper.rb
Hexdump.Dumper.format_printable
def format_printable(word) if @word_size == 1 PRINTABLE[word] elsif (RUBY_VERSION > '1.9.' && (word >= -2 && word <= 0x7fffffff)) begin word.chr(Encoding::UTF_8) rescue RangeError UNPRINTABLE end else UNPRINTABLE end end
ruby
def format_printable(word) if @word_size == 1 PRINTABLE[word] elsif (RUBY_VERSION > '1.9.' && (word >= -2 && word <= 0x7fffffff)) begin word.chr(Encoding::UTF_8) rescue RangeError UNPRINTABLE end else UNPRINTABLE end end
[ "def", "format_printable", "(", "word", ")", "if", "@word_size", "==", "1", "PRINTABLE", "[", "word", "]", "elsif", "(", "RUBY_VERSION", ">", "'1.9.'", "&&", "(", "word", ">=", "-", "2", "&&", "word", "<=", "0x7fffffff", ")", ")", "begin", "word", ".", "chr", "(", "Encoding", "::", "UTF_8", ")", "rescue", "RangeError", "UNPRINTABLE", "end", "else", "UNPRINTABLE", "end", "end" ]
Converts a word into a printable String. @param [Integer] word The word to convert. @return [String] The printable representation of the word. @since 0.2.0
[ "Converts", "a", "word", "into", "a", "printable", "String", "." ]
e9138798b7e23ca2b9588cc3b254bd54fc334edf
https://github.com/postmodern/hexdump/blob/e9138798b7e23ca2b9588cc3b254bd54fc334edf/lib/hexdump/dumper.rb#L434-L446
22,774
Beagle123/visualruby
lib/treeview/columns/CellRendererCombo.rb
VR::Col::Ren.CellRendererCombo.set_model
def set_model(vr_combo) # :nodoc: self.model = Gtk::ListStore.new(String) vr_combo.selections.each { |s| r = self.model.append ; r[0] = s } self.text_column = 0 end
ruby
def set_model(vr_combo) # :nodoc: self.model = Gtk::ListStore.new(String) vr_combo.selections.each { |s| r = self.model.append ; r[0] = s } self.text_column = 0 end
[ "def", "set_model", "(", "vr_combo", ")", "# :nodoc:", "self", ".", "model", "=", "Gtk", "::", "ListStore", ".", "new", "(", "String", ")", "vr_combo", ".", "selections", ".", "each", "{", "|", "s", "|", "r", "=", "self", ".", "model", ".", "append", ";", "r", "[", "0", "]", "=", "s", "}", "self", ".", "text_column", "=", "0", "end" ]
This sets the renderer's "editable" property to true, and makes it save the edited value to the model. When a user edits a row in the ListView the value isn't automatically saved by Gtk. This method groups both actions together, so setting edit_save=true, allows both editing and saving of the field. Also, you can use VR::ListView and VR::TreeView's convenience methods to envoke call this method: NAME = 0 ADDR = 1 @view.set_attr([NAME, ADDR], :edit_save => true) #sets model_col = 0, 1 @view.set_edit_save( 0 => true, 1 => false) is_editable = boolean
[ "This", "sets", "the", "renderer", "s", "editable", "property", "to", "true", "and", "makes", "it", "save", "the", "edited", "value", "to", "the", "model", ".", "When", "a", "user", "edits", "a", "row", "in", "the", "ListView", "the", "value", "isn", "t", "automatically", "saved", "by", "Gtk", ".", "This", "method", "groups", "both", "actions", "together", "so", "setting", "edit_save", "=", "true", "allows", "both", "editing", "and", "saving", "of", "the", "field", "." ]
245e22864c9d7c7c4e6f92562447caa5d6a705a9
https://github.com/Beagle123/visualruby/blob/245e22864c9d7c7c4e6f92562447caa5d6a705a9/lib/treeview/columns/CellRendererCombo.rb#L58-L62
22,775
Beagle123/visualruby
lib/treeview/FileTreeView.rb
VR.FileTreeView.refresh
def refresh(flags={}) @root = flags[:root] if flags[:root] open_folders = flags[:open_folders] ? flags[:open_folders] : get_open_folders() model.clear @root_iter = add_file(@root, nil) open_folders([@root_iter[:path]]) open_folders(open_folders) end
ruby
def refresh(flags={}) @root = flags[:root] if flags[:root] open_folders = flags[:open_folders] ? flags[:open_folders] : get_open_folders() model.clear @root_iter = add_file(@root, nil) open_folders([@root_iter[:path]]) open_folders(open_folders) end
[ "def", "refresh", "(", "flags", "=", "{", "}", ")", "@root", "=", "flags", "[", ":root", "]", "if", "flags", "[", ":root", "]", "open_folders", "=", "flags", "[", ":open_folders", "]", "?", "flags", "[", ":open_folders", "]", ":", "get_open_folders", "(", ")", "model", ".", "clear", "@root_iter", "=", "add_file", "(", "@root", ",", "nil", ")", "open_folders", "(", "[", "@root_iter", "[", ":path", "]", "]", ")", "open_folders", "(", "open_folders", ")", "end" ]
FileTreeView creates a TreeView of files with folders and icons. Often you should subclass this class for a particular use. @param [String] root Root folder of the tree @param [String] icon_path Path to a folder where icons are stored. See VR::IconHash @param [String] glob Glob designating the files to be included. Google: "ruby glob" for more. @param [Proc] validate_block Block that limits files and folders to include. When block returns true file is includud. (false = excluded) Refresh the file tree, optionally with a new root folder, and optionally opening an array of folders. @param [Hash] flags You can change the root and/or open an array of folders. @option flags [String] :root Path to root folder to open @option flags [Array] :open_folders A list of folders to open, possibly from #get_open_folders. Default: the currently open folders, so the tree doesn't collapse when refreshed.
[ "FileTreeView", "creates", "a", "TreeView", "of", "files", "with", "folders", "and", "icons", ".", "Often", "you", "should", "subclass", "this", "class", "for", "a", "particular", "use", "." ]
245e22864c9d7c7c4e6f92562447caa5d6a705a9
https://github.com/Beagle123/visualruby/blob/245e22864c9d7c7c4e6f92562447caa5d6a705a9/lib/treeview/FileTreeView.rb#L45-L52
22,776
Beagle123/visualruby
lib/treeview/FileTreeView.rb
VR.FileTreeView.open_folders
def open_folders(folder_paths) model.each do |model, path, iter| if folder_paths.include?(iter[id(:path)]) fill_folder(iter) # expand_row(path, false) # self__row_expanded(self, iter, path) end end end
ruby
def open_folders(folder_paths) model.each do |model, path, iter| if folder_paths.include?(iter[id(:path)]) fill_folder(iter) # expand_row(path, false) # self__row_expanded(self, iter, path) end end end
[ "def", "open_folders", "(", "folder_paths", ")", "model", ".", "each", "do", "|", "model", ",", "path", ",", "iter", "|", "if", "folder_paths", ".", "include?", "(", "iter", "[", "id", "(", ":path", ")", "]", ")", "fill_folder", "(", "iter", ")", "# expand_row(path, false)", "# self__row_expanded(self, iter, path) \r", "end", "end", "end" ]
Opens a list of folders. @param [Array] folder_paths Array of Strings of folder names to expand, possibly from the #get_open_folders method.
[ "Opens", "a", "list", "of", "folders", "." ]
245e22864c9d7c7c4e6f92562447caa5d6a705a9
https://github.com/Beagle123/visualruby/blob/245e22864c9d7c7c4e6f92562447caa5d6a705a9/lib/treeview/FileTreeView.rb#L94-L102
22,777
Beagle123/visualruby
lib/treeview/FileTreeView.rb
VR.FileTreeView.add_file
def add_file(filename, parent = @root_iter) my_path = File.dirname(filename) model.each do |model, path, iter| return if iter[id(:path)] == filename # duplicate parent = iter if iter[id(:path)] == my_path end fn = filename.gsub("\\", "/") parent[id(:empty)] = false unless parent.nil? child = add_row(parent) child[:pix] = @icons.get_icon(File.directory?(fn) ? "x.folder" : fn) if @icons child[:file_name] = File.basename(fn) child[:path] = fn if File.directory?(fn) child[:sort_on] = "0" + child[:file_name] child[:empty] = true add_row(child) # dummy record so expander appears else child[id(:sort_on)] = "1" + child[id(:file_name)] end return child end
ruby
def add_file(filename, parent = @root_iter) my_path = File.dirname(filename) model.each do |model, path, iter| return if iter[id(:path)] == filename # duplicate parent = iter if iter[id(:path)] == my_path end fn = filename.gsub("\\", "/") parent[id(:empty)] = false unless parent.nil? child = add_row(parent) child[:pix] = @icons.get_icon(File.directory?(fn) ? "x.folder" : fn) if @icons child[:file_name] = File.basename(fn) child[:path] = fn if File.directory?(fn) child[:sort_on] = "0" + child[:file_name] child[:empty] = true add_row(child) # dummy record so expander appears else child[id(:sort_on)] = "1" + child[id(:file_name)] end return child end
[ "def", "add_file", "(", "filename", ",", "parent", "=", "@root_iter", ")", "my_path", "=", "File", ".", "dirname", "(", "filename", ")", "model", ".", "each", "do", "|", "model", ",", "path", ",", "iter", "|", "return", "if", "iter", "[", "id", "(", ":path", ")", "]", "==", "filename", "# duplicate", "parent", "=", "iter", "if", "iter", "[", "id", "(", ":path", ")", "]", "==", "my_path", "end", "fn", "=", "filename", ".", "gsub", "(", "\"\\\\\"", ",", "\"/\"", ")", "parent", "[", "id", "(", ":empty", ")", "]", "=", "false", "unless", "parent", ".", "nil?", "child", "=", "add_row", "(", "parent", ")", "child", "[", ":pix", "]", "=", "@icons", ".", "get_icon", "(", "File", ".", "directory?", "(", "fn", ")", "?", "\"x.folder\"", ":", "fn", ")", "if", "@icons", "child", "[", ":file_name", "]", "=", "File", ".", "basename", "(", "fn", ")", "child", "[", ":path", "]", "=", "fn", "if", "File", ".", "directory?", "(", "fn", ")", "child", "[", ":sort_on", "]", "=", "\"0\"", "+", "child", "[", ":file_name", "]", "child", "[", ":empty", "]", "=", "true", "add_row", "(", "child", ")", "# dummy record so expander appears \r", "else", "child", "[", "id", "(", ":sort_on", ")", "]", "=", "\"1\"", "+", "child", "[", "id", "(", ":file_name", ")", "]", "end", "return", "child", "end" ]
Adds a file to the tree under a given parent iter. @param [String] filename Full path to file to add.
[ "Adds", "a", "file", "to", "the", "tree", "under", "a", "given", "parent", "iter", "." ]
245e22864c9d7c7c4e6f92562447caa5d6a705a9
https://github.com/Beagle123/visualruby/blob/245e22864c9d7c7c4e6f92562447caa5d6a705a9/lib/treeview/FileTreeView.rb#L106-L126
22,778
muffinista/namey
lib/namey/generator.rb
Namey.Generator.generate
def generate(params = {}) params = { :type => random_gender, :frequency => :common, :with_surname => true }.merge(params) if ! ( params[:min_freq] || params[:max_freq] ) params[:min_freq], params[:max_freq] = frequency_values(params[:frequency]) else # # do some basic data validation in case someone is being a knucklehead # params[:min_freq] = params[:min_freq].to_i params[:max_freq] = params[:max_freq].to_i params[:max_freq] = params[:min_freq] + 1 if params[:max_freq] <= params[:min_freq] # max_freq needs to be at least 4 to get any results back, # because the most common male name only rates 3.3 # JAMES 3.318 3.318 1 params[:max_freq] = 4 if params[:max_freq] < 4 end name = get_name(params[:type], params[:min_freq], params[:max_freq]) # add surname if needed if params[:type] != :surname && params[:with_surname] == true name = "#{name} #{get_name(:surname, params[:min_freq], params[:max_freq])}" end name end
ruby
def generate(params = {}) params = { :type => random_gender, :frequency => :common, :with_surname => true }.merge(params) if ! ( params[:min_freq] || params[:max_freq] ) params[:min_freq], params[:max_freq] = frequency_values(params[:frequency]) else # # do some basic data validation in case someone is being a knucklehead # params[:min_freq] = params[:min_freq].to_i params[:max_freq] = params[:max_freq].to_i params[:max_freq] = params[:min_freq] + 1 if params[:max_freq] <= params[:min_freq] # max_freq needs to be at least 4 to get any results back, # because the most common male name only rates 3.3 # JAMES 3.318 3.318 1 params[:max_freq] = 4 if params[:max_freq] < 4 end name = get_name(params[:type], params[:min_freq], params[:max_freq]) # add surname if needed if params[:type] != :surname && params[:with_surname] == true name = "#{name} #{get_name(:surname, params[:min_freq], params[:max_freq])}" end name end
[ "def", "generate", "(", "params", "=", "{", "}", ")", "params", "=", "{", ":type", "=>", "random_gender", ",", ":frequency", "=>", ":common", ",", ":with_surname", "=>", "true", "}", ".", "merge", "(", "params", ")", "if", "!", "(", "params", "[", ":min_freq", "]", "||", "params", "[", ":max_freq", "]", ")", "params", "[", ":min_freq", "]", ",", "params", "[", ":max_freq", "]", "=", "frequency_values", "(", "params", "[", ":frequency", "]", ")", "else", "#", "# do some basic data validation in case someone is being a knucklehead", "#", "params", "[", ":min_freq", "]", "=", "params", "[", ":min_freq", "]", ".", "to_i", "params", "[", ":max_freq", "]", "=", "params", "[", ":max_freq", "]", ".", "to_i", "params", "[", ":max_freq", "]", "=", "params", "[", ":min_freq", "]", "+", "1", "if", "params", "[", ":max_freq", "]", "<=", "params", "[", ":min_freq", "]", "# max_freq needs to be at least 4 to get any results back,", "# because the most common male name only rates 3.3", "# JAMES 3.318 3.318 1", "params", "[", ":max_freq", "]", "=", "4", "if", "params", "[", ":max_freq", "]", "<", "4", "end", "name", "=", "get_name", "(", "params", "[", ":type", "]", ",", "params", "[", ":min_freq", "]", ",", "params", "[", ":max_freq", "]", ")", "# add surname if needed", "if", "params", "[", ":type", "]", "!=", ":surname", "&&", "params", "[", ":with_surname", "]", "==", "true", "name", "=", "\"#{name} #{get_name(:surname, params[:min_freq], params[:max_freq])}\"", "end", "name", "end" ]
generate a name using the supplied parameter hash * +params+ - A hash of parameters ==== Params * +:type+ - :male, :female, :surname * +:frequency+ - :common, :rare, :all * +:min_freq+ - raw frequency values to specify a precise range * +:max_freq+ - raw frequency values to specify a precise range
[ "generate", "a", "name", "using", "the", "supplied", "parameter", "hash" ]
10e62cba0bab2603f95ad454f752c1dc93685461
https://github.com/muffinista/namey/blob/10e62cba0bab2603f95ad454f752c1dc93685461/lib/namey/generator.rb#L67-L101
22,779
muffinista/namey
lib/namey/generator.rb
Namey.Generator.random_sort
def random_sort(set) set.order do # this is a bit of a hack obviously, but it checks the sort of # data engine being used to figure out how to randomly sort if set.class.name !~ /mysql/i random.function else rand.function end end end
ruby
def random_sort(set) set.order do # this is a bit of a hack obviously, but it checks the sort of # data engine being used to figure out how to randomly sort if set.class.name !~ /mysql/i random.function else rand.function end end end
[ "def", "random_sort", "(", "set", ")", "set", ".", "order", "do", "# this is a bit of a hack obviously, but it checks the sort of", "# data engine being used to figure out how to randomly sort", "if", "set", ".", "class", ".", "name", "!~", "/", "/i", "random", ".", "function", "else", "rand", ".", "function", "end", "end", "end" ]
randomly sort a result set according to the data adapter class
[ "randomly", "sort", "a", "result", "set", "according", "to", "the", "data", "adapter", "class" ]
10e62cba0bab2603f95ad454f752c1dc93685461
https://github.com/muffinista/namey/blob/10e62cba0bab2603f95ad454f752c1dc93685461/lib/namey/generator.rb#L141-L151
22,780
muffinista/namey
lib/namey/generator.rb
Namey.Generator.get_name
def get_name(src, min_freq = 0, max_freq = 100) tmp = random_sort(@db[src.to_sym].filter{(freq >= min_freq) & (freq <= max_freq)}) tmp.count > 0 ? tmp.first[:name] : nil end
ruby
def get_name(src, min_freq = 0, max_freq = 100) tmp = random_sort(@db[src.to_sym].filter{(freq >= min_freq) & (freq <= max_freq)}) tmp.count > 0 ? tmp.first[:name] : nil end
[ "def", "get_name", "(", "src", ",", "min_freq", "=", "0", ",", "max_freq", "=", "100", ")", "tmp", "=", "random_sort", "(", "@db", "[", "src", ".", "to_sym", "]", ".", "filter", "{", "(", "freq", ">=", "min_freq", ")", "&", "(", "freq", "<=", "max_freq", ")", "}", ")", "tmp", ".", "count", ">", "0", "?", "tmp", ".", "first", "[", ":name", "]", ":", "nil", "end" ]
query the db for a name
[ "query", "the", "db", "for", "a", "name" ]
10e62cba0bab2603f95ad454f752c1dc93685461
https://github.com/muffinista/namey/blob/10e62cba0bab2603f95ad454f752c1dc93685461/lib/namey/generator.rb#L156-L159
22,781
schmich/kappa
lib/kappa/video.rb
Twitch::V2.Videos.top
def top(options = {}, &block) params = {} if options[:game] params[:game] = options[:game] end period = options[:period] || :week if ![:week, :month, :all].include?(period) raise ArgumentError, 'period' end params[:period] = period.to_s return @query.connection.accumulate( :path => 'videos/top', :params => params, :json => 'videos', :create => -> hash { Video.new(hash, @query) }, :limit => options[:limit], :offset => options[:offset], &block ) end
ruby
def top(options = {}, &block) params = {} if options[:game] params[:game] = options[:game] end period = options[:period] || :week if ![:week, :month, :all].include?(period) raise ArgumentError, 'period' end params[:period] = period.to_s return @query.connection.accumulate( :path => 'videos/top', :params => params, :json => 'videos', :create => -> hash { Video.new(hash, @query) }, :limit => options[:limit], :offset => options[:offset], &block ) end
[ "def", "top", "(", "options", "=", "{", "}", ",", "&", "block", ")", "params", "=", "{", "}", "if", "options", "[", ":game", "]", "params", "[", ":game", "]", "=", "options", "[", ":game", "]", "end", "period", "=", "options", "[", ":period", "]", "||", ":week", "if", "!", "[", ":week", ",", ":month", ",", ":all", "]", ".", "include?", "(", "period", ")", "raise", "ArgumentError", ",", "'period'", "end", "params", "[", ":period", "]", "=", "period", ".", "to_s", "return", "@query", ".", "connection", ".", "accumulate", "(", ":path", "=>", "'videos/top'", ",", ":params", "=>", "params", ",", ":json", "=>", "'videos'", ",", ":create", "=>", "->", "hash", "{", "Video", ".", "new", "(", "hash", ",", "@query", ")", "}", ",", ":limit", "=>", "options", "[", ":limit", "]", ",", ":offset", "=>", "options", "[", ":offset", "]", ",", "block", ")", "end" ]
Get the list of most popular videos based on view count. @note The number of videos returned is potentially very large, so it's recommended that you specify a `:limit`. @example Twitch.videos.top @example Twitch.videos.top(:period => :month, :game => 'Super Meat Boy') @example Twitch.videos.top(:period => :all, :limit => 10) @example Twitch.videos.top(:period => :all) do |video| next if video.view_count < 10000 puts video.url end @param options [Hash] Filter criteria. @option options [Symbol] :period (:week) Return videos only in this time period. Valid values are `:week`, `:month`, `:all`. @option options [String] :game (nil) Return videos only for this game. @option options [Fixnum] :limit (nil) Limit on the number of results returned. @option options [Fixnum] :offset (0) Offset into the result set to begin enumeration. @yield Optional. If a block is given, each top video is yielded. @yieldparam [Video] video Current video. @see https://github.com/justintv/Twitch-API/blob/master/v2_resources/videos.md#get-videostop GET /videos/top @raise [ArgumentError] If `:period` is not one of `:week`, `:month`, or `:all`. @return [Array<Video>] Top videos, if no block is given. @return [nil] If a block is given.
[ "Get", "the", "list", "of", "most", "popular", "videos", "based", "on", "view", "count", "." ]
09b2a8374257d7088292060bda8131f4b96b7867
https://github.com/schmich/kappa/blob/09b2a8374257d7088292060bda8131f4b96b7867/lib/kappa/video.rb#L154-L177
22,782
schmich/kappa
lib/kappa/video.rb
Twitch::V2.Videos.for_channel
def for_channel(channel, options = {}) if channel.respond_to?(:name) channel_name = channel.name else channel_name = channel.to_s end params = {} type = options[:type] || :highlights if !type.nil? if ![:broadcasts, :highlights].include?(type) raise ArgumentError, 'type' end params[:broadcasts] = (type == :broadcasts) end name = CGI.escape(channel_name) return @query.connection.accumulate( :path => "channels/#{name}/videos", :params => params, :json => 'videos', :create => -> hash { Video.new(hash, @query) }, :limit => options[:limit], :offset => options[:offset] ) end
ruby
def for_channel(channel, options = {}) if channel.respond_to?(:name) channel_name = channel.name else channel_name = channel.to_s end params = {} type = options[:type] || :highlights if !type.nil? if ![:broadcasts, :highlights].include?(type) raise ArgumentError, 'type' end params[:broadcasts] = (type == :broadcasts) end name = CGI.escape(channel_name) return @query.connection.accumulate( :path => "channels/#{name}/videos", :params => params, :json => 'videos', :create => -> hash { Video.new(hash, @query) }, :limit => options[:limit], :offset => options[:offset] ) end
[ "def", "for_channel", "(", "channel", ",", "options", "=", "{", "}", ")", "if", "channel", ".", "respond_to?", "(", ":name", ")", "channel_name", "=", "channel", ".", "name", "else", "channel_name", "=", "channel", ".", "to_s", "end", "params", "=", "{", "}", "type", "=", "options", "[", ":type", "]", "||", ":highlights", "if", "!", "type", ".", "nil?", "if", "!", "[", ":broadcasts", ",", ":highlights", "]", ".", "include?", "(", "type", ")", "raise", "ArgumentError", ",", "'type'", "end", "params", "[", ":broadcasts", "]", "=", "(", "type", "==", ":broadcasts", ")", "end", "name", "=", "CGI", ".", "escape", "(", "channel_name", ")", "return", "@query", ".", "connection", ".", "accumulate", "(", ":path", "=>", "\"channels/#{name}/videos\"", ",", ":params", "=>", "params", ",", ":json", "=>", "'videos'", ",", ":create", "=>", "->", "hash", "{", "Video", ".", "new", "(", "hash", ",", "@query", ")", "}", ",", ":limit", "=>", "options", "[", ":limit", "]", ",", ":offset", "=>", "options", "[", ":offset", "]", ")", "end" ]
Get the videos for a channel, most recently created first. @example v = Twitch.videos.for_channel('dreamhacktv') @example v = Twitch.videos.for_channel('dreamhacktv', :type => :highlights, :limit => 10) @example Twitch.videos.for_channel('dreamhacktv') do |video| next if video.view_count < 10000 puts video.url end @param options [Hash] Filter criteria. @option options [Symbol] :type (:highlights) The type of videos to return. Valid values are `:broadcasts`, `:highlights`. @option options [Fixnum] :limit (nil) Limit on the number of results returned. @option options [Fixnum] :offset (0) Offset into the result set to begin enumeration. @yield Optional. If a block is given, each video is yielded. @yieldparam [Video] video Current video. @see Channel#videos Channel#videos @see https://github.com/justintv/Twitch-API/blob/master/v2_resources/videos.md#get-channelschannelvideos GET /channels/:channel/videos @raise [ArgumentError] If `:type` is not one of `:broadcasts` or `:highlights`. @return [Array<Video>] Videos for the channel, if no block is given. @return [nil] If a block is given.
[ "Get", "the", "videos", "for", "a", "channel", "most", "recently", "created", "first", "." ]
09b2a8374257d7088292060bda8131f4b96b7867
https://github.com/schmich/kappa/blob/09b2a8374257d7088292060bda8131f4b96b7867/lib/kappa/video.rb#L200-L227
22,783
schmich/kappa
lib/kappa/user.rb
Twitch::V2.User.following
def following(options = {}, &block) name = CGI.escape(@name) return @query.connection.accumulate( :path => "users/#{name}/follows/channels", :json => 'follows', :sub_json => 'channel', :create => -> hash { Channel.new(hash, @query) }, :limit => options[:limit], :offset => options[:offset], &block ) end
ruby
def following(options = {}, &block) name = CGI.escape(@name) return @query.connection.accumulate( :path => "users/#{name}/follows/channels", :json => 'follows', :sub_json => 'channel', :create => -> hash { Channel.new(hash, @query) }, :limit => options[:limit], :offset => options[:offset], &block ) end
[ "def", "following", "(", "options", "=", "{", "}", ",", "&", "block", ")", "name", "=", "CGI", ".", "escape", "(", "@name", ")", "return", "@query", ".", "connection", ".", "accumulate", "(", ":path", "=>", "\"users/#{name}/follows/channels\"", ",", ":json", "=>", "'follows'", ",", ":sub_json", "=>", "'channel'", ",", ":create", "=>", "->", "hash", "{", "Channel", ".", "new", "(", "hash", ",", "@query", ")", "}", ",", ":limit", "=>", "options", "[", ":limit", "]", ",", ":offset", "=>", "options", "[", ":offset", "]", ",", "block", ")", "end" ]
Get the channels the user is currently following. @example user.following(:limit => 10) @example user.following do |channel| next if channel.game_name !~ /starcraft/i puts channel.display_name end @param options [Hash] Filter criteria. @option options [Fixnum] :limit (nil) Limit on the number of results returned. @option options [Fixnum] :offset (0) Offset into the result set to begin enumeration. @yield Optional. If a block is given, each followed channel is yielded. @yieldparam [Channel] channel Current channel. @see #following? @see https://github.com/justintv/Twitch-API/blob/master/v2_resources/follows.md#get-usersuserfollowschannels GET /users/:user/follows/channels @return [Array<Channel>] Channels the user is currently following, if no block is given. @return [nil] If a block is given.
[ "Get", "the", "channels", "the", "user", "is", "currently", "following", "." ]
09b2a8374257d7088292060bda8131f4b96b7867
https://github.com/schmich/kappa/blob/09b2a8374257d7088292060bda8131f4b96b7867/lib/kappa/user.rb#L73-L84
22,784
domcleal/rspec-puppet-augeas
lib/rspec-puppet-augeas/fixtures.rb
RSpec::Puppet::Augeas.Fixtures.load_fixtures
def load_fixtures(resource, file) if block_given? Dir.mktmpdir("rspec-puppet-augeas") do |dir| prepare_fixtures(dir, resource, file) yield dir end else dir = Dir.mktmpdir("rspec-puppet-augeas") prepare_fixtures(dir, resource, file) dir end end
ruby
def load_fixtures(resource, file) if block_given? Dir.mktmpdir("rspec-puppet-augeas") do |dir| prepare_fixtures(dir, resource, file) yield dir end else dir = Dir.mktmpdir("rspec-puppet-augeas") prepare_fixtures(dir, resource, file) dir end end
[ "def", "load_fixtures", "(", "resource", ",", "file", ")", "if", "block_given?", "Dir", ".", "mktmpdir", "(", "\"rspec-puppet-augeas\"", ")", "do", "|", "dir", "|", "prepare_fixtures", "(", "dir", ",", "resource", ",", "file", ")", "yield", "dir", "end", "else", "dir", "=", "Dir", ".", "mktmpdir", "(", "\"rspec-puppet-augeas\"", ")", "prepare_fixtures", "(", "dir", ",", "resource", ",", "file", ")", "dir", "end", "end" ]
Copies test fixtures to a temporary directory If file is nil, copies the entire augeas_fixtures directory If file is a hash, it copies the "value" from augeas_fixtures to each "key" path
[ "Copies", "test", "fixtures", "to", "a", "temporary", "directory", "If", "file", "is", "nil", "copies", "the", "entire", "augeas_fixtures", "directory", "If", "file", "is", "a", "hash", "it", "copies", "the", "value", "from", "augeas_fixtures", "to", "each", "key", "path" ]
7110a831a23e1b7716c525eef256454083cc9f72
https://github.com/domcleal/rspec-puppet-augeas/blob/7110a831a23e1b7716c525eef256454083cc9f72/lib/rspec-puppet-augeas/fixtures.rb#L11-L22
22,785
domcleal/rspec-puppet-augeas
lib/rspec-puppet-augeas/fixtures.rb
RSpec::Puppet::Augeas.Fixtures.apply
def apply(resource, logs) logs.clear Puppet::Util::Log.newdestination(Puppet::Test::LogCollector.new(logs)) Puppet::Util::Log.level = 'debug' confdir = Dir.mktmpdir oldconfdir = Puppet[:confdir] Puppet[:confdir] = confdir [:require, :before, :notify, :subscribe].each { |p| resource.delete p } catalog = Puppet::Resource::Catalog.new catalog.add_resource resource catalog = catalog.to_ral if resource.is_a? Puppet::Resource txn = catalog.apply Puppet::Util::Log.close_all txn ensure if confdir Puppet[:confdir] = oldconfdir FileUtils.rm_rf(confdir) end end
ruby
def apply(resource, logs) logs.clear Puppet::Util::Log.newdestination(Puppet::Test::LogCollector.new(logs)) Puppet::Util::Log.level = 'debug' confdir = Dir.mktmpdir oldconfdir = Puppet[:confdir] Puppet[:confdir] = confdir [:require, :before, :notify, :subscribe].each { |p| resource.delete p } catalog = Puppet::Resource::Catalog.new catalog.add_resource resource catalog = catalog.to_ral if resource.is_a? Puppet::Resource txn = catalog.apply Puppet::Util::Log.close_all txn ensure if confdir Puppet[:confdir] = oldconfdir FileUtils.rm_rf(confdir) end end
[ "def", "apply", "(", "resource", ",", "logs", ")", "logs", ".", "clear", "Puppet", "::", "Util", "::", "Log", ".", "newdestination", "(", "Puppet", "::", "Test", "::", "LogCollector", ".", "new", "(", "logs", ")", ")", "Puppet", "::", "Util", "::", "Log", ".", "level", "=", "'debug'", "confdir", "=", "Dir", ".", "mktmpdir", "oldconfdir", "=", "Puppet", "[", ":confdir", "]", "Puppet", "[", ":confdir", "]", "=", "confdir", "[", ":require", ",", ":before", ",", ":notify", ",", ":subscribe", "]", ".", "each", "{", "|", "p", "|", "resource", ".", "delete", "p", "}", "catalog", "=", "Puppet", "::", "Resource", "::", "Catalog", ".", "new", "catalog", ".", "add_resource", "resource", "catalog", "=", "catalog", ".", "to_ral", "if", "resource", ".", "is_a?", "Puppet", "::", "Resource", "txn", "=", "catalog", ".", "apply", "Puppet", "::", "Util", "::", "Log", ".", "close_all", "txn", "ensure", "if", "confdir", "Puppet", "[", ":confdir", "]", "=", "oldconfdir", "FileUtils", ".", "rm_rf", "(", "confdir", ")", "end", "end" ]
Runs a particular resource via a catalog and stores logs in the caller's supplied array
[ "Runs", "a", "particular", "resource", "via", "a", "catalog", "and", "stores", "logs", "in", "the", "caller", "s", "supplied", "array" ]
7110a831a23e1b7716c525eef256454083cc9f72
https://github.com/domcleal/rspec-puppet-augeas/blob/7110a831a23e1b7716c525eef256454083cc9f72/lib/rspec-puppet-augeas/fixtures.rb#L38-L60
22,786
schmich/kappa
lib/kappa/channel.rb
Twitch::V2.Channel.followers
def followers(options = {}, &block) name = CGI.escape(@name) return @query.connection.accumulate( :path => "channels/#{name}/follows", :json => 'follows', :sub_json => 'user', :create => -> hash { User.new(hash, @query) }, :limit => options[:limit], :offset => options[:offset], &block ) end
ruby
def followers(options = {}, &block) name = CGI.escape(@name) return @query.connection.accumulate( :path => "channels/#{name}/follows", :json => 'follows', :sub_json => 'user', :create => -> hash { User.new(hash, @query) }, :limit => options[:limit], :offset => options[:offset], &block ) end
[ "def", "followers", "(", "options", "=", "{", "}", ",", "&", "block", ")", "name", "=", "CGI", ".", "escape", "(", "@name", ")", "return", "@query", ".", "connection", ".", "accumulate", "(", ":path", "=>", "\"channels/#{name}/follows\"", ",", ":json", "=>", "'follows'", ",", ":sub_json", "=>", "'user'", ",", ":create", "=>", "->", "hash", "{", "User", ".", "new", "(", "hash", ",", "@query", ")", "}", ",", ":limit", "=>", "options", "[", ":limit", "]", ",", ":offset", "=>", "options", "[", ":offset", "]", ",", "block", ")", "end" ]
Get the users following this channel. @note The number of followers is potentially very large, so it's recommended that you specify a `:limit`. @example channel.followers(:limit => 20) @example channel.followers do |follower| puts follower.display_name end @param options [Hash] Filter criteria. @option options [Fixnum] :limit (nil) Limit on the number of results returned. @option options [Fixnum] :offset (0) Offset into the result set to begin enumeration. @yield Optional. If a block is given, each follower is yielded. @yieldparam [User] follower Current follower. @see User @see https://github.com/justintv/Twitch-API/blob/master/v2_resources/channels.md#get-channelschannelfollows GET /channels/:channel/follows @return [Array<User>] Users following this channel, if no block is given. @return [nil] If a block is given.
[ "Get", "the", "users", "following", "this", "channel", "." ]
09b2a8374257d7088292060bda8131f4b96b7867
https://github.com/schmich/kappa/blob/09b2a8374257d7088292060bda8131f4b96b7867/lib/kappa/channel.rb#L85-L96
22,787
schmich/kappa
lib/kappa/game.rb
Twitch::V2.Games.find
def find(options) raise ArgumentError, 'options' if options.nil? raise ArgumentError, 'name' if options[:name].nil? params = { :query => options[:name], :type => 'suggest' } if options[:live] params.merge!(:live => true) end return @query.connection.accumulate( :path => 'search/games', :params => params, :json => 'games', :create => GameSuggestion, :limit => options[:limit] ) end
ruby
def find(options) raise ArgumentError, 'options' if options.nil? raise ArgumentError, 'name' if options[:name].nil? params = { :query => options[:name], :type => 'suggest' } if options[:live] params.merge!(:live => true) end return @query.connection.accumulate( :path => 'search/games', :params => params, :json => 'games', :create => GameSuggestion, :limit => options[:limit] ) end
[ "def", "find", "(", "options", ")", "raise", "ArgumentError", ",", "'options'", "if", "options", ".", "nil?", "raise", "ArgumentError", ",", "'name'", "if", "options", "[", ":name", "]", ".", "nil?", "params", "=", "{", ":query", "=>", "options", "[", ":name", "]", ",", ":type", "=>", "'suggest'", "}", "if", "options", "[", ":live", "]", "params", ".", "merge!", "(", ":live", "=>", "true", ")", "end", "return", "@query", ".", "connection", ".", "accumulate", "(", ":path", "=>", "'search/games'", ",", ":params", "=>", "params", ",", ":json", "=>", "'games'", ",", ":create", "=>", "GameSuggestion", ",", ":limit", "=>", "options", "[", ":limit", "]", ")", "end" ]
Get a list of games with names similar to the specified name. @example Twitch.games.find(:name => 'diablo') @example Twitch.games.find(:name => 'starcraft', :live => true) @example Twitch.games.find(:name => 'starcraft') do |suggestion| next if suggestion.name =~ /heart of the swarm/i puts suggestion.name end @param options [Hash] Search criteria. @option options [String] :name Game name search term. This can be a partial name, e.g. `"league"`. @option options [Boolean] :live (false) If `true`, only returns games that are currently live on at least one channel. @option options [Fixnum] :limit (nil) Limit on the number of results returned. @yield Optional. If a block is given, each game suggestion is yielded. @yieldparam [GameSuggestion] suggestion Current game suggestion. @see GameSuggestion GameSuggestion @see https://github.com/justintv/Twitch-API/blob/master/v2_resources/search.md#get-searchgames GET /search/games @raise [ArgumentError] If `:name` is not specified. @return [Array<GameSuggestion>] Games matching the criteria, if no block is given. @return [nil] If a block is given.
[ "Get", "a", "list", "of", "games", "with", "names", "similar", "to", "the", "specified", "name", "." ]
09b2a8374257d7088292060bda8131f4b96b7867
https://github.com/schmich/kappa/blob/09b2a8374257d7088292060bda8131f4b96b7867/lib/kappa/game.rb#L194-L214
22,788
domcleal/rspec-puppet-augeas
lib/rspec-puppet-augeas/resource.rb
RSpec::Puppet::Augeas.Resource.idempotent
def idempotent @logs_idempotent = [] root = load_fixtures(resource, {"." => "#{@root}/."}) oldroot = resource[:root] resource[:root] = root @txn_idempotent = apply(resource, @logs_idempotent) FileUtils.rm_r root resource[:root] = oldroot @txn_idempotent end
ruby
def idempotent @logs_idempotent = [] root = load_fixtures(resource, {"." => "#{@root}/."}) oldroot = resource[:root] resource[:root] = root @txn_idempotent = apply(resource, @logs_idempotent) FileUtils.rm_r root resource[:root] = oldroot @txn_idempotent end
[ "def", "idempotent", "@logs_idempotent", "=", "[", "]", "root", "=", "load_fixtures", "(", "resource", ",", "{", "\".\"", "=>", "\"#{@root}/.\"", "}", ")", "oldroot", "=", "resource", "[", ":root", "]", "resource", "[", ":root", "]", "=", "root", "@txn_idempotent", "=", "apply", "(", "resource", ",", "@logs_idempotent", ")", "FileUtils", ".", "rm_r", "root", "resource", "[", ":root", "]", "=", "oldroot", "@txn_idempotent", "end" ]
Run the resource a second time, against the output dir from the first @return [Puppet::Transaction] repeated transaction
[ "Run", "the", "resource", "a", "second", "time", "against", "the", "output", "dir", "from", "the", "first" ]
7110a831a23e1b7716c525eef256454083cc9f72
https://github.com/domcleal/rspec-puppet-augeas/blob/7110a831a23e1b7716c525eef256454083cc9f72/lib/rspec-puppet-augeas/resource.rb#L27-L38
22,789
schmich/kappa
lib/kappa/stream.rb
Twitch::V2.Streams.all
def all(options = {}, &block) return @query.connection.accumulate( :path => 'streams', :json => 'streams', :create => -> hash { Stream.new(hash, @query) }, :limit => options[:limit], :offset => options[:offset], &block ) end
ruby
def all(options = {}, &block) return @query.connection.accumulate( :path => 'streams', :json => 'streams', :create => -> hash { Stream.new(hash, @query) }, :limit => options[:limit], :offset => options[:offset], &block ) end
[ "def", "all", "(", "options", "=", "{", "}", ",", "&", "block", ")", "return", "@query", ".", "connection", ".", "accumulate", "(", ":path", "=>", "'streams'", ",", ":json", "=>", "'streams'", ",", ":create", "=>", "->", "hash", "{", "Stream", ".", "new", "(", "hash", ",", "@query", ")", "}", ",", ":limit", "=>", "options", "[", ":limit", "]", ",", ":offset", "=>", "options", "[", ":offset", "]", ",", "block", ")", "end" ]
Get all currently live streams sorted by descending viewer count. @example Twitch.streams.all @example Twitch.streams.all(:offset => 100, :limit => 10) @example Twitch.streams.all do |stream| next if stream.viewer_count < 1000 puts stream.url end @param options [Hash] Limit criteria. @option options [Fixnum] :limit (nil) Limit on the number of results returned. @option options [Fixnum] :offset (0) Offset into the result set to begin enumeration. @yield Optional. If a block is given, each stream is yielded. @yieldparam [Stream] stream Current stream. @see #get @see https://github.com/justintv/Twitch-API/blob/master/v2_resources/streams.md#get-streams GET /streams @return [Array<Stream>] Currently live streams, sorted by descending viewer count, if no block is given. @return [nil] If a block is given.
[ "Get", "all", "currently", "live", "streams", "sorted", "by", "descending", "viewer", "count", "." ]
09b2a8374257d7088292060bda8131f4b96b7867
https://github.com/schmich/kappa/blob/09b2a8374257d7088292060bda8131f4b96b7867/lib/kappa/stream.rb#L146-L155
22,790
schmich/kappa
lib/kappa/stream.rb
Twitch::V2.Streams.find
def find(options, &block) check = options.dup check.delete(:limit) check.delete(:offset) raise ArgumentError, 'options' if check.empty? params = {} channels = options[:channel] if channels if !channels.respond_to?(:map) raise ArgumentError, ':channel' end params[:channel] = channels.map { |channel| if channel.respond_to?(:name) channel.name else channel.to_s end }.join(',') end game = options[:game] if game if game.respond_to?(:name) params[:game] = game.name else params[:game] = game.to_s end end if options[:hls] params[:hls] = true end if options[:embeddable] params[:embeddable] = true end return @query.connection.accumulate( :path => 'streams', :params => params, :json => 'streams', :create => -> hash { Stream.new(hash, @query) }, :limit => options[:limit], :offset => options[:offset], &block ) end
ruby
def find(options, &block) check = options.dup check.delete(:limit) check.delete(:offset) raise ArgumentError, 'options' if check.empty? params = {} channels = options[:channel] if channels if !channels.respond_to?(:map) raise ArgumentError, ':channel' end params[:channel] = channels.map { |channel| if channel.respond_to?(:name) channel.name else channel.to_s end }.join(',') end game = options[:game] if game if game.respond_to?(:name) params[:game] = game.name else params[:game] = game.to_s end end if options[:hls] params[:hls] = true end if options[:embeddable] params[:embeddable] = true end return @query.connection.accumulate( :path => 'streams', :params => params, :json => 'streams', :create => -> hash { Stream.new(hash, @query) }, :limit => options[:limit], :offset => options[:offset], &block ) end
[ "def", "find", "(", "options", ",", "&", "block", ")", "check", "=", "options", ".", "dup", "check", ".", "delete", "(", ":limit", ")", "check", ".", "delete", "(", ":offset", ")", "raise", "ArgumentError", ",", "'options'", "if", "check", ".", "empty?", "params", "=", "{", "}", "channels", "=", "options", "[", ":channel", "]", "if", "channels", "if", "!", "channels", ".", "respond_to?", "(", ":map", ")", "raise", "ArgumentError", ",", "':channel'", "end", "params", "[", ":channel", "]", "=", "channels", ".", "map", "{", "|", "channel", "|", "if", "channel", ".", "respond_to?", "(", ":name", ")", "channel", ".", "name", "else", "channel", ".", "to_s", "end", "}", ".", "join", "(", "','", ")", "end", "game", "=", "options", "[", ":game", "]", "if", "game", "if", "game", ".", "respond_to?", "(", ":name", ")", "params", "[", ":game", "]", "=", "game", ".", "name", "else", "params", "[", ":game", "]", "=", "game", ".", "to_s", "end", "end", "if", "options", "[", ":hls", "]", "params", "[", ":hls", "]", "=", "true", "end", "if", "options", "[", ":embeddable", "]", "params", "[", ":embeddable", "]", "=", "true", "end", "return", "@query", ".", "connection", ".", "accumulate", "(", ":path", "=>", "'streams'", ",", ":params", "=>", "params", ",", ":json", "=>", "'streams'", ",", ":create", "=>", "->", "hash", "{", "Stream", ".", "new", "(", "hash", ",", "@query", ")", "}", ",", ":limit", "=>", "options", "[", ":limit", "]", ",", ":offset", "=>", "options", "[", ":offset", "]", ",", "block", ")", "end" ]
Get streams for a specific game, for a set of channels, or by other criteria, sorted by descending viewer count. @example Twitch.streams.find(:game => 'League of Legends', :limit => 50) @example Twitch.streams.find(:channel => ['fgtvlive', 'incontroltv', 'destiny']) @example Twitch.streams.find(:game => 'Diablo III', :channel => ['nl_kripp', 'protech']) @example Twitch.streams.find(:game => 'League of Legends') do |stream| next if stream.viewer_count < 1000 puts stream.url end @param options [Hash] Search criteria. @option options [String, Game, #name] :game Only return streams currently streaming the specified game. @option options [Array<String, Channel, #name>] :channel Only return streams for these channels. If a channel is not currently streaming, it is omitted. You must specify an array of channels or channel names. If you want to find the stream for a single channel, see {Streams#get}. @option options [Boolean] :embeddable (nil) If `true`, limit the streams to those that can be embedded. If `false` or `nil`, do not limit. @option options [Boolean] :hls (nil) If `true`, limit the streams to those using HLS (HTTP Live Streaming). If `false` or `nil`, do not limit. @option options [Fixnum] :limit (nil) Limit on the number of results returned. @option options [Fixnum] :offset (0) Offset into the result set to begin enumeration. @yield Optional. If a block is given, each stream found is yielded. @yieldparam [Stream] stream Current stream. @see #get @see https://github.com/justintv/Twitch-API/blob/master/v2_resources/streams.md#get-streams GET /streams @raise [ArgumentError] If `options` does not specify a search criteria (`:game`, `:channel`, `:embeddable`, or `:hls`). @raise [ArgumentError] If `:channel` is not an array. @return [Array<Stream>] Streams matching the specified criteria, sorted by descending viewer count, if no block is given. @return [nil] If a block is given.
[ "Get", "streams", "for", "a", "specific", "game", "for", "a", "set", "of", "channels", "or", "by", "other", "criteria", "sorted", "by", "descending", "viewer", "count", "." ]
09b2a8374257d7088292060bda8131f4b96b7867
https://github.com/schmich/kappa/blob/09b2a8374257d7088292060bda8131f4b96b7867/lib/kappa/stream.rb#L187-L236
22,791
voydz/souyuz
lib/souyuz/runner.rb
Souyuz.Runner.apk_file
def apk_file build_path = Souyuz.project.options[:output_path] assembly_name = Souyuz.project.options[:assembly_name] Souyuz.cache[:build_apk_path] = "#{build_path}/#{assembly_name}.apk" "#{build_path}/#{assembly_name}.apk" end
ruby
def apk_file build_path = Souyuz.project.options[:output_path] assembly_name = Souyuz.project.options[:assembly_name] Souyuz.cache[:build_apk_path] = "#{build_path}/#{assembly_name}.apk" "#{build_path}/#{assembly_name}.apk" end
[ "def", "apk_file", "build_path", "=", "Souyuz", ".", "project", ".", "options", "[", ":output_path", "]", "assembly_name", "=", "Souyuz", ".", "project", ".", "options", "[", ":assembly_name", "]", "Souyuz", ".", "cache", "[", ":build_apk_path", "]", "=", "\"#{build_path}/#{assembly_name}.apk\"", "\"#{build_path}/#{assembly_name}.apk\"", "end" ]
android build stuff to follow..
[ "android", "build", "stuff", "to", "follow", ".." ]
ee6e13d21197bea5d58bb272988e06027dd358cb
https://github.com/voydz/souyuz/blob/ee6e13d21197bea5d58bb272988e06027dd358cb/lib/souyuz/runner.rb#L38-L45
22,792
voydz/souyuz
lib/souyuz/runner.rb
Souyuz.Runner.package_path
def package_path build_path = Souyuz.project.options[:output_path] assembly_name = Souyuz.project.options[:assembly_name] # in the upcomming switch we determin the output path of iOS ipa files # those change in the Xamarin.iOS Cycle 9 release # see https://developer.xamarin.com/releases/ios/xamarin.ios_10/xamarin.ios_10.4/ if File.exist? "#{build_path}/#{assembly_name}.ipa" # after Xamarin.iOS Cycle 9 package_path = build_path else # before Xamarin.iOS Cycle 9 package_path = Dir.glob("#{build_path}/#{assembly_name} *").sort.last end package_path end
ruby
def package_path build_path = Souyuz.project.options[:output_path] assembly_name = Souyuz.project.options[:assembly_name] # in the upcomming switch we determin the output path of iOS ipa files # those change in the Xamarin.iOS Cycle 9 release # see https://developer.xamarin.com/releases/ios/xamarin.ios_10/xamarin.ios_10.4/ if File.exist? "#{build_path}/#{assembly_name}.ipa" # after Xamarin.iOS Cycle 9 package_path = build_path else # before Xamarin.iOS Cycle 9 package_path = Dir.glob("#{build_path}/#{assembly_name} *").sort.last end package_path end
[ "def", "package_path", "build_path", "=", "Souyuz", ".", "project", ".", "options", "[", ":output_path", "]", "assembly_name", "=", "Souyuz", ".", "project", ".", "options", "[", ":assembly_name", "]", "# in the upcomming switch we determin the output path of iOS ipa files", "# those change in the Xamarin.iOS Cycle 9 release", "# see https://developer.xamarin.com/releases/ios/xamarin.ios_10/xamarin.ios_10.4/", "if", "File", ".", "exist?", "\"#{build_path}/#{assembly_name}.ipa\"", "# after Xamarin.iOS Cycle 9", "package_path", "=", "build_path", "else", "# before Xamarin.iOS Cycle 9", "package_path", "=", "Dir", ".", "glob", "(", "\"#{build_path}/#{assembly_name} *\"", ")", ".", "sort", ".", "last", "end", "package_path", "end" ]
ios build stuff to follow..
[ "ios", "build", "stuff", "to", "follow", ".." ]
ee6e13d21197bea5d58bb272988e06027dd358cb
https://github.com/voydz/souyuz/blob/ee6e13d21197bea5d58bb272988e06027dd358cb/lib/souyuz/runner.rb#L65-L81
22,793
iande/onstomp
lib/onstomp/interfaces/uri_configurable.rb
OnStomp::Interfaces::UriConfigurable.ClassMethods.attr_configurable_single
def attr_configurable_single *args, &block trans = attr_configurable_wrap lambda { |v| v.is_a?(Array) ? v.first : v }, block attr_configurable(*args, &trans) end
ruby
def attr_configurable_single *args, &block trans = attr_configurable_wrap lambda { |v| v.is_a?(Array) ? v.first : v }, block attr_configurable(*args, &trans) end
[ "def", "attr_configurable_single", "*", "args", ",", "&", "block", "trans", "=", "attr_configurable_wrap", "lambda", "{", "|", "v", "|", "v", ".", "is_a?", "(", "Array", ")", "?", "v", ".", "first", ":", "v", "}", ",", "block", "attr_configurable", "(", "args", ",", "trans", ")", "end" ]
Creates a group readable and writeable attributes that can be set by a URI query parameter sharing the same name, a property of a URI or a default value. The value of this attribute will be transformed by invoking the given block, if one has been provided. If the attributes created by this method are assigned an `Array`, only the first element will be used as their value.
[ "Creates", "a", "group", "readable", "and", "writeable", "attributes", "that", "can", "be", "set", "by", "a", "URI", "query", "parameter", "sharing", "the", "same", "name", "a", "property", "of", "a", "URI", "or", "a", "default", "value", ".", "The", "value", "of", "this", "attribute", "will", "be", "transformed", "by", "invoking", "the", "given", "block", "if", "one", "has", "been", "provided", ".", "If", "the", "attributes", "created", "by", "this", "method", "are", "assigned", "an", "Array", "only", "the", "first", "element", "will", "be", "used", "as", "their", "value", "." ]
0a3e00871167b37dc424a682003d3182ba3e5c42
https://github.com/iande/onstomp/blob/0a3e00871167b37dc424a682003d3182ba3e5c42/lib/onstomp/interfaces/uri_configurable.rb#L46-L49
22,794
iande/onstomp
lib/onstomp/interfaces/uri_configurable.rb
OnStomp::Interfaces::UriConfigurable.ClassMethods.attr_configurable_arr
def attr_configurable_arr *args, &block trans = attr_configurable_wrap lambda { |v| Array(v) }, block attr_configurable(*args, &trans) end
ruby
def attr_configurable_arr *args, &block trans = attr_configurable_wrap lambda { |v| Array(v) }, block attr_configurable(*args, &trans) end
[ "def", "attr_configurable_arr", "*", "args", ",", "&", "block", "trans", "=", "attr_configurable_wrap", "lambda", "{", "|", "v", "|", "Array", "(", "v", ")", "}", ",", "block", "attr_configurable", "(", "args", ",", "trans", ")", "end" ]
Creates a group readable and writeable attributes that can be set by a URI query parameter sharing the same name, a property of a URI or a default value. The value of this attribute will be transformed by invoking the given block, if one has been provided. If the attributes created by this method are assigned a value that is not an `Array`, the value will be wrapped in an array.
[ "Creates", "a", "group", "readable", "and", "writeable", "attributes", "that", "can", "be", "set", "by", "a", "URI", "query", "parameter", "sharing", "the", "same", "name", "a", "property", "of", "a", "URI", "or", "a", "default", "value", ".", "The", "value", "of", "this", "attribute", "will", "be", "transformed", "by", "invoking", "the", "given", "block", "if", "one", "has", "been", "provided", ".", "If", "the", "attributes", "created", "by", "this", "method", "are", "assigned", "a", "value", "that", "is", "not", "an", "Array", "the", "value", "will", "be", "wrapped", "in", "an", "array", "." ]
0a3e00871167b37dc424a682003d3182ba3e5c42
https://github.com/iande/onstomp/blob/0a3e00871167b37dc424a682003d3182ba3e5c42/lib/onstomp/interfaces/uri_configurable.rb#L68-L71
22,795
iande/onstomp
lib/onstomp/interfaces/uri_configurable.rb
OnStomp::Interfaces::UriConfigurable.ClassMethods.attr_configurable_int
def attr_configurable_int *args, &block trans = attr_configurable_wrap lambda { |v| v.to_i }, block attr_configurable_single(*args, &trans) end
ruby
def attr_configurable_int *args, &block trans = attr_configurable_wrap lambda { |v| v.to_i }, block attr_configurable_single(*args, &trans) end
[ "def", "attr_configurable_int", "*", "args", ",", "&", "block", "trans", "=", "attr_configurable_wrap", "lambda", "{", "|", "v", "|", "v", ".", "to_i", "}", ",", "block", "attr_configurable_single", "(", "args", ",", "trans", ")", "end" ]
Creates readable and writeable attributes that are automatically converted into integers.
[ "Creates", "readable", "and", "writeable", "attributes", "that", "are", "automatically", "converted", "into", "integers", "." ]
0a3e00871167b37dc424a682003d3182ba3e5c42
https://github.com/iande/onstomp/blob/0a3e00871167b37dc424a682003d3182ba3e5c42/lib/onstomp/interfaces/uri_configurable.rb#L75-L78
22,796
TinderBox/soapforce
lib/soapforce/sobject.rb
Soapforce.SObject.method_missing
def method_missing(method, *args, &block) # Check string keys first, original and downcase string_method = method.to_s if raw_hash.key?(string_method) return self[string_method] elsif raw_hash.key?(string_method.downcase) return self[string_method.downcase] end if string_method =~ /[A-Z+]/ string_method = string_method.snakecase end index = string_method.downcase.to_sym # Check symbol key and return local hash entry. return self[index] if raw_hash.has_key?(index) # Then delegate to hash object. if raw_hash.respond_to?(method) return raw_hash.send(method, *args) end # Finally return nil. nil end
ruby
def method_missing(method, *args, &block) # Check string keys first, original and downcase string_method = method.to_s if raw_hash.key?(string_method) return self[string_method] elsif raw_hash.key?(string_method.downcase) return self[string_method.downcase] end if string_method =~ /[A-Z+]/ string_method = string_method.snakecase end index = string_method.downcase.to_sym # Check symbol key and return local hash entry. return self[index] if raw_hash.has_key?(index) # Then delegate to hash object. if raw_hash.respond_to?(method) return raw_hash.send(method, *args) end # Finally return nil. nil end
[ "def", "method_missing", "(", "method", ",", "*", "args", ",", "&", "block", ")", "# Check string keys first, original and downcase", "string_method", "=", "method", ".", "to_s", "if", "raw_hash", ".", "key?", "(", "string_method", ")", "return", "self", "[", "string_method", "]", "elsif", "raw_hash", ".", "key?", "(", "string_method", ".", "downcase", ")", "return", "self", "[", "string_method", ".", "downcase", "]", "end", "if", "string_method", "=~", "/", "/", "string_method", "=", "string_method", ".", "snakecase", "end", "index", "=", "string_method", ".", "downcase", ".", "to_sym", "# Check symbol key and return local hash entry.", "return", "self", "[", "index", "]", "if", "raw_hash", ".", "has_key?", "(", "index", ")", "# Then delegate to hash object.", "if", "raw_hash", ".", "respond_to?", "(", "method", ")", "return", "raw_hash", ".", "send", "(", "method", ",", "args", ")", "end", "# Finally return nil.", "nil", "end" ]
Allows method-like access to the hash using camelcase field names.
[ "Allows", "method", "-", "like", "access", "to", "the", "hash", "using", "camelcase", "field", "names", "." ]
4b07b9fe3f74ce024c9b0298adcc8f4147802e4e
https://github.com/TinderBox/soapforce/blob/4b07b9fe3f74ce024c9b0298adcc8f4147802e4e/lib/soapforce/sobject.rb#L44-L67
22,797
benedikt/layer-ruby
lib/layer/user.rb
Layer.User.blocks
def blocks RelationProxy.new(self, Block, [Operations::Create, Operations::List, Operations::Delete]) do def from_response(response, client) response['url'] ||= "#{base.url}#{resource_type.url}/#{response['user_id']}" super end def create(attributes, client = self.client) response = client.post(url, attributes) from_response({ 'user_id' => attributes['user_id'] }, client) end end end
ruby
def blocks RelationProxy.new(self, Block, [Operations::Create, Operations::List, Operations::Delete]) do def from_response(response, client) response['url'] ||= "#{base.url}#{resource_type.url}/#{response['user_id']}" super end def create(attributes, client = self.client) response = client.post(url, attributes) from_response({ 'user_id' => attributes['user_id'] }, client) end end end
[ "def", "blocks", "RelationProxy", ".", "new", "(", "self", ",", "Block", ",", "[", "Operations", "::", "Create", ",", "Operations", "::", "List", ",", "Operations", "::", "Delete", "]", ")", "do", "def", "from_response", "(", "response", ",", "client", ")", "response", "[", "'url'", "]", "||=", "\"#{base.url}#{resource_type.url}/#{response['user_id']}\"", "super", "end", "def", "create", "(", "attributes", ",", "client", "=", "self", ".", "client", ")", "response", "=", "client", ".", "post", "(", "url", ",", "attributes", ")", "from_response", "(", "{", "'user_id'", "=>", "attributes", "[", "'user_id'", "]", "}", ",", "client", ")", "end", "end", "end" ]
Returns the users blocked by this user @return [Layer::RelationProxy] the users the user blocks @!macro platform-api
[ "Returns", "the", "users", "blocked", "by", "this", "user" ]
3eafc708f71961b98de86d01080ee5970e8482ef
https://github.com/benedikt/layer-ruby/blob/3eafc708f71961b98de86d01080ee5970e8482ef/lib/layer/user.rb#L12-L24
22,798
benedikt/layer-ruby
lib/layer/user.rb
Layer.User.identity
def identity SingletonRelationProxy.new(self, Layer::Identity) do def from_response(response, client) response['url'] ||= "#{base.url}#{resource_type.url}" super end def create(attributes, client = self.client) client.post(url, attributes) fetch end def delete(client = self.client) client.delete(url) end end end
ruby
def identity SingletonRelationProxy.new(self, Layer::Identity) do def from_response(response, client) response['url'] ||= "#{base.url}#{resource_type.url}" super end def create(attributes, client = self.client) client.post(url, attributes) fetch end def delete(client = self.client) client.delete(url) end end end
[ "def", "identity", "SingletonRelationProxy", ".", "new", "(", "self", ",", "Layer", "::", "Identity", ")", "do", "def", "from_response", "(", "response", ",", "client", ")", "response", "[", "'url'", "]", "||=", "\"#{base.url}#{resource_type.url}\"", "super", "end", "def", "create", "(", "attributes", ",", "client", "=", "self", ".", "client", ")", "client", ".", "post", "(", "url", ",", "attributes", ")", "fetch", "end", "def", "delete", "(", "client", "=", "self", ".", "client", ")", "client", ".", "delete", "(", "url", ")", "end", "end", "end" ]
Returns the identity object for this user @return [Layer::RelationProxy] identity object @!macro platform-api
[ "Returns", "the", "identity", "object", "for", "this", "user" ]
3eafc708f71961b98de86d01080ee5970e8482ef
https://github.com/benedikt/layer-ruby/blob/3eafc708f71961b98de86d01080ee5970e8482ef/lib/layer/user.rb#L30-L46
22,799
benedikt/layer-ruby
lib/layer/conversation.rb
Layer.Conversation.messages
def messages RelationProxy.new(self, Message, [Operations::Create, Operations::Paginate, Operations::Find, Operations::Delete, Operations::Destroy]) end
ruby
def messages RelationProxy.new(self, Message, [Operations::Create, Operations::Paginate, Operations::Find, Operations::Delete, Operations::Destroy]) end
[ "def", "messages", "RelationProxy", ".", "new", "(", "self", ",", "Message", ",", "[", "Operations", "::", "Create", ",", "Operations", "::", "Paginate", ",", "Operations", "::", "Find", ",", "Operations", "::", "Delete", ",", "Operations", "::", "Destroy", "]", ")", "end" ]
Returns the conversations messages @return [Layer::RelationProxy] the conversation's messages @!macro various-apis
[ "Returns", "the", "conversations", "messages" ]
3eafc708f71961b98de86d01080ee5970e8482ef
https://github.com/benedikt/layer-ruby/blob/3eafc708f71961b98de86d01080ee5970e8482ef/lib/layer/conversation.rb#L58-L60