repo
stringlengths
5
67
sha
stringlengths
40
40
path
stringlengths
4
234
url
stringlengths
85
339
language
stringclasses
6 values
split
stringclasses
3 values
doc
stringlengths
3
51.2k
sign
stringlengths
5
8.01k
problem
stringlengths
13
51.2k
output
stringlengths
0
3.87M
jmettraux/rufus-tokyo
910413a982ed501e03d0c16f755929ce54d84644
lib/rufus/edo/cabcore.rb
https://github.com/jmettraux/rufus-tokyo/blob/910413a982ed501e03d0c16f755929ce54d84644/lib/rufus/edo/cabcore.rb#L246-L259
ruby
test
# Given a list of keys, deletes all the matching entries (in one sweep). # # Warning : this is a naive (slow) implementation.
def ldelete (*keys)
# Given a list of keys, deletes all the matching entries (in one sweep). # # Warning : this is a naive (slow) implementation. def ldelete (*keys)
keys = keys.flatten.collect { |k| k.to_s } # only ADB has the #misc method... if @db.respond_to?(:misc) @db.misc('outlist', keys) else keys.each { |k| self.delete(k) } end nil end
jmettraux/rufus-tokyo
910413a982ed501e03d0c16f755929ce54d84644
lib/rufus/edo/cabcore.rb
https://github.com/jmettraux/rufus-tokyo/blob/910413a982ed501e03d0c16f755929ce54d84644/lib/rufus/edo/cabcore.rb#L269-L281
ruby
test
# Increments the value stored under the given key with the given increment # (defaults to 1 (integer)). # # Warning : Tokyo Cabinet/Tyrant doesn't store counter values as regular # strings (db['key'] won't yield something that replies properly to #to_i) # # Use #counter_value(k) to get the current value set for the counter.
def incr (key, val=1)
# Increments the value stored under the given key with the given increment # (defaults to 1 (integer)). # # Warning : Tokyo Cabinet/Tyrant doesn't store counter values as regular # strings (db['key'] won't yield something that replies properly to #to_i) # # Use #counter_value(k) to get the current value set for the counter. def incr (key, val=1)
key = key.to_s v = val.is_a?(Fixnum) ? @db.addint(key, val) : @db.adddouble(key, val) raise(EdoError.new( "incr failed, there is probably already a string value set " + "for the key '#{key}'. Make sure there is no value before incrementing" )) unless v v end
reformgroup/dynamic_nested_forms
14c4318d7a9cd6585480538cfc08bd7475768315
lib/dynamic_nested_forms/view_helpers.rb
https://github.com/reformgroup/dynamic_nested_forms/blob/14c4318d7a9cd6585480538cfc08bd7475768315/lib/dynamic_nested_forms/view_helpers.rb#L10-L21
ruby
test
# .nested-container # .nested-autocomplete # .nested-items # .nested-item # .nested-content # .nested-value # .remove-item
def autocomplete_to_add_item(name, f, association, source, options = {})
# .nested-container # .nested-autocomplete # .nested-items # .nested-item # .nested-content # .nested-value # .remove-item def autocomplete_to_add_item(name, f, association, source, options = {})
new_object = f.object.send(association).klass.new options[:class] = ["autocomplete add-item", options[:class]].compact.join " " options[:data] ||= {} options[:data][:id] = new_object.object_id options[:data][:source] = source options[:data][:item] = f.fields_for(association, new_object, child_index: options[:data][:id]) do |builder| render(association.to_s.singularize + "_item", f: builder).gsub "\n", "" end text_field_tag "autocomplete_nested_content", nil, options end
reformgroup/dynamic_nested_forms
14c4318d7a9cd6585480538cfc08bd7475768315
lib/dynamic_nested_forms/view_helpers.rb
https://github.com/reformgroup/dynamic_nested_forms/blob/14c4318d7a9cd6585480538cfc08bd7475768315/lib/dynamic_nested_forms/view_helpers.rb#L38-L42
ruby
test
# def link_to_add_item(name, f, association, options = {}) # options = data_attr name, f, association, options # link_to name, "#", options # end # # def data_attr(name, f, association, options = {}) # new_object = f.object.send(association).klass.new # options[:class] = ["add-item", options[:class]].compact.join " " # options[:id] = new_object.object_id # options[:item] = f.fields_for(association, new_object, child_index: options[:id]) do |builder| # render(association.to_s.singularize + "_item", f: builder).gsub "\n", "" # end # options # end
def link_to_remove_item(name = nil, options = {})
# def link_to_add_item(name, f, association, options = {}) # options = data_attr name, f, association, options # link_to name, "#", options # end # # def data_attr(name, f, association, options = {}) # new_object = f.object.send(association).klass.new # options[:class] = ["add-item", options[:class]].compact.join " " # options[:id] = new_object.object_id # options[:item] = f.fields_for(association, new_object, child_index: options[:id]) do |builder| # render(association.to_s.singularize + "_item", f: builder).gsub "\n", "" # end # options # end def link_to_remove_item(name = nil, options = {})
name ||= "Remove" options[:class] = ["remove-item", options[:class]].compact.join " " link_to name, "#", options end
jmettraux/rufus-tokyo
910413a982ed501e03d0c16f755929ce54d84644
lib/rufus/tokyo/dystopia/core.rb
https://github.com/jmettraux/rufus-tokyo/blob/910413a982ed501e03d0c16f755929ce54d84644/lib/rufus/tokyo/dystopia/core.rb#L123-L136
ruby
test
# Return the document at the specified index
def fetch( id )
# Return the document at the specified index def fetch( id )
r = nil begin r = lib.tcidbget( @db, id ) rescue => e # if we have 'no record found' then return nil if lib.tcidbecode( @db ) == 22 then return nil else raise_error end end return r end
jmettraux/rufus-tokyo
910413a982ed501e03d0c16f755929ce54d84644
lib/rufus/tokyo/dystopia/core.rb
https://github.com/jmettraux/rufus-tokyo/blob/910413a982ed501e03d0c16f755929ce54d84644/lib/rufus/tokyo/dystopia/core.rb#L144-L152
ruby
test
# Return the document ids of the documents that matche the search expression # # http://tokyocabinet.sourceforge.net/dystopiadoc/#dystopiaapi and scroll # down to 'Compound Expression of Search'
def search( expression )
# Return the document ids of the documents that matche the search expression # # http://tokyocabinet.sourceforge.net/dystopiadoc/#dystopiaapi and scroll # down to 'Compound Expression of Search' def search( expression )
out_count = ::FFI::MemoryPointer.new :pointer out_list = ::FFI::MemoryPointer.new :pointer out_list = lib.tcidbsearch2( @db, expression, out_count ) count = out_count.read_int results = out_list.get_array_of_uint64(0, count ) return results end
jmettraux/rufus-tokyo
910413a982ed501e03d0c16f755929ce54d84644
lib/rufus/tokyo/dystopia/core.rb
https://github.com/jmettraux/rufus-tokyo/blob/910413a982ed501e03d0c16f755929ce54d84644/lib/rufus/tokyo/dystopia/core.rb#L189-L193
ruby
test
# Raises a dystopian error (asks the db which one)
def raise_error
# Raises a dystopian error (asks the db which one) def raise_error
code = lib.tcidbecode( @db ) msg = lib.tcidberrmsg( code ) raise Error.new("[ERROR #{code}] : #{msg}") end
ntamvl/poloniex_ruby
0f1cd1de78f970e88e2799b1ad28e777e7746a30
lib/deep_symbolize.rb
https://github.com/ntamvl/poloniex_ruby/blob/0f1cd1de78f970e88e2799b1ad28e777e7746a30/lib/deep_symbolize.rb#L50-L57
ruby
test
# handling recursion - any Enumerable elements (except String) # is being extended with the module, and then symbolized
def _recurse_(value, &block)
# handling recursion - any Enumerable elements (except String) # is being extended with the module, and then symbolized def _recurse_(value, &block)
if value.is_a?(Enumerable) && !value.is_a?(String) # support for a use case without extended core Hash value.extend DeepSymbolizable unless value.class.include?(DeepSymbolizable) value = value.deep_symbolize(&block) end value end
andymeneely/game_icons
f108e7211e4b860292487bcbee79ce1640a3ec02
lib/game_icons/did_you_mean.rb
https://github.com/andymeneely/game_icons/blob/f108e7211e4b860292487bcbee79ce1640a3ec02/lib/game_icons/did_you_mean.rb#L28-L38
ruby
test
# Computes a hash of each character
def char_freq(str)
# Computes a hash of each character def char_freq(str)
freqs = Hash.new(0) (1..4).each do |i| str.chars.each_cons(i).inject(freqs) do |freq, ngram| ngram = ngram.join freq[ngram] = freq[ngram] + 1 freq end end freqs end
andymeneely/game_icons
f108e7211e4b860292487bcbee79ce1640a3ec02
lib/game_icons/did_you_mean.rb
https://github.com/andymeneely/game_icons/blob/f108e7211e4b860292487bcbee79ce1640a3ec02/lib/game_icons/did_you_mean.rb#L59-L61
ruby
test
# Return top scoring, sorted by lowest
def top(n, scores)
# Return top scoring, sorted by lowest def top(n, scores)
scores.sort {|a,b| a[1] <=> b[1]}.map{|x| x[0]}.first(n) end
andymeneely/game_icons
f108e7211e4b860292487bcbee79ce1640a3ec02
lib/game_icons/icon.rb
https://github.com/andymeneely/game_icons/blob/f108e7211e4b860292487bcbee79ce1640a3ec02/lib/game_icons/icon.rb#L16-L27
ruby
test
# Modify the background and foreground colors and their opacities
def recolor(bg: '#000', fg: '#fff', bg_opacity: "1.0", fg_opacity: "1.0")
# Modify the background and foreground colors and their opacities def recolor(bg: '#000', fg: '#fff', bg_opacity: "1.0", fg_opacity: "1.0")
OptionalDeps.require_nokogiri bg.prepend('#') unless bg.start_with? '#' fg.prepend('#') unless fg.start_with? '#' doc = Nokogiri::XML(self.string) doc.css('path')[0]['fill'] = bg # dark backdrop doc.css('path')[1]['fill'] = fg # light drawing doc.css('path')[0]['fill-opacity'] = bg_opacity.to_s # dark backdrop doc.css('path')[1]['fill-opacity'] = fg_opacity.to_s # light drawing @svgstr = doc.to_xml self end
jmettraux/rufus-tokyo
910413a982ed501e03d0c16f755929ce54d84644
lib/rufus/tokyo/outlen.rb
https://github.com/jmettraux/rufus-tokyo/blob/910413a982ed501e03d0c16f755929ce54d84644/lib/rufus/tokyo/outlen.rb#L30-L47
ruby
test
# A wrapper for library returning a string (binary data potentially)
def outlen_op (method, *args)
# A wrapper for library returning a string (binary data potentially) def outlen_op (method, *args)
args.unshift(@db) outlen = FFI::MemoryPointer.new(:int) args << outlen out = lib.send(method, *args) return nil if out.address == 0 out.get_bytes(0, outlen.get_int(0)) ensure outlen.free lib.tcfree(out) #lib.free(out) end
jmettraux/rufus-tokyo
910413a982ed501e03d0c16f755929ce54d84644
lib/rufus/tokyo/cabinet/abstract.rb
https://github.com/jmettraux/rufus-tokyo/blob/910413a982ed501e03d0c16f755929ce54d84644/lib/rufus/tokyo/cabinet/abstract.rb#L262-L267
ruby
test
# No comment
def []= (k, v)
# No comment def []= (k, v)
k = k.to_s; v = v.to_s lib.abs_put(@db, k, Rufus::Tokyo.blen(k), v, Rufus::Tokyo.blen(v)) end
jmettraux/rufus-tokyo
910413a982ed501e03d0c16f755929ce54d84644
lib/rufus/tokyo/cabinet/abstract.rb
https://github.com/jmettraux/rufus-tokyo/blob/910413a982ed501e03d0c16f755929ce54d84644/lib/rufus/tokyo/cabinet/abstract.rb#L272-L277
ruby
test
# Like #put but doesn't overwrite the value if already set. Returns true # only if there no previous entry for k.
def putkeep (k, v)
# Like #put but doesn't overwrite the value if already set. Returns true # only if there no previous entry for k. def putkeep (k, v)
k = k.to_s; v = v.to_s lib.abs_putkeep(@db, k, Rufus::Tokyo.blen(k), v, Rufus::Tokyo.blen(v)) end
jmettraux/rufus-tokyo
910413a982ed501e03d0c16f755929ce54d84644
lib/rufus/tokyo/cabinet/abstract.rb
https://github.com/jmettraux/rufus-tokyo/blob/910413a982ed501e03d0c16f755929ce54d84644/lib/rufus/tokyo/cabinet/abstract.rb#L284-L289
ruby
test
# Appends the given string at the end of the current string value for key k. # If there is no record for key k, a new record will be created. # # Returns true if successful.
def putcat (k, v)
# Appends the given string at the end of the current string value for key k. # If there is no record for key k, a new record will be created. # # Returns true if successful. def putcat (k, v)
k = k.to_s; v = v.to_s lib.abs_putcat(@db, k, Rufus::Tokyo.blen(k), v, Rufus::Tokyo.blen(v)) end
jmettraux/rufus-tokyo
910413a982ed501e03d0c16f755929ce54d84644
lib/rufus/tokyo/cabinet/abstract.rb
https://github.com/jmettraux/rufus-tokyo/blob/910413a982ed501e03d0c16f755929ce54d84644/lib/rufus/tokyo/cabinet/abstract.rb#L293-L298
ruby
test
# (The actual #[] method is provided by HashMethods
def get (k)
# (The actual #[] method is provided by HashMethods def get (k)
k = k.to_s outlen_op(:abs_get, k, Rufus::Tokyo.blen(k)) end
jmettraux/rufus-tokyo
910413a982ed501e03d0c16f755929ce54d84644
lib/rufus/tokyo/cabinet/abstract.rb
https://github.com/jmettraux/rufus-tokyo/blob/910413a982ed501e03d0c16f755929ce54d84644/lib/rufus/tokyo/cabinet/abstract.rb#L304-L311
ruby
test
# Removes a record from the cabinet, returns the value if successful # else nil.
def delete (k)
# Removes a record from the cabinet, returns the value if successful # else nil. def delete (k)
k = k.to_s v = self[k] lib.abs_out(@db, k, Rufus::Tokyo.blen(k)) ? v : nil end
jmettraux/rufus-tokyo
910413a982ed501e03d0c16f755929ce54d84644
lib/rufus/tokyo/cabinet/abstract.rb
https://github.com/jmettraux/rufus-tokyo/blob/910413a982ed501e03d0c16f755929ce54d84644/lib/rufus/tokyo/cabinet/abstract.rb#L363-L368
ruby
test
# Copies the current cabinet to a new file. # # Does it by copying each entry afresh to the target file. Spares some # space, hence the 'compact' label...
def compact_copy (target_path)
# Copies the current cabinet to a new file. # # Does it by copying each entry afresh to the target file. Spares some # space, hence the 'compact' label... def compact_copy (target_path)
@other_db = Cabinet.new(target_path) self.each { |k, v| @other_db[k] = v } @other_db.close end
jmettraux/rufus-tokyo
910413a982ed501e03d0c16f755929ce54d84644
lib/rufus/tokyo/cabinet/abstract.rb
https://github.com/jmettraux/rufus-tokyo/blob/910413a982ed501e03d0c16f755929ce54d84644/lib/rufus/tokyo/cabinet/abstract.rb#L391-L407
ruby
test
# Returns an array with all the keys in the databse # # With no options given, this method will return all the keys (strings) # in a Ruby array. # # :prefix --> returns only the keys who match a given string prefix # # :limit --> returns a limited number of keys # # :native --> returns an instance of Rufus::Tokyo::List instead of # a Ruby Hash, you have to call #free on that List when done with it ! # Else you're exposing yourself to a memory leak.
def keys (options={})
# Returns an array with all the keys in the databse # # With no options given, this method will return all the keys (strings) # in a Ruby array. # # :prefix --> returns only the keys who match a given string prefix # # :limit --> returns a limited number of keys # # :native --> returns an instance of Rufus::Tokyo::List instead of # a Ruby Hash, you have to call #free on that List when done with it ! # Else you're exposing yourself to a memory leak. def keys (options={})
if @type == "tcf" min, max = "min", "max" l = lib.tcfdbrange2( as_fixed, min, Rufus::Tokyo.blen(min), max, Rufus::Tokyo.blen(max), -1) else pre = options.fetch(:prefix, "") l = lib.abs_fwmkeys( @db, pre, Rufus::Tokyo.blen(pre), options[:limit] || -1) end l = Rufus::Tokyo::List.new(l) options[:native] ? l : l.release end
jmettraux/rufus-tokyo
910413a982ed501e03d0c16f755929ce54d84644
lib/rufus/tokyo/cabinet/abstract.rb
https://github.com/jmettraux/rufus-tokyo/blob/910413a982ed501e03d0c16f755929ce54d84644/lib/rufus/tokyo/cabinet/abstract.rb#L411-L418
ruby
test
# Deletes all the entries whose keys begin with the given prefix
def delete_keys_with_prefix (prefix)
# Deletes all the entries whose keys begin with the given prefix def delete_keys_with_prefix (prefix)
call_misc( 'outlist', lib.abs_fwmkeys(@db, prefix, Rufus::Tokyo.blen(prefix), -1)) # -1 for no limits nil end
jmettraux/rufus-tokyo
910413a982ed501e03d0c16f755929ce54d84644
lib/rufus/tokyo/cabinet/abstract.rb
https://github.com/jmettraux/rufus-tokyo/blob/910413a982ed501e03d0c16f755929ce54d84644/lib/rufus/tokyo/cabinet/abstract.rb#L423-L428
ruby
test
# Given a list of keys, returns a Hash { key => value } of the # matching entries (in one sweep).
def lget (*keys)
# Given a list of keys, returns a Hash { key => value } of the # matching entries (in one sweep). def lget (*keys)
keys = keys.flatten.collect { |k| k.to_s } Hash[*call_misc('getlist', Rufus::Tokyo::List.new(keys))] end
jmettraux/rufus-tokyo
910413a982ed501e03d0c16f755929ce54d84644
lib/rufus/tokyo/cabinet/abstract.rb
https://github.com/jmettraux/rufus-tokyo/blob/910413a982ed501e03d0c16f755929ce54d84644/lib/rufus/tokyo/cabinet/abstract.rb#L434-L445
ruby
test
# Merges the given hash into this Cabinet (or Tyrant) and returns self.
def merge! (hash)
# Merges the given hash into this Cabinet (or Tyrant) and returns self. def merge! (hash)
call_misc( 'putlist', hash.inject(Rufus::Tokyo::List.new) { |l, (k, v)| l << k.to_s l << v.to_s l }) self end
jmettraux/rufus-tokyo
910413a982ed501e03d0c16f755929ce54d84644
lib/rufus/tokyo/cabinet/abstract.rb
https://github.com/jmettraux/rufus-tokyo/blob/910413a982ed501e03d0c16f755929ce54d84644/lib/rufus/tokyo/cabinet/abstract.rb#L450-L455
ruby
test
# Given a list of keys, deletes all the matching entries (in one sweep).
def ldelete (*keys)
# Given a list of keys, deletes all the matching entries (in one sweep). def ldelete (*keys)
call_misc( 'outlist', Rufus::Tokyo::List.new(keys.flatten.collect { |k| k.to_s })) end
jmettraux/rufus-tokyo
910413a982ed501e03d0c16f755929ce54d84644
lib/rufus/tokyo/cabinet/abstract.rb
https://github.com/jmettraux/rufus-tokyo/blob/910413a982ed501e03d0c16f755929ce54d84644/lib/rufus/tokyo/cabinet/abstract.rb#L467-L481
ruby
test
# Increments the value stored under the given key with the given increment # (defaults to 1 (integer)). # # Accepts an integer or a double value. # # Warning : Tokyo Cabinet/Tyrant doesn't store counter values as regular # strings (db['key'] won't yield something that replies properly to #to_i) # # Use #counter_value(k) to get the current value set for the counter.
def incr (key, inc=1)
# Increments the value stored under the given key with the given increment # (defaults to 1 (integer)). # # Accepts an integer or a double value. # # Warning : Tokyo Cabinet/Tyrant doesn't store counter values as regular # strings (db['key'] won't yield something that replies properly to #to_i) # # Use #counter_value(k) to get the current value set for the counter. def incr (key, inc=1)
key = key.to_s v = inc.is_a?(Fixnum) ? lib.addint(@db, key, Rufus::Tokyo.blen(key), inc) : lib.adddouble(@db, key, Rufus::Tokyo.blen(key), inc) raise(TokyoError.new( "incr failed, there is probably already a string value set " + "for the key '#{key}'. Make sure there is no value before incrementing" )) if v == Rufus::Tokyo::INT_MIN || (v.respond_to?(:nan?) && v.nan?) v end
jmettraux/rufus-tokyo
910413a982ed501e03d0c16f755929ce54d84644
lib/rufus/tokyo/cabinet/abstract.rb
https://github.com/jmettraux/rufus-tokyo/blob/910413a982ed501e03d0c16f755929ce54d84644/lib/rufus/tokyo/cabinet/abstract.rb#L498-L506
ruby
test
# Triggers a defrag run (TC >= 1.4.21 only)
def defrag
# Triggers a defrag run (TC >= 1.4.21 only) def defrag
raise(NotImplementedError.new( "method defrag is supported since Tokyo Cabinet 1.4.21. " + "your TC version doesn't support it" )) unless lib.respond_to?(:tctdbsetdfunit) call_misc('defrag', Rufus::Tokyo::List.new) end
jmettraux/rufus-tokyo
910413a982ed501e03d0c16f755929ce54d84644
lib/rufus/tokyo/cabinet/abstract.rb
https://github.com/jmettraux/rufus-tokyo/blob/910413a982ed501e03d0c16f755929ce54d84644/lib/rufus/tokyo/cabinet/abstract.rb#L553-L557
ruby
test
# -- # # BTREE methods # # ++ # This is a B+ Tree method only, puts a value for a key who has # [potentially] multiple values.
def putdup (k, v)
# -- # # BTREE methods # # ++ # This is a B+ Tree method only, puts a value for a key who has # [potentially] multiple values. def putdup (k, v)
lib.tcbdbputdup( as_btree, k, Rufus::Tokyo.blen(k), v, Rufus::Tokyo.blen(v)) end
jmettraux/rufus-tokyo
910413a982ed501e03d0c16f755929ce54d84644
lib/rufus/tokyo/cabinet/abstract.rb
https://github.com/jmettraux/rufus-tokyo/blob/910413a982ed501e03d0c16f755929ce54d84644/lib/rufus/tokyo/cabinet/abstract.rb#L562-L566
ruby
test
# This is a B+ Tree method only, returns all the values for a given # key.
def get4 (k)
# This is a B+ Tree method only, returns all the values for a given # key. def get4 (k)
l = lib.tcbdbget4(as_btree, k, Rufus::Tokyo.blen(k)) Rufus::Tokyo::List.new(l).release end
jmettraux/rufus-tokyo
910413a982ed501e03d0c16f755929ce54d84644
lib/rufus/tokyo/cabinet/abstract.rb
https://github.com/jmettraux/rufus-tokyo/blob/910413a982ed501e03d0c16f755929ce54d84644/lib/rufus/tokyo/cabinet/abstract.rb#L617-L629
ruby
test
# -- # def check_transaction_support # raise(TokyoError.new( # "The version of Tokyo Cabinet you're using doesn't support " + # "transactions for non-table structures. Upgrade to TC >= 1.4.13.") # ) unless lib.respond_to?(:tcadbtranbegin) # end # ++ # Wrapping tcadbmisc or tcrdbmisc # (and taking care of freeing the list_pointer)
def call_misc (function, list_pointer)
# -- # def check_transaction_support # raise(TokyoError.new( # "The version of Tokyo Cabinet you're using doesn't support " + # "transactions for non-table structures. Upgrade to TC >= 1.4.13.") # ) unless lib.respond_to?(:tcadbtranbegin) # end # ++ # Wrapping tcadbmisc or tcrdbmisc # (and taking care of freeing the list_pointer) def call_misc (function, list_pointer)
list_pointer = list_pointer.pointer \ if list_pointer.is_a?(Rufus::Tokyo::List) begin l = do_call_misc(function, list_pointer) raise "function '#{function}' failed" unless l Rufus::Tokyo::List.new(l).release ensure Rufus::Tokyo::List.free(list_pointer) end end
jmettraux/rufus-tokyo
910413a982ed501e03d0c16f755929ce54d84644
lib/rufus/tokyo/tyrant/ext.rb
https://github.com/jmettraux/rufus-tokyo/blob/910413a982ed501e03d0c16f755929ce54d84644/lib/rufus/tokyo/tyrant/ext.rb#L39-L50
ruby
test
# Calls a lua embedded function # (http://tokyocabinet.sourceforge.net/tyrantdoc/#luaext) # # Options are :global_locking and :record_locking # # Returns the return value of the called function. # # Nil is returned in case of failure.
def ext (func_name, key='', value='', opts={})
# Calls a lua embedded function # (http://tokyocabinet.sourceforge.net/tyrantdoc/#luaext) # # Options are :global_locking and :record_locking # # Returns the return value of the called function. # # Nil is returned in case of failure. def ext (func_name, key='', value='', opts={})
k = key.to_s v = value.to_s outlen_op( :tcrdbext, func_name.to_s, compute_ext_opts(opts), k, Rufus::Tokyo.blen(k), v, Rufus::Tokyo.blen(v)) end
jmettraux/rufus-tokyo
910413a982ed501e03d0c16f755929ce54d84644
lib/rufus/tokyo/cabinet/util.rb
https://github.com/jmettraux/rufus-tokyo/blob/910413a982ed501e03d0c16f755929ce54d84644/lib/rufus/tokyo/cabinet/util.rb#L101-L106
ruby
test
# Creates an empty instance of a Tokyo Cabinet in-memory map # # (It's OK to pass the pointer of a C map directly, this is in fact # used in rufus/tokyo/table when retrieving entries) # # Inserts key/value pair
def []= (k, v)
# Creates an empty instance of a Tokyo Cabinet in-memory map # # (It's OK to pass the pointer of a C map directly, this is in fact # used in rufus/tokyo/table when retrieving entries) # # Inserts key/value pair def []= (k, v)
clib.tcmapput(pointer, k, Rufus::Tokyo::blen(k), v, Rufus::Tokyo::blen(v)) v end
jmettraux/rufus-tokyo
910413a982ed501e03d0c16f755929ce54d84644
lib/rufus/tokyo/cabinet/util.rb
https://github.com/jmettraux/rufus-tokyo/blob/910413a982ed501e03d0c16f755929ce54d84644/lib/rufus/tokyo/cabinet/util.rb#L110-L119
ruby
test
# Deletes an entry
def delete (k)
# Deletes an entry def delete (k)
v = self[k] return nil unless v clib.tcmapout(pointer_or_raise, k, Rufus::Tokyo::blen(k)) || raise("failed to remove key '#{k}'") v end
jmettraux/rufus-tokyo
910413a982ed501e03d0c16f755929ce54d84644
lib/rufus/tokyo/cabinet/util.rb
https://github.com/jmettraux/rufus-tokyo/blob/910413a982ed501e03d0c16f755929ce54d84644/lib/rufus/tokyo/cabinet/util.rb#L138-L156
ruby
test
# Returns an array of all the keys in the map
def keys
# Returns an array of all the keys in the map def keys
clib.tcmapiterinit(pointer_or_raise) a = [] klen = FFI::MemoryPointer.new(:int) loop do k = clib.tcmapiternext(@pointer, klen) break if k.address == 0 a << k.get_bytes(0, klen.get_int(0)) end return a ensure klen.free end
jmettraux/rufus-tokyo
910413a982ed501e03d0c16f755929ce54d84644
lib/rufus/tokyo/cabinet/util.rb
https://github.com/jmettraux/rufus-tokyo/blob/910413a982ed501e03d0c16f755929ce54d84644/lib/rufus/tokyo/cabinet/util.rb#L282-L310
ruby
test
# The put operation.
def []= (a, b, c=nil)
# The put operation. def []= (a, b, c=nil)
i, s = c.nil? ? [ a, b ] : [ [a, b], c ] range = if i.is_a?(Range) i elsif i.is_a?(Array) start, count = i (start..start + count - 1) else [ i ] end range = norm(range) values = s.is_a?(Array) ? s : [ s ] # not "values = Array(s)" range.each_with_index do |offset, index| val = values[index] if val clib.tclistover(@pointer, offset, val, Rufus::Tokyo.blen(val)) else outlen_op(:tclistremove, values.size) end end self end
jmettraux/rufus-tokyo
910413a982ed501e03d0c16f755929ce54d84644
lib/rufus/tokyo/cabinet/util.rb
https://github.com/jmettraux/rufus-tokyo/blob/910413a982ed501e03d0c16f755929ce54d84644/lib/rufus/tokyo/cabinet/util.rb#L342-L357
ruby
test
# The equivalent of Ruby Array#[]
def [] (i, count=nil)
# The equivalent of Ruby Array#[] def [] (i, count=nil)
return nil if (count != nil) && count < 1 len = self.size range = if count.nil? i.is_a?(Range) ? i : [i] else (i..i + count - 1) end r = norm(range).collect { |ii| outlen_op(:tclistval, ii) } range.first == range.last ? r.first : r end
jmettraux/rufus-tokyo
910413a982ed501e03d0c16f755929ce54d84644
lib/rufus/tokyo/cabinet/util.rb
https://github.com/jmettraux/rufus-tokyo/blob/910413a982ed501e03d0c16f755929ce54d84644/lib/rufus/tokyo/cabinet/util.rb#L422-L429
ruby
test
# Makes sure this offset/range fits the size of the list
def norm (i)
# Makes sure this offset/range fits the size of the list def norm (i)
l = self.length case i when Range then ((i.first % l)..(i.last % l)) when Array then [ i.first % l ] else i % l end end
jmettraux/rufus-tokyo
910413a982ed501e03d0c16f755929ce54d84644
lib/rufus/tokyo/cabinet/table.rb
https://github.com/jmettraux/rufus-tokyo/blob/910413a982ed501e03d0c16f755929ce54d84644/lib/rufus/tokyo/cabinet/table.rb#L226-L233
ruby
test
# Sets an index on a column of the table. # # Types maybe be :lexical or :decimal. # # Recently (TC 1.4.26 and 1.4.27) inverted indexes have been added, # they are :token and :qgram. There is an :opt index as well. # # Sorry couldn't find any good doc about those inverted indexes apart from : # # http://alpha.mixi.co.jp/blog/?p=1147 # http://www.excite-webtl.jp/world/english/web/?wb_url=http%3A%2F%2Falpha.mixi.co.jp%2Fblog%2F%3Fp%3D1147&wb_lp=JAEN&wb_dis=2&wb_submit=+%96%7C+%96%F3+ # # Use :keep to "add" and # :remove (or :void) to "remove" an index. # # If column_name is :pk or "", the index will be set on the primary key. # # Returns true in case of success.
def set_index (column_name, *types)
# Sets an index on a column of the table. # # Types maybe be :lexical or :decimal. # # Recently (TC 1.4.26 and 1.4.27) inverted indexes have been added, # they are :token and :qgram. There is an :opt index as well. # # Sorry couldn't find any good doc about those inverted indexes apart from : # # http://alpha.mixi.co.jp/blog/?p=1147 # http://www.excite-webtl.jp/world/english/web/?wb_url=http%3A%2F%2Falpha.mixi.co.jp%2Fblog%2F%3Fp%3D1147&wb_lp=JAEN&wb_dis=2&wb_submit=+%96%7C+%96%F3+ # # Use :keep to "add" and # :remove (or :void) to "remove" an index. # # If column_name is :pk or "", the index will be set on the primary key. # # Returns true in case of success. def set_index (column_name, *types)
column_name = column_name == :pk ? '' : column_name.to_s ii = types.inject(0) { |i, t| i = i | INDEX_TYPES[t]; i } lib.tab_setindex(@db, column_name, ii) end
jmettraux/rufus-tokyo
910413a982ed501e03d0c16f755929ce54d84644
lib/rufus/tokyo/cabinet/table.rb
https://github.com/jmettraux/rufus-tokyo/blob/910413a982ed501e03d0c16f755929ce54d84644/lib/rufus/tokyo/cabinet/table.rb#L246-L260
ruby
test
# Inserts a record in the table db # # table['pk0'] = [ 'name', 'fred', 'age', '45' ] # table['pk1'] = { 'name' => 'jeff', 'age' => '46' } # # Accepts both a hash or an array (expects the array to be of the # form [ key, value, key, value, ... ] else it will raise # an ArgumentError) # # Raises an error in case of failure.
def []= (pk, h_or_a)
# Inserts a record in the table db # # table['pk0'] = [ 'name', 'fred', 'age', '45' ] # table['pk1'] = { 'name' => 'jeff', 'age' => '46' } # # Accepts both a hash or an array (expects the array to be of the # form [ key, value, key, value, ... ] else it will raise # an ArgumentError) # # Raises an error in case of failure. def []= (pk, h_or_a)
pk = pk.to_s h_or_a = Rufus::Tokyo.h_or_a_to_s(h_or_a) m = Rufus::Tokyo::Map[h_or_a] r = lib.tab_put(@db, pk, Rufus::Tokyo.blen(pk), m.pointer) m.free r || raise_error # raising potential error after freeing map h_or_a end
jmettraux/rufus-tokyo
910413a982ed501e03d0c16f755929ce54d84644
lib/rufus/tokyo/cabinet/table.rb
https://github.com/jmettraux/rufus-tokyo/blob/910413a982ed501e03d0c16f755929ce54d84644/lib/rufus/tokyo/cabinet/table.rb#L267-L276
ruby
test
# Removes an entry in the table # # (might raise an error if the delete itself failed, but returns nil # if there was no entry for the given key)
def delete (k)
# Removes an entry in the table # # (might raise an error if the delete itself failed, but returns nil # if there was no entry for the given key) def delete (k)
k = k.to_s v = self[k] return nil unless v libcall(:tab_out, k, Rufus::Tokyo.blen(k)) v end
jmettraux/rufus-tokyo
910413a982ed501e03d0c16f755929ce54d84644
lib/rufus/tokyo/cabinet/table.rb
https://github.com/jmettraux/rufus-tokyo/blob/910413a982ed501e03d0c16f755929ce54d84644/lib/rufus/tokyo/cabinet/table.rb#L298-L308
ruby
test
# Returns an array of all the primary keys in the table # # With no options given, this method will return all the keys (strings) # in a Ruby array. # # :prefix --> returns only the keys who match a given string prefix # # :limit --> returns a limited number of keys # # :native --> returns an instance of Rufus::Tokyo::List instead of # a Ruby Hash, you have to call #free on that List when done with it ! # Else you're exposing yourself to a memory leak.
def keys (options={})
# Returns an array of all the primary keys in the table # # With no options given, this method will return all the keys (strings) # in a Ruby array. # # :prefix --> returns only the keys who match a given string prefix # # :limit --> returns a limited number of keys # # :native --> returns an instance of Rufus::Tokyo::List instead of # a Ruby Hash, you have to call #free on that List when done with it ! # Else you're exposing yourself to a memory leak. def keys (options={})
pre = options.fetch(:prefix, "") l = lib.tab_fwmkeys( @db, pre, Rufus::Tokyo.blen(pre), options[:limit] || -1) l = Rufus::Tokyo::List.new(l) options[:native] ? l : l.release end
jmettraux/rufus-tokyo
910413a982ed501e03d0c16f755929ce54d84644
lib/rufus/tokyo/cabinet/table.rb
https://github.com/jmettraux/rufus-tokyo/blob/910413a982ed501e03d0c16f755929ce54d84644/lib/rufus/tokyo/cabinet/table.rb#L321-L329
ruby
test
# No 'misc' methods for the table library, so this lget is equivalent # to calling get for each key. Hoping later versions of TC will provide # a mget method.
def lget (*keys)
# No 'misc' methods for the table library, so this lget is equivalent # to calling get for each key. Hoping later versions of TC will provide # a mget method. def lget (*keys)
keys.flatten.inject({}) { |h, k| k = k.to_s v = self[k] h[k] = v if v h } end
jmettraux/rufus-tokyo
910413a982ed501e03d0c16f755929ce54d84644
lib/rufus/tokyo/cabinet/table.rb
https://github.com/jmettraux/rufus-tokyo/blob/910413a982ed501e03d0c16f755929ce54d84644/lib/rufus/tokyo/cabinet/table.rb#L353-L362
ruby
test
# Prepares and runs a query, returns a ResultSet instance # (takes care of freeing the query structure)
def do_query (&block)
# Prepares and runs a query, returns a ResultSet instance # (takes care of freeing the query structure) def do_query (&block)
q = prepare_query(&block) rs = q.run return rs ensure q && q.free end
jmettraux/rufus-tokyo
910413a982ed501e03d0c16f755929ce54d84644
lib/rufus/tokyo/cabinet/table.rb
https://github.com/jmettraux/rufus-tokyo/blob/910413a982ed501e03d0c16f755929ce54d84644/lib/rufus/tokyo/cabinet/table.rb#L367-L376
ruby
test
# Prepares and runs a query, returns an array of hashes (all Ruby) # (takes care of freeing the query and the result set structures)
def query (&block)
# Prepares and runs a query, returns an array of hashes (all Ruby) # (takes care of freeing the query and the result set structures) def query (&block)
rs = do_query(&block) a = rs.to_a return a ensure rs && rs.free end
jmettraux/rufus-tokyo
910413a982ed501e03d0c16f755929ce54d84644
lib/rufus/tokyo/cabinet/table.rb
https://github.com/jmettraux/rufus-tokyo/blob/910413a982ed501e03d0c16f755929ce54d84644/lib/rufus/tokyo/cabinet/table.rb#L380-L389
ruby
test
# Prepares a query and then runs it and deletes all the results.
def query_delete (&block)
# Prepares a query and then runs it and deletes all the results. def query_delete (&block)
q = prepare_query(&block) rs = q.delete return rs ensure q && q.free end
jmettraux/rufus-tokyo
910413a982ed501e03d0c16f755929ce54d84644
lib/rufus/tokyo/cabinet/table.rb
https://github.com/jmettraux/rufus-tokyo/blob/910413a982ed501e03d0c16f755929ce54d84644/lib/rufus/tokyo/cabinet/table.rb#L393-L401
ruby
test
# Prepares a query and then runs it and deletes all the results.
def query_count (&block)
# Prepares a query and then runs it and deletes all the results. def query_count (&block)
q = prepare_query { |q| q.pk_only # improve efficiency, since we have to do the query } q.count ensure q.free if q end
jmettraux/rufus-tokyo
910413a982ed501e03d0c16f755929ce54d84644
lib/rufus/tokyo/cabinet/table.rb
https://github.com/jmettraux/rufus-tokyo/blob/910413a982ed501e03d0c16f755929ce54d84644/lib/rufus/tokyo/cabinet/table.rb#L525-L554
ruby
test
# A #search a la ruby-tokyotyrant # (http://github.com/actsasflinn/ruby-tokyotyrant/tree) # # r = table.search( # :intersection, # @t.prepare_query { |q| # q.add 'lang', :includes, 'es' # }, # @t.prepare_query { |q| # q.add 'lang', :includes, 'li' # } # ) # # Accepts the symbols :union, :intersection, :difference or :diff as # first parameter. # # If the last element element passed to this method is the value 'false', # the return value will the array of matching primary keys.
def search (type, *queries)
# A #search a la ruby-tokyotyrant # (http://github.com/actsasflinn/ruby-tokyotyrant/tree) # # r = table.search( # :intersection, # @t.prepare_query { |q| # q.add 'lang', :includes, 'es' # }, # @t.prepare_query { |q| # q.add 'lang', :includes, 'li' # } # ) # # Accepts the symbols :union, :intersection, :difference or :diff as # first parameter. # # If the last element element passed to this method is the value 'false', # the return value will the array of matching primary keys. def search (type, *queries)
run_query = true run_query = queries.pop if queries.last == false raise( ArgumentError.new("pass at least one prepared query") ) if queries.size < 1 raise( ArgumentError.new("pass instances of Rufus::Tokyo::TableQuery only") ) if queries.find { |q| q.class != TableQuery } t = META_TYPES[type] raise( ArgumentError.new("no search type #{type.inspect}") ) unless t qs = FFI::MemoryPointer.new(:pointer, queries.size) qs.write_array_of_pointer(queries.collect { |q| q.pointer }) r = lib.tab_metasearch(qs, queries.size, t) qs.free pks = Rufus::Tokyo::List.new(r).release run_query ? lget(pks) : pks end
jmettraux/rufus-tokyo
910413a982ed501e03d0c16f755929ce54d84644
lib/rufus/tokyo/cabinet/table.rb
https://github.com/jmettraux/rufus-tokyo/blob/910413a982ed501e03d0c16f755929ce54d84644/lib/rufus/tokyo/cabinet/table.rb#L566-L573
ruby
test
# Returns the value (as a Ruby Hash) else nil # # (the actual #[] method is provided by HashMethods)
def get (k)
# Returns the value (as a Ruby Hash) else nil # # (the actual #[] method is provided by HashMethods) def get (k)
k = k.to_s m = lib.tab_get(@db, k, Rufus::Tokyo.blen(k)) return nil if m.address == 0 Map.to_h(m) # which frees the map end
jmettraux/rufus-tokyo
910413a982ed501e03d0c16f755929ce54d84644
lib/rufus/tokyo/cabinet/table.rb
https://github.com/jmettraux/rufus-tokyo/blob/910413a982ed501e03d0c16f755929ce54d84644/lib/rufus/tokyo/cabinet/table.rb#L587-L593
ruby
test
# Obviously something got wrong, let's ask the db about it and raise # a TokyoError
def raise_error
# Obviously something got wrong, let's ask the db about it and raise # a TokyoError def raise_error
err_code = lib.tab_ecode(@db) err_msg = lib.tab_errmsg(err_code) raise TokyoError.new("(err #{err_code}) #{err_msg}") end
jmettraux/rufus-tokyo
910413a982ed501e03d0c16f755929ce54d84644
lib/rufus/tokyo/cabinet/table.rb
https://github.com/jmettraux/rufus-tokyo/blob/910413a982ed501e03d0c16f755929ce54d84644/lib/rufus/tokyo/cabinet/table.rb#L781-L808
ruby
test
# Process each record using the supplied block, which will be passed # two parameters, the primary key and the value hash. # # The block passed to this method accepts two parameters : the [String] # primary key and a Hash of the values for the record. # # The return value of the passed block does matter. Three different # values are expected :stop, :delete or a Hash instance. # # :stop will make the iteration stop, further matching records will not # be passed to the block # # :delete will let Tokyo Cabinet delete the record just seen. # # a Hash is passed to let TC update the values for the record just seen. # # Passing an array is possible : [ :stop, { 'name' => 'Toto' } ] will # update the record just seen to a unique column 'name' and will stop the # iteration. Likewise, returning [ :stop, :delete ] will work as well. # # (by Matthew King)
def process (&block)
# Process each record using the supplied block, which will be passed # two parameters, the primary key and the value hash. # # The block passed to this method accepts two parameters : the [String] # primary key and a Hash of the values for the record. # # The return value of the passed block does matter. Three different # values are expected :stop, :delete or a Hash instance. # # :stop will make the iteration stop, further matching records will not # be passed to the block # # :delete will let Tokyo Cabinet delete the record just seen. # # a Hash is passed to let TC update the values for the record just seen. # # Passing an array is possible : [ :stop, { 'name' => 'Toto' } ] will # update the record just seen to a unique column 'name' and will stop the # iteration. Likewise, returning [ :stop, :delete ] will work as well. # # (by Matthew King) def process (&block)
callback = lambda do |pk, pklen, map, opt_param| key = pk.read_string(pklen) val = Rufus::Tokyo::Map.new(map).to_h r = block.call(key, val) r = [ r ] unless r.is_a?(Array) if updated_value = r.find { |e| e.is_a?(Hash) } Rufus::Tokyo::Map.new(map).merge!(updated_value) end r.inject(0) { |i, v| case v when :stop then i = i | 1 << 24 when :delete then i = i | 2 when Hash then i = i | 1 end i } end lib.qry_proc(@query, callback, nil) self end
jmettraux/rufus-tokyo
910413a982ed501e03d0c16f755929ce54d84644
lib/rufus/tokyo/cabinet/table.rb
https://github.com/jmettraux/rufus-tokyo/blob/910413a982ed501e03d0c16f755929ce54d84644/lib/rufus/tokyo/cabinet/table.rb#L877-L889
ruby
test
# The classical each
def each
# The classical each def each
(0..size-1).each do |i| pk = @list[i] if @opts[:pk_only] yield(pk) else val = @table[pk] val[:pk] = pk unless @opts[:no_pk] yield(val) end end end
andymeneely/game_icons
f108e7211e4b860292487bcbee79ce1640a3ec02
lib/game_icons/finder.rb
https://github.com/andymeneely/game_icons/blob/f108e7211e4b860292487bcbee79ce1640a3ec02/lib/game_icons/finder.rb#L11-L17
ruby
test
# Find the icon, possibly without the extension. # @example Finder.new.find('glass-heart') # Raises an error if the icon could not be found.
def find(icon)
# Find the icon, possibly without the extension. # @example Finder.new.find('glass-heart') # Raises an error if the icon could not be found. def find(icon)
str = icon.to_s.downcase file = DB.files[str] || DB.files[str.sub(/\.svg$/,'')] || not_found(str, icon) Icon.new(file) end
dhrubomoy/to-arff
b34e4b85cab4c19007144ccee1e6562f4974ab89
lib/to-arff/sqlitedb.rb
https://github.com/dhrubomoy/to-arff/blob/b34e4b85cab4c19007144ccee1e6562f4974ab89/lib/to-arff/sqlitedb.rb#L46-L53
ruby
test
# Get all colums for a given table.
def get_columns(table_name)
# Get all colums for a given table. def get_columns(table_name)
columns_arr = [] pst = @db.prepare "SELECT * FROM #{table_name} LIMIT 6" pst.columns.each do |c| columns_arr.push(c) end columns_arr end
dhrubomoy/to-arff
b34e4b85cab4c19007144ccee1e6562f4974ab89
lib/to-arff/sqlitedb.rb
https://github.com/dhrubomoy/to-arff/blob/b34e4b85cab4c19007144ccee1e6562f4974ab89/lib/to-arff/sqlitedb.rb#L62-L68
ruby
test
# If the column type is nominal return true.
def is_numeric(table_name, column_name)
# If the column type is nominal return true. def is_numeric(table_name, column_name)
if @db.execute("SELECT #{column_name} from #{table_name} LIMIT 1").first.first.is_a? Numeric return true else return false end end
dhrubomoy/to-arff
b34e4b85cab4c19007144ccee1e6562f4974ab89
lib/to-arff/sqlitedb.rb
https://github.com/dhrubomoy/to-arff/blob/b34e4b85cab4c19007144ccee1e6562f4974ab89/lib/to-arff/sqlitedb.rb#L180-L193
ruby
test
# If valid option was provided in convert method
def deal_with_valid_option(temp_tables, temp_columns, temp_column_types, res)
# If valid option was provided in convert method def deal_with_valid_option(temp_tables, temp_columns, temp_column_types, res)
if !temp_tables.empty? check_given_tables_validity(temp_tables) temp_tables.each do |t| res << convert_table(t) end elsif !temp_columns.keys.empty? check_given_columns_validity(temp_columns) res << convert_from_columns_hash(temp_columns) elsif !temp_column_types.empty? check_given_columns_validity(temp_column_types) res << convert_from_column_types_hash(temp_column_types) end end
northwoodspd/dryspec
1072a9714c24dc82fd8ea5c88c3ce7ca3f97dcca
lib/dryspec/helpers.rb
https://github.com/northwoodspd/dryspec/blob/1072a9714c24dc82fd8ea5c88c3ce7ca3f97dcca/lib/dryspec/helpers.rb#L30-L42
ruby
test
# This allows us to simplify the case where we want to # have a context which contains one or more `let` statements # # Supports giving either a Hash or a String and a Hash as arguments # In both cases the Hash will be used to define `let` statements # When a String is specified that becomes the context description # If String isn't specified, Hash#inspect becomes the context description # # @example Defining a simple let variable # # Before # subject { a + 1 } # context('a is 1') do # let(:a) { 1 } # it { should eq 2 } # end # # # After # subject { a + 1 } # let_context(a: 1) { it { should eq 2 } } # # @example Giving a descriptive string # subject { a + 1 } # let_context('Negative number', a: -1) { it { should eq 0 } } # # @example Multiple variables # subject { a + b } # let_context(a: 1, b: 2) { it { should eq 3 } }
def let_context(*args, &block)
# This allows us to simplify the case where we want to # have a context which contains one or more `let` statements # # Supports giving either a Hash or a String and a Hash as arguments # In both cases the Hash will be used to define `let` statements # When a String is specified that becomes the context description # If String isn't specified, Hash#inspect becomes the context description # # @example Defining a simple let variable # # Before # subject { a + 1 } # context('a is 1') do # let(:a) { 1 } # it { should eq 2 } # end # # # After # subject { a + 1 } # let_context(a: 1) { it { should eq 2 } } # # @example Giving a descriptive string # subject { a + 1 } # let_context('Negative number', a: -1) { it { should eq 0 } } # # @example Multiple variables # subject { a + b } # let_context(a: 1, b: 2) { it { should eq 3 } } def let_context(*args, &block)
context_string, hash = case args.map(&:class) when [String, Hash] then ["#{args[0]} #{args[1]}", args[1]] when [Hash] then [args[0].inspect, args[0]] end context(context_string) do hash.each { |var, value| let(var) { value } } instance_eval(&block) end end
northwoodspd/dryspec
1072a9714c24dc82fd8ea5c88c3ce7ca3f97dcca
lib/dryspec/helpers.rb
https://github.com/northwoodspd/dryspec/blob/1072a9714c24dc82fd8ea5c88c3ce7ca3f97dcca/lib/dryspec/helpers.rb#L68-L76
ruby
test
# Allows you to simply specify that the subject should raise an exception # Takes no arguments or arguments of an exception class, a string, or both. # # As with RSpec's basic `to raise_error` matcher, if you don't give an error # then the an unexpected error may cause your test to pass incorrectly # # @example Raising a string # # Before # subject { fail 'Test' } # it "should raise 'Test'" do # expect { subject }.to raise_error 'Test' # end # # # After # subject { fail 'Test' } # subject_should_raise 'Test' # # @example Raising an exception class # subject { fail ArgumentError } # subject_should_raise ArgumentError # # @example Raising an exception class and string # subject { fail ArgumentError, 'Test' } # subject_should_raise ArgumentError, 'Test'
def subject_should_raise(*args)
# Allows you to simply specify that the subject should raise an exception # Takes no arguments or arguments of an exception class, a string, or both. # # As with RSpec's basic `to raise_error` matcher, if you don't give an error # then the an unexpected error may cause your test to pass incorrectly # # @example Raising a string # # Before # subject { fail 'Test' } # it "should raise 'Test'" do # expect { subject }.to raise_error 'Test' # end # # # After # subject { fail 'Test' } # subject_should_raise 'Test' # # @example Raising an exception class # subject { fail ArgumentError } # subject_should_raise ArgumentError # # @example Raising an exception class and string # subject { fail ArgumentError, 'Test' } # subject_should_raise ArgumentError, 'Test' def subject_should_raise(*args)
error, message = args it_string = "subject should raise #{error}" it_string += " (#{message.inspect})" if message it it_string do expect { subject }.to raise_error error, message end end
northwoodspd/dryspec
1072a9714c24dc82fd8ea5c88c3ce7ca3f97dcca
lib/dryspec/helpers.rb
https://github.com/northwoodspd/dryspec/blob/1072a9714c24dc82fd8ea5c88c3ce7ca3f97dcca/lib/dryspec/helpers.rb#L94-L102
ruby
test
# Allows you to simply specify that the subject should not raise an exception. # Takes no arguments or arguments of an exception class, a string, or both. # # As with RSpec's basic `not_to raise_error` matcher, if you give a specific error, other # unexpected errors may be swallowed silently # # @example Subject does not raise an error # # Before # subject { 1 } # it 'should not raise an exception' do # expect { subject }.not_to raise_error # end # # # After # subject { 1 } # subject_should_not_raise
def subject_should_not_raise(*args)
# Allows you to simply specify that the subject should not raise an exception. # Takes no arguments or arguments of an exception class, a string, or both. # # As with RSpec's basic `not_to raise_error` matcher, if you give a specific error, other # unexpected errors may be swallowed silently # # @example Subject does not raise an error # # Before # subject { 1 } # it 'should not raise an exception' do # expect { subject }.not_to raise_error # end # # # After # subject { 1 } # subject_should_not_raise def subject_should_not_raise(*args)
error, message = args it_string = "subject should not raise #{error}" it_string += " (#{message.inspect})" if message it it_string do expect { subject }.not_to raise_error error, message end end
translationexchange/tml-ruby
e82b8768b36a2d2d4eb1493205784555151e741e
lib/tml/config.rb
https://github.com/translationexchange/tml-ruby/blob/e82b8768b36a2d2d4eb1493205784555151e741e/lib/tml/config.rb#L414-L434
ruby
test
# Application # # # def default_level # return Tml.session.application.default_level if Tml.session.application # @default_level # end
def xmessage_rule_key_mapping
# Application # # # def default_level # return Tml.session.application.default_level if Tml.session.application # @default_level # end def xmessage_rule_key_mapping
@rule_key_mapping ||= { number: { one: 'singular', few: 'few', many: 'many', other: 'plural' }, gender: { male: 'male', female: 'female', neutral: 'neutral', other: 'other', }, date: { future: 'future', present: 'present', past: 'past' } } end
ysbaddaden/janus
a4d1f9705b48e765377b7296765ffeff8d35f771
lib/janus/manager.rb
https://github.com/ysbaddaden/janus/blob/a4d1f9705b48e765377b7296765ffeff8d35f771/lib/janus/manager.rb#L38-L42
ruby
test
# Logs a user in. # # FIXME: what should happen when a user signs in but a user is already signed in for the same scope?!
def login(user, options = {})
# Logs a user in. # # FIXME: what should happen when a user signs in but a user is already signed in for the same scope?! def login(user, options = {})
options[:scope] ||= Janus.scope_for(user) set_user(user, options) Janus::Manager.run_callbacks(:login, user, self, options) end
ysbaddaden/janus
a4d1f9705b48e765377b7296765ffeff8d35f771
lib/janus/manager.rb
https://github.com/ysbaddaden/janus/blob/a4d1f9705b48e765377b7296765ffeff8d35f771/lib/janus/manager.rb#L47-L57
ruby
test
# Logs a user out from the given scopes or from all scopes at once # if no scope is defined. If no scope is left after logout, then the # whole session will be resetted.
def logout(*scopes)
# Logs a user out from the given scopes or from all scopes at once # if no scope is defined. If no scope is left after logout, then the # whole session will be resetted. def logout(*scopes)
scopes = janus_sessions.keys if scopes.empty? scopes.each do |scope| _user = user(scope) unset_user(scope) Janus::Manager.run_callbacks(:logout, _user, self, :scope => scope) end request.reset_session if janus_sessions.empty? end
ysbaddaden/janus
a4d1f9705b48e765377b7296765ffeff8d35f771
lib/janus/manager.rb
https://github.com/ysbaddaden/janus/blob/a4d1f9705b48e765377b7296765ffeff8d35f771/lib/janus/manager.rb#L61-L64
ruby
test
# Manually sets a user without going throught the whole login or # authenticate process.
def set_user(user, options = {})
# Manually sets a user without going throught the whole login or # authenticate process. def set_user(user, options = {})
scope = options[:scope] || Janus.scope_for(user) janus_sessions[scope.to_s] = { 'user_class' => user.class.name, 'user_id' => user.id } end
ysbaddaden/janus
a4d1f9705b48e765377b7296765ffeff8d35f771
lib/janus/manager.rb
https://github.com/ysbaddaden/janus/blob/a4d1f9705b48e765377b7296765ffeff8d35f771/lib/janus/manager.rb#L67-L70
ruby
test
# Manually removes the user without going throught the whole logout process.
def unset_user(scope)
# Manually removes the user without going throught the whole logout process. def unset_user(scope)
janus_sessions.delete(scope.to_s) @users.delete(scope.to_sym) unless @users.nil? end
ysbaddaden/janus
a4d1f9705b48e765377b7296765ffeff8d35f771
lib/janus/manager.rb
https://github.com/ysbaddaden/janus/blob/a4d1f9705b48e765377b7296765ffeff8d35f771/lib/janus/manager.rb#L73-L90
ruby
test
# Returns the currently connected user.
def user(scope)
# Returns the currently connected user. def user(scope)
scope = scope.to_sym @users ||= {} if authenticated?(scope) if @users[scope].nil? begin @users[scope] = user_class(scope).find(session(scope)['user_id']) rescue ActiveRecord::RecordNotFound unset_user(scope) else Janus::Manager.run_callbacks(:fetch, @users[scope], self, :scope => scope) end end @users[scope] end end
translationexchange/tml-ruby
e82b8768b36a2d2d4eb1493205784555151e741e
lib/tml/cache.rb
https://github.com/translationexchange/tml-ruby/blob/e82b8768b36a2d2d4eb1493205784555151e741e/lib/tml/cache.rb#L103-L106
ruby
test
# namespace of each cache key
def namespace
# namespace of each cache key def namespace
return '#' if Tml.config.disabled? @namespace || Tml.config.cache[:namespace] || Tml.config.application[:key][0..5] end
translationexchange/tml-ruby
e82b8768b36a2d2d4eb1493205784555151e741e
lib/tml/cache.rb
https://github.com/translationexchange/tml-ruby/blob/e82b8768b36a2d2d4eb1493205784555151e741e/lib/tml/cache.rb#L140-L153
ruby
test
# Pulls cache version from CDN
def extract_version(app, version = nil)
# Pulls cache version from CDN def extract_version(app, version = nil)
if version Tml.cache.version.set(version.to_s) else version_data = app.api_client.get_from_cdn('version', {t: Time.now.to_i}, {uncompressed: true}) unless version_data Tml.logger.debug('No releases have been generated yet. Please visit your Dashboard and publish translations.') return end Tml.cache.version.set(version_data['version']) end end
translationexchange/tml-ruby
e82b8768b36a2d2d4eb1493205784555151e741e
lib/tml/cache.rb
https://github.com/translationexchange/tml-ruby/blob/e82b8768b36a2d2d4eb1493205784555151e741e/lib/tml/cache.rb#L156-L162
ruby
test
# Warms up cache from CDN or local files
def warmup(version = nil, cache_path = nil)
# Warms up cache from CDN or local files def warmup(version = nil, cache_path = nil)
if cache_path.nil? warmup_from_cdn(version) else warmup_from_files(version, cache_path) end end
translationexchange/tml-ruby
e82b8768b36a2d2d4eb1493205784555151e741e
lib/tml/cache.rb
https://github.com/translationexchange/tml-ruby/blob/e82b8768b36a2d2d4eb1493205784555151e741e/lib/tml/cache.rb#L165-L196
ruby
test
# Warms up cache from local files
def warmup_from_files(version = nil, cache_path = nil)
# Warms up cache from local files def warmup_from_files(version = nil, cache_path = nil)
t0 = Time.now Tml.logger = Logger.new(STDOUT) Tml.logger.debug('Starting cache warmup from local files...') version ||= Tml.config.cache[:version] cache_path ||= Tml.config.cache[:path] cache_path = "#{cache_path}/#{version}" Tml.cache.version.set(version.to_s) Tml.logger.debug("Warming Up Version: #{Tml.cache.version}") application = JSON.parse(File.read("#{cache_path}/application.json")) Tml.cache.store(Tml::Application.cache_key, application) sources = JSON.parse(File.read("#{cache_path}/sources.json")) application['languages'].each do |lang| locale = lang['locale'] language = JSON.parse(File.read("#{cache_path}/#{locale}/language.json")) Tml.cache.store(Tml::Language.cache_key(locale), language) sources.each do |src| source = JSON.parse(File.read("#{cache_path}/#{locale}/sources/#{src}.json")) Tml.cache.store(Tml::Source.cache_key(locale, src), source) end end t1 = Time.now Tml.logger.debug("Cache warmup took #{t1-t0}s") end
translationexchange/tml-ruby
e82b8768b36a2d2d4eb1493205784555151e741e
lib/tml/cache.rb
https://github.com/translationexchange/tml-ruby/blob/e82b8768b36a2d2d4eb1493205784555151e741e/lib/tml/cache.rb#L199-L227
ruby
test
# Warms up cache from CDN
def warmup_from_cdn(version = nil)
# Warms up cache from CDN def warmup_from_cdn(version = nil)
t0 = Time.now Tml.logger = Logger.new(STDOUT) Tml.logger.debug('Starting cache warmup from CDN...') app = Tml::Application.new(key: Tml.config.application[:key], cdn_host: Tml.config.application[:cdn_host]) extract_version(app, version) Tml.logger.debug("Warming Up Version: #{Tml.cache.version}") application = app.api_client.get_from_cdn('application', {t: Time.now.to_i}) Tml.cache.store(Tml::Application.cache_key, application) sources = app.api_client.get_from_cdn('sources', {t: Time.now.to_i}, {uncompressed: true}) application['languages'].each do |lang| locale = lang['locale'] language = app.api_client.get_from_cdn("#{locale}/language", {t: Time.now.to_i}) Tml.cache.store(Tml::Language.cache_key(locale), language) sources.each do |src| source = app.api_client.get_from_cdn("#{locale}/sources/#{src}", {t: Time.now.to_i}) Tml.cache.store(Tml::Source.cache_key(locale, src), source) end end t1 = Time.now Tml.logger.debug("Cache warmup took #{t1-t0}s") end
translationexchange/tml-ruby
e82b8768b36a2d2d4eb1493205784555151e741e
lib/tml/cache.rb
https://github.com/translationexchange/tml-ruby/blob/e82b8768b36a2d2d4eb1493205784555151e741e/lib/tml/cache.rb#L230-L238
ruby
test
# default cache path
def default_cache_path
# default cache path def default_cache_path
@cache_path ||= begin path = Tml.config.cache[:path] path ||= 'config/tml' FileUtils.mkdir_p(path) FileUtils.chmod(0777, path) path end end
translationexchange/tml-ruby
e82b8768b36a2d2d4eb1493205784555151e741e
lib/tml/cache.rb
https://github.com/translationexchange/tml-ruby/blob/e82b8768b36a2d2d4eb1493205784555151e741e/lib/tml/cache.rb#L241-L279
ruby
test
# downloads cache from the CDN
def download(cache_path = default_cache_path, version = nil)
# downloads cache from the CDN def download(cache_path = default_cache_path, version = nil)
t0 = Time.now Tml.logger = Logger.new(STDOUT) Tml.logger.debug('Starting cache download...') app = Tml::Application.new(key: Tml.config.application[:key], cdn_host: Tml.config.application[:cdn_host]) extract_version(app, version) Tml.logger.debug("Downloading Version: #{Tml.cache.version}") archive_name = "#{Tml.cache.version}.tar.gz" path = "#{cache_path}/#{archive_name}" url = "#{app.cdn_host}/#{Tml.config.application[:key]}/#{archive_name}" Tml.logger.debug("Downloading cache file: #{url}") open(path, 'wb') do |file| file << open(url).read end Tml.logger.debug('Extracting cache file...') version_path = "#{cache_path}/#{Tml.cache.version}" Tml::Utils.untar(Tml::Utils.ungzip(File.new(path)), version_path) Tml.logger.debug("Cache has been stored in #{version_path}") File.unlink(path) begin current_path = 'current' FileUtils.chdir(cache_path) FileUtils.rm(current_path) if File.exist?(current_path) FileUtils.ln_s(Tml.cache.version.to_s, current_path) Tml.logger.debug("The new version #{Tml.cache.version} has been marked as current") rescue Exception => ex Tml.logger.debug("Could not generate current symlink to the cache path: #{ex.message}") end t1 = Time.now Tml.logger.debug("Cache download took #{t1-t0}s") end
translationexchange/tml-ruby
e82b8768b36a2d2d4eb1493205784555151e741e
lib/tml/cache.rb
https://github.com/translationexchange/tml-ruby/blob/e82b8768b36a2d2d4eb1493205784555151e741e/lib/tml/cache.rb#L282-L296
ruby
test
# remove extensions
def strip_extensions(data)
# remove extensions def strip_extensions(data)
if data.is_a?(Hash) data = data.dup data.delete('extensions') return data end if data.is_a?(String) and data.match(/^\{/) data = JSON.parse(data) data.delete('extensions') data = data.to_json end data end
ruby-bdb/sbdb
50e2fbe843d63f48b4919c9a768771926a3171cd
lib/sbdb/db.rb
https://github.com/ruby-bdb/sbdb/blob/50e2fbe843d63f48b4919c9a768771926a3171cd/lib/sbdb/db.rb#L95-L97
ruby
test
# Arguments: # * file # * name # * type # * flags # * mode # * env # or: **file**, **opts**. *opts* must be a *::Hash* with keys like above, excluded *file*.
def each key = nil, val = nil, &exe
# Arguments: # * file # * name # * type # * flags # * mode # * env # or: **file**, **opts**. *opts* must be a *::Hash* with keys like above, excluded *file*. def each key = nil, val = nil, &exe
cursor {|c| c.each key, val, &exe } end
translationexchange/tml-ruby
e82b8768b36a2d2d4eb1493205784555151e741e
lib/tml/session.rb
https://github.com/translationexchange/tml-ruby/blob/e82b8768b36a2d2d4eb1493205784555151e741e/lib/tml/session.rb#L156-L165
ruby
test
# Block Options
def block_option(key, lookup = true)
# Block Options def block_option(key, lookup = true)
if lookup block_options_queue.reverse.each do |options| value = options[key.to_s] || options[key.to_sym] return value if value end return nil end block_options[key] end
kmalakoff/couchwatcher-gem
50e83d2a7ad855b3a34d4afdc094f896272930e2
lib/couchwatcher/database_listener.rb
https://github.com/kmalakoff/couchwatcher-gem/blob/50e83d2a7ad855b3a34d4afdc094f896272930e2/lib/couchwatcher/database_listener.rb#L9-L12
ruby
test
# shortcut to say
def say(message, color=nil)
# shortcut to say def say(message, color=nil)
@shell ||= Thor::Shell::Basic.new @shell.say message, color end
translationexchange/tml-ruby
e82b8768b36a2d2d4eb1493205784555151e741e
lib/tml/cache_version.rb
https://github.com/translationexchange/tml-ruby/blob/e82b8768b36a2d2d4eb1493205784555151e741e/lib/tml/cache_version.rb#L63-L89
ruby
test
# validate that current cache version hasn't expired
def validate_cache_version(version) # if cache version is hardcoded, use it
# validate that current cache version hasn't expired def validate_cache_version(version) # if cache version is hardcoded, use it
if Tml.config.cache[:version] return Tml.config.cache[:version] end return version unless version.is_a?(Hash) return 'undefined' unless version['t'].is_a?(Numeric) return version['version'] if cache.read_only? # if version check interval is disabled, don't try to check for the new # cache version on the CDN if version_check_interval == -1 Tml.logger.debug('Cache version check is disabled') return version['version'] end expires_at = version['t'] + version_check_interval if expires_at < Time.now.to_i Tml.logger.debug('Cache version is outdated, needs refresh') return 'undefined' end delta = expires_at - Time.now.to_i Tml.logger.debug("Cache version is up to date, expires in #{delta}s") version['version'] end
translationexchange/tml-ruby
e82b8768b36a2d2d4eb1493205784555151e741e
lib/tml/cache_version.rb
https://github.com/translationexchange/tml-ruby/blob/e82b8768b36a2d2d4eb1493205784555151e741e/lib/tml/cache_version.rb#L92-L99
ruby
test
# fetches the version from the cache
def fetch
# fetches the version from the cache def fetch
self.version = begin ver = cache.fetch(CACHE_VERSION_KEY) do {'version' => Tml.config.cache[:version] || 'undefined', 't' => cache_timestamp} end validate_cache_version(ver) end end
ruby-bdb/sbdb
50e2fbe843d63f48b4919c9a768771926a3171cd
lib/sbdb/environment.rb
https://github.com/ruby-bdb/sbdb/blob/50e2fbe843d63f48b4919c9a768771926a3171cd/lib/sbdb/environment.rb#L95-L99
ruby
test
# Opens a Database. # see SBDB::DB, SBDB::Btree, SBDB::Hash, SBDB::Recno, SBDB::Queue
def open type, file, *ps, &exe
# Opens a Database. # see SBDB::DB, SBDB::Btree, SBDB::Hash, SBDB::Recno, SBDB::Queue def open type, file, *ps, &exe
ps.push ::Hash.new unless ::Hash === ps.last ps.last[:env] = self (type || SBDB::Unkown).new file, *ps, &exe end
ruby-bdb/sbdb
50e2fbe843d63f48b4919c9a768771926a3171cd
lib/sbdb/environment.rb
https://github.com/ruby-bdb/sbdb/blob/50e2fbe843d63f48b4919c9a768771926a3171cd/lib/sbdb/environment.rb#L107-L113
ruby
test
# Returns the DB like open, but if it's already opened, # it returns the old instance. # If you use this, never use close. It's possible somebody else use it too. # The Databases, which are opened, will close, if the Environment will close.
def [] file, *ps, &exe
# Returns the DB like open, but if it's already opened, # it returns the old instance. # If you use this, never use close. It's possible somebody else use it too. # The Databases, which are opened, will close, if the Environment will close. def [] file, *ps, &exe
opts = ::Hash === ps.last ? ps.pop : {} opts[:env] = self name, type, flg = ps[0] || opts[:name], ps[1] || opts[:type], ps[2] || opts[:flags] ps.push opts @dbs[ [file, name, flg | CREATE]] ||= (type || SBDB::Unknown).new file, *ps, &exe end
ysbaddaden/janus
a4d1f9705b48e765377b7296765ffeff8d35f771
lib/janus/strategies.rb
https://github.com/ysbaddaden/janus/blob/a4d1f9705b48e765377b7296765ffeff8d35f771/lib/janus/strategies.rb#L6-L8
ruby
test
# Runs authentication strategies to log a user in.
def run_strategies(scope)
# Runs authentication strategies to log a user in. def run_strategies(scope)
Janus::Manager.strategies.each { |name| break if run_strategy(name, scope) } end
ysbaddaden/janus
a4d1f9705b48e765377b7296765ffeff8d35f771
lib/janus/strategies.rb
https://github.com/ysbaddaden/janus/blob/a4d1f9705b48e765377b7296765ffeff8d35f771/lib/janus/strategies.rb#L11-L24
ruby
test
# Runs a given strategy and returns true if it succeeded.
def run_strategy(name, scope)
# Runs a given strategy and returns true if it succeeded. def run_strategy(name, scope)
strategy = "Janus::Strategies::#{name.to_s.camelize}".constantize.new(scope, self) if strategy.valid? strategy.authenticate! if strategy.success? send(strategy.auth_method, strategy.user, :scope => scope) Janus::Manager.run_callbacks(:authenticate, strategy.user, self, :scope => scope) end end strategy.success? end
sue445/paraduct
4d42641a7dbe1d801304ea41131699392d6c5884
lib/paraduct/runner.rb
https://github.com/sue445/paraduct/blob/4d42641a7dbe1d801304ea41131699392d6c5884/lib/paraduct/runner.rb#L26-L34
ruby
test
# run script with params # @param script [String, Array<String>] script file, script(s) # @return [String] stdout # @raise [Paraduct::Errors::ProcessError] command exited error status
def perform(script)
# run script with params # @param script [String, Array<String>] script file, script(s) # @return [String] stdout # @raise [Paraduct::Errors::ProcessError] command exited error status def perform(script)
export_variables = @params.reverse_merge("PARADUCT_JOB_ID" => @job_id, "PARADUCT_JOB_NAME" => job_name) variable_string = export_variables.map { |key, value| %(export #{key}="#{value}";) }.join(" ") Array.wrap(script).inject("") do |stdout, command| stdout << run_command("#{variable_string} #{command}") stdout end end
bkon/gliffy
4bc70b34e85bb9cb4911cdded2e04f743ca6c7b7
lib/gliffy/account.rb
https://github.com/bkon/gliffy/blob/4bc70b34e85bb9cb4911cdded2e04f743ca6c7b7/lib/gliffy/account.rb#L55-L63
ruby
test
# observer callback
def update(event, target)
# observer callback def update(event, target)
case event when :user_deleted @users = @users.delete_if { |element| element == target } target.delete_observer(self) else raise ArgumentError.new(event) end end
plataformatec/responders_backport
81b144c1673d9d82144547c3f18755dc4321f2a2
lib/responders_backport/respond_to.rb
https://github.com/plataformatec/responders_backport/blob/81b144c1673d9d82144547c3f18755dc4321f2a2/lib/responders_backport/respond_to.rb#L95-L110
ruby
test
# Collects mimes and return the response for the negotiated format. Returns # nil if :not_acceptable was sent to the client.
def retrieve_response_from_mimes(mimes, &block)
# Collects mimes and return the response for the negotiated format. Returns # nil if :not_acceptable was sent to the client. def retrieve_response_from_mimes(mimes, &block)
responder = ActionController::MimeResponds::Responder.new(self) mimes = collect_mimes_from_class_level if mimes.empty? mimes.each { |mime| responder.send(mime) } block.call(responder) if block_given? if format = responder.negotiate_mime self.response.template.template_format = format.to_sym self.response.content_type = format.to_s self.formats = [ format.to_sym ] responder.response_for(format) || proc { default_render } else head :not_acceptable nil end end
NUBIC/abstractor
d8acce620e93902d1d57451621d4109bffcca02a
lib/generators/abstractor/install/install_generator.rb
https://github.com/NUBIC/abstractor/blob/d8acce620e93902d1d57451621d4109bffcca02a/lib/generators/abstractor/install/install_generator.rb#L33-L48
ruby
test
# shameless steal from forem git://github.com/radar/forem.git
def add_abstractor_user_method
# shameless steal from forem git://github.com/radar/forem.git def add_abstractor_user_method
current_user_helper = options["current-user-helper"].presence || ask("What is the current_user helper called in your app? [current_user]").presence || 'current_user if defined?(current_user)' puts "Defining abstractor_user method inside ApplicationController..." abstractor_user_method = %Q{ def abstractor_user #{current_user_helper} end helper_method :abstractor_user } inject_into_file("#{Rails.root}/app/controllers/application_controller.rb", abstractor_user_method, :after => "ActionController::Base\n") end
plataformatec/responders_backport
81b144c1673d9d82144547c3f18755dc4321f2a2
lib/responders_backport/responder.rb
https://github.com/plataformatec/responders_backport/blob/81b144c1673d9d82144547c3f18755dc4321f2a2/lib/responders_backport/responder.rb#L144-L152
ruby
test
# This is the common behavior for "navigation" requests, like :html, :iphone and so forth.
def navigation_behavior(error)
# This is the common behavior for "navigation" requests, like :html, :iphone and so forth. def navigation_behavior(error)
if get? raise error elsif has_errors? && default_action render :action => default_action else redirect_to resource_location end end
plataformatec/responders_backport
81b144c1673d9d82144547c3f18755dc4321f2a2
lib/responders_backport/responder.rb
https://github.com/plataformatec/responders_backport/blob/81b144c1673d9d82144547c3f18755dc4321f2a2/lib/responders_backport/responder.rb#L155-L165
ruby
test
# This is the common behavior for "API" requests, like :xml and :json.
def api_behavior(error)
# This is the common behavior for "API" requests, like :xml and :json. def api_behavior(error)
if get? display resource elsif has_errors? display resource.errors, :status => :unprocessable_entity elsif post? display resource, :status => :created, :location => resource_location else head :ok end end
bkon/gliffy
4bc70b34e85bb9cb4911cdded2e04f743ca6c7b7
lib/gliffy/folder.rb
https://github.com/bkon/gliffy/blob/4bc70b34e85bb9cb4911cdded2e04f743ca6c7b7/lib/gliffy/folder.rb#L94-L107
ruby
test
# observer callback
def update(event, target)
# observer callback def update(event, target)
case event when :document_removed, :document_deleted @documents = @documents.delete_if { |element| element == target } target.delete_observer(self) when :document_added @documents.push target target.add_observer(self) when :folder_deleted @folders = @folders.delete_if { |element| element == target } else raise ArgumentError.new(event) end end
ab/sixword
4d7b831923a92798e44bbd1edba73fff285bd3db
lib/sixword/cli.rb
https://github.com/ab/sixword/blob/4d7b831923a92798e44bbd1edba73fff285bd3db/lib/sixword/cli.rb#L72-L93
ruby
test
# Format data as hex in various styles.
def print_hex(data, chunk_index, cols=80)
# Format data as hex in various styles. def print_hex(data, chunk_index, cols=80)
case hex_style when 'lower', 'lowercase' # encode to lowercase hex with no newlines print Sixword::Hex.encode(data) when 'finger', 'fingerprint' # encode to GPG fingerprint like hex with newlines newlines_every = cols / 5 if chunk_index != 0 if chunk_index % newlines_every == 0 print "\n" else print ' ' end end print Sixword::Hex.encode_fingerprint(data) when 'colon', 'colons' # encode to SSL/SSH fingerprint like hex with colons print ':' unless chunk_index == 0 print Sixword::Hex.encode_colons(data) end end
ab/sixword
4d7b831923a92798e44bbd1edba73fff285bd3db
lib/sixword/cli.rb
https://github.com/ab/sixword/blob/4d7b831923a92798e44bbd1edba73fff285bd3db/lib/sixword/cli.rb#L96-L115
ruby
test
# Run the encoding/decoding operation, printing the result to stdout.
def run!
# Run the encoding/decoding operation, printing the result to stdout. def run!
if encoding? do_encode! do |encoded| puts encoded end else chunk_index = 0 do_decode! do |decoded| if hex_style print_hex(decoded, chunk_index) chunk_index += 1 else print decoded end end # add trailing newline for hex output puts if hex_style end end
ab/sixword
4d7b831923a92798e44bbd1edba73fff285bd3db
lib/sixword/cli.rb
https://github.com/ab/sixword/blob/4d7b831923a92798e44bbd1edba73fff285bd3db/lib/sixword/cli.rb#L187-L211
ruby
test
# Yield data 6 words at a time until EOF
def read_input_by_6_words
# Yield data 6 words at a time until EOF def read_input_by_6_words
word_arr = [] while true line = stream.gets if line.nil? break # EOF end line.scan(/\S+/) do |word| word_arr << word # return the array if we have accumulated 6 words if word_arr.length == 6 yield word_arr word_arr.clear end end end # yield whatever we have left, if anything if !word_arr.empty? yield word_arr end end
d11wtq/oedipus
37af27d0e5cd7d23896fd0d8f61134a962fc290f
lib/oedipus/query_builder.rb
https://github.com/d11wtq/oedipus/blob/37af27d0e5cd7d23896fd0d8f61134a962fc290f/lib/oedipus/query_builder.rb#L31-L42
ruby
test
# Initialize a new QueryBuilder for +index_name+. # # @param [Symbol] index_name # the name of the index being queried # Build a SphinxQL query for the fulltext search +query+ and filters in +filters+. # # @param [String] query # the fulltext query to execute (may be empty) # # @param [Hash] filters # additional attribute filters and other options # # @return [String] # a SphinxQL query
def select(query, filters)
# Initialize a new QueryBuilder for +index_name+. # # @param [Symbol] index_name # the name of the index being queried # Build a SphinxQL query for the fulltext search +query+ and filters in +filters+. # # @param [String] query # the fulltext query to execute (may be empty) # # @param [Hash] filters # additional attribute filters and other options # # @return [String] # a SphinxQL query def select(query, filters)
where, *bind_values = conditions(query, filters) [ [ from(filters), where, order_by(filters), limits(filters) ].join(" "), *bind_values ] end
d11wtq/oedipus
37af27d0e5cd7d23896fd0d8f61134a962fc290f
lib/oedipus/query_builder.rb
https://github.com/d11wtq/oedipus/blob/37af27d0e5cd7d23896fd0d8f61134a962fc290f/lib/oedipus/query_builder.rb#L68-L78
ruby
test
# Build a SphinxQL query to update the record identified by +id+ with the given attributes. # # @param [Fixnum] id # the unique ID of the document to update # # @param [Hash] attributes # a Hash of attributes # # @return [String] # the SphinxQL to update the record
def update(id, attributes)
# Build a SphinxQL query to update the record identified by +id+ with the given attributes. # # @param [Fixnum] id # the unique ID of the document to update # # @param [Hash] attributes # a Hash of attributes # # @return [String] # the SphinxQL to update the record def update(id, attributes)
set_attrs, *bind_values = update_attributes(attributes) [ [ "UPDATE #{@index_name} SET", set_attrs, "WHERE id = ?" ].join(" "), *bind_values.push(id) ] end
d11wtq/oedipus
37af27d0e5cd7d23896fd0d8f61134a962fc290f
lib/oedipus/connection.rb
https://github.com/d11wtq/oedipus/blob/37af27d0e5cd7d23896fd0d8f61134a962fc290f/lib/oedipus/connection.rb#L90-L92
ruby
test
# Execute a single read query. # # @param [String] sql # a single SphinxQL statement # # @param [Object...] bind_values # values to be substituted in place of '?' in the query # # @return [Array] # an array of Hashes containing the matched records # # Note that SphinxQL does not support prepared statements.
def query(sql, *bind_values)
# Execute a single read query. # # @param [String] sql # a single SphinxQL statement # # @param [Object...] bind_values # values to be substituted in place of '?' in the query # # @return [Array] # an array of Hashes containing the matched records # # Note that SphinxQL does not support prepared statements. def query(sql, *bind_values)
@pool.acquire { |conn| conn.query(sql, *bind_values).first } end
mboeh/woodhouse
ae19cf88a5da6901f62fd860a761615eccc705d0
lib/woodhouse/worker.rb
https://github.com/mboeh/woodhouse/blob/ae19cf88a5da6901f62fd860a761615eccc705d0/lib/woodhouse/worker.rb#L60-L69
ruby
test
# Sets the name for this worker class if not already set (i.e., if it's # an anonymous class). The first time the name for the worker is set, # it becomes registered with MixinRegistry. After that, attempting to # change the worker class will raise ArgumentError.
def set_worker_name(name)
# Sets the name for this worker class if not already set (i.e., if it's # an anonymous class). The first time the name for the worker is set, # it becomes registered with MixinRegistry. After that, attempting to # change the worker class will raise ArgumentError. def set_worker_name(name)
if @worker_name raise ArgumentError, "cannot change worker name" else if name and !name.empty? @worker_name = name.to_sym Woodhouse::MixinRegistry.register self end end end
mboeh/woodhouse
ae19cf88a5da6901f62fd860a761615eccc705d0
lib/woodhouse/worker.rb
https://github.com/mboeh/woodhouse/blob/ae19cf88a5da6901f62fd860a761615eccc705d0/lib/woodhouse/worker.rb#L84-L94
ruby
test
# You can dispatch a job +baz+ on class +FooBar+ by calling FooBar.async_baz.
def method_missing(method, *args, &block)
# You can dispatch a job +baz+ on class +FooBar+ by calling FooBar.async_baz. def method_missing(method, *args, &block)
if method.to_s =~ /^asynch?_(.*)/ if instance_methods(false).detect{|meth| meth.to_s == $1 } Woodhouse.dispatch(@worker_name, $1, args.first) else super end else super end end
mboeh/woodhouse
ae19cf88a5da6901f62fd860a761615eccc705d0
lib/woodhouse/layout.rb
https://github.com/mboeh/woodhouse/blob/ae19cf88a5da6901f62fd860a761615eccc705d0/lib/woodhouse/layout.rb#L46-L53
ruby
test
# Adds a Node to this layout. If +node+ is a Symbol, a Node will be # automatically created with that name. # # # Example: # # layout.add_node Woodhouse::Layout::Node.new(:isis) # # # Is equivalent to # # layout.add_node :isis
def add_node(node)
# Adds a Node to this layout. If +node+ is a Symbol, a Node will be # automatically created with that name. # # # Example: # # layout.add_node Woodhouse::Layout::Node.new(:isis) # # # Is equivalent to # # layout.add_node :isis def add_node(node)
if node.respond_to?(:to_sym) node = Woodhouse::Layout::Node.new(node.to_sym) end expect_arg :node, Woodhouse::Layout::Node, node @nodes << node node end
mboeh/woodhouse
ae19cf88a5da6901f62fd860a761615eccc705d0
lib/woodhouse/layout.rb
https://github.com/mboeh/woodhouse/blob/ae19cf88a5da6901f62fd860a761615eccc705d0/lib/woodhouse/layout.rb#L56-L61
ruby
test
# Looks up a Node by name and returns it.
def node(name)
# Looks up a Node by name and returns it. def node(name)
name = name.to_sym @nodes.detect{|node| node.name == name } end
mboeh/woodhouse
ae19cf88a5da6901f62fd860a761615eccc705d0
lib/woodhouse/layout.rb
https://github.com/mboeh/woodhouse/blob/ae19cf88a5da6901f62fd860a761615eccc705d0/lib/woodhouse/layout.rb#L68-L73
ruby
test
# Returns a frozen copy of this Layout and all of its child Node and # Worker objects. Woodhouse::Server always takes a frozen copy of the # layout it is given. It is thus safe to modify the same layout # subsequently, and the changes only take effect when the layout is # passed to the server again and Woodhouse::Server#reload is called.
def frozen_clone
# Returns a frozen copy of this Layout and all of its child Node and # Worker objects. Woodhouse::Server always takes a frozen copy of the # layout it is given. It is thus safe to modify the same layout # subsequently, and the changes only take effect when the layout is # passed to the server again and Woodhouse::Server#reload is called. def frozen_clone
clone.tap do |cloned| cloned.nodes = @nodes.map{|node| node.frozen_clone }.freeze cloned.freeze end end
samstokes/deferrable_gratification
254d72b5c65e4d2a264013420036a9012d7d8425
lib/deferrable_gratification/combinators.rb
https://github.com/samstokes/deferrable_gratification/blob/254d72b5c65e4d2a264013420036a9012d7d8425/lib/deferrable_gratification/combinators.rb#L205-L217
ruby
test
# If this Deferrable succeeds, ensure that the arguments passed to # +Deferrable#succeed+ meet certain criteria (specified by passing a # predicate as a block). If they do, subsequently defined callbacks will # fire as normal, receiving the same arguments; if they do not, this # Deferrable will fail instead, calling its errbacks with a {GuardFailed} # exception. # # This follows the usual Deferrable semantics of calling +Deferrable#fail+ # inside a callback: any callbacks defined *before* the call to {#guard} # will still execute as normal, but those defined *after* the call to # {#guard} will only execute if the predicate returns truthy. # # Multiple successive calls to {#guard} will work as expected: the # predicates will be evaluated in order, stopping as soon as any of them # returns falsy, and subsequent callbacks will fire only if all the # predicates pass. # # If instead of returning a boolean, the predicate raises an exception, # the Deferrable will fail, but errbacks will receive the exception raised # instead of {GuardFailed}. You could use this to indicate the reason for # failure in a complex guard expression; however the same intent might be # more clearly expressed by multiple guard expressions with appropriate # reason messages. # # @param [String] reason optional description of the reason for the guard: # specifying this will both serve as code # documentation, and be included in the # {GuardFailed} exception for error handling # purposes. # # @yieldparam *args the arguments passed to callbacks if this Deferrable # succeeds. # @yieldreturn [Boolean] +true+ if subsequent callbacks should fire (with # the same arguments); +false+ if instead errbacks # should fire. # # @raise [ArgumentError] if called without a predicate
def guard(reason = nil, &block)
# If this Deferrable succeeds, ensure that the arguments passed to # +Deferrable#succeed+ meet certain criteria (specified by passing a # predicate as a block). If they do, subsequently defined callbacks will # fire as normal, receiving the same arguments; if they do not, this # Deferrable will fail instead, calling its errbacks with a {GuardFailed} # exception. # # This follows the usual Deferrable semantics of calling +Deferrable#fail+ # inside a callback: any callbacks defined *before* the call to {#guard} # will still execute as normal, but those defined *after* the call to # {#guard} will only execute if the predicate returns truthy. # # Multiple successive calls to {#guard} will work as expected: the # predicates will be evaluated in order, stopping as soon as any of them # returns falsy, and subsequent callbacks will fire only if all the # predicates pass. # # If instead of returning a boolean, the predicate raises an exception, # the Deferrable will fail, but errbacks will receive the exception raised # instead of {GuardFailed}. You could use this to indicate the reason for # failure in a complex guard expression; however the same intent might be # more clearly expressed by multiple guard expressions with appropriate # reason messages. # # @param [String] reason optional description of the reason for the guard: # specifying this will both serve as code # documentation, and be included in the # {GuardFailed} exception for error handling # purposes. # # @yieldparam *args the arguments passed to callbacks if this Deferrable # succeeds. # @yieldreturn [Boolean] +true+ if subsequent callbacks should fire (with # the same arguments); +false+ if instead errbacks # should fire. # # @raise [ArgumentError] if called without a predicate def guard(reason = nil, &block)
raise ArgumentError, 'must be called with a block' unless block_given? callback do |*callback_args| begin unless block.call(*callback_args) raise ::DeferrableGratification::GuardFailed.new(reason, callback_args) end rescue => exception fail(exception) end end self end
menglifang/task-manager
c6196c0e30d27d008f406321b0abb7e3fb9c02c6
app/models/task_manager/plan.rb
https://github.com/menglifang/task-manager/blob/c6196c0e30d27d008f406321b0abb7e3fb9c02c6/app/models/task_manager/plan.rb#L39-L50
ruby
test
# 生成计划任务 # # 为每一个计划的执行者创建一个计划任务。
def generate_tasks
# 生成计划任务 # # 为每一个计划的执行者创建一个计划任务。 def generate_tasks
tasks = [] Plan.transaction do assignables.each do |a| tasks << generate_task_for_assignable(a) end end update_attributes(last_task_created_at: Time.now) tasks end
marcandre/scheherazade
321e8e5f9f84c777168de10de8df6075141be215
lib/scheherazade/character_builder.rb
https://github.com/marcandre/scheherazade/blob/321e8e5f9f84c777168de10de8df6075141be215/lib/scheherazade/character_builder.rb#L28-L43
ruby
test
# Note: must be equal? to AUTO (i.e. same object), not just == # builds a character, filling required attributes, # default attributes for this type of character and # the attributes given. # # If the built object is invalid, the attributes with # errors will also be filled. # # An invalid object may be returned. In particular, it is # possible that it is only invalid because an associated # model is not yet valid.
def build(attribute_list = nil)
# Note: must be equal? to AUTO (i.e. same object), not just == # builds a character, filling required attributes, # default attributes for this type of character and # the attributes given. # # If the built object is invalid, the attributes with # errors will also be filled. # # An invalid object may be returned. In particular, it is # possible that it is only invalid because an associated # model is not yet valid. def build(attribute_list = nil)
@seq = (story.counter[@model] += 1) lists = [required_attributes, *default_attribute_lists, attribute_list] lists.prepend [:created_at] if @ar.has_attribute?(:created_at) attribute_list = lists.map{|al| canonical(al)}.inject(:merge) log(:building, attribute_list) set_attributes(attribute_list) unless @ar.valid? attribute_list = canonical(@ar.errors.map{|attr, _| attr}) log(:fixing_errors, attribute_list) set_attributes(attribute_list) end yield @ar if block_given? log(:final_value, @ar) @ar end