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
apeiros/tabledata
e277b6a1fdb567a6d73f42349bb9946ffad67134
lib/tabledata/row.rb
https://github.com/apeiros/tabledata/blob/e277b6a1fdb567a6d73f42349bb9946ffad67134/lib/tabledata/row.rb#L84-L90
ruby
test
# Convenience access of values in the row. # Can either be used like Array#[], i.e. it accepts an offset, # an offset + length, or an offset-to-offset range. # Alternatively you can use a Symbol, if it's a valid accessor in this table. # And the last variant is using a String, which will access the value of # the corresponding header. # # @return [Array, Object] Either the value of a given cell, or an array of values. # # @see #slice for a faster way to use ranges or offset+length # @see #at_accessor for a faster way to access by name # @see #at_index for a faster way to access by index # @see #at_header for a faster way to access by header value
def [](a,b=nil)
# Convenience access of values in the row. # Can either be used like Array#[], i.e. it accepts an offset, # an offset + length, or an offset-to-offset range. # Alternatively you can use a Symbol, if it's a valid accessor in this table. # And the last variant is using a String, which will access the value of # the corresponding header. # # @return [Array, Object] Either the value of a given cell, or an array of values. # # @see #slice for a faster way to use ranges or offset+length # @see #at_accessor for a faster way to access by name # @see #at_index for a faster way to access by index # @see #at_header for a faster way to access by header value def [](a,b=nil)
if b || a.is_a?(Range) then slice(a,b) else at(a) end end
apeiros/tabledata
e277b6a1fdb567a6d73f42349bb9946ffad67134
lib/tabledata/row.rb
https://github.com/apeiros/tabledata/blob/e277b6a1fdb567a6d73f42349bb9946ffad67134/lib/tabledata/row.rb#L119-L127
ruby
test
# Access a single cell by either index, index-range, accessor or header-name. # # @example # table = Tabledata.table header: %w[x y z], body: [[:a,:b,:c]], accessors: %i[foo bar baz] # row = table.row(1) # row.at(0) # => :a # row.at(:foo) # => :a # row.at("x") # => :a
def at(column)
# Access a single cell by either index, index-range, accessor or header-name. # # @example # table = Tabledata.table header: %w[x y z], body: [[:a,:b,:c]], accessors: %i[foo bar baz] # row = table.row(1) # row.at(0) # => :a # row.at(:foo) # => :a # row.at("x") # => :a def at(column)
case column when Symbol then at_accessor(column) when String then at_header(column) when Integer then at_index(column) when Range then @data[column] else raise InvalidColumnSpecifier, "Invalid index type, expected Symbol, String or Integer, but got #{column.class}" end end
apeiros/tabledata
e277b6a1fdb567a6d73f42349bb9946ffad67134
lib/tabledata/row.rb
https://github.com/apeiros/tabledata/blob/e277b6a1fdb567a6d73f42349bb9946ffad67134/lib/tabledata/row.rb#L175-L187
ruby
test
# Access multiple values by either index, index-range, accessor or header-name. # @example # table = Tabledata.table header: %w[x y z], body: [[:a,:b,:c]], accessors: %i[foo bar baz] # row = table.row(1) # row.values_at(2,1,0) # => [:c, :b, :a] # row.values_at(:foo,'z') # => [:a, :c] # row.values_at(0..1, 2..-1) # => [:a, :b, :c]
def values_at(*columns)
# Access multiple values by either index, index-range, accessor or header-name. # @example # table = Tabledata.table header: %w[x y z], body: [[:a,:b,:c]], accessors: %i[foo bar baz] # row = table.row(1) # row.values_at(2,1,0) # => [:c, :b, :a] # row.values_at(:foo,'z') # => [:a, :c] # row.values_at(0..1, 2..-1) # => [:a, :b, :c] def values_at(*columns)
result = [] columns.each do |column| data = at(column) if column.is_a?(Range) result.concat(data) if data else result << data end end result end
apeiros/tabledata
e277b6a1fdb567a6d73f42349bb9946ffad67134
lib/tabledata/row.rb
https://github.com/apeiros/tabledata/blob/e277b6a1fdb567a6d73f42349bb9946ffad67134/lib/tabledata/row.rb#L219-L236
ruby
test
# Allow reading and writing cell values by their accessor name.
def method_missing(name, *args, &block)
# Allow reading and writing cell values by their accessor name. def method_missing(name, *args, &block)
return super unless @table.accessors? name =~ /^(\w+)(=)?$/ name_mod, assign = $1, $2 index = @table.index_for_accessor(name_mod) arg_count = assign ? 1 : 0 return super unless index raise ArgumentError, "Wrong number of arguments (#{args.size} for #{arg_count})" if args.size > arg_count if assign then @data[index] = args.first else @data[index] end end
hybridgroup/taskmapper-unfuddle
7a43746814bf7359dea6418e3f2f6d73239caf8c
lib/provider/unfuddle.rb
https://github.com/hybridgroup/taskmapper-unfuddle/blob/7a43746814bf7359dea6418e3f2f6d73239caf8c/lib/provider/unfuddle.rb#L15-L24
ruby
test
# Providers must define an authorize method. This is used to initialize and set authentication # parameters to access the API
def authorize(auth = {})
# Providers must define an authorize method. This is used to initialize and set authentication # parameters to access the API def authorize(auth = {})
@authentication ||= TaskMapper::Authenticator.new(auth) auth = @authentication if (auth.account.nil? and auth.subdomain.nil?) or auth.username.nil? or auth.password.nil? raise "Please provide at least an account (subdomain), username and password)" end UnfuddleAPI.protocol = auth.protocol if auth.protocol? UnfuddleAPI.account = auth.account || auth.subdomain UnfuddleAPI.authenticate(auth.username, auth.password) end
chetan/bixby-auth
5dec1eec500c7075ddd04608e56e33e78f41a0f6
lib/api_auth/helpers.rb
https://github.com/chetan/bixby-auth/blob/5dec1eec500c7075ddd04608e56e33e78f41a0f6/lib/api_auth/helpers.rb#L5-L12
ruby
test
# :nodoc:
def b64_encode(string)
# :nodoc: def b64_encode(string)
if Base64.respond_to?(:strict_encode64) Base64.strict_encode64(string) else # Fall back to stripping out newlines on Ruby 1.8. Base64.encode64(string).gsub(/\n/, '') end end
hakamadare/rubygem-reliquary
23f380010d1174ccb7c0da0a6978679ffde8abec
lib/reliquary/client.rb
https://github.com/hakamadare/rubygem-reliquary/blob/23f380010d1174ccb7c0da0a6978679ffde8abec/lib/reliquary/client.rb#L49-L57
ruby
test
# @!method initialize(api_key = get_api_key_from_env) # Constructor method # @param api_key [String] (see api_key) # @return [Reliquary::Client] the initialized client # # @!method parse(json) # Parse returned JSON into a Ruby object # # @param [String] json JSON-formatted string # @return [Object] Ruby object representing JSON-formatted string
def parse(json)
# @!method initialize(api_key = get_api_key_from_env) # Constructor method # @param api_key [String] (see api_key) # @return [Reliquary::Client] the initialized client # # @!method parse(json) # Parse returned JSON into a Ruby object # # @param [String] json JSON-formatted string # @return [Object] Ruby object representing JSON-formatted string def parse(json)
begin # strip off some layers of nonsense added by Oj MultiJson.load(json, :symbolize_keys => true).values[0] rescue StandardError => e raise e end end
hakamadare/rubygem-reliquary
23f380010d1174ccb7c0da0a6978679ffde8abec
lib/reliquary/client.rb
https://github.com/hakamadare/rubygem-reliquary/blob/23f380010d1174ccb7c0da0a6978679ffde8abec/lib/reliquary/client.rb#L66-L73
ruby
test
# @!method method_missing(method_name, *args, &block) # Delegate HTTP method calls to RestClient::Resource # # @param method_name [Symbol] name of method (must be a member of # {Reliquary::Client::HTTP_METHODS}) # @param args [Array] additional method params # @param block [Proc] block to which method will yield
def method_missing(method_name, *args, &block)
# @!method method_missing(method_name, *args, &block) # Delegate HTTP method calls to RestClient::Resource # # @param method_name [Symbol] name of method (must be a member of # {Reliquary::Client::HTTP_METHODS}) # @param args [Array] additional method params # @param block [Proc] block to which method will yield def method_missing(method_name, *args, &block)
begin self.api_base.send(method_name.to_sym, *args, &block) rescue StandardError => e raise e end end
balmoral/volt-watch
6290e5060db68e8353d6141906f57eb09d29f91e
lib/volt/watch.rb
https://github.com/balmoral/volt-watch/blob/6290e5060db68e8353d6141906f57eb09d29f91e/lib/volt/watch.rb#L100-L105
ruby
test
# Adds a watch for a shallow change in the contents # (attributes, elements, or key-value pairs) of one or # more reactive objects. # # Reactive objects are any of: # Volt::Model # Volt::ArrayModel # Volt::ReactiveArray # Volt::ReactiveHash # # When any value in the model, array or hash changes then # the given block will be called. # # The values of a Volt::Model are its attributes. # # The values of a Volt::ArrayModel or Volt::ReactiveArray are its elements. # # The values of an Volt::ReactiveHash are its key-value pairs. # # If the args contain more than one object or the arity of the # block, then the block will be passed the object, the # locus and the value. If only one object is given and the # block arity is less than 3, then the locus and the value # will be passed to the block. # # The locus is: # the field name for a Volt::Model # the integer index or :size for a Volt::ArrayModel # the integer index or :size for a Volt::ReactiveArray # the key for Volt::ReactiveHash # # For example: # # ``` # on_change_in(user) do |object, attr, value| # puts "#{object}.#{attr} => #{value}" # end # ``` # or # # ``` # on_change_in(user) do |attr| # puts "user.#{attr} => #{user.get(attr)}" # end # ``` # or # # ``` # on_change_in(page._items) do |index, value| # puts "page[#{index}] => #{item}" # end # ``` # or # # ``` # on_change_in(page._items) do |index| # puts "page[#{index}] => #{page._items[index]}" # end # ``` # or # # ``` # on_change_in(store.dictionary) do |key, entry| # puts "dictionary[#{key}] => #{entry}" # end # ``` # or # ``` # on_change_in(store.dictionary) do |key| # puts "dictionary[#{key}] => #{store.dictionary[key]}" # end # ```
def on_change_in(*args, except: nil, &block)
# Adds a watch for a shallow change in the contents # (attributes, elements, or key-value pairs) of one or # more reactive objects. # # Reactive objects are any of: # Volt::Model # Volt::ArrayModel # Volt::ReactiveArray # Volt::ReactiveHash # # When any value in the model, array or hash changes then # the given block will be called. # # The values of a Volt::Model are its attributes. # # The values of a Volt::ArrayModel or Volt::ReactiveArray are its elements. # # The values of an Volt::ReactiveHash are its key-value pairs. # # If the args contain more than one object or the arity of the # block, then the block will be passed the object, the # locus and the value. If only one object is given and the # block arity is less than 3, then the locus and the value # will be passed to the block. # # The locus is: # the field name for a Volt::Model # the integer index or :size for a Volt::ArrayModel # the integer index or :size for a Volt::ReactiveArray # the key for Volt::ReactiveHash # # For example: # # ``` # on_change_in(user) do |object, attr, value| # puts "#{object}.#{attr} => #{value}" # end # ``` # or # # ``` # on_change_in(user) do |attr| # puts "user.#{attr} => #{user.get(attr)}" # end # ``` # or # # ``` # on_change_in(page._items) do |index, value| # puts "page[#{index}] => #{item}" # end # ``` # or # # ``` # on_change_in(page._items) do |index| # puts "page[#{index}] => #{page._items[index]}" # end # ``` # or # # ``` # on_change_in(store.dictionary) do |key, entry| # puts "dictionary[#{key}] => #{entry}" # end # ``` # or # ``` # on_change_in(store.dictionary) do |key| # puts "dictionary[#{key}] => #{store.dictionary[key]}" # end # ``` def on_change_in(*args, except: nil, &block)
args.each do |arg| ensure_reactive(arg) traverse(arg, :shallow, except, args.size > 1 || block.arity == 3, block) end end
balmoral/volt-watch
6290e5060db68e8353d6141906f57eb09d29f91e
lib/volt/watch.rb
https://github.com/balmoral/volt-watch/blob/6290e5060db68e8353d6141906f57eb09d29f91e/lib/volt/watch.rb#L204-L209
ruby
test
# Does a deep traversal of all values reachable from # the given root object(s). # # Such values include: # * attributes and field values of Volt::Model's # * size and elements of Volt::ArrayModel's # * size and elements of Volt::ReactiveArray's # * size and key-value pairs of Volt::ReactiveHash's # * nested values of the above # # The root(s) may be a Volt::Model, Volt::ArrayModel, # Volt::ReactiveArray or Volt::ReactiveHash. # # The given block may accept one, two or three arguments. # # The block will be called when any value reachable from # (one of) the root(s) changes. # 1. the model (owner) of the value that changed # i.e. the model, array or hash holding the value # 2. the locus of the value, either: # * the attribute or field name for a model # * the index in an array # * the key in a hash # * the symbol :size if array or hash size changes # 3. the new value # The block may choose to accept 2 or 3 arguments. # This mode is suitable when watching for deep changes # to the contents of a model/array/hash and you DO need # to identify what value that changed. # # In both modes, an optional argument specifying attributes # you don't want to watch may be given with the :except # keyword argument. The argument should be a symbol or # integer or array of symbols or integers matching model # attributes, array indexes or hash keys which you wish # to ignore changes to. It may also include `:size` if you # wish to ignore changes to the size of arrays or hashes. # TODO: make :except more precise, perhaps with pairs of # [parent, locus] to identify exceptions more accurately. # Also allow for [Class, locus] to except any object of # the given class. # # For example: # # ``` # class Contact < Volt::Model # field :street # field :city # field :zip # field :country # field :phone # field :email # end # # class Customer < Volt::Model # field :name # field :contact # end # # class Order < Volt::Model # field :customer # field :product # field :date # field :quantity # end # # ... # # def deep_order_watch # # one argument in given block has no detail of change # on_deep_change_in orders do |store._orders| # puts "something unknown changed in orders" # end # end # # def on_deep_change_in # # three arguments in given block gives detail of change # on_deep_change_in store._orders do |context, locus, value| # case # when context == store._orders # if locus == :size # puts "orders.size has changed to #{value}" # else # index = locus # puts "orders[#{index}] has changed to #{value}" # end # when context.is_a? Order # order, attr = context, locus # puts "Order[#{order.id}].#{attr} has changed to #{value}" # when context.is_a? Customer # customer, attr = context, locus # puts "customer #{customer.id} #{attr} has changed to #{value}" # end # end # end # ```
def on_deep_change_in(*roots, except: nil, &block)
# Does a deep traversal of all values reachable from # the given root object(s). # # Such values include: # * attributes and field values of Volt::Model's # * size and elements of Volt::ArrayModel's # * size and elements of Volt::ReactiveArray's # * size and key-value pairs of Volt::ReactiveHash's # * nested values of the above # # The root(s) may be a Volt::Model, Volt::ArrayModel, # Volt::ReactiveArray or Volt::ReactiveHash. # # The given block may accept one, two or three arguments. # # The block will be called when any value reachable from # (one of) the root(s) changes. # 1. the model (owner) of the value that changed # i.e. the model, array or hash holding the value # 2. the locus of the value, either: # * the attribute or field name for a model # * the index in an array # * the key in a hash # * the symbol :size if array or hash size changes # 3. the new value # The block may choose to accept 2 or 3 arguments. # This mode is suitable when watching for deep changes # to the contents of a model/array/hash and you DO need # to identify what value that changed. # # In both modes, an optional argument specifying attributes # you don't want to watch may be given with the :except # keyword argument. The argument should be a symbol or # integer or array of symbols or integers matching model # attributes, array indexes or hash keys which you wish # to ignore changes to. It may also include `:size` if you # wish to ignore changes to the size of arrays or hashes. # TODO: make :except more precise, perhaps with pairs of # [parent, locus] to identify exceptions more accurately. # Also allow for [Class, locus] to except any object of # the given class. # # For example: # # ``` # class Contact < Volt::Model # field :street # field :city # field :zip # field :country # field :phone # field :email # end # # class Customer < Volt::Model # field :name # field :contact # end # # class Order < Volt::Model # field :customer # field :product # field :date # field :quantity # end # # ... # # def deep_order_watch # # one argument in given block has no detail of change # on_deep_change_in orders do |store._orders| # puts "something unknown changed in orders" # end # end # # def on_deep_change_in # # three arguments in given block gives detail of change # on_deep_change_in store._orders do |context, locus, value| # case # when context == store._orders # if locus == :size # puts "orders.size has changed to #{value}" # else # index = locus # puts "orders[#{index}] has changed to #{value}" # end # when context.is_a? Order # order, attr = context, locus # puts "Order[#{order.id}].#{attr} has changed to #{value}" # when context.is_a? Customer # customer, attr = context, locus # puts "customer #{customer.id} #{attr} has changed to #{value}" # end # end # end # ``` def on_deep_change_in(*roots, except: nil, &block)
roots.each do |root| ensure_reactive(root) traverse(root, :node, except, true, block) end end
balmoral/volt-watch
6290e5060db68e8353d6141906f57eb09d29f91e
lib/volt/watch.rb
https://github.com/balmoral/volt-watch/blob/6290e5060db68e8353d6141906f57eb09d29f91e/lib/volt/watch.rb#L240-L245
ruby
test
# Must behave like a Volt::Model # and respond to #get(attribute)
def reactive_model?(model)
# Must behave like a Volt::Model # and respond to #get(attribute) def reactive_model?(model)
Volt::Model === model || # dirty way of letting anything be reactive if it wants (model.respond_to?(:reactive_model?) && model.reactive_model?) || (model.class.respond_to?(:reactive_model?) && model.class.reactive_model?) end
balmoral/volt-watch
6290e5060db68e8353d6141906f57eb09d29f91e
lib/volt/watch.rb
https://github.com/balmoral/volt-watch/blob/6290e5060db68e8353d6141906f57eb09d29f91e/lib/volt/watch.rb#L248-L254
ruby
test
# Must behave like a Volt::ArrayModel or Volt::ReactiveArray
def reactive_array?(model)
# Must behave like a Volt::ArrayModel or Volt::ReactiveArray def reactive_array?(model)
Volt::ArrayModel === model || Volt::ReactiveArray === model || # dirty way of letting anything be reactive if it wants (model.respond_to?(:reactive_array?) && model.reactive_array?) || (model.class.respond_to?(:reactive_array?) && model.class.reactive_array?) end
balmoral/volt-watch
6290e5060db68e8353d6141906f57eb09d29f91e
lib/volt/watch.rb
https://github.com/balmoral/volt-watch/blob/6290e5060db68e8353d6141906f57eb09d29f91e/lib/volt/watch.rb#L257-L262
ruby
test
# Must behave like a Volt::ReactiveHash
def reactive_hash?(model)
# Must behave like a Volt::ReactiveHash def reactive_hash?(model)
Volt::ReactiveHash === model || # dirty way of letting anything be reactive if it wants (model.respond_to?(:reactive_hash?) && model.reactive_hash?) || (model.class.respond_to?(:reactive_hash?) && model.class.reactive_hash?) end
miya0001/pb-cli
abb7802f406de743d28e964329efc4637b4e10d3
lib/pb/cli/push.rb
https://github.com/miya0001/pb-cli/blob/abb7802f406de743d28e964329efc4637b4e10d3/lib/pb/cli/push.rb#L16-L36
ruby
test
# method_option :person, :aliases => "-p", :desc => "Delete the file after parsing it"
def create( message = "" )
# method_option :person, :aliases => "-p", :desc => "Delete the file after parsing it" def create( message = "" )
if "help" == message invoke( :help, [ "create" ] ); exit 0 end if File.pipe?( STDIN ) || File.select( [STDIN], [], [], 0 ) != nil then message = STDIN.readlines().join( "" ) end url = "https://api.pushbullet.com/v2/pushes" token = Utils::get_token( options ) unless message.empty? args = Utils::get_push_args( options ) args['body'] = message Utils::send( url, token, "post", args ) else puts "Nothing to do." end end
aphyr/risky
2f3dac30ff6b8aa06429bf68849b8b870f16831f
lib/risky/secondary_indexes.rb
https://github.com/aphyr/risky/blob/2f3dac30ff6b8aa06429bf68849b8b870f16831f/lib/risky/secondary_indexes.rb#L14-L39
ruby
test
# Add a new secondary index to this model. # Default option is :type => :int, can also be :bin # Default option is :multi => false, can also be true # Option :map can be used to map the index to a model (see map_model). # This assumes by default that the index name ends in _id (use :map => true) # If it ends in something else, use :map => '_suffix'
def index2i(name, opts = {})
# Add a new secondary index to this model. # Default option is :type => :int, can also be :bin # Default option is :multi => false, can also be true # Option :map can be used to map the index to a model (see map_model). # This assumes by default that the index name ends in _id (use :map => true) # If it ends in something else, use :map => '_suffix' def index2i(name, opts = {})
name = name.to_s opts.replace({:type => :int, :multi => false, :finder => :find}.merge(opts)) indexes2i[name] = opts class_eval %Q{ def #{name} @indexes2i['#{name}'] end def #{name}=(value) @indexes2i['#{name}'] = value end } if opts[:map] if opts[:map] === true # assume that it ends in _id model_name = name[0..-4] map_model(model_name, opts) else model_name = name[0..-(opts[:map].length + 1)] map_model(model_name, opts.merge(:suffix => opts[:map])) end end end
aphyr/risky
2f3dac30ff6b8aa06429bf68849b8b870f16831f
lib/risky/secondary_indexes.rb
https://github.com/aphyr/risky/blob/2f3dac30ff6b8aa06429bf68849b8b870f16831f/lib/risky/secondary_indexes.rb#L103-L124
ruby
test
# The map_model method is a convenience method to map the model_id to getters and setters. # The assumption is that you have a value or index2i for model_id. # The default suffix is '_id', so map_model :promotion implies that promotion_id is the index2i. # # For example, map_model :promotion will create these three methods # ```ruby # def promotion # @promotion ||= Promotion.find_by_id promotion_id # end # # def promotion=(value) # @promotion = promotion # self.promotion_id = value.nil? ? nil : value.id # end # # def promotion_id=(value) # @promotion = nil if self.promotion_id != value # indexes2i['promotion_id'] = value # end # ```
def map_model(model_name, opts = {})
# The map_model method is a convenience method to map the model_id to getters and setters. # The assumption is that you have a value or index2i for model_id. # The default suffix is '_id', so map_model :promotion implies that promotion_id is the index2i. # # For example, map_model :promotion will create these three methods # ```ruby # def promotion # @promotion ||= Promotion.find_by_id promotion_id # end # # def promotion=(value) # @promotion = promotion # self.promotion_id = value.nil? ? nil : value.id # end # # def promotion_id=(value) # @promotion = nil if self.promotion_id != value # indexes2i['promotion_id'] = value # end # ``` def map_model(model_name, opts = {})
model_name = model_name.to_s class_name = Risky::Inflector.classify(model_name) opts.replace({:type => :index2i, :suffix => '_id'}.merge(opts)) class_eval %Q{ def #{model_name} @#{model_name} ||= #{class_name}.#{opts[:finder]} #{model_name}#{opts[:suffix]} end def #{model_name}=(value) @#{model_name} = value self.#{model_name}#{opts[:suffix]} = value.nil? ? nil : value.id end def #{model_name}_id=(value) @#{model_name} = nil if self.#{model_name}_id != value indexes2i['#{model_name}#{opts[:suffix]}'] = value end } end
CiscoSystems/ropenstack
77dcb332711da2a35fe5abf2b6c63a0415c0bf69
lib/ropenstack/networking/v2/extensions/l3.rb
https://github.com/CiscoSystems/ropenstack/blob/77dcb332711da2a35fe5abf2b6c63a0415c0bf69/lib/ropenstack/networking/v2/extensions/l3.rb#L10-L16
ruby
test
# Get a list of a tenants routers # # :call-seq: # routers(id) => A single router with the id matching the parameter # routers => All routers visible to the tenant making the request
def routers(id = nil)
# Get a list of a tenants routers # # :call-seq: # routers(id) => A single router with the id matching the parameter # routers => All routers visible to the tenant making the request def routers(id = nil)
endpoint = "routers" unless id.nil? endpoint = endpoint + "/" + id end return get_request(address(endpoint), @token) end
CiscoSystems/ropenstack
77dcb332711da2a35fe5abf2b6c63a0415c0bf69
lib/ropenstack/networking/v2/extensions/l3.rb
https://github.com/CiscoSystems/ropenstack/blob/77dcb332711da2a35fe5abf2b6c63a0415c0bf69/lib/ropenstack/networking/v2/extensions/l3.rb#L20-L28
ruby
test
# Create a new router with a given name.
def create_router(name, admin_state_up = true)
# Create a new router with a given name. def create_router(name, admin_state_up = true)
data = { 'router' =>{ 'name' => name, 'admin_state_up' => admin_state_up, } } return post_request(address("routers"), data, @token) end
CiscoSystems/ropenstack
77dcb332711da2a35fe5abf2b6c63a0415c0bf69
lib/ropenstack/networking/v2/extensions/l3.rb
https://github.com/CiscoSystems/ropenstack/blob/77dcb332711da2a35fe5abf2b6c63a0415c0bf69/lib/ropenstack/networking/v2/extensions/l3.rb#L53-L60
ruby
test
# Delete a connection between a subnet and router given either port # or subnet ids. # # :call-seq: # delete_router_interface(router_id, subnet_id, "subnet") # delete_router_interface(router_id, port_id, "port")
def delete_router_interface(router, id, type)
# Delete a connection between a subnet and router given either port # or subnet ids. # # :call-seq: # delete_router_interface(router_id, subnet_id, "subnet") # delete_router_interface(router_id, port_id, "port") def delete_router_interface(router, id, type)
data = case type when 'port' then { 'port_id' => id } when 'subnet' then { 'subnet_id' => id } else raise "Invalid Interface Type" end return put_request(address("routers/" + router + "/remove_router_interface"), data, @token) end
fntz/ov
b1d954c3a3e7deb4130adb704bd4b62d329769ca
lib/ov/ov_array.rb
https://github.com/fntz/ov/blob/b1d954c3a3e7deb4130adb704bd4b62d329769ca/lib/ov/ov_array.rb#L8-L19
ruby
test
# find in self # find in ancestors # find types # find any types
def where(method)
# find in self # find in ancestors # find types # find any types def where(method)
@complete, @result = nil, nil z = find_or_next(method) { |method| self.find{|m| m.eql?(method) } }.find_or_next(method) { |method| self.find{|m| m.eql0?(method) } }.find_or_next(method) { |method| self.find{|m| m.like?(method) } }.find_or_next(method) {|method| self.find{|m| m.like0?(method) } }.get end
mjacobus/semistatic
ea750ef2b91028226f4da67b0d74738fbf311dd1
lib/semistatic/configuration.rb
https://github.com/mjacobus/semistatic/blob/ea750ef2b91028226f4da67b0d74738fbf311dd1/lib/semistatic/configuration.rb#L38-L43
ruby
test
# load config from files
def load
# load config from files def load
config_files.each do |file| config = YAML::load(File.open(file)) @config.merge! config end end
lyfeyaj/rsqoot
0b3157f55f3a1fa2b21ac5389fe1686a77e6a4fd
lib/rsqoot/provider.rb
https://github.com/lyfeyaj/rsqoot/blob/0b3157f55f3a1fa2b21ac5389fe1686a77e6a4fd/lib/rsqoot/provider.rb#L6-L16
ruby
test
# Retrieve a list of providers base on the following parameters # # @return [RSqoot::SqootProvider]
def providers(options = {})
# Retrieve a list of providers base on the following parameters # # @return [RSqoot::SqootProvider] def providers(options = {})
options = update_by_expire_time options query = options.delete(:query) if providers_not_latest?(options) @rsqoot_providers = get('providers', options, SqootProvider) @rsqoot_providers = @rsqoot_providers.providers.map(&:provider) if @rsqoot_providers end result = query.present? ? query_providers(query) : @rsqoot_providers logger(uri: sqoot_query_uri, records: result, type: 'providers', opts: options) result end
lyfeyaj/rsqoot
0b3157f55f3a1fa2b21ac5389fe1686a77e6a4fd
lib/rsqoot/category.rb
https://github.com/lyfeyaj/rsqoot/blob/0b3157f55f3a1fa2b21ac5389fe1686a77e6a4fd/lib/rsqoot/category.rb#L7-L17
ruby
test
# Retrieve a list of categories base on the following parameters # # @return [RSqoot::SqootCategory] category list
def categories(options = {})
# Retrieve a list of categories base on the following parameters # # @return [RSqoot::SqootCategory] category list def categories(options = {})
options = update_by_expire_time options query = options.delete(:query) if categories_not_latest?(options) @rsqoot_categories = get('categories', options, SqootCategory) @rsqoot_categories = @rsqoot_categories.categories.map(&:category) if @rsqoot_categories end result = query.present? ? query_categories(query) : @rsqoot_categories logger(uri: sqoot_query_uri, records: result, type: 'categories', opts: options) result end
jdtornow/challah-rolls
ba235d5f0f1e65210907b1e4d3dcb0a7d765077a
lib/challah/rolls/role.rb
https://github.com/jdtornow/challah-rolls/blob/ba235d5f0f1e65210907b1e4d3dcb0a7d765077a/lib/challah/rolls/role.rb#L57-L94
ruby
test
# This method sets up the +Role+ class with all baked in methods. # # A role requires the presence of the +name+ and +default_path+ attributes. # # Once this method has been called, the {InstanceMethods} and {ClassMethods} modules # will be accessibile within the Role model.
def challah_role
# This method sets up the +Role+ class with all baked in methods. # # A role requires the presence of the +name+ and +default_path+ attributes. # # Once this method has been called, the {InstanceMethods} and {ClassMethods} modules # will be accessibile within the Role model. def challah_role
unless included_modules.include?(InstanceMethods) include InstanceMethods extend ClassMethods end class_eval do # Validations ################################################################ validates :name, :presence => true, :uniqueness => true # Relationships ################################################################ has_many :permission_roles, :dependent => :destroy has_many :permissions, :through => :permission_roles, :order => 'permissions.name' has_many :users, :order => 'users.first_name, users.last_name' # Scoped Finders ################################################################ default_scope order('roles.name') # Callbacks ################################################################ after_save :save_permission_keys # Attributes ################################################################ attr_accessible :description, :default_path, :locked, :name end end
sixoverground/tang
66fff66d5abe03f5e69e98601346a88c71e54675
app/models/tang/subscription.rb
https://github.com/sixoverground/tang/blob/66fff66d5abe03f5e69e98601346a88c71e54675/app/models/tang/subscription.rb#L123-L128
ruby
test
# def nil_if_blank # self.trial_end = nil if self.trial_end.blank? # end
def check_for_upgrade
# def nil_if_blank # self.trial_end = nil if self.trial_end.blank? # end def check_for_upgrade
if plan_id_changed? old_plan = Plan.find(plan_id_was) if plan_id_was.present? self.upgraded = true if old_plan.nil? || old_plan.order < plan.order end end
zeevex/zeevex_proxy
b85204495be256cf711595592780aa7b5b371c52
lib/zeevex_proxy/base.rb
https://github.com/zeevex/zeevex_proxy/blob/b85204495be256cf711595592780aa7b5b371c52/lib/zeevex_proxy/base.rb#L62-L65
ruby
test
# if chainable method or returns "self" for some other reason, # return this proxy instead
def method_missing(name, *args, &block)
# if chainable method or returns "self" for some other reason, # return this proxy instead def method_missing(name, *args, &block)
obj = __getobj__ __substitute_self__(obj.__send__(name, *args, &block), obj) end
lyfeyaj/rsqoot
0b3157f55f3a1fa2b21ac5389fe1686a77e6a4fd
lib/rsqoot/deal.rb
https://github.com/lyfeyaj/rsqoot/blob/0b3157f55f3a1fa2b21ac5389fe1686a77e6a4fd/lib/rsqoot/deal.rb#L12-L22
ruby
test
# Retrieve a list of deals based on the following parameters # # @param [String] query (Search deals by title, description, fine print, merchant name, provider, and category.) # @param [String] location (Limit results to a particular area. We'll resolve whatever you pass us (including an IP address) to coordinates and search near there.) # @param [Integer] radius (Measured in miles. Defaults to 10.) # @param [Integer] page (Which page of result to return. Default to 1.) # @param [Integer] per_page (Number of results to return at once. Defaults to 10.)
def deals(options = {})
# Retrieve a list of deals based on the following parameters # # @param [String] query (Search deals by title, description, fine print, merchant name, provider, and category.) # @param [String] location (Limit results to a particular area. We'll resolve whatever you pass us (including an IP address) to coordinates and search near there.) # @param [Integer] radius (Measured in miles. Defaults to 10.) # @param [Integer] page (Which page of result to return. Default to 1.) # @param [Integer] per_page (Number of results to return at once. Defaults to 10.) def deals(options = {})
options = update_by_expire_time options if deals_not_latest?(options) uniq = !!options.delete(:uniq) @rsqoot_deals = get('deals', options, SqootDeal) || [] @rsqoot_deals = @rsqoot_deals.deals.map(&:deal) unless @rsqoot_deals.empty? @rsqoot_deals = uniq_deals(@rsqoot_deals) if uniq end logger(uri: sqoot_query_uri, records: @rsqoot_deals, type: 'deals', opts: options) @rsqoot_deals end
lyfeyaj/rsqoot
0b3157f55f3a1fa2b21ac5389fe1686a77e6a4fd
lib/rsqoot/deal.rb
https://github.com/lyfeyaj/rsqoot/blob/0b3157f55f3a1fa2b21ac5389fe1686a77e6a4fd/lib/rsqoot/deal.rb#L26-L34
ruby
test
# Retrieve a deal by id
def deal(id, options = {})
# Retrieve a deal by id def deal(id, options = {})
options = update_by_expire_time options if deal_not_latest?(id) @rsqoot_deal = get("deals/#{id}", options, SqootDeal) @rsqoot_deal = @rsqoot_deal.deal if @rsqoot_deal end logger(uri: sqoot_query_uri, records: [@rsqoot_deal], type: 'deal', opts: options) @rsqoot_deal end
lyfeyaj/rsqoot
0b3157f55f3a1fa2b21ac5389fe1686a77e6a4fd
lib/rsqoot/deal.rb
https://github.com/lyfeyaj/rsqoot/blob/0b3157f55f3a1fa2b21ac5389fe1686a77e6a4fd/lib/rsqoot/deal.rb#L41-L53
ruby
test
# Auto Increment for deals query.
def total_sqoot_deals(options = {})
# Auto Increment for deals query. def total_sqoot_deals(options = {})
@total_deals ||= [] @cached_pages ||= [] page = options[:page] || 1 check_query_change options unless page_cached? page @total_deals += deals(options) @total_deals.uniq! @cached_pages << page.to_s @cached_pages.uniq! end @total_deals end
lyfeyaj/rsqoot
0b3157f55f3a1fa2b21ac5389fe1686a77e6a4fd
lib/rsqoot/deal.rb
https://github.com/lyfeyaj/rsqoot/blob/0b3157f55f3a1fa2b21ac5389fe1686a77e6a4fd/lib/rsqoot/deal.rb#L63-L70
ruby
test
# Uniq deals from Sqoot, because there are some many duplicated deals # with different ids # Simplely distinguish them by their titles
def uniq_deals(deals = [])
# Uniq deals from Sqoot, because there are some many duplicated deals # with different ids # Simplely distinguish them by their titles def uniq_deals(deals = [])
titles = deals.map(&:title).uniq titles.map do |title| deals.map do |deal| deal if deal.try(:title) == title end.compact.last end.flatten end
lyfeyaj/rsqoot
0b3157f55f3a1fa2b21ac5389fe1686a77e6a4fd
lib/rsqoot/deal.rb
https://github.com/lyfeyaj/rsqoot/blob/0b3157f55f3a1fa2b21ac5389fe1686a77e6a4fd/lib/rsqoot/deal.rb#L76-L91
ruby
test
# A status checker for method :total_sqoot_deals # If the query parameters changed, this will reset the cache # else it will do nothing
def check_query_change(options = {})
# A status checker for method :total_sqoot_deals # If the query parameters changed, this will reset the cache # else it will do nothing def check_query_change(options = {})
options = update_by_expire_time options @last_deals_query ||= '' current_query = options[:query].to_s current_query += options[:category_slugs].to_s current_query += options[:location].to_s current_query += options[:radius].to_s current_query += options[:online].to_s current_query += options[:expired_in].to_s current_query += options[:per_page].to_s if @last_deals_query != current_query @last_deals_query = current_query @total_deals = [] @cached_pages = [] end end
gutenye/tagen
aab0199ca30af9ba3065a3b8e872496d1f8f1633
lib/tagen/watir.rb
https://github.com/gutenye/tagen/blob/aab0199ca30af9ba3065a3b8e872496d1f8f1633/lib/tagen/watir.rb#L20-L50
ruby
test
# Read cookies from Mozilla cookies.txt-style IO stream # # @param file [IO,String]
def load_cookies(file)
# Read cookies from Mozilla cookies.txt-style IO stream # # @param file [IO,String] def load_cookies(file)
now = ::Time.now io = case file when String open(file) else file end io.each_line do |line| line.chomp! line.gsub!(/#.+/, '') fields = line.split("\t") next if fields.length != 7 name, value, domain, for_domain, path, secure, version = fields[5], fields[6], fields[0], (fields[1] == "TRUE"), fields[2], (fields[3] == "TRUE"), 0 expires_seconds = fields[4].to_i expires = (expires_seconds == 0) ? nil : ::Time.at(expires_seconds) next if expires and (expires < now) cookies.add(name, value, domain: domain, path: path, expires: expires, secure: secure) end io.close if String === file self end
gutenye/tagen
aab0199ca30af9ba3065a3b8e872496d1f8f1633
lib/tagen/watir.rb
https://github.com/gutenye/tagen/blob/aab0199ca30af9ba3065a3b8e872496d1f8f1633/lib/tagen/watir.rb#L55-L78
ruby
test
# Write cookies to Mozilla cookies.txt-style IO stream # # @param file [IO,String]
def dump_cookies(file)
# Write cookies to Mozilla cookies.txt-style IO stream # # @param file [IO,String] def dump_cookies(file)
io = case file when String open(file, "w") else file end cookies.to_a.each do |cookie| io.puts([ cookie[:domain], "FALSE", # for_domain cookie[:path], cookie[:secure] ? "TRUE" : "FALSE", cookie[:expires].to_i.to_s, cookie[:name], cookie[:value] ].join("\t")) end io.close if String === file self end
gutenye/tagen
aab0199ca30af9ba3065a3b8e872496d1f8f1633
lib/tagen/watir.rb
https://github.com/gutenye/tagen/blob/aab0199ca30af9ba3065a3b8e872496d1f8f1633/lib/tagen/watir.rb#L94-L109
ruby
test
# quick set value. # # @example # # form = browser.form(id: "foo") # form.set2("//input[@name='value']", "hello") # form.set2("//input[@name='check']", true) # form.set2("//select[@name='foo']", "Bar") # form.set2("//textarea[@name='foo']", "bar")
def set2(selector, value=nil)
# quick set value. # # @example # # form = browser.form(id: "foo") # form.set2("//input[@name='value']", "hello") # form.set2("//input[@name='check']", true) # form.set2("//select[@name='foo']", "Bar") # form.set2("//textarea[@name='foo']", "bar") def set2(selector, value=nil)
elem = element(xpath: selector).to_subtype case elem when Watir::Radio elem.set when Watir::Select elem.select value when Watir::Input elem.set value when Watir::TextArea elem.set value else elem.click end end
lyfeyaj/rsqoot
0b3157f55f3a1fa2b21ac5389fe1686a77e6a4fd
lib/rsqoot/helper.rb
https://github.com/lyfeyaj/rsqoot/blob/0b3157f55f3a1fa2b21ac5389fe1686a77e6a4fd/lib/rsqoot/helper.rb#L61-L65
ruby
test
# Add expired time functionality to this gem # By default is 1.hour, and can be replaced anywhere
def update_by_expire_time(options = {})
# Add expired time functionality to this gem # By default is 1.hour, and can be replaced anywhere def update_by_expire_time(options = {})
@expired_in = options[:expired_in] if options[:expired_in].present? time = Time.now.to_i / expired_in.to_i options.merge(expired_in: time) end
fun-ruby/ruby-meetup2
f6d54b1c6691def7228f400d935527bbbea07700
lib/ruby_meetup.rb
https://github.com/fun-ruby/ruby-meetup2/blob/f6d54b1c6691def7228f400d935527bbbea07700/lib/ruby_meetup.rb#L68-L81
ruby
test
# Make a GET API call with the current path value and @options. # Return a JSON string if successful, otherwise an Exception
def get(options={})
# Make a GET API call with the current path value and @options. # Return a JSON string if successful, otherwise an Exception def get(options={})
uri = new_uri params = merge_params(options) uri.query = URI.encode_www_form(params) Net::HTTP.start(uri.host, uri.port, :use_ssl => uri.scheme == 'https') do |http| request = Net::HTTP::Get.new(uri) response = http.request(request) unless response.is_a?(Net::HTTPSuccess) raise "#{response.code} #{response.message}\n#{response.body}" end return response.body end end
maxivak/optimacms
1e71d98b67cfe06d977102823b296b3010b10a83
app/controllers/optimacms/admin/templates_controller.rb
https://github.com/maxivak/optimacms/blob/1e71d98b67cfe06d977102823b296b3010b10a83/app/controllers/optimacms/admin/templates_controller.rb#L144-L150
ruby
test
# layout
def newlayout
# layout def newlayout
@item = model.new({:tpl_format=>Optimacms::Template::EXTENSION_DEFAULT, :type_id=>TemplateType::TYPE_LAYOUT}) item_init_parent @item.set_basedirpath_from_parent @url_back = url_list end
maxivak/optimacms
1e71d98b67cfe06d977102823b296b3010b10a83
app/controllers/optimacms/admin/templates_controller.rb
https://github.com/maxivak/optimacms/blob/1e71d98b67cfe06d977102823b296b3010b10a83/app/controllers/optimacms/admin/templates_controller.rb#L174-L180
ruby
test
# block
def newblock
# block def newblock
@item = model.new({:tpl_format=>Optimacms::Template::EXTENSION_DEFAULT, :type_id=>TemplateType::TYPE_BLOCKVIEW}) item_init_parent @item.set_basedirpath_from_parent @url_back = url_list end
maxivak/optimacms
1e71d98b67cfe06d977102823b296b3010b10a83
app/controllers/optimacms/admin/templates_controller.rb
https://github.com/maxivak/optimacms/blob/1e71d98b67cfe06d977102823b296b3010b10a83/app/controllers/optimacms/admin/templates_controller.rb#L237-L242
ruby
test
# folders
def newfolder
# folders def newfolder
@item = model.new(:is_folder=>true) item_init_parent @item.basedirpath = @item.parent.basepath+'/' unless @item.parent_id.nil? end
CiscoSystems/ropenstack
77dcb332711da2a35fe5abf2b6c63a0415c0bf69
lib/ropenstack/image/v1.rb
https://github.com/CiscoSystems/ropenstack/blob/77dcb332711da2a35fe5abf2b6c63a0415c0bf69/lib/ropenstack/image/v1.rb#L14-L20
ruby
test
# No ID provided - Lists details for available images. # ID provided - Shows the image details as headers and the image binary in the body.
def images(id, tenant_id)
# No ID provided - Lists details for available images. # ID provided - Shows the image details as headers and the image binary in the body. def images(id, tenant_id)
if id.nil? return get_request(address(tenant_id, "images/detail"), @token) else return get_request(address(tenant_id, "images/" + id), @token) end end
CiscoSystems/ropenstack
77dcb332711da2a35fe5abf2b6c63a0415c0bf69
lib/ropenstack/image/v1.rb
https://github.com/CiscoSystems/ropenstack/blob/77dcb332711da2a35fe5abf2b6c63a0415c0bf69/lib/ropenstack/image/v1.rb#L25-L36
ruby
test
# Registers a virtual machine image.
def image_create(name, disk_format, container_format, create_image, tenant_id)
# Registers a virtual machine image. def image_create(name, disk_format, container_format, create_image, tenant_id)
data = { :name => name, :disk_format => disk_format, :container_format => container_format } unless create_image.nil? data[:create_image] = create_image end post_request(address(tenant_id, "images"), data, @token) end
CiscoSystems/ropenstack
77dcb332711da2a35fe5abf2b6c63a0415c0bf69
lib/ropenstack/image/v1.rb
https://github.com/CiscoSystems/ropenstack/blob/77dcb332711da2a35fe5abf2b6c63a0415c0bf69/lib/ropenstack/image/v1.rb#L57-L62
ruby
test
# Replaces the membership list for an image. # @param memberships List of memberships in format [{'member_id': 'tenant1', 'can_share': 'false'}]
def replace_memberships(id, memberships, tenant_id)
# Replaces the membership list for an image. # @param memberships List of memberships in format [{'member_id': 'tenant1', 'can_share': 'false'}] def replace_memberships(id, memberships, tenant_id)
data = { :memberships => memberships } put_request(address(tenant_id, "images/" + id + "/members"), data, @token) end
CiscoSystems/ropenstack
77dcb332711da2a35fe5abf2b6c63a0415c0bf69
lib/ropenstack/image/v1.rb
https://github.com/CiscoSystems/ropenstack/blob/77dcb332711da2a35fe5abf2b6c63a0415c0bf69/lib/ropenstack/image/v1.rb#L69-L80
ruby
test
# Adds a member to an image. # @param member_id The member to be added # @param can_share Optional boolean specifiying can_share value. Will default to false.
def add_member(id, member_id, can_share, tenant_id)
# Adds a member to an image. # @param member_id The member to be added # @param can_share Optional boolean specifiying can_share value. Will default to false. def add_member(id, member_id, can_share, tenant_id)
if can_share.nil? data = { :member => {:can_share => false} } else data = { :member => {:can_share => can_share} } end put_request(address(tenant_id, "images/" + id + "/members/" + member_id), data, @token) end
gurgeous/scripto
e28792ca91dbb578725882799d76f82a64dfaa80
lib/scripto/file_commands.rb
https://github.com/gurgeous/scripto/blob/e28792ca91dbb578725882799d76f82a64dfaa80/lib/scripto/file_commands.rb#L10-L14
ruby
test
# Like mkdir -p +dir+. If +owner+ is specified, the directory will be # chowned to owner. If +mode+ is specified, the directory will be chmodded # to mode. Like all file commands, the operation will be printed out if # verbose?.
def mkdir(dir, owner: nil, mode: nil)
# Like mkdir -p +dir+. If +owner+ is specified, the directory will be # chowned to owner. If +mode+ is specified, the directory will be chmodded # to mode. Like all file commands, the operation will be printed out if # verbose?. def mkdir(dir, owner: nil, mode: nil)
FileUtils.mkdir_p(dir, verbose: verbose?) chown(dir, owner) if owner chmod(dir, mode) if mode end
gurgeous/scripto
e28792ca91dbb578725882799d76f82a64dfaa80
lib/scripto/file_commands.rb
https://github.com/gurgeous/scripto/blob/e28792ca91dbb578725882799d76f82a64dfaa80/lib/scripto/file_commands.rb#L21-L26
ruby
test
# Like cp -pr +src+ +dst. If +mkdir+ is true, the dst directoy will be # created if necessary before the copy. If +owner+ is specified, the # directory will be chowned to owner. If +mode+ is specified, the # directory will be chmodded to mode. Like all file commands, the # operation will be printed out if verbose?.
def cp(src, dst, mkdir: false, owner: nil, mode: nil)
# Like cp -pr +src+ +dst. If +mkdir+ is true, the dst directoy will be # created if necessary before the copy. If +owner+ is specified, the # directory will be chowned to owner. If +mode+ is specified, the # directory will be chmodded to mode. Like all file commands, the # operation will be printed out if verbose?. def cp(src, dst, mkdir: false, owner: nil, mode: nil)
mkdir_if_necessary(File.dirname(dst)) if mkdir FileUtils.cp_r(src, dst, preserve: true, verbose: verbose?) chown(dst, owner) if owner && !File.symlink?(dst) chmod(dst, mode) if mode end
gurgeous/scripto
e28792ca91dbb578725882799d76f82a64dfaa80
lib/scripto/file_commands.rb
https://github.com/gurgeous/scripto/blob/e28792ca91dbb578725882799d76f82a64dfaa80/lib/scripto/file_commands.rb#L31-L34
ruby
test
# Like mv +src+ +dst. If +mkdir+ is true, the dst directoy will be created # if necessary before the copy. Like all file commands, the operation will # be printed out if verbose?.
def mv(src, dst, mkdir: false)
# Like mv +src+ +dst. If +mkdir+ is true, the dst directoy will be created # if necessary before the copy. Like all file commands, the operation will # be printed out if verbose?. def mv(src, dst, mkdir: false)
mkdir_if_necessary(File.dirname(dst)) if mkdir FileUtils.mv(src, dst, verbose: verbose?) end
gurgeous/scripto
e28792ca91dbb578725882799d76f82a64dfaa80
lib/scripto/file_commands.rb
https://github.com/gurgeous/scripto/blob/e28792ca91dbb578725882799d76f82a64dfaa80/lib/scripto/file_commands.rb#L38-L44
ruby
test
# Like ln -sf +src+ +dst. The command will be printed out if # verbose?.
def ln(src, dst)
# Like ln -sf +src+ +dst. The command will be printed out if # verbose?. def ln(src, dst)
FileUtils.ln_sf(src, dst, verbose: verbose?) rescue Errno::EEXIST => e # It's a race - this can occur because ln_sf removes the old # dst, then creates the symlink. Raise if they don't match. raise e if !(File.symlink?(dst) && src == File.readlink(dst)) end
gurgeous/scripto
e28792ca91dbb578725882799d76f82a64dfaa80
lib/scripto/file_commands.rb
https://github.com/gurgeous/scripto/blob/e28792ca91dbb578725882799d76f82a64dfaa80/lib/scripto/file_commands.rb#L55-L59
ruby
test
# Runs #mkdir, but ONLY if +dir+ doesn't already exist. Returns true if # directory had to be created. This is useful with verbose?, to get an # exact changelog.
def mkdir_if_necessary(dir, owner: nil, mode: nil)
# Runs #mkdir, but ONLY if +dir+ doesn't already exist. Returns true if # directory had to be created. This is useful with verbose?, to get an # exact changelog. def mkdir_if_necessary(dir, owner: nil, mode: nil)
return if File.exist?(dir) || File.symlink?(dir) mkdir(dir, owner: owner, mode: mode) true end
gurgeous/scripto
e28792ca91dbb578725882799d76f82a64dfaa80
lib/scripto/file_commands.rb
https://github.com/gurgeous/scripto/blob/e28792ca91dbb578725882799d76f82a64dfaa80/lib/scripto/file_commands.rb#L64-L68
ruby
test
# Runs #cp, but ONLY if +dst+ doesn't exist or differs from +src+. Returns # true if the file had to be copied. This is useful with verbose?, to get # an exact changelog.
def cp_if_necessary(src, dst, mkdir: false, owner: nil, mode: nil)
# Runs #cp, but ONLY if +dst+ doesn't exist or differs from +src+. Returns # true if the file had to be copied. This is useful with verbose?, to get # an exact changelog. def cp_if_necessary(src, dst, mkdir: false, owner: nil, mode: nil)
return if File.exist?(dst) && FileUtils.compare_file(src, dst) cp(src, dst, mkdir: mkdir, owner: owner, mode: mode) true end
gurgeous/scripto
e28792ca91dbb578725882799d76f82a64dfaa80
lib/scripto/file_commands.rb
https://github.com/gurgeous/scripto/blob/e28792ca91dbb578725882799d76f82a64dfaa80/lib/scripto/file_commands.rb#L73-L81
ruby
test
# Runs #ln, but ONLY if +dst+ isn't a symlink or differs from +src+. # Returns true if the file had to be symlinked. This is useful with # verbose?, to get an exact changelog.
def ln_if_necessary(src, dst)
# Runs #ln, but ONLY if +dst+ isn't a symlink or differs from +src+. # Returns true if the file had to be symlinked. This is useful with # verbose?, to get an exact changelog. def ln_if_necessary(src, dst)
if File.symlink?(dst) return if src == File.readlink(dst) rm(dst) end ln(src, dst) true end
gurgeous/scripto
e28792ca91dbb578725882799d76f82a64dfaa80
lib/scripto/file_commands.rb
https://github.com/gurgeous/scripto/blob/e28792ca91dbb578725882799d76f82a64dfaa80/lib/scripto/file_commands.rb#L93-L100
ruby
test
# Like chown user:user file. Like all file commands, the operation will be printed # out if verbose?.
def chown(file, user) # who is the current owner?
# Like chown user:user file. Like all file commands, the operation will be printed # out if verbose?. def chown(file, user) # who is the current owner?
@scripto_uids ||= {} @scripto_uids[user] ||= Etc.getpwnam(user).uid uid = @scripto_uids[user] return if File.stat(file).uid == uid FileUtils.chown(uid, uid, file, verbose: verbose?) end
gurgeous/scripto
e28792ca91dbb578725882799d76f82a64dfaa80
lib/scripto/file_commands.rb
https://github.com/gurgeous/scripto/blob/e28792ca91dbb578725882799d76f82a64dfaa80/lib/scripto/file_commands.rb#L104-L107
ruby
test
# Like chmod mode file. Like all file commands, the operation will be # printed out if verbose?.
def chmod(file, mode)
# Like chmod mode file. Like all file commands, the operation will be # printed out if verbose?. def chmod(file, mode)
return if File.stat(file).mode == mode FileUtils.chmod(mode, file, verbose: verbose?) end
gurgeous/scripto
e28792ca91dbb578725882799d76f82a64dfaa80
lib/scripto/file_commands.rb
https://github.com/gurgeous/scripto/blob/e28792ca91dbb578725882799d76f82a64dfaa80/lib/scripto/file_commands.rb#L111-L115
ruby
test
# Like rm -rf && mkdir -p. Like all file commands, the operation will be # printed out if verbose?.
def rm_and_mkdir(dir)
# Like rm -rf && mkdir -p. Like all file commands, the operation will be # printed out if verbose?. def rm_and_mkdir(dir)
raise "don't do this" if dir == "" FileUtils.rm_rf(dir, verbose: verbose?) mkdir(dir) end
gurgeous/scripto
e28792ca91dbb578725882799d76f82a64dfaa80
lib/scripto/file_commands.rb
https://github.com/gurgeous/scripto/blob/e28792ca91dbb578725882799d76f82a64dfaa80/lib/scripto/file_commands.rb#L119-L123
ruby
test
# Copy mode, atime and mtime from +src+ to +dst+. This one is rarely used # and doesn't echo.
def copy_metadata(src, dst)
# Copy mode, atime and mtime from +src+ to +dst+. This one is rarely used # and doesn't echo. def copy_metadata(src, dst)
stat = File.stat(src) File.chmod(stat.mode, dst) File.utime(stat.atime, stat.mtime, dst) end
gurgeous/scripto
e28792ca91dbb578725882799d76f82a64dfaa80
lib/scripto/file_commands.rb
https://github.com/gurgeous/scripto/blob/e28792ca91dbb578725882799d76f82a64dfaa80/lib/scripto/file_commands.rb#L126-L134
ruby
test
# Atomically write to +path+. An open temp file is yielded.
def atomic_write(path)
# Atomically write to +path+. An open temp file is yielded. def atomic_write(path)
tmp = Tempfile.new(File.basename(path)) yield(tmp) tmp.close chmod(tmp.path, 0o644) mv(tmp.path, path) ensure rm_if_necessary(tmp.path) end
wordtreefoundation/wordtree-ruby
2434b3417cf82ab07c7719f4e36548c86994fdb7
lib/wordtree/book_list.rb
https://github.com/wordtreefoundation/wordtree-ruby/blob/2434b3417cf82ab07c7719f4e36548c86994fdb7/lib/wordtree/book_list.rb#L15-L32
ruby
test
# can be initialized from the following sources: # - a WordTree::Disk::Library object # - an open File object (containing a list of files or paths to books) # - a String directory (presumed to be the library on disk) # - a String file (containing a list of files or paths to books)
def iterable_from_source(source)
# can be initialized from the following sources: # - a WordTree::Disk::Library object # - an open File object (containing a list of files or paths to books) # - a String directory (presumed to be the library on disk) # - a String file (containing a list of files or paths to books) def iterable_from_source(source)
case source when WordTree::Disk::Library then source when File then source.read.split("\n").tap do |file| file.close end when String then if File.directory?(source) WordTree::Disk::Library.new(source) elsif File.exist?(source) IO.read(source).split("\n") else raise Errno::ENOENT, "Unable to find source for BookList, #{source.inspect}" end end end
dcrosby42/conject
df4b89ac97f65c6334db46b4652bfa6ae0a7446e
lib/conject/object_factory.rb
https://github.com/dcrosby42/conject/blob/df4b89ac97f65c6334db46b4652bfa6ae0a7446e/lib/conject/object_factory.rb#L53-L83
ruby
test
# This implementation is what I'm loosely calling "type 1" or "regular" object creation: # - Assume we're looking for a class to create an instance with # - it may or may not have a declared list of named objects it needs to be constructed with
def type_1_constructor(klass, name, object_context, overrides=nil)
# This implementation is what I'm loosely calling "type 1" or "regular" object creation: # - Assume we're looking for a class to create an instance with # - it may or may not have a declared list of named objects it needs to be constructed with def type_1_constructor(klass, name, object_context, overrides=nil)
klass ||= class_finder.find_class(name) if !klass.object_peers.empty? anchor_object_peers object_context, klass.object_peers end constructor_func = nil if klass.has_object_definition? object_map = dependency_resolver.resolve_for_class(klass, object_context, overrides) constructor_func = lambda do klass.new(object_map) end elsif Utilities.has_zero_arg_constructor?(klass) # Default construction constructor_func = lambda do klass.new end else # Oops, out of ideas on how to build. raise ArgumentError.new("Class #{klass} has no special component needs, but neither does it have a zero-argument constructor."); end object = nil Conject.override_object_context_with object_context do begin object = constructor_func.call rescue Exception => ex origin = "#{ex.message}\n\t#{ex.backtrace.join("\n\t")}" name ||= "(no name)" raise "Error while constructing object '#{name}' of class #{klass}: #{origin}" end end end
adimichele/capybarbecue
329771dd61f286b63dba1427b439a75d2db80ca7
lib/capybarbecue/server.rb
https://github.com/adimichele/capybarbecue/blob/329771dd61f286b63dba1427b439a75d2db80ca7/lib/capybarbecue/server.rb#L22-L34
ruby
test
# Should be run by another thread - respond to all queued requests
def handle_requests
# Should be run by another thread - respond to all queued requests def handle_requests
until @requestmq.empty? request = @requestmq.deq(true) begin request.response = @app.call(request.env) rescue Exception => e request.exception = e ensure body = request.response.try(:last) body.close if body.respond_to? :close end end end
apeiros/tabledata
e277b6a1fdb567a6d73f42349bb9946ffad67134
lib/tabledata/column.rb
https://github.com/apeiros/tabledata/blob/e277b6a1fdb567a6d73f42349bb9946ffad67134/lib/tabledata/column.rb#L47-L55
ruby
test
# Similar to Tabledata::Table#[], but only returns values for this column. # Provides array like access to this column's data. Only considers body # values (i.e., does not consider header and footer). # # @return [Array, Object]
def [](*args)
# Similar to Tabledata::Table#[], but only returns values for this column. # Provides array like access to this column's data. Only considers body # values (i.e., does not consider header and footer). # # @return [Array, Object] def [](*args)
rows = @table.body[*args] if rows.is_a?(Array) # slice rows.map { |row| row[@index] } else # single row rows[@index] end end
apeiros/tabledata
e277b6a1fdb567a6d73f42349bb9946ffad67134
lib/tabledata/column.rb
https://github.com/apeiros/tabledata/blob/e277b6a1fdb567a6d73f42349bb9946ffad67134/lib/tabledata/column.rb#L108-L119
ruby
test
# @param [Hash] options # @option options [Symbol] :include_header # Defaults to true. If set to false, the header (if present) is excluded. # @option options [Symbol] :include_footer # Defaults to true. If set to false, the footer (if present) is excluded. # # @return [Array] All values in the column, including header and footer.
def to_a(options=nil)
# @param [Hash] options # @option options [Symbol] :include_header # Defaults to true. If set to false, the header (if present) is excluded. # @option options [Symbol] :include_footer # Defaults to true. If set to false, the footer (if present) is excluded. # # @return [Array] All values in the column, including header and footer. def to_a(options=nil)
data = @table.data.transpose[@index] if options start_offset = options[:include_header] && @table.headers? ? 1 : 0 end_offset = options[:include_footer] && @table.footer? ? -2 : -1 data[start_offset..end_offset] else data end end
GeoffWilliams/vagrantomatic
9e249c8ea4a1dd7ccf127d8bfc3b5ee123c300b1
lib/vagrantomatic/instance.rb
https://github.com/GeoffWilliams/vagrantomatic/blob/9e249c8ea4a1dd7ccf127d8bfc3b5ee123c300b1/lib/vagrantomatic/instance.rb#L53-L71
ruby
test
# Add a new folder to @config in the correct place. Folders must be # specified as colon delimited strings: `HOST_PATH:VM_PATH`, eg # `/home/geoff:/stuff` would mount `/home/geoff` from the main computer and # would mount it inside the VM at /stuff. Vagrant expects the `HOST_PATH` # to be an absolute path, however, you may specify a relative path here and # vagrantomatic will attempt to extract a fully qualified path by prepending # the present working directory. If this is incorrect its up to the # programmer to fix this by passing in a fully qualified path in the first # place
def add_shared_folder(folders)
# Add a new folder to @config in the correct place. Folders must be # specified as colon delimited strings: `HOST_PATH:VM_PATH`, eg # `/home/geoff:/stuff` would mount `/home/geoff` from the main computer and # would mount it inside the VM at /stuff. Vagrant expects the `HOST_PATH` # to be an absolute path, however, you may specify a relative path here and # vagrantomatic will attempt to extract a fully qualified path by prepending # the present working directory. If this is incorrect its up to the # programmer to fix this by passing in a fully qualified path in the first # place def add_shared_folder(folders)
folders=Array(folders) # can't use dig() might not be ruby 2.3 if ! @config.has_key?("folders") @config["folders"] = [] end # all paths must be fully qualified. If we were asked to do a relative path, change # it to the current directory since that's probably what the user wanted. Not right? # user supply correct path! folders.each { |folder| if ! folder.start_with? '/' folder = "#{Dir.pwd}/#{folder}" end @config["folders"] << folder } end
GeoffWilliams/vagrantomatic
9e249c8ea4a1dd7ccf127d8bfc3b5ee123c300b1
lib/vagrantomatic/instance.rb
https://github.com/GeoffWilliams/vagrantomatic/blob/9e249c8ea4a1dd7ccf127d8bfc3b5ee123c300b1/lib/vagrantomatic/instance.rb#L122-L139
ruby
test
# return a hash of the configfile or empty hash if error encountered
def configfile_hash
# return a hash of the configfile or empty hash if error encountered def configfile_hash
config = {} begin json = File.read(configfile) config = JSON.parse(json) rescue Errno::ENOENT # depending on whether the instance has been saved or not, we may not # yet have a configfile - allow to proceed @logger.debug "#{configfile} does not exist" @force_save = true rescue JSON::ParserError # swallow parse errors so that we can destroy and recreate automatically @logger.debug "JSON parse error in #{configfile}" @force_save = true end config end
CiscoSystems/ropenstack
77dcb332711da2a35fe5abf2b6c63a0415c0bf69
lib/ropenstack/objectStorage.rb
https://github.com/CiscoSystems/ropenstack/blob/77dcb332711da2a35fe5abf2b6c63a0415c0bf69/lib/ropenstack/objectStorage.rb#L10-L16
ruby
test
# Accounts
def account(id, head)
# Accounts def account(id, head)
if head get_request(address(id), @token) else head_request(address(id), @token) end end
CiscoSystems/ropenstack
77dcb332711da2a35fe5abf2b6c63a0415c0bf69
lib/ropenstack/objectStorage.rb
https://github.com/CiscoSystems/ropenstack/blob/77dcb332711da2a35fe5abf2b6c63a0415c0bf69/lib/ropenstack/objectStorage.rb#L22-L28
ruby
test
# Containers
def container(account, container, head)
# Containers def container(account, container, head)
if head get_request(address(account + "/" + container), @token) else head_request(address(account + "/" + container), @token) end end
mimosa/simple_format
02cc6c051d6e02cebcb0b74929529a1c740c0aa4
lib/simple_format/emoji.rb
https://github.com/mimosa/simple_format/blob/02cc6c051d6e02cebcb0b74929529a1c740c0aa4/lib/simple_format/emoji.rb#L61-L67
ruby
test
# 通过(名称、字符)替换表情
def replace_emoji_with_images(string)
# 通过(名称、字符)替换表情 def replace_emoji_with_images(string)
return string unless string html ||= string.dup html = replace_name_with_images(html) html = replace_unicode_with_images(html.to_str) return html end
mimosa/simple_format
02cc6c051d6e02cebcb0b74929529a1c740c0aa4
lib/simple_format/emoji.rb
https://github.com/mimosa/simple_format/blob/02cc6c051d6e02cebcb0b74929529a1c740c0aa4/lib/simple_format/emoji.rb#L69-L81
ruby
test
# 通过(名称)替换表情
def replace_name_with_images(string)
# 通过(名称)替换表情 def replace_name_with_images(string)
unless string && string.match(names_regex) return string end string.to_str.gsub(names_regex) do |match| if names.include?($1) %Q{<img class="emoji" src="//#{ image_url_for_name($1) }" />} else match end end end
mimosa/simple_format
02cc6c051d6e02cebcb0b74929529a1c740c0aa4
lib/simple_format/emoji.rb
https://github.com/mimosa/simple_format/blob/02cc6c051d6e02cebcb0b74929529a1c740c0aa4/lib/simple_format/emoji.rb#L83-L92
ruby
test
# 通过(字符)替换表情
def replace_unicode_with_images(string)
# 通过(字符)替换表情 def replace_unicode_with_images(string)
unless string && string.match(unicodes_regex) return string end html ||= string.dup html.gsub!(unicodes_regex) do |unicode| %Q{<img class="emoji" src="//#{ image_url_for_unicode(unicode) }" />} end end
mimosa/simple_format
02cc6c051d6e02cebcb0b74929529a1c740c0aa4
lib/simple_format/emoji.rb
https://github.com/mimosa/simple_format/blob/02cc6c051d6e02cebcb0b74929529a1c740c0aa4/lib/simple_format/emoji.rb#L94-L102
ruby
test
# 通过(名称)合成图片地址
def image_url_for_name(name)
# 通过(名称)合成图片地址 def image_url_for_name(name)
image_url = "#{asset_host}#{ File.join(asset_path, name) }.png" if image_url.present? if asset_size.present? && asset_size.in?(sizes) image_url = [image_url, asset_size].join(asset_delimiter) end end return image_url end
praxis/praxis-mapper
f8baf44948943194f0e4acddd24aa168add60645
lib/praxis-mapper/identity_map.rb
https://github.com/praxis/praxis-mapper/blob/f8baf44948943194f0e4acddd24aa168add60645/lib/praxis-mapper/identity_map.rb#L194-L212
ruby
test
# Last parameter in array can be a hash of objects # It is implemented this way (instead of (*models, instrument: true)) because when passing in # Sequel models, ruby will invoke the ".to_hash" on them, causing a "load" when trying to restructure the args
def finalize!(*models_and_opts)
# Last parameter in array can be a hash of objects # It is implemented this way (instead of (*models, instrument: true)) because when passing in # Sequel models, ruby will invoke the ".to_hash" on them, causing a "load" when trying to restructure the args def finalize!(*models_and_opts)
models, instrument = if models_and_opts.last.kind_of?(::Hash) ins = models_and_opts.last.fetch(:instrument) do true end [ models_and_opts[0..-2], ins ] else [ models_and_opts, true ] end if instrument ActiveSupport::Notifications.instrument 'praxis.mapper.finalize' do _finalize!(*models) end else _finalize!(*models) end end
praxis/praxis-mapper
f8baf44948943194f0e4acddd24aa168add60645
lib/praxis-mapper/identity_map.rb
https://github.com/praxis/praxis-mapper/blob/f8baf44948943194f0e4acddd24aa168add60645/lib/praxis-mapper/identity_map.rb#L234-L319
ruby
test
# don't doc. never ever use yourself! # FIXME: make private and fix specs that break?
def finalize_model!(model, query = nil)
# don't doc. never ever use yourself! # FIXME: make private and fix specs that break? def finalize_model!(model, query = nil)
staged_queries = @staged[model].delete(:_queries) || [] staged_keys = @staged[model].keys non_identities = staged_keys - model.identities results = Set.new return results if @staged[model].all? { |(_key, values)| values.empty? } if query.nil? query_class = @connection_manager.repository(model.repository_name)[:query] query = query_class.new(self, model) end # Apply any relevant blocks passed to track in the original queries staged_queries.each do |staged_query| staged_query.track.each do |(association_name, block)| next unless block spec = staged_query.model.associations[association_name] if spec[:model] == model query.instance_eval(&block) if (spec[:type] == :many_to_one || spec[:type] == :array_to_many) && query.where file, line = block.source_location trace = ["#{file}:#{line}"] | caller raise RuntimeError, "Error finalizing model #{model.name} for association #{association_name.inspect} -- using a where clause when tracking associations of type #{spec[:type].inspect} is not supported", trace end end end end # process non-unique staged keys # select identity (any one should do) for those keys and stage blindly # load and add records. if non_identities.any? to_stage = Hash.new do |hash,identity| hash[identity] = Set.new end non_identities.each do |key| values = @staged[model].delete(key) rows = query.multi_get(key, values, select: model.identities, raw: true) rows.each do |row| model.identities.each do |identity| if identity.kind_of? Array to_stage[identity] << row.values_at(*identity) else to_stage[identity] << row[identity] end end end end self.stage(model, to_stage) end model.identities.each do |identity_name| values = self.get_staged(model,identity_name) next if values.empty? query.where = nil # clear out any where clause from non-identity records = query.multi_get(identity_name, values) # TODO: refactor this to better-hide queries? self.queries[model].add(query) results.merge(add_records(records)) # add nil records for records that were not found by the multi_get missing_keys = self.get_staged(model,identity_name) missing_keys.each do |missing_key| @row_keys[model][identity_name][missing_key] = nil get_staged(model, identity_name).delete(missing_key) end end query.freeze # TODO: check whether really really did get all the records we should have.... results.to_a end
praxis/praxis-mapper
f8baf44948943194f0e4acddd24aa168add60645
lib/praxis-mapper/identity_map.rb
https://github.com/praxis/praxis-mapper/blob/f8baf44948943194f0e4acddd24aa168add60645/lib/praxis-mapper/identity_map.rb#L520-L548
ruby
test
# return the record provided (if added to the identity map) # or return the corresponding record if it was already present
def add_record(record)
# return the record provided (if added to the identity map) # or return the corresponding record if it was already present def add_record(record)
model = record.class record.identities.each do |identity, key| # FIXME: Should we be overwriting (possibly) a "nil" value from before? # (due to that row not being found by a previous query) # (That'd be odd since that means we tried to load that same identity) if (existing = @row_keys[model][identity][key]) # FIXME: should merge record into existing to add any additional fields return existing end get_staged(model, identity).delete(key) @row_keys[model][identity][key] = record end @secondary_indexes[model].each do |key, indexed_values| val = if key.kind_of? Array key.collect { |k| record.send(k) } else record.send(key) end indexed_values[val] << record end record.identity_map = self @rows[model] << record record end
mimosa/simple_format
02cc6c051d6e02cebcb0b74929529a1c740c0aa4
lib/simple_format/auto_link.rb
https://github.com/mimosa/simple_format/blob/02cc6c051d6e02cebcb0b74929529a1c740c0aa4/lib/simple_format/auto_link.rb#L23-L48
ruby
test
# Turns all urls into clickable links. If a block is given, each url # is yielded and the result is used as the link text.
def urls(text)
# Turns all urls into clickable links. If a block is given, each url # is yielded and the result is used as the link text. def urls(text)
text.gsub(@regex[:protocol]) do scheme, href = $1, $& punctuation = [] if auto_linked?($`, $') # do not change string; URL is already linked href else # don't include trailing punctuation character as part of the URL while href.sub!(/[^#{@regex[:word_pattern]}\/-]$/, '') punctuation.push $& if opening = @regex[:brackets][punctuation.last] and href.scan(opening).size > href.scan(punctuation.last).size href << punctuation.pop break end end link_text = block_given?? yield(href) : href href = '//' + href unless scheme "<a href='#{href}' target='_blank'>#{link_text}</a>" + punctuation.reverse.join('') end end end
mimosa/simple_format
02cc6c051d6e02cebcb0b74929529a1c740c0aa4
lib/simple_format/auto_link.rb
https://github.com/mimosa/simple_format/blob/02cc6c051d6e02cebcb0b74929529a1c740c0aa4/lib/simple_format/auto_link.rb#L52-L63
ruby
test
# Turns all email addresses into clickable links. If a block is given, # each email is yielded and the result is used as the link text.
def email_addresses(text)
# Turns all email addresses into clickable links. If a block is given, # each email is yielded and the result is used as the link text. def email_addresses(text)
text.gsub(@regex[:mail]) do text = $& if auto_linked?($`, $') text else display_text = (block_given?) ? yield(text) : text # mail_to text, display_text "<a href='mailto:#{text}'>#{display_text}</a>" end end end
aphyr/risky
2f3dac30ff6b8aa06429bf68849b8b870f16831f
lib/risky/inflector.rb
https://github.com/aphyr/risky/blob/2f3dac30ff6b8aa06429bf68849b8b870f16831f/lib/risky/inflector.rb#L35-L39
ruby
test
# Specifies a new pluralization rule and its replacement. The rule can either be a string or a regular expression. # The replacement should always be a string that may include references to the matched data from the rule.
def plural(rule, replacement)
# Specifies a new pluralization rule and its replacement. The rule can either be a string or a regular expression. # The replacement should always be a string that may include references to the matched data from the rule. def plural(rule, replacement)
@uncountables.delete(rule) if rule.is_a?(String) @uncountables.delete(replacement) @plurals.insert(0, [rule, replacement]) end
aphyr/risky
2f3dac30ff6b8aa06429bf68849b8b870f16831f
lib/risky/inflector.rb
https://github.com/aphyr/risky/blob/2f3dac30ff6b8aa06429bf68849b8b870f16831f/lib/risky/inflector.rb#L43-L47
ruby
test
# Specifies a new singularization rule and its replacement. The rule can either be a string or a regular expression. # The replacement should always be a string that may include references to the matched data from the rule.
def singular(rule, replacement)
# Specifies a new singularization rule and its replacement. The rule can either be a string or a regular expression. # The replacement should always be a string that may include references to the matched data from the rule. def singular(rule, replacement)
@uncountables.delete(rule) if rule.is_a?(String) @uncountables.delete(replacement) @singulars.insert(0, [rule, replacement]) end
aphyr/risky
2f3dac30ff6b8aa06429bf68849b8b870f16831f
lib/risky/inflector.rb
https://github.com/aphyr/risky/blob/2f3dac30ff6b8aa06429bf68849b8b870f16831f/lib/risky/inflector.rb#L55-L67
ruby
test
# Specifies a new irregular that applies to both pluralization and singularization at the same time. This can only be used # for strings, not regular expressions. You simply pass the irregular in singular and plural form. # # Examples: # irregular 'octopus', 'octopi' # irregular 'person', 'people'
def irregular(singular, plural)
# Specifies a new irregular that applies to both pluralization and singularization at the same time. This can only be used # for strings, not regular expressions. You simply pass the irregular in singular and plural form. # # Examples: # irregular 'octopus', 'octopi' # irregular 'person', 'people' def irregular(singular, plural)
@uncountables.delete(singular) @uncountables.delete(plural) if singular[0,1].upcase == plural[0,1].upcase plural(Regexp.new("(#{singular[0,1]})#{singular[1..-1]}$", "i"), '\1' + plural[1..-1]) singular(Regexp.new("(#{plural[0,1]})#{plural[1..-1]}$", "i"), '\1' + singular[1..-1]) else plural(Regexp.new("#{singular[0,1].upcase}(?i)#{singular[1..-1]}$"), plural[0,1].upcase + plural[1..-1]) plural(Regexp.new("#{singular[0,1].downcase}(?i)#{singular[1..-1]}$"), plural[0,1].downcase + plural[1..-1]) singular(Regexp.new("#{plural[0,1].upcase}(?i)#{plural[1..-1]}$"), singular[0,1].upcase + singular[1..-1]) singular(Regexp.new("#{plural[0,1].downcase}(?i)#{plural[1..-1]}$"), singular[0,1].downcase + singular[1..-1]) end end
robertwahler/revenc
8b0ad162d916a239c4507b93cc8e5530f38d8afb
lib/revenc/io.rb
https://github.com/robertwahler/revenc/blob/8b0ad162d916a239c4507b93cc8e5530f38d8afb/lib/revenc/io.rb#L178-L192
ruby
test
# run the action if valid and return true if successful
def execute
# run the action if valid and return true if successful def execute
raise errors.to_sentences unless valid? # default failing command result = false # protect command from recursion mutex = Mutagem::Mutex.new('revenc.lck') lock_successful = mutex.execute do result = system_cmd(cmd) end raise "action failed, lock file present" unless lock_successful result end
maxivak/optimacms
1e71d98b67cfe06d977102823b296b3010b10a83
app/controllers/optimacms/pages_controller.rb
https://github.com/maxivak/optimacms/blob/1e71d98b67cfe06d977102823b296b3010b10a83/app/controllers/optimacms/pages_controller.rb#L57-L121
ruby
test
# =begin # def my_set_render_template(tpl_view, tpl_layout) # @optimacms_tpl = tpl_view # @optimacms_layout = tpl_layout # end # # def my_set_meta(meta) # #@optimacms_meta = meta # @optimacms_meta_title = meta[:title] # @optimacms_meta_keywords = meta[:keywords] # @optimacms_meta_description = meta[:description] # end # =end
def renderActionInOtherController(controller,action,params, tpl_view=nil, tpl_layout=nil) # include render into controller class
# =begin # def my_set_render_template(tpl_view, tpl_layout) # @optimacms_tpl = tpl_view # @optimacms_layout = tpl_layout # end # # def my_set_meta(meta) # #@optimacms_meta = meta # @optimacms_meta_title = meta[:title] # @optimacms_meta_keywords = meta[:keywords] # @optimacms_meta_description = meta[:description] # end # =end def renderActionInOtherController(controller,action,params, tpl_view=nil, tpl_layout=nil) # include render into controller class
if current_cms_admin_user controller.send 'include', Optimacms::Renderer::AdminPageRenderer controller.send 'renderer_admin_edit' end # c = controller.new c.params = params if current_cms_admin_user #if !controller.respond_to?(:render_base, true) if !c.respond_to?(:render_base, true) controller.send :alias_method, :render_base, :render controller.send :define_method, "render" do |options = nil, extra_options = {}, &block| if current_cms_admin_user && @pagedata render_with_edit(options, extra_options, &block) else render_base(options, extra_options, &block) end end end end #c.process_action(action, request) #c.dispatch(action, request) #c.send 'index_page' c.request = request #c.request.path_parameters = params.with_indifferent_access c.request.format = params[:format] || 'html' c.action_name = action c.response = ActionDispatch::Response.new c.send 'my_set_render' c.send 'optimacms_set_pagedata', @pagedata c.send 'my_set_render_template', tpl_view, tpl_layout c.send 'my_set_meta', @pagedata.meta #renderer_admin_edit #c.process_action(action) c.dispatch(action, request, c.response) #c.process_action(action, tpl_filename) #app = "NewsController".constantize.action(action) #app.process params # result #c c.response.body #app.response.body end
chiligumdev/rmetrics
f5ec07655406db9ac099953babf43eaa35fb200c
lib/rmetrics/influx.rb
https://github.com/chiligumdev/rmetrics/blob/f5ec07655406db9ac099953babf43eaa35fb200c/lib/rmetrics/influx.rb#L17-L32
ruby
test
# rubocop:disable Metrics/MethodLength
def adjust_values(act, payload)
# rubocop:disable Metrics/MethodLength def adjust_values(act, payload)
payload.each do |key, value| case value when Hash act[:tags].merge!(value.select { |_, v| v.is_a?(String) }) when Numeric, Integer act[:values][key.to_sym] = value.to_f when String, TrueClass, FalseClass act[:values][key.to_sym] = value when Symbol act[:values][key.to_sym] = value.to_s else next end end end
chiligumdev/rmetrics
f5ec07655406db9ac099953babf43eaa35fb200c
lib/rmetrics/influx.rb
https://github.com/chiligumdev/rmetrics/blob/f5ec07655406db9ac099953babf43eaa35fb200c/lib/rmetrics/influx.rb#L35-L46
ruby
test
# rubocop:enable Metrics/MethodLength
def organize_event(event)
# rubocop:enable Metrics/MethodLength def organize_event(event)
act = { values: { duration: event.duration }, tags: { name: event.name } } adjust_values(act, event.payload) act end
xlymian/hansel
f8a07b3a7b3a5e3659944cfafc3de7fcf08f9a04
lib/hansel/hansel.rb
https://github.com/xlymian/hansel/blob/f8a07b3a7b3a5e3659944cfafc3de7fcf08f9a04/lib/hansel/hansel.rb#L38-L45
ruby
test
# Output the results based on the requested output format
def output
# Output the results based on the requested output format def output
opts = options if opts.format FileUtils.mkdir_p opts.output_dir formatted_output end @results.clear end
xlymian/hansel
f8a07b3a7b3a5e3659944cfafc3de7fcf08f9a04
lib/hansel/hansel.rb
https://github.com/xlymian/hansel/blob/f8a07b3a7b3a5e3659944cfafc3de7fcf08f9a04/lib/hansel/hansel.rb#L54-L68
ruby
test
# Run httperf from low_rate to high_rate, stepping by rate_step
def run
# Run httperf from low_rate to high_rate, stepping by rate_step def run
while @jobs.length > 0 do # do a warm up run first with the highest connection rate @current_job = @jobs.pop @current_rate = @current_job.high_rate.to_i httperf true (@current_job.low_rate.to_i..@current_job.high_rate.to_i). step(@current_job.rate_step.to_i) do |rate| @current_rate = rate httperf end output end end
colstrom/laag
a122cb8d4efdd7c2d6146f61f45411d857326305
lib/laag/build_environment.rb
https://github.com/colstrom/laag/blob/a122cb8d4efdd7c2d6146f61f45411d857326305/lib/laag/build_environment.rb#L79-L82
ruby
test
# Detection
def file?(filename)
# Detection def file?(filename)
return unless filename File.exist? File.join(@library.source_path, filename.split('/')) end
CiscoSystems/ropenstack
77dcb332711da2a35fe5abf2b6c63a0415c0bf69
lib/ropenstack/identity/v2.rb
https://github.com/CiscoSystems/ropenstack/blob/77dcb332711da2a35fe5abf2b6c63a0415c0bf69/lib/ropenstack/identity/v2.rb#L14-L27
ruby
test
# Authenticate via keystone, unless a token and tenant are defined then a unscoped # token is returned with all associated data and stored in the @data variable. # Does not return anything, but all data is accessible through accessor methods.
def authenticate(username, password, tenant = nil)
# Authenticate via keystone, unless a token and tenant are defined then a unscoped # token is returned with all associated data and stored in the @data variable. # Does not return anything, but all data is accessible through accessor methods. def authenticate(username, password, tenant = nil)
data = { "auth" => { "passwordCredentials" => { "username" => username, "password" => password } } } unless tenant.nil? data["auth"]["tenantName"] = tenant end @data = post_request(address("/tokens"), data, @token) end
CiscoSystems/ropenstack
77dcb332711da2a35fe5abf2b6c63a0415c0bf69
lib/ropenstack/identity/v2.rb
https://github.com/CiscoSystems/ropenstack/blob/77dcb332711da2a35fe5abf2b6c63a0415c0bf69/lib/ropenstack/identity/v2.rb#L37-L44
ruby
test
# Scope token provides two ways to call it: # scope_token(tenantName) => Just using the current token and a tenantName it # scopes in the token. Token stays the same. # scope_token(username, password, tenantName) => This uses the username and # password to reauthenticate with a tenant. The # token changes.
def scope_token(para1, para2 = nil, para3 = nil)
# Scope token provides two ways to call it: # scope_token(tenantName) => Just using the current token and a tenantName it # scopes in the token. Token stays the same. # scope_token(username, password, tenantName) => This uses the username and # password to reauthenticate with a tenant. The # token changes. def scope_token(para1, para2 = nil, para3 = nil)
if ( para2.nil? ) data = { "auth" => { "tenantName" => para1, "token" => { "id" => token() } } } @data = post_request(address("/tokens"), data, token()) else authenticate(para1, para2, token(), para3) end end
CiscoSystems/ropenstack
77dcb332711da2a35fe5abf2b6c63a0415c0bf69
lib/ropenstack/identity/v2.rb
https://github.com/CiscoSystems/ropenstack/blob/77dcb332711da2a35fe5abf2b6c63a0415c0bf69/lib/ropenstack/identity/v2.rb#L125-L134
ruby
test
# Add a service to the keystone services directory
def add_to_services(name, type, description)
# Add a service to the keystone services directory def add_to_services(name, type, description)
data = { 'OS-KSADM:service' => { 'name' => name, 'type' => type, 'description' => description } } return post_request(address("/OS-KSADM/services"), data, token()) end
CiscoSystems/ropenstack
77dcb332711da2a35fe5abf2b6c63a0415c0bf69
lib/ropenstack/identity/v2.rb
https://github.com/CiscoSystems/ropenstack/blob/77dcb332711da2a35fe5abf2b6c63a0415c0bf69/lib/ropenstack/identity/v2.rb#L146-L157
ruby
test
# Add an endpoint list
def add_endpoint(region, service_id, publicurl, adminurl, internalurl)
# Add an endpoint list def add_endpoint(region, service_id, publicurl, adminurl, internalurl)
data = { 'endpoint' => { 'region' => region, 'service_id' => service_id, 'publicurl' => publicurl, 'adminurl' => adminurl, 'internalurl' => internalurl } } return post_request(address("/endpoints"), data, token()) end
CiscoSystems/ropenstack
77dcb332711da2a35fe5abf2b6c63a0415c0bf69
lib/ropenstack/identity/v2.rb
https://github.com/CiscoSystems/ropenstack/blob/77dcb332711da2a35fe5abf2b6c63a0415c0bf69/lib/ropenstack/identity/v2.rb#L162-L168
ruby
test
# Get the endpoint list
def get_endpoints(token = nil)
# Get the endpoint list def get_endpoints(token = nil)
if token.nil? return get_request(address("/endpoints"), token()) else return get_request(address("/tokens/#{token}/endpoints"), token()) end end
dcuddeback/method_disabling
1617972d5ce9ef3b5f31f8c01f89fed358aa1f9b
lib/method_disabling.rb
https://github.com/dcuddeback/method_disabling/blob/1617972d5ce9ef3b5f31f8c01f89fed358aa1f9b/lib/method_disabling.rb#L42-L45
ruby
test
# Disables an instance method. # # @param [Symbol,String] method_name The name of the method to disable. # @param [String] message An error message. Defaults to "Class#method is disabled".
def disable_method(method_name, message = nil)
# Disables an instance method. # # @param [Symbol,String] method_name The name of the method to disable. # @param [String] message An error message. Defaults to "Class#method is disabled". def disable_method(method_name, message = nil)
disabled_methods[method_name] ||= DisabledMethod.new(self, method_name, message) disabled_methods[method_name].disable! end
dcuddeback/method_disabling
1617972d5ce9ef3b5f31f8c01f89fed358aa1f9b
lib/method_disabling.rb
https://github.com/dcuddeback/method_disabling/blob/1617972d5ce9ef3b5f31f8c01f89fed358aa1f9b/lib/method_disabling.rb#L118-L125
ruby
test
# Returns a Proc that acts as a replacement for the disabled method.
def to_proc
# Returns a Proc that acts as a replacement for the disabled method. def to_proc
disabled_method = self # This proc will be evaluated with "self" set to the original object. Proc.new do |*args, &block| disabled_method.execute(self, *args, &block) end end
dcuddeback/method_disabling
1617972d5ce9ef3b5f31f8c01f89fed358aa1f9b
lib/method_disabling.rb
https://github.com/dcuddeback/method_disabling/blob/1617972d5ce9ef3b5f31f8c01f89fed358aa1f9b/lib/method_disabling.rb#L135-L141
ruby
test
# The replacement for the original method. It will raise a NoMethodError if the method is # disabled. Otherwise, it will execute the original method. # # @param [Object] object The "self" object of the method being called. # @param [Array] args The arguments that were passed to the method. # @param [Proc] block The block that was passed to the method. # # @return Whatever the original method returns.
def execute(object, *args, &block)
# The replacement for the original method. It will raise a NoMethodError if the method is # disabled. Otherwise, it will execute the original method. # # @param [Object] object The "self" object of the method being called. # @param [Array] args The arguments that were passed to the method. # @param [Proc] block The block that was passed to the method. # # @return Whatever the original method returns. def execute(object, *args, &block)
if disabled? raise NoMethodError, message else object.send(aliased_name, *args, &block) end end
dcuddeback/method_disabling
1617972d5ce9ef3b5f31f8c01f89fed358aa1f9b
lib/method_disabling.rb
https://github.com/dcuddeback/method_disabling/blob/1617972d5ce9ef3b5f31f8c01f89fed358aa1f9b/lib/method_disabling.rb#L154-L158
ruby
test
# Replaces the original implementation of the method with an implementation that allows # disabling.
def alias_method!
# Replaces the original implementation of the method with an implementation that allows # disabling. def alias_method!
klass.send(:define_method, replacement_name, &self) klass.send(:alias_method, aliased_name, method_name) klass.send(:alias_method, method_name, replacement_name) end
mijinc0/ed25519_keccak
7eb8e2ef1395f104429a7ad6285c33d401744900
lib/ed25519_keccak/ed25519base.rb
https://github.com/mijinc0/ed25519_keccak/blob/7eb8e2ef1395f104429a7ad6285c33d401744900/lib/ed25519_keccak/ed25519base.rb#L22-L25
ruby
test
# calculate public key from secret
def secret_to_public(secret, form=:byte)
# calculate public key from secret def secret_to_public(secret, form=:byte)
publickey = p_secret_to_public( change_argument_format(secret, form) ) return change_result_format( publickey, form ) end
mijinc0/ed25519_keccak
7eb8e2ef1395f104429a7ad6285c33d401744900
lib/ed25519_keccak/ed25519base.rb
https://github.com/mijinc0/ed25519_keccak/blob/7eb8e2ef1395f104429a7ad6285c33d401744900/lib/ed25519_keccak/ed25519base.rb#L73-L80
ruby
test
# convert int to byte-string (littleEndian) # num : unsigned number to convert to bytes # length : byte length
def int_to_bytes( num , length )
# convert int to byte-string (littleEndian) # num : unsigned number to convert to bytes # length : byte length def int_to_bytes( num , length )
raise ArgumentError , "num :" + num.to_s if num < 0 raise ArgumentError , "length :" + length.to_s if length < 0 hex_str = num.to_s(16) hex_str = hex_str.rjust(length*2,"0") return hexstr_to_bytes(hex_str).reverse[0,length] end
mijinc0/ed25519_keccak
7eb8e2ef1395f104429a7ad6285c33d401744900
lib/ed25519_keccak/ed25519base.rb
https://github.com/mijinc0/ed25519_keccak/blob/7eb8e2ef1395f104429a7ad6285c33d401744900/lib/ed25519_keccak/ed25519base.rb#L98-L110
ruby
test
# region calculate mod # calculate base**exponent % modulus
def pow_mod(base, exponent, modulus)
# region calculate mod # calculate base**exponent % modulus def pow_mod(base, exponent, modulus)
raise ArgumentError if exponent<0 || modulus<0 # result of Nmod1 is always 0 return 0 if modulus.equal? 1 result = 1 base = base % modulus while exponent > 0 result = result*base%modulus if (exponent%2).equal? 1 exponent = exponent >> 1 base = base*base%modulus end return result end
mijinc0/ed25519_keccak
7eb8e2ef1395f104429a7ad6285c33d401744900
lib/ed25519_keccak/ed25519base.rb
https://github.com/mijinc0/ed25519_keccak/blob/7eb8e2ef1395f104429a7ad6285c33d401744900/lib/ed25519_keccak/ed25519base.rb#L132-L142
ruby
test
# region calculate point of ed25519 curve # Points are represented as array [X, Y, Z, T] of extended # coordinates, with x = X/Z, y = Y/Z, x*y = T/Z # # [arguments] # pa : point A # pb : point B
def point_add( pa , pb )
# region calculate point of ed25519 curve # Points are represented as array [X, Y, Z, T] of extended # coordinates, with x = X/Z, y = Y/Z, x*y = T/Z # # [arguments] # pa : point A # pb : point B def point_add( pa , pb )
_A = (pa[1]-pa[0]) * (pb[1]-pb[0]) % @@p _B = (pa[1]+pa[0]) * (pb[1]+pb[0]) % @@p _C = 2 * pa[3] * pb[3] * @@d % @@p _D = 2 * pa[2] * pb[2] % @@p _E = _B - _A _F = _D - _C _G = _D + _C _H = _B + _A return [ _E*_F , _G*_H , _F*_G , _E*_H ] end
mijinc0/ed25519_keccak
7eb8e2ef1395f104429a7ad6285c33d401744900
lib/ed25519_keccak/ed25519base.rb
https://github.com/mijinc0/ed25519_keccak/blob/7eb8e2ef1395f104429a7ad6285c33d401744900/lib/ed25519_keccak/ed25519base.rb#L145-L153
ruby
test
# Computes pointQ = s * pointA
def point_mul(s, pa)
# Computes pointQ = s * pointA def point_mul(s, pa)
pq = [0, 1, 1, 0] # Neutral element while s > 0 do pq = point_add(pq, pa) unless (s & 1).equal? 0 pa = point_add(pa, pa) s >>= 1 end return pq end
mijinc0/ed25519_keccak
7eb8e2ef1395f104429a7ad6285c33d401744900
lib/ed25519_keccak/ed25519base.rb
https://github.com/mijinc0/ed25519_keccak/blob/7eb8e2ef1395f104429a7ad6285c33d401744900/lib/ed25519_keccak/ed25519base.rb#L156-L161
ruby
test
# return point A == point B
def point_equal(pa, pb) # x1 / z1 == x2 / z2 <==> x1 * z2 == x2 * z1
# return point A == point B def point_equal(pa, pb) # x1 / z1 == x2 / z2 <==> x1 * z2 == x2 * z1
return false if (pa[0] * pb[2] - pb[0] * pa[2]) % @@p != 0 return false if (pa[1] * pb[2] - pb[1] * pa[2]) % @@p != 0 return true end
mijinc0/ed25519_keccak
7eb8e2ef1395f104429a7ad6285c33d401744900
lib/ed25519_keccak/ed25519base.rb
https://github.com/mijinc0/ed25519_keccak/blob/7eb8e2ef1395f104429a7ad6285c33d401744900/lib/ed25519_keccak/ed25519base.rb#L168-L186
ruby
test
# region point manipulation # Compute corresponding x-coordinate, with low bit corresponding to # sign, or return nil on failure
def recover_x(y, sign)
# region point manipulation # Compute corresponding x-coordinate, with low bit corresponding to # sign, or return nil on failure def recover_x(y, sign)
return nil if y >= @@p # x2 means x^2 x2 = (y*y-1) * modp_inv(@@d*y*y+1) # when x2==0 and sign!=0, these combination of arguments is illegal if x2.equal? 0 then unless sign.equal? 0 then return nil else return 0 end end # Compute square root of x2 x = pow_mod(x2 , ((@@p+3) / 8) , @@p) x = x * @@modp_sqrt_m1 % @@p unless ((x*x - x2) % @@p).equal? 0 return nil unless ((x*x - x2) % @@p).equal? 0 x = @@p - x unless (x & 1).equal? sign return x end
mijinc0/ed25519_keccak
7eb8e2ef1395f104429a7ad6285c33d401744900
lib/ed25519_keccak/ed25519base.rb
https://github.com/mijinc0/ed25519_keccak/blob/7eb8e2ef1395f104429a7ad6285c33d401744900/lib/ed25519_keccak/ed25519base.rb#L195-L203
ruby
test
# compress element[point] of ed25519 curve # # = Compressed format of Point(x,y) = # [ y0,y1...y253,y254 | x0 ] ArgumentError , # # Change the most significant bit of "y" to the least significant bit of "x" # The most significant bit of "y" is always zero because "0 <= y < 2^255-19"
def point_compress(p)
# compress element[point] of ed25519 curve # # = Compressed format of Point(x,y) = # [ y0,y1...y253,y254 | x0 ] ArgumentError , # # Change the most significant bit of "y" to the least significant bit of "x" # The most significant bit of "y" is always zero because "0 <= y < 2^255-19" def point_compress(p)
zinv = modp_inv(p[2]) x = p[0] * zinv % @@p y = p[1] * zinv % @@p # OR can be used to set the least significant bit of x to the most significant bit of y # because the most significant bit of "y" is always zero c = y | ((x & 1) << 255) return int_to_bytes(y | ((x & 1) << 255) , 32) end