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
|
|---|---|---|---|---|---|---|---|---|---|
jmcaffee/qbt_client
|
1e34d86c9ffc2e06fb7f0723fea13ba4596a1054
|
lib/qbt_client/web_ui.rb
|
https://github.com/jmcaffee/qbt_client/blob/1e34d86c9ffc2e06fb7f0723fea13ba4596a1054/lib/qbt_client/web_ui.rb#L494-L503
|
ruby
|
test
|
# Set location for a torrent
|
def set_location(torrent_hashes, path)
|
# Set location for a torrent
def set_location(torrent_hashes, path)
|
torrent_hashes = Array(torrent_hashes)
torrent_hashes = torrent_hashes.join('|')
options = {
body: { "hashes" => torrent_hashes, "location" => path },
}
self.class.post('/command/setLocation', options)
end
|
jmcaffee/qbt_client
|
1e34d86c9ffc2e06fb7f0723fea13ba4596a1054
|
lib/qbt_client/web_ui.rb
|
https://github.com/jmcaffee/qbt_client/blob/1e34d86c9ffc2e06fb7f0723fea13ba4596a1054/lib/qbt_client/web_ui.rb#L512-L521
|
ruby
|
test
|
# Increase the priority of one or more torrents
#
# If passing multiple torrent hashes, pass them as an array.
# Note: This does nothing unless queueing has been enabled
# via preferences.
|
def increase_priority torrent_hashes
|
# Increase the priority of one or more torrents
#
# If passing multiple torrent hashes, pass them as an array.
# Note: This does nothing unless queueing has been enabled
# via preferences.
def increase_priority torrent_hashes
|
torrent_hashes = Array(torrent_hashes)
torrent_hashes = torrent_hashes.join('|')
options = {
body: "hashes=#{torrent_hashes}"
}
self.class.post('/command/increasePrio', options)
end
|
jmcaffee/qbt_client
|
1e34d86c9ffc2e06fb7f0723fea13ba4596a1054
|
lib/qbt_client/web_ui.rb
|
https://github.com/jmcaffee/qbt_client/blob/1e34d86c9ffc2e06fb7f0723fea13ba4596a1054/lib/qbt_client/web_ui.rb#L530-L539
|
ruby
|
test
|
# Decrease the priority of one or more torrents
#
# If passing multiple torrent hashes, pass them as an array.
# Note: This does nothing unless queueing has been enabled
# via preferences.
|
def decrease_priority torrent_hashes
|
# Decrease the priority of one or more torrents
#
# If passing multiple torrent hashes, pass them as an array.
# Note: This does nothing unless queueing has been enabled
# via preferences.
def decrease_priority torrent_hashes
|
torrent_hashes = Array(torrent_hashes)
torrent_hashes = torrent_hashes.join('|')
options = {
body: "hashes=#{torrent_hashes}"
}
self.class.post('/command/decreasePrio', options)
end
|
jmcaffee/qbt_client
|
1e34d86c9ffc2e06fb7f0723fea13ba4596a1054
|
lib/qbt_client/web_ui.rb
|
https://github.com/jmcaffee/qbt_client/blob/1e34d86c9ffc2e06fb7f0723fea13ba4596a1054/lib/qbt_client/web_ui.rb#L548-L557
|
ruby
|
test
|
# Increase the priority of one or more torrents to the maximum value
#
# If passing multiple torrent hashes, pass them as an array.
# Note: This does nothing unless queueing has been enabled
# via preferences.
|
def maximize_priority torrent_hashes
|
# Increase the priority of one or more torrents to the maximum value
#
# If passing multiple torrent hashes, pass them as an array.
# Note: This does nothing unless queueing has been enabled
# via preferences.
def maximize_priority torrent_hashes
|
torrent_hashes = Array(torrent_hashes)
torrent_hashes = torrent_hashes.join('|')
options = {
body: "hashes=#{torrent_hashes}"
}
self.class.post('/command/topPrio', options)
end
|
jmcaffee/qbt_client
|
1e34d86c9ffc2e06fb7f0723fea13ba4596a1054
|
lib/qbt_client/web_ui.rb
|
https://github.com/jmcaffee/qbt_client/blob/1e34d86c9ffc2e06fb7f0723fea13ba4596a1054/lib/qbt_client/web_ui.rb#L566-L575
|
ruby
|
test
|
# Decrease the priority of one or more torrents to the minimum value
#
# If passing multiple torrent hashes, pass them as an array.
# Note: This does nothing unless queueing has been enabled
# via preferences.
|
def minimize_priority torrent_hashes
|
# Decrease the priority of one or more torrents to the minimum value
#
# If passing multiple torrent hashes, pass them as an array.
# Note: This does nothing unless queueing has been enabled
# via preferences.
def minimize_priority torrent_hashes
|
torrent_hashes = Array(torrent_hashes)
torrent_hashes = torrent_hashes.join('|')
options = {
body: "hashes=#{torrent_hashes}"
}
self.class.post('/command/bottomPrio', options)
end
|
jmcaffee/qbt_client
|
1e34d86c9ffc2e06fb7f0723fea13ba4596a1054
|
lib/qbt_client/web_ui.rb
|
https://github.com/jmcaffee/qbt_client/blob/1e34d86c9ffc2e06fb7f0723fea13ba4596a1054/lib/qbt_client/web_ui.rb#L582-L590
|
ruby
|
test
|
# Set the download priority of a file within a torrent
#
# file_id is a 0 based position of the file within the torrent
|
def set_file_priority torrent_hash, file_id, priority
|
# Set the download priority of a file within a torrent
#
# file_id is a 0 based position of the file within the torrent
def set_file_priority torrent_hash, file_id, priority
|
query = ["hash=#{torrent_hash}", "id=#{file_id}", "priority=#{priority}"]
options = {
body: query.join('&')
}
self.class.post('/command/setFilePrio', options)
end
|
jmcaffee/qbt_client
|
1e34d86c9ffc2e06fb7f0723fea13ba4596a1054
|
lib/qbt_client/web_ui.rb
|
https://github.com/jmcaffee/qbt_client/blob/1e34d86c9ffc2e06fb7f0723fea13ba4596a1054/lib/qbt_client/web_ui.rb#L677-L685
|
ruby
|
test
|
# Set a torrent's download limit
#
# A limit of 0 means unlimited.
#
# torrent_hash: string
# limit: integer (bytes)
|
def set_download_limit torrent_hash, limit
|
# Set a torrent's download limit
#
# A limit of 0 means unlimited.
#
# torrent_hash: string
# limit: integer (bytes)
def set_download_limit torrent_hash, limit
|
query = ["hashes=#{torrent_hash}", "limit=#{limit}"]
options = {
body: query.join('&')
}
self.class.post('/command/setTorrentsDlLimit', options)
end
|
jmcaffee/qbt_client
|
1e34d86c9ffc2e06fb7f0723fea13ba4596a1054
|
lib/qbt_client/web_ui.rb
|
https://github.com/jmcaffee/qbt_client/blob/1e34d86c9ffc2e06fb7f0723fea13ba4596a1054/lib/qbt_client/web_ui.rb#L714-L722
|
ruby
|
test
|
# Set a torrent's upload limit
#
# A limit of 0 means unlimited.
#
# torrent_hash: string
# limit: integer (bytes)
|
def set_upload_limit torrent_hash, limit
|
# Set a torrent's upload limit
#
# A limit of 0 means unlimited.
#
# torrent_hash: string
# limit: integer (bytes)
def set_upload_limit torrent_hash, limit
|
query = ["hashes=#{torrent_hash}", "limit=#{limit}"]
options = {
body: query.join('&')
}
self.class.post('/command/setTorrentsUpLimit', options)
end
|
gurgeous/scripto
|
e28792ca91dbb578725882799d76f82a64dfaa80
|
lib/scripto/misc_commands.rb
|
https://github.com/gurgeous/scripto/blob/e28792ca91dbb578725882799d76f82a64dfaa80/lib/scripto/misc_commands.rb#L19-L27
|
ruby
|
test
|
# Return the md5 checksum for the file at +path+.
|
def md5_file(path)
|
# Return the md5 checksum for the file at +path+.
def md5_file(path)
|
File.open(path) do |f|
digest, buf = Digest::MD5.new, ""
while f.read(4096, buf)
digest.update(buf)
end
digest.hexdigest
end
end
|
aphyr/risky
|
2f3dac30ff6b8aa06429bf68849b8b870f16831f
|
lib/risky/list_keys.rb
|
https://github.com/aphyr/risky/blob/2f3dac30ff6b8aa06429bf68849b8b870f16831f/lib/risky/list_keys.rb#L30-L45
|
ruby
|
test
|
# Iterate over all keys.
|
def keys(*a)
|
# Iterate over all keys.
def keys(*a)
|
if block_given?
bucket.keys(*a) do |keys|
# This API is currently inconsistent from protobuffs to http
if keys.kind_of? Array
keys.each do |key|
yield key
end
else
yield keys
end
end
else
bucket.keys(*a)
end
end
|
aphyr/risky
|
2f3dac30ff6b8aa06429bf68849b8b870f16831f
|
lib/risky/list_keys.rb
|
https://github.com/aphyr/risky/blob/2f3dac30ff6b8aa06429bf68849b8b870f16831f/lib/risky/list_keys.rb#L48-L56
|
ruby
|
test
|
# Iterate over all items using key streaming.
|
def each
|
# Iterate over all items using key streaming.
def each
|
bucket.keys do |keys|
keys.each do |key|
if x = self[key]
yield x
end
end
end
end
|
gurgeous/scripto
|
e28792ca91dbb578725882799d76f82a64dfaa80
|
lib/scripto/run_commands.rb
|
https://github.com/gurgeous/scripto/blob/e28792ca91dbb578725882799d76f82a64dfaa80/lib/scripto/run_commands.rb#L16-L20
|
ruby
|
test
|
# Run an external command. Raise Error if something goes wrong. The
# command will be echoed if verbose?.
#
# Usage is similar to Kernel#system. If +args+ is nil, +command+ will be
# passed to the shell. If +args+ are included, the +command+ and +args+
# will be run directly without the shell.
|
def run(command, args = nil)
|
# Run an external command. Raise Error if something goes wrong. The
# command will be echoed if verbose?.
#
# Usage is similar to Kernel#system. If +args+ is nil, +command+ will be
# passed to the shell. If +args+ are included, the +command+ and +args+
# will be run directly without the shell.
def run(command, args = nil)
|
cmd = CommandLine.new(command, args)
vputs(cmd)
cmd.run
end
|
lyfeyaj/rsqoot
|
0b3157f55f3a1fa2b21ac5389fe1686a77e6a4fd
|
lib/rsqoot/click.rb
|
https://github.com/lyfeyaj/rsqoot/blob/0b3157f55f3a1fa2b21ac5389fe1686a77e6a4fd/lib/rsqoot/click.rb#L10-L19
|
ruby
|
test
|
# Retrieve a list of clicks based on the following parameters
#
# @param [String] :to Start date
# @param [String] :from End date
#
# @return [RSqoot::SqootClick]
|
def clicks(options = {})
|
# Retrieve a list of clicks based on the following parameters
#
# @param [String] :to Start date
# @param [String] :from End date
#
# @return [RSqoot::SqootClick]
def clicks(options = {})
|
options = update_by_expire_time options
if clicks_not_latest?(options)
@rsqoot_clicks = get('clicks', options, SqootClick)
@rsqoot_clicks = @rsqoot_clicks.clicks if @rsqoot_clicks
@rsqoot_clicks = @rsqoot_clicks.clicks.map(&:click) if @rsqoot_clicks.clicks
end
logger(uri: sqoot_query_uri, records: @rsqoot_clicks, type: 'clicks', opts: options)
@rsqoot_clicks
end
|
pricees/rodeo_clown
|
be0e60b0cb5901904a762429f256d420e31581f1
|
lib/rodeo_clown/instance_builder.rb
|
https://github.com/pricees/rodeo_clown/blob/be0e60b0cb5901904a762429f256d420e31581f1/lib/rodeo_clown/instance_builder.rb#L34-L47
|
ruby
|
test
|
# Build instances using build options
#
# if :template is passed, only build on, used as a template for a new image
|
def build_instances(template = nil)
|
# Build instances using build options
#
# if :template is passed, only build on, used as a template for a new image
def build_instances(template = nil)
|
build_args =
if template == :template
[build_options.first.merge(count: 1)]
else
build_options
end
build_args.map do |args|
instances = create_instance args
apply_tags(instances)
instances
end.flatten
end
|
hanlindev/scoped_enum
|
9fc346b17baa42e64ce74b4813582c42de2c7bff
|
lib/scoped_enum/scope_creator.rb
|
https://github.com/hanlindev/scoped_enum/blob/9fc346b17baa42e64ce74b4813582c42de2c7bff/lib/scoped_enum/scope_creator.rb#L16-L45
|
ruby
|
test
|
# Initialize a new ScopeCreator object
# @param [ActiveRecord]
# @param [String, Symbol]
# Add a scope of the enum to the class. It creates an instance method - <scope_name>? and a
# ActiveRecord class scope with the same name as the enum scope.
# @param [String, Symbol] The name of the enum scope
# @param [Array<String>, Array<Symbol>] The list of keys of the enum
|
def scope(scope_name, scope_enum_keys)
|
# Initialize a new ScopeCreator object
# @param [ActiveRecord]
# @param [String, Symbol]
# Add a scope of the enum to the class. It creates an instance method - <scope_name>? and a
# ActiveRecord class scope with the same name as the enum scope.
# @param [String, Symbol] The name of the enum scope
# @param [Array<String>, Array<Symbol>] The list of keys of the enum
def scope(scope_name, scope_enum_keys)
|
target_enum = @record_class.defined_enums[@enum_name.to_s]
sub_enum_values = target_enum.values_at(*scope_enum_keys)
if @record_class.defined_enum_scopes.has_key?(scope_name)
fail ArgumentError,
"Conflicting scope names. A scope named #{scope_name} has already been defined"
elsif sub_enum_values.include?(nil)
unknown_key = scope_enum_keys[sub_enum_values.index(nil)]
fail ArgumentError, "Unknown key - #{unknown_key} for enum #{@enum_name}"
elsif @record_class.respond_to?(scope_name.to_s.pluralize)
fail ArgumentError,
"Scope name - #{scope_name} conflicts with a class method of the same name"
elsif @record_class.instance_methods.include?("#{scope_name}?".to_sym)
fail ArgumentError,
"Scope name - #{scope_name} conflicts with the instance method - #{scope_name}?"
end
sub_enum_entries = target_enum.slice(*scope_enum_keys)
@record_class.defined_enum_scopes[scope_name] = sub_enum_entries
# 1. Instance method <scope_name>?
@record_class.send(:define_method, "#{scope_name}?") { sub_enum_entries.include? self.role }
# 2. The class scope with the scope name
@record_class.scope scope_name.to_s.pluralize,
-> { @record_class.where("#{@enum_name}" => sub_enum_entries.values) }
@scope_names << scope_name
end
|
dansimpson/em-ws-client
|
6499762a21ed3087ede7b99c6594ed83ae53d0f7
|
lib/em-ws-client/decoder.rb
|
https://github.com/dansimpson/em-ws-client/blob/6499762a21ed3087ede7b99c6594ed83ae53d0f7/lib/em-ws-client/decoder.rb#L33-L204
|
ruby
|
test
|
# Public: Feed the decoder raw data from the wire
#
# data - The raw websocket frame data
#
# Examples
#
# decoder << raw
#
# Returns nothing
|
def << data
# put the data into the buffer, as
# we might be replaying
|
# Public: Feed the decoder raw data from the wire
#
# data - The raw websocket frame data
#
# Examples
#
# decoder << raw
#
# Returns nothing
def << data
# put the data into the buffer, as
# we might be replaying
|
if data
@buffer << data
end
# Don't do work if we don't have to
if @buffer.length < 2
return
end
# decode the first 2 bytes, with
# opcode, lengthgth, masking bit, and frag bit
h1, h2 = @buffer.unpack("CC")
# check the fragmentation bit to see
# if this is a message fragment
fin = ((h1 & 0x80) == 0x80)
# used to keep track of our position in the buffer
offset = 2
# see above for possible opcodes
opcode = (h1 & 0x0F)
# the leading length idicator
length = (h2 & 0x7F)
# masking bit, is the data masked with
# a specified masking key?
masked = ((h2 & 0x80) == 0x80)
# Find errors and fail fast
if h1 & 0b01110000 != 0
return emit :error, 1002, "RSV bits must be 0"
end
if opcode > 7
if !fin
return emit :error, 1002, "Control frame cannot be fragmented"
elsif length > 125
return emit :error, 1002, "Control frame is too large #{length}"
elsif opcode > 0xA
return emit :error, 1002, "Unexpected reserved opcode #{opcode}"
elsif opcode == CLOSE && length == 1
return emit :error, 1002, "Close control frame with payload of length 1"
end
else
if opcode != CONTINUATION && opcode != TEXT_FRAME && opcode != BINARY_FRAME
return emit :error, 1002, "Unexpected reserved opcode #{opcode}"
end
end
# Get the actual size of the payload
if length > 125
if length == 126
length = @buffer.unpack("@#{offset}n").first
offset += 2
else
length = @buffer.unpack("@#{offset}L!>").first
offset += 8
end
end
# unpack the masking key
if masked
key = @buffer.unpack("@#{offset}N").first
offset += 4
end
# replay on next frame
if @buffer.size < (length + offset)
return false
end
# Read the important bits
payload = @buffer.unpack("@#{offset}C#{length}")
# Unmask the data if it"s masked
if masked
payload.bytesize.times do |i|
payload[i] = ((payload[i] ^ (key >> ((3 - (i % 4)) * 8))) & 0xFF)
end
end
payload = payload.pack("C*")
case opcode
when CONTINUATION
# We shouldn't get a contination without
# knowing whether or not it's binary or text
unless @fragmented
return emit :error, 1002, "Unexepected continuation"
end
if @fragmented == :text
@chunks << payload.force_encoding("UTF-8")
else
@chunks << payload
end
if fin
if @fragmented == :text && !valid_utf8?(@chunks)
return emit :error, 1007, "Invalid UTF"
end
emit :frame, @chunks, @fragmented == :binary
@chunks = nil
@fragmented = false
end
when TEXT_FRAME
# We shouldn't get a text frame when we
# are expecting a continuation
if @fragmented
return emit :error, 1002, "Unexepected frame"
end
# emit or buffer
if fin
unless valid_utf8?(payload)
return emit :error, 1007, "Invalid UTF Hmm"
end
emit :frame, payload, false
else
@chunks = payload.force_encoding("UTF-8")
@fragmented = :text
end
when BINARY_FRAME
# We shouldn't get a text frame when we
# are expecting a continuation
if @fragmented
return emit :error, 1002, "Unexepected frame"
end
# emit or buffer
if fin
emit :frame, payload, true
else
@chunks = payload
@fragmented = :binary
end
when CLOSE
code, explain = payload.unpack("nA*")
if explain && !valid_utf8?(explain)
emit :close, 1007
else
emit :close, response_close_code(code)
end
when PING
emit :ping, payload
when PONG
emit :pong, payload
end
# Remove data we made use of and call back
# TODO: remove recursion
@buffer = @buffer[offset + length..-1] || ""
if not @buffer.empty?
self << nil
end
end
|
robertwahler/revenc
|
8b0ad162d916a239c4507b93cc8e5530f38d8afb
|
lib/revenc/settings.rb
|
https://github.com/robertwahler/revenc/blob/8b0ad162d916a239c4507b93cc8e5530f38d8afb/lib/revenc/settings.rb#L20-L94
|
ruby
|
test
|
# read options from YAML config
|
def configure
# config file default options
|
# read options from YAML config
def configure
# config file default options
|
configuration = {
:options => {
:verbose => false,
:coloring => 'AUTO'
},
:mount => {
:source => {
:name => nil
},
:mountpoint => {
:name => nil
},
:passphrasefile => {
:name => 'passphrase'
},
:keyfile => {
:name => 'encfs6.xml'
},
:cmd => nil,
:executable => nil
},
:unmount => {
:mountpoint => {
:name => nil
},
:cmd => nil,
:executable => nil
},
:copy => {
:source => {
:name => nil
},
:destination => {
:name => nil
},
:cmd => nil,
:executable => nil
}
}
# set default config if not given on command line
config = @options[:config]
unless config
config = [
File.join(@working_dir, "revenc.conf"),
File.join(@working_dir, ".revenc.conf"),
File.join(@working_dir, "config", "revenc.conf"),
File.expand_path(File.join("~", ".revenc.conf"))
].detect { |filename| File.exists?(filename) }
end
if config && File.exists?(config)
# rewrite options full path for config for later use
@options[:config] = config
# load options from the config file, overwriting hard-coded defaults
config_contents = YAML::load(File.open(config))
configuration.merge!(config_contents.symbolize_keys!) if config_contents && config_contents.is_a?(Hash)
else
# user specified a config file?, no error if user did not specify config file
raise "config file not found" if @options[:config]
end
# the command line options override options read from the config file
@options = configuration[:options].merge!(@options)
@options.symbolize_keys!
# mount, unmount and copy configuration hashes
@options[:mount] = configuration[:mount].recursively_symbolize_keys! if configuration[:mount]
@options[:unmount] = configuration[:unmount].recursively_symbolize_keys! if configuration[:unmount]
@options[:copy] = configuration[:copy].recursively_symbolize_keys! if configuration[:copy]
end
|
sixoverground/tang
|
66fff66d5abe03f5e69e98601346a88c71e54675
|
app/controllers/tang/admin/subscriptions_controller.rb
|
https://github.com/sixoverground/tang/blob/66fff66d5abe03f5e69e98601346a88c71e54675/app/controllers/tang/admin/subscriptions_controller.rb#L24-L37
|
ruby
|
test
|
# PATCH/PUT /subscriptions/1
|
def update
|
# PATCH/PUT /subscriptions/1
def update
|
@subscription.end_trial_now = (params[:subscription][:end_trial_now] == '1')
if @subscription.end_trial_now
params[:subscription]['trial_end(1i)'] = ''
params[:subscription]['trial_end(2i)'] = ''
params[:subscription]['trial_end(3i)'] = ''
end
if @subscription.update(subscription_params)
redirect_to [:admin, @subscription], notice: 'Subscription was successfully updated.'
else
render :edit
end
end
|
jsl/feedtosis
|
26f0e10a10c8fc0722133b5eb3ed22ef2175531f
|
lib/feedtosis/client.rb
|
https://github.com/jsl/feedtosis/blob/26f0e10a10c8fc0722133b5eb3ed22ef2175531f/lib/feedtosis/client.rb#L51-L56
|
ruby
|
test
|
# Initializes a new feedtosis library. It must be initialized with a valid URL as the first argument.
# A following optional +options+ Hash may take the arguments:
# * backend: a key-value store to be used for summary structures of feeds fetched. Moneta backends work well, but any object acting like a Hash is valid.
# * retained_digest_size: an Integer specifying the number of previous MD5 sets of entries to keep, used for new feed detection
# Retrieves the latest entries from this feed. Returns a Feedtosis::Result
# object which delegates methods to the Curl::Easy object making the request
# and the FeedNormalizer::Feed object that may have been created from the
# HTTP response body.
|
def fetch
|
# Initializes a new feedtosis library. It must be initialized with a valid URL as the first argument.
# A following optional +options+ Hash may take the arguments:
# * backend: a key-value store to be used for summary structures of feeds fetched. Moneta backends work well, but any object acting like a Hash is valid.
# * retained_digest_size: an Integer specifying the number of previous MD5 sets of entries to keep, used for new feed detection
# Retrieves the latest entries from this feed. Returns a Feedtosis::Result
# object which delegates methods to the Curl::Easy object making the request
# and the FeedNormalizer::Feed object that may have been created from the
# HTTP response body.
def fetch
|
curl = build_curl_easy
curl.perform
feed = process_curl_response(curl)
Feedtosis::Result.new(curl, feed)
end
|
jsl/feedtosis
|
26f0e10a10c8fc0722133b5eb3ed22ef2175531f
|
lib/feedtosis/client.rb
|
https://github.com/jsl/feedtosis/blob/26f0e10a10c8fc0722133b5eb3ed22ef2175531f/lib/feedtosis/client.rb#L62-L73
|
ruby
|
test
|
# Marks entries as either seen or not seen based on the unique signature of
# the entry, which is calculated by taking the MD5 of common attributes.
|
def mark_new_entries(response)
|
# Marks entries as either seen or not seen based on the unique signature of
# the entry, which is calculated by taking the MD5 of common attributes.
def mark_new_entries(response)
|
digests = summary_digests
# For each entry in the responses object, mark @_seen as false if the
# digest of this entry doesn't exist in the cached object.
response.entries.each do |e|
seen = digests.include?(digest_for(e))
e.instance_variable_set(:@_seen, seen)
end
response
end
|
jsl/feedtosis
|
26f0e10a10c8fc0722133b5eb3ed22ef2175531f
|
lib/feedtosis/client.rb
|
https://github.com/jsl/feedtosis/blob/26f0e10a10c8fc0722133b5eb3ed22ef2175531f/lib/feedtosis/client.rb#L85-L92
|
ruby
|
test
|
# Processes the results by identifying which entries are new if the response
# is a 200. Otherwise, returns the Curl::Easy object for the user to inspect.
|
def process_curl_response(curl)
|
# Processes the results by identifying which entries are new if the response
# is a 200. Otherwise, returns the Curl::Easy object for the user to inspect.
def process_curl_response(curl)
|
if curl.response_code == 200
response = parser_for_xml(curl.body_str)
response = mark_new_entries(response)
store_summary_to_backend(response, curl)
response
end
end
|
jsl/feedtosis
|
26f0e10a10c8fc0722133b5eb3ed22ef2175531f
|
lib/feedtosis/client.rb
|
https://github.com/jsl/feedtosis/blob/26f0e10a10c8fc0722133b5eb3ed22ef2175531f/lib/feedtosis/client.rb#L116-L125
|
ruby
|
test
|
# Sets the headers from the backend, if available
|
def set_header_options(curl)
|
# Sets the headers from the backend, if available
def set_header_options(curl)
|
summary = summary_for_feed
unless summary.nil?
curl.headers['If-None-Match'] = summary[:etag] unless summary[:etag].nil?
curl.headers['If-Modified-Since'] = summary[:last_modified] unless summary[:last_modified].nil?
end
curl
end
|
jsl/feedtosis
|
26f0e10a10c8fc0722133b5eb3ed22ef2175531f
|
lib/feedtosis/client.rb
|
https://github.com/jsl/feedtosis/blob/26f0e10a10c8fc0722133b5eb3ed22ef2175531f/lib/feedtosis/client.rb#L136-L156
|
ruby
|
test
|
# Stores information about the retrieval, including ETag, Last-Modified,
# and MD5 digests of all entries to the backend store. This enables
# conditional GET usage on subsequent requests and marking of entries as
# either new or seen.
|
def store_summary_to_backend(feed, curl)
|
# Stores information about the retrieval, including ETag, Last-Modified,
# and MD5 digests of all entries to the backend store. This enables
# conditional GET usage on subsequent requests and marking of entries as
# either new or seen.
def store_summary_to_backend(feed, curl)
|
headers = HttpHeaders.new(curl.header_str)
# Store info about HTTP retrieval
summary = { }
summary.merge!(:etag => headers.etag) unless headers.etag.nil?
summary.merge!(:last_modified => headers.last_modified) unless headers.last_modified.nil?
# Store digest for each feed entry so we can detect new feeds on the next
# retrieval
new_digest_set = feed.entries.map do |e|
digest_for(e)
end
new_digest_set = summary_for_feed[:digests].unshift(new_digest_set)
new_digest_set = new_digest_set[0..@options[:retained_digest_size]]
summary.merge!( :digests => new_digest_set )
set_summary(summary)
end
|
jsl/feedtosis
|
26f0e10a10c8fc0722133b5eb3ed22ef2175531f
|
lib/feedtosis/client.rb
|
https://github.com/jsl/feedtosis/blob/26f0e10a10c8fc0722133b5eb3ed22ef2175531f/lib/feedtosis/client.rb#L165-L167
|
ruby
|
test
|
# Computes a unique signature for the FeedNormalizer::Entry object given.
# This signature will be the MD5 of enough fields to have a reasonable
# probability of determining if the entry is unique or not.
|
def digest_for(entry)
|
# Computes a unique signature for the FeedNormalizer::Entry object given.
# This signature will be the MD5 of enough fields to have a reasonable
# probability of determining if the entry is unique or not.
def digest_for(entry)
|
MD5.hexdigest( [ entry.title, entry.content, entry.date_published ].join )
end
|
gurgeous/scripto
|
e28792ca91dbb578725882799d76f82a64dfaa80
|
lib/scripto/print_commands.rb
|
https://github.com/gurgeous/scripto/blob/e28792ca91dbb578725882799d76f82a64dfaa80/lib/scripto/print_commands.rb#L37-L41
|
ruby
|
test
|
# Print a colored banner to $stderr in green.
|
def banner(str, color: GREEN)
|
# Print a colored banner to $stderr in green.
def banner(str, color: GREEN)
|
now = Time.new.strftime("%H:%M:%S")
s = "#{str} ".ljust(72, " ")
$stderr.puts "#{color}[#{now}] #{s}#{RESET}"
end
|
lyfeyaj/rsqoot
|
0b3157f55f3a1fa2b21ac5389fe1686a77e6a4fd
|
lib/rsqoot/logger.rb
|
https://github.com/lyfeyaj/rsqoot/blob/0b3157f55f3a1fa2b21ac5389fe1686a77e6a4fd/lib/rsqoot/logger.rb#L8-L39
|
ruby
|
test
|
# Add logger support, easy for log monitor when running your app
# Output errors and valid records count
# TODO add color support
|
def logger(options = { records: [], uri: '', error: '', type: '', opts: {} })
|
# Add logger support, easy for log monitor when running your app
# Output errors and valid records count
# TODO add color support
def logger(options = { records: [], uri: '', error: '', type: '', opts: {} })
|
records = options[:records].nil? ? [] : options[:records]
error = options[:error]
uri = options[:uri]
type = options[:type]
opts = options[:opts]
if defined? Rails
if error.present?
Rails.logger.info ">>> Error: #{error}"
else
Rails.logger.info ">>> Querying Sqoot API V2: #{type}"
Rails.logger.info ">>> #{uri}"
Rails.logger.info ">>> #{opts}"
Rails.logger.info ">>> Hit #{records.count} records"
end
else
if error.present?
puts ">>> Error: #{error}"
puts ''
else
puts ">>> Querying Sqoot API V2: #{type}"
puts ''
puts ">>> #{uri}"
puts ''
puts ">>> #{opts}"
puts ''
puts ">>> Hit #{records.count} records"
puts ''
end
end
end
|
averell23/assit
|
4daf03ddfcbfead42d1f639bd4c70bcde0ec1bab
|
lib/assit/actions/console_action.rb
|
https://github.com/averell23/assit/blob/4daf03ddfcbfead42d1f639bd4c70bcde0ec1bab/lib/assit/actions/console_action.rb#L7-L11
|
ruby
|
test
|
# The action
|
def assert_it(message)
|
# The action
def assert_it(message)
|
$stderr.puts("Assertion failed: " + message.to_s)
$stderr.puts("at: ")
caller.each { |trace| $stderr.puts trace }
end
|
monkeyx/pbw
|
f7fc2638a2f50c4f7fdfa571330f5c2225f5eb2a
|
app/models/pbw/container.rb
|
https://github.com/monkeyx/pbw/blob/f7fc2638a2f50c4f7fdfa571330f5c2225f5eb2a/app/models/pbw/container.rb#L49-L52
|
ruby
|
test
|
# ATTACHED PROCESSES
|
def attach_tick_process(process, ticks_to_wait=0)
|
# ATTACHED PROCESSES
def attach_tick_process(process, ticks_to_wait=0)
|
self.attached_processes << AttachedProcess.build(process: process, tickable: true, ticks_waiting: ticks_to_wait)
save!
end
|
monkeyx/pbw
|
f7fc2638a2f50c4f7fdfa571330f5c2225f5eb2a
|
app/models/pbw/container.rb
|
https://github.com/monkeyx/pbw/blob/f7fc2638a2f50c4f7fdfa571330f5c2225f5eb2a/app/models/pbw/container.rb#L96-L98
|
ruby
|
test
|
# TOKENS
|
def has_token?(token)
|
# TOKENS
def has_token?(token)
|
token && token._id && self.tokens.where(_id: token._id).first
end
|
monkeyx/pbw
|
f7fc2638a2f50c4f7fdfa571330f5c2225f5eb2a
|
app/models/pbw/container.rb
|
https://github.com/monkeyx/pbw/blob/f7fc2638a2f50c4f7fdfa571330f5c2225f5eb2a/app/models/pbw/container.rb#L117-L125
|
ruby
|
test
|
# CONSTRAINTS
|
def add_constraint!(constraint)
|
# CONSTRAINTS
def add_constraint!(constraint)
|
raise PbwArgumentError('Invalid constraint') unless constraint
return false if has_constraint?(constraint)
return false unless constraint.before_add(self)
self.constraints << constraint
save!
constraint.after_add(self)
self
end
|
monkeyx/pbw
|
f7fc2638a2f50c4f7fdfa571330f5c2225f5eb2a
|
app/models/pbw/container.rb
|
https://github.com/monkeyx/pbw/blob/f7fc2638a2f50c4f7fdfa571330f5c2225f5eb2a/app/models/pbw/container.rb#L143-L151
|
ruby
|
test
|
# CAPABILITIES
|
def add_capability!(capability)
|
# CAPABILITIES
def add_capability!(capability)
|
raise PbwArgumentError('Invalid capability') unless capability
return false if has_capability?(capability)
return false unless capability.before_add(self)
self.capabilities << capability
save!
capability.after_add(self)
self
end
|
monkeyx/pbw
|
f7fc2638a2f50c4f7fdfa571330f5c2225f5eb2a
|
app/models/pbw/container.rb
|
https://github.com/monkeyx/pbw/blob/f7fc2638a2f50c4f7fdfa571330f5c2225f5eb2a/app/models/pbw/container.rb#L169-L176
|
ruby
|
test
|
# TRIGGERS
|
def add_trigger!(trigger)
|
# TRIGGERS
def add_trigger!(trigger)
|
raise PbwArgumentError('Invalid trigger') unless trigger
return false if has_trigger?(trigger)
self.triggers << trigger
save!
trigger.after_add(self)
self
end
|
CiscoSystems/ropenstack
|
77dcb332711da2a35fe5abf2b6c63a0415c0bf69
|
lib/ropenstack/common/rest.rb
|
https://github.com/CiscoSystems/ropenstack/blob/77dcb332711da2a35fe5abf2b6c63a0415c0bf69/lib/ropenstack/common/rest.rb#L17-L24
|
ruby
|
test
|
# Build a HTTP object having been given a timeout and a URI object
# Returns Net::HTTP object.
|
def build_http(uri, timeout)
|
# Build a HTTP object having been given a timeout and a URI object
# Returns Net::HTTP object.
def build_http(uri, timeout)
|
http = Net::HTTP.new(uri.host, uri.port)
if(timeout > 0)
http.open_timeout = timeout
http.read_timeout = timeout
end
return http
end
|
CiscoSystems/ropenstack
|
77dcb332711da2a35fe5abf2b6c63a0415c0bf69
|
lib/ropenstack/common/rest.rb
|
https://github.com/CiscoSystems/ropenstack/blob/77dcb332711da2a35fe5abf2b6c63a0415c0bf69/lib/ropenstack/common/rest.rb#L33-L54
|
ruby
|
test
|
# All responses from openstack where any errors need to be caught are passed through
# this function. Unless a successful response is passed it will throw a Ropenstack
# error.
# If successful returns a hash of response body, unless response body is nil then it
# returns an empty hash.
|
def error_manager(uri, response)
|
# All responses from openstack where any errors need to be caught are passed through
# this function. Unless a successful response is passed it will throw a Ropenstack
# error.
# If successful returns a hash of response body, unless response body is nil then it
# returns an empty hash.
def error_manager(uri, response)
|
case response
when Net::HTTPSuccess then
# This covers cases where the response may not validate as JSON.
begin
data = JSON.parse(response.body)
rescue
data = {}
end
## Get the Headers out of the response object
data['headers'] = response.to_hash()
return data
when Net::HTTPBadRequest
raise Ropenstack::MalformedRequestError, response.body
when Net::HTTPNotFound
raise Ropenstack::NotFoundError, "URI: #{uri} \n" + response.body
when Net::HTTPUnauthorized
raise Ropenstack::UnauthorisedError, response.body
else
raise Ropenstack::RopenstackError, response.body
end
end
|
CiscoSystems/ropenstack
|
77dcb332711da2a35fe5abf2b6c63a0415c0bf69
|
lib/ropenstack/common/rest.rb
|
https://github.com/CiscoSystems/ropenstack/blob/77dcb332711da2a35fe5abf2b6c63a0415c0bf69/lib/ropenstack/common/rest.rb#L75-L89
|
ruby
|
test
|
# The function which you call to perform a http request
# using the request object given in the parameters. By
# default manage errors is true, so all responses are passed
# through the error manager which converts the into Ropenstack errors.
|
def do_request(uri, request, manage_errors = true, timeout = 10)
|
# The function which you call to perform a http request
# using the request object given in the parameters. By
# default manage errors is true, so all responses are passed
# through the error manager which converts the into Ropenstack errors.
def do_request(uri, request, manage_errors = true, timeout = 10)
|
begin
http = build_http(uri, timeout)
if(manage_errors)
return error_manager(uri, http.request(request))
else
http.request(request)
return { "Success" => true }
end
rescue Timeout::Error
raise Ropenstack::TimeoutError, "It took longer than #{timeout} to connect to #{uri.to_s}"
rescue Errno::ECONNREFUSED
raise Ropenstack::TimeoutError, "It took longer than #{timeout} to connect to #{uri.to_s}"
end
end
|
CiscoSystems/ropenstack
|
77dcb332711da2a35fe5abf2b6c63a0415c0bf69
|
lib/ropenstack/common/rest.rb
|
https://github.com/CiscoSystems/ropenstack/blob/77dcb332711da2a35fe5abf2b6c63a0415c0bf69/lib/ropenstack/common/rest.rb#L97-L100
|
ruby
|
test
|
# Wrapper function for a get request, just provide a uri
# and it will return you a hash with the result data.
# For authenticated transactions a token can be provided.
# Implemented using the do_request method.
|
def get_request(uri, token = nil, manage_errors = true)
|
# Wrapper function for a get request, just provide a uri
# and it will return you a hash with the result data.
# For authenticated transactions a token can be provided.
# Implemented using the do_request method.
def get_request(uri, token = nil, manage_errors = true)
|
request = Net::HTTP::Get.new(uri.request_uri, initheader = build_headers(token))
return do_request(uri, request, manage_errors)
end
|
CiscoSystems/ropenstack
|
77dcb332711da2a35fe5abf2b6c63a0415c0bf69
|
lib/ropenstack/common/rest.rb
|
https://github.com/CiscoSystems/ropenstack/blob/77dcb332711da2a35fe5abf2b6c63a0415c0bf69/lib/ropenstack/common/rest.rb#L108-L111
|
ruby
|
test
|
# Wrapper function for delete requests, just provide a uri
# and it will return you a hash with the result data.
# For authenticated transactions a token can be provided.
# Implemented using the do_request method.
|
def delete_request(uri, token = nil, manage_errors = true)
|
# Wrapper function for delete requests, just provide a uri
# and it will return you a hash with the result data.
# For authenticated transactions a token can be provided.
# Implemented using the do_request method.
def delete_request(uri, token = nil, manage_errors = true)
|
request = Net::HTTP::Delete.new(uri.request_uri, initheader = build_headers(token))
return do_request(uri, request, manage_errors)
end
|
CiscoSystems/ropenstack
|
77dcb332711da2a35fe5abf2b6c63a0415c0bf69
|
lib/ropenstack/common/rest.rb
|
https://github.com/CiscoSystems/ropenstack/blob/77dcb332711da2a35fe5abf2b6c63a0415c0bf69/lib/ropenstack/common/rest.rb#L120-L124
|
ruby
|
test
|
# Wrapper function for a put request, just provide a uri
# and a hash of the data to send, then it will return you a hash
# with the result data.
# For authenticated transactions a token can be provided.
# Implemented using the do_request method
|
def put_request(uri, body, token = nil, manage_errors = true)
|
# Wrapper function for a put request, just provide a uri
# and a hash of the data to send, then it will return you a hash
# with the result data.
# For authenticated transactions a token can be provided.
# Implemented using the do_request method
def put_request(uri, body, token = nil, manage_errors = true)
|
request = Net::HTTP::Put.new(uri.request_uri, initheader = build_headers(token))
request.body = body.to_json
return do_request(uri, request, manage_errors)
end
|
CiscoSystems/ropenstack
|
77dcb332711da2a35fe5abf2b6c63a0415c0bf69
|
lib/ropenstack/common/rest.rb
|
https://github.com/CiscoSystems/ropenstack/blob/77dcb332711da2a35fe5abf2b6c63a0415c0bf69/lib/ropenstack/common/rest.rb#L132-L136
|
ruby
|
test
|
# Wrapper function for a put request, just provide a uri
# and a hash of the data to send, then it will return you a hash
# with the result data.
# For authenticated transactions a token can be provided.
|
def post_request(uri, body, token = nil, manage_errors = true)
|
# Wrapper function for a put request, just provide a uri
# and a hash of the data to send, then it will return you a hash
# with the result data.
# For authenticated transactions a token can be provided.
def post_request(uri, body, token = nil, manage_errors = true)
|
request = Net::HTTP::Post.new(uri.request_uri, initheader = build_headers(token))
request.body = body.to_json
return do_request(uri, request, manage_errors)
end
|
plexus/fn
|
238410ad52f874793051334fd89373b5ae241cf4
|
lib/fn.rb
|
https://github.com/plexus/fn/blob/238410ad52f874793051334fd89373b5ae241cf4/lib/fn.rb#L16-L20
|
ruby
|
test
|
# Functional composition, f · g
|
def comp(g)
|
# Functional composition, f · g
def comp(g)
|
Fn { |*a, &b|
call(g.call(*a, &b))
}
end
|
bjjb/sfkb
|
a0bc802c08fed3d246090d2c73fdb5a199d4e2cf
|
lib/sfkb/knowledge.rb
|
https://github.com/bjjb/sfkb/blob/a0bc802c08fed3d246090d2c73fdb5a199d4e2cf/lib/sfkb/knowledge.rb#L17-L23
|
ruby
|
test
|
# Enumerates articles
|
def articles
|
# Enumerates articles
def articles
|
Enumerator.new do |y|
article_ids.each do |id|
y << article(id)
end
end
end
|
bjjb/sfkb
|
a0bc802c08fed3d246090d2c73fdb5a199d4e2cf
|
lib/sfkb/knowledge.rb
|
https://github.com/bjjb/sfkb/blob/a0bc802c08fed3d246090d2c73fdb5a199d4e2cf/lib/sfkb/knowledge.rb#L26-L30
|
ruby
|
test
|
# Gets an article by ID
|
def article(id)
|
# Gets an article by ID
def article(id)
|
url = index.knowledgeManagement.articles.article
url = url(url, ArticleID: id)
decorate(get(url).body) { |o| autodefine(o) }
end
|
CiscoSystems/ropenstack
|
77dcb332711da2a35fe5abf2b6c63a0415c0bf69
|
lib/ropenstack/image/v2.rb
|
https://github.com/CiscoSystems/ropenstack/blob/77dcb332711da2a35fe5abf2b6c63a0415c0bf69/lib/ropenstack/image/v2.rb#L80-L106
|
ruby
|
test
|
# BELOW HERE IS OLD CODE THAT MAY OR MAYNOT WORK, THAR BE DRAGONS
#
# Upload an image to the Image Service from a file, takes in a ruby file object.
# More convoluted than it should be because for a bug in Quantum
# which just returns an error no matter the outcome.
|
def upload_image_from_file(name, disk_format, container_format, minDisk, minRam, is_public, file)
|
# BELOW HERE IS OLD CODE THAT MAY OR MAYNOT WORK, THAR BE DRAGONS
#
# Upload an image to the Image Service from a file, takes in a ruby file object.
# More convoluted than it should be because for a bug in Quantum
# which just returns an error no matter the outcome.
def upload_image_from_file(name, disk_format, container_format, minDisk, minRam, is_public, file)
|
data = {
"name" => name,
"disk_format" => disk_format,
"container_format" => container_format,
"minDisk" => minDisk,
"minRam" => minRam,
"public" => is_public
}
imagesBefore = images()
post_request(address("images"), data, @token, false)
imagesAfter = images()
foundNewImage = true
image = nil
imagesAfter.each do |imageA|
imagesBefore.each do |imageB|
if(imageA == imageB)
foundNewImage = false
end
end
if(foundNewImage)
image = imageA
break
end
end
return put_octect(address(image["file"]), file.read, false)
end
|
CiscoSystems/ropenstack
|
77dcb332711da2a35fe5abf2b6c63a0415c0bf69
|
lib/ropenstack/image/v2.rb
|
https://github.com/CiscoSystems/ropenstack/blob/77dcb332711da2a35fe5abf2b6c63a0415c0bf69/lib/ropenstack/image/v2.rb#L113-L119
|
ruby
|
test
|
# Special rest call for sending a file stream using an octet-stream
# main change is just custom headers.
# Still implemented using do_request function.
|
def put_octect(uri, data, manage_errors)
|
# Special rest call for sending a file stream using an octet-stream
# main change is just custom headers.
# Still implemented using do_request function.
def put_octect(uri, data, manage_errors)
|
headers = build_headers(@token)
headers["Content-Type"] = 'application/octet-stream'
req = Net::HTTP::Put.new(uri.request_uri, initheader = headers)
req.body = data
return do_request(uri, req, manage_errors, 0)
end
|
arnab/game_of_life
|
06a5dd4c21610bab1df2a21ca6b723922dfd5a6a
|
lib/game_of_life/rules.rb
|
https://github.com/arnab/game_of_life/blob/06a5dd4c21610bab1df2a21ca6b723922dfd5a6a/lib/game_of_life/rules.rb#L10-L18
|
ruby
|
test
|
# The rules followed are:
# 1. Any live cell with fewer than two live neighbours dies, as if caused by under-population.
# 2. Any live cell with two or three live neighbours lives on to the next generation.
# 3. Any live cell with more than three live neighbours dies, as if by overcrowding.
# 4. Any dead cell with exactly three live neighbours becomes a live cell, as if by reproduction.
# 5. Any live cell that is over 3 generations dies
|
def should_cell_live?(board, cell, x, y)
|
# The rules followed are:
# 1. Any live cell with fewer than two live neighbours dies, as if caused by under-population.
# 2. Any live cell with two or three live neighbours lives on to the next generation.
# 3. Any live cell with more than three live neighbours dies, as if by overcrowding.
# 4. Any dead cell with exactly three live neighbours becomes a live cell, as if by reproduction.
# 5. Any live cell that is over 3 generations dies
def should_cell_live?(board, cell, x, y)
|
live_neighbors_count = board.neighbors_of_cell_at(x, y).select { |n| n.alive? }.size
case cell.state
when :live
((2..3).include? live_neighbors_count) && (! cell.old?)
when :dead
live_neighbors_count == 3
end
end
|
balexand/qwiki
|
e472aac254675de24f45b37076bf9d32f1fe195e
|
lib/qwiki/app.rb
|
https://github.com/balexand/qwiki/blob/e472aac254675de24f45b37076bf9d32f1fe195e/lib/qwiki/app.rb#L31-L39
|
ruby
|
test
|
# Returns a path relative to the base path, given the full path. This is the inverse of
# full_path.
|
def relative_path(path)
|
# Returns a path relative to the base path, given the full path. This is the inverse of
# full_path.
def relative_path(path)
|
path = File.expand_path(path)
root = full_path("")
if path.size >= root.size && path[0...root.size] == root
path[0...root.size] = ""
path = "/" if path.size == 0
path
end
end
|
balexand/qwiki
|
e472aac254675de24f45b37076bf9d32f1fe195e
|
lib/qwiki/app.rb
|
https://github.com/balexand/qwiki/blob/e472aac254675de24f45b37076bf9d32f1fe195e/lib/qwiki/app.rb#L47-L57
|
ruby
|
test
|
# Renders an index page for the specified directory.
|
def index(path)
|
# Renders an index page for the specified directory.
def index(path)
|
@entries = []
Dir.entries(path).each do |entry|
relative_path = relative_path(File.join(path, entry))
if entry != "." && relative_path
@entries << {:name => entry, :href => relative_path}
end
end
@path = path
haml :index
end
|
gialib/rails-sprite
|
8adc00379f758383294b0794d3ce298879275200
|
lib/rails_sprite/sprite_util.rb
|
https://github.com/gialib/rails-sprite/blob/8adc00379f758383294b0794d3ce298879275200/lib/rails_sprite/sprite_util.rb#L58-L107
|
ruby
|
test
|
# :css_extend => "",
# :root_path => '.',
# :scope_name => "rails_xxx",
# :recipe_path => "icons/16x16",
# :file_extend => '.png',
# :spacing => 10,
# :image_to_folder => "app/assets/images",
# :image_source_folder => 'app/assets/images/rails_xxx/sprite_sources',
# :stylesheet_to => "app/assets/stylesheets/rails_xxx/sprite/icons/16x16.css.scss.erb",
# :image_to_file_path => "rails_xxx/sprite/icons/16x16.png"
|
def perform
|
# :css_extend => "",
# :root_path => '.',
# :scope_name => "rails_xxx",
# :recipe_path => "icons/16x16",
# :file_extend => '.png',
# :spacing => 10,
# :image_to_folder => "app/assets/images",
# :image_source_folder => 'app/assets/images/rails_xxx/sprite_sources',
# :stylesheet_to => "app/assets/stylesheets/rails_xxx/sprite/icons/16x16.css.scss.erb",
# :image_to_file_path => "rails_xxx/sprite/icons/16x16.png"
def perform
|
file_infos = []
# puts "image_source_folder: #{image_source_folder}"
# puts "image_to_file_path: #{image_to_file_path}"
# puts "stylesheet_to: #{stylesheet_to}"
counter = 0
x = 0
y = 0
max_w = 0
max_h = 0
Dir.entries( image_source_folder ).each do |file_name|
if file_name != '.' && file_name != '..' && file_name.end_with?(file_extend)
file_path = "#{image_source_folder}/#{file_name}"
if ::File.file?(file_path)
file_name_split = file_name.split('.')
file_name_split.pop
file_purename = file_name_split.join('.')
file_info = {
:filepath => file_path,
:filename => file_name,
:file_purename => file_purename,
:idx => counter
}.merge(
_library.load( file_path )
)
file_info[:x] = x
file_info[:y] = y
y += (spacing + file_info[:height])
max_w = [max_w, file_info[:width]].max
max_h = y
file_infos << file_info
counter += 1
end
end
end
_composite_images(:file_infos => file_infos, :max_w => max_w, :max_h => max_h)
_composite_css(file_infos, :max_w => max_w, :max_h => max_h)
end
|
apeiros/tabledata
|
e277b6a1fdb567a6d73f42349bb9946ffad67134
|
lib/tabledata/table.rb
|
https://github.com/apeiros/tabledata/blob/e277b6a1fdb567a6d73f42349bb9946ffad67134/lib/tabledata/table.rb#L196-L200
|
ruby
|
test
|
# Create a new table.
#
# @param [Hash] options
# A list of options. Mostly identical to {Table#initialize}'s options
# hash, but with the additional options :file_type and :table_class.
#
# @option options [String] :name
# The name of the table
# @option options [Array<Symbol>, Hash<Symbol => Integer>, nil] :accessors
# A list of accessors for the columns. Allows accessing columns by that accessor.
# @option options [Symbol] :data
# An array of arrays with the table data. Mutually exclusive with
# :header, :body and :footer.
# @option options [Symbol] :header
# An array with the header values. To be used together with :body and :footer.
# Mutually exclusive with :data.
# Automatically sets :has_headers to true.
# @option options [Symbol] :body
# An array with the header values. To be used together with :header and :footer.
# Mutually exclusive with :data.
# Automatically sets :has_headers to false if :header is not also present.
# Automatically sets :has_footer to false if :footer is not also present.
# @option options [Symbol] :footer
# An array with the header values. To be used together with :header and :body.
# Mutually exclusive with :data.
# Automatically sets :has_footer to true.
# @option options [true, false] :has_headers
# Whether the table has a header, defaults to true
# @option options [true, false] :has_footer
# Whether the table has a footer, defaults to false
#
# Automatically create accessors from the headers of the table.
# It does that by downcasing the headers, replace everything which is not in [a-z0-9_] with an _,
# replace all repeated occurrences of _ with a single _.
#
# @note
# The actual transformation algorithm might change in the future.
|
def accessors_from_headers!
|
# Create a new table.
#
# @param [Hash] options
# A list of options. Mostly identical to {Table#initialize}'s options
# hash, but with the additional options :file_type and :table_class.
#
# @option options [String] :name
# The name of the table
# @option options [Array<Symbol>, Hash<Symbol => Integer>, nil] :accessors
# A list of accessors for the columns. Allows accessing columns by that accessor.
# @option options [Symbol] :data
# An array of arrays with the table data. Mutually exclusive with
# :header, :body and :footer.
# @option options [Symbol] :header
# An array with the header values. To be used together with :body and :footer.
# Mutually exclusive with :data.
# Automatically sets :has_headers to true.
# @option options [Symbol] :body
# An array with the header values. To be used together with :header and :footer.
# Mutually exclusive with :data.
# Automatically sets :has_headers to false if :header is not also present.
# Automatically sets :has_footer to false if :footer is not also present.
# @option options [Symbol] :footer
# An array with the header values. To be used together with :header and :body.
# Mutually exclusive with :data.
# Automatically sets :has_footer to true.
# @option options [true, false] :has_headers
# Whether the table has a header, defaults to true
# @option options [true, false] :has_footer
# Whether the table has a footer, defaults to false
#
# Automatically create accessors from the headers of the table.
# It does that by downcasing the headers, replace everything which is not in [a-z0-9_] with an _,
# replace all repeated occurrences of _ with a single _.
#
# @note
# The actual transformation algorithm might change in the future.
def accessors_from_headers!
|
raise "Can't define accessors from headers in a table without headers" unless @has_headers
self.accessors = headers.map { |val| (val && !val.empty?) ? val.to_s.downcase.tr('^a-z0-9_', '_').squeeze('_').gsub(/\A_|_\z/, '').to_sym : nil }
end
|
apeiros/tabledata
|
e277b6a1fdb567a6d73f42349bb9946ffad67134
|
lib/tabledata/table.rb
|
https://github.com/apeiros/tabledata/blob/e277b6a1fdb567a6d73f42349bb9946ffad67134/lib/tabledata/table.rb#L207-L224
|
ruby
|
test
|
# @param [Array<Symbol>, Hash<Symbol => Integer>, nil] accessors
#
# Define the name of the accessors used in Tabledata::Row.
# If you pass in a Hash, it's supposed to be in the form of
# {accessor_name: column_index}.
|
def accessors=(accessors)
|
# @param [Array<Symbol>, Hash<Symbol => Integer>, nil] accessors
#
# Define the name of the accessors used in Tabledata::Row.
# If you pass in a Hash, it's supposed to be in the form of
# {accessor_name: column_index}.
def accessors=(accessors)
|
@accessor_columns = {}
case accessors
when nil
# nothing to do
when Array
accessors.each_with_index do |name, idx|
@accessor_columns[name.to_sym] = idx if name
end
when Hash
@accessor_columns = Hash[accessors.map { |name, index| [name.to_sym, index] }]
else
raise ArgumentError, "Expected nil, an Array or a Hash, but got #{accessors.class}"
end
@accessor_columns.freeze
@column_accessors = @accessor_columns.invert.freeze
@accessors = @column_accessors.values_at(*0..(@column_accessors.keys.max || -1)).freeze
end
|
apeiros/tabledata
|
e277b6a1fdb567a6d73f42349bb9946ffad67134
|
lib/tabledata/table.rb
|
https://github.com/apeiros/tabledata/blob/e277b6a1fdb567a6d73f42349bb9946ffad67134/lib/tabledata/table.rb#L254-L268
|
ruby
|
test
|
# @return [Tabledata::Row]
# The row at the given row number (zero based). Includes headers and footer.
# Returns the given default value or invokes the default block if the desired row does not
# exist.
#
# @raise [KeyError]
# If the row was not found and neither a default value nor a default block were given.
|
def fetch_row(row, *default)
|
# @return [Tabledata::Row]
# The row at the given row number (zero based). Includes headers and footer.
# Returns the given default value or invokes the default block if the desired row does not
# exist.
#
# @raise [KeyError]
# If the row was not found and neither a default value nor a default block were given.
def fetch_row(row, *default)
|
raise ArgumentError, "Must only provide at max one default value or one default block" if default.size > (block_given? ? 0 : 1)
row_data = row(row)
if row_data
row_data
elsif block_given?
yield(self, row)
elsif default.empty?
raise KeyError, "Row not found: #{row.inspect}"
else
default.first
end
end
|
apeiros/tabledata
|
e277b6a1fdb567a6d73f42349bb9946ffad67134
|
lib/tabledata/table.rb
|
https://github.com/apeiros/tabledata/blob/e277b6a1fdb567a6d73f42349bb9946ffad67134/lib/tabledata/table.rb#L283-L297
|
ruby
|
test
|
# @return [Object]
# The cell value at the given row and column number (zero based). Includes headers and footer.
# Returns the given default value or invokes the default block if the desired cell does not
# exist.
#
# @raise [KeyError]
# If the cell was not found and neither a default value nor a default block were given.
|
def fetch_cell(row, column, *default_value, &default_block)
|
# @return [Object]
# The cell value at the given row and column number (zero based). Includes headers and footer.
# Returns the given default value or invokes the default block if the desired cell does not
# exist.
#
# @raise [KeyError]
# If the cell was not found and neither a default value nor a default block were given.
def fetch_cell(row, column, *default_value, &default_block)
|
raise ArgumentError, "Must only provide at max one default value or one default block" if default_value.size > (block_given? ? 0 : 1)
row_data = row(row)
if row_data
row_data.fetch(column, *default_value, &default_block)
elsif block_given?
yield(self, row, column)
elsif default_value.empty?
raise IndexError, "Row not found: #{row.inspect}, #{column.inspect}"
else
default_value.first
end
end
|
apeiros/tabledata
|
e277b6a1fdb567a6d73f42349bb9946ffad67134
|
lib/tabledata/table.rb
|
https://github.com/apeiros/tabledata/blob/e277b6a1fdb567a6d73f42349bb9946ffad67134/lib/tabledata/table.rb#L406-L420
|
ruby
|
test
|
# Append a row to the table.
#
# @param [Array, #to_ary] row
# The row to append to the table
#
# @return [self]
|
def <<(row)
|
# Append a row to the table.
#
# @param [Array, #to_ary] row
# The row to append to the table
#
# @return [self]
def <<(row)
|
index = @data.size
begin
row = row.to_ary
rescue NoMethodError
raise ArgumentError, "Row must be provided as Array or respond to `to_ary`, but got #{row.class} in row #{index}" unless row.respond_to?(:to_ary)
raise
end
raise InvalidColumnCount.new(index, row.size, column_count) if @data.first && row.size != @data.first.size
@data << row
@rows << Row.new(self, index, row)
self
end
|
griffinmyers/hemingway
|
65d876d7b85a2d8c3ca28f1e2b9bd1f293162ace
|
lib/hemingway/footnote/footnote_nodes.rb
|
https://github.com/griffinmyers/hemingway/blob/65d876d7b85a2d8c3ca28f1e2b9bd1f293162ace/lib/hemingway/footnote/footnote_nodes.rb#L10-L13
|
ruby
|
test
|
# This is the method that will place the anchor tag and id of the
# footnote within the paragraph body itself.
#
# I'm passing in a time variable here to make links unique. You see,
# if you parse many of these entries on a single HTML page you'll end up
# with multiple #footnote1 divs. To make them unique, we'll pass down
# a time variable from above to seed them.
|
def html(id, time)
|
# This is the method that will place the anchor tag and id of the
# footnote within the paragraph body itself.
#
# I'm passing in a time variable here to make links unique. You see,
# if you parse many of these entries on a single HTML page you'll end up
# with multiple #footnote1 divs. To make them unique, we'll pass down
# a time variable from above to seed them.
def html(id, time)
|
inline_footnote_label = Build.tag("span", Build.tag("sup", id.to_s), :class => "inline-footnote-number")
Build.tag("a", inline_footnote_label, :href => "#footnote#{id}#{time}")
end
|
griffinmyers/hemingway
|
65d876d7b85a2d8c3ca28f1e2b9bd1f293162ace
|
lib/hemingway/footnote/footnote_nodes.rb
|
https://github.com/griffinmyers/hemingway/blob/65d876d7b85a2d8c3ca28f1e2b9bd1f293162ace/lib/hemingway/footnote/footnote_nodes.rb#L25-L29
|
ruby
|
test
|
# This is the method that will actually spit out the div that the
# footnote's content is in. This will generally be called after all of the
# paragraph's text has been spit out so that the footnotes can be appended
# after. Note that it needs to be passed an id from the caller so that it
# can be linked to corretly with an anchor tag in the body of the main text.
#
# I'm passing in a time variable here to make links unique. You see,
# if you parse many of these entries on a single HTML page you'll end up
# with multiple #footnote1 divs. To make them unique, we'll pass down
# a time variable from above to seed them.
|
def footnote_html(id, time)
|
# This is the method that will actually spit out the div that the
# footnote's content is in. This will generally be called after all of the
# paragraph's text has been spit out so that the footnotes can be appended
# after. Note that it needs to be passed an id from the caller so that it
# can be linked to corretly with an anchor tag in the body of the main text.
#
# I'm passing in a time variable here to make links unique. You see,
# if you parse many of these entries on a single HTML page you'll end up
# with multiple #footnote1 divs. To make them unique, we'll pass down
# a time variable from above to seed them.
def footnote_html(id, time)
|
footnote_label = Build.tag("span", Build.tag("sup", id.to_s), :class => "footnote-number")
footnote_content = sequence.elements.map { |s| s.html }.join
Build.tag("div", footnote_label + footnote_content, :id => "footnote#{id}#{time}", :class => "footnote")
end
|
CiscoSystems/ropenstack
|
77dcb332711da2a35fe5abf2b6c63a0415c0bf69
|
lib/ropenstack/database/v1.rb
|
https://github.com/CiscoSystems/ropenstack/blob/77dcb332711da2a35fe5abf2b6c63a0415c0bf69/lib/ropenstack/database/v1.rb#L46-L61
|
ruby
|
test
|
# Database Instance Actions
|
def instance_action(id, action, param)
|
# Database Instance Actions
def instance_action(id, action, param)
|
case action
when "RESTART"
post_request(address("/instances/" + id + "/action"), {:restart => {}}, @token)
when "RESIZE"
if param.is_a? String
post_request(address("/instances/" + id + "/action"), {:resize => {:flavorRef => param }}, @token)
elsif param.is_a? Int
post_request(address("/instances/" + id + "/action"), {:resize => {:volume => {:size => param }}}, @token)
else
raise Ropenstack::RopenstackError, "Invalid Parameter Passed"
end
else
raise Ropenstack::RopenstackError, "Invalid Action Passed"
end
end
|
dcrosby42/conject
|
df4b89ac97f65c6334db46b4652bfa6ae0a7446e
|
lib/conject/dependency_resolver.rb
|
https://github.com/dcrosby42/conject/blob/df4b89ac97f65c6334db46b4652bfa6ae0a7446e/lib/conject/dependency_resolver.rb#L12-L18
|
ruby
|
test
|
# Given a Class, generate a map of dependencies needed to construct a new
# instance of that class. Dependencies are looked up (and/or instantiated, as
# determined within the ObjectContext) via the provided ObjectContext.
#
# This method assumes the Class has_object_defintion? (Client code should
# determine that before invoking this method.)
|
def resolve_for_class(klass, object_context, remapping=nil)
|
# Given a Class, generate a map of dependencies needed to construct a new
# instance of that class. Dependencies are looked up (and/or instantiated, as
# determined within the ObjectContext) via the provided ObjectContext.
#
# This method assumes the Class has_object_defintion? (Client code should
# determine that before invoking this method.)
def resolve_for_class(klass, object_context, remapping=nil)
|
remapping ||= {}
klass.object_definition.component_names.inject({}) do |obj_map, name|
obj_map[name] = search_for(klass, object_context, remapping[name.to_sym] || remapping[name.to_s] || name)
obj_map
end
end
|
robertwahler/revenc
|
8b0ad162d916a239c4507b93cc8e5530f38d8afb
|
lib/revenc/errors.rb
|
https://github.com/robertwahler/revenc/blob/8b0ad162d916a239c4507b93cc8e5530f38d8afb/lib/revenc/errors.rb#L11-L26
|
ruby
|
test
|
# add errors, error_on can be a symbol or object instance
|
def add(error_on, message = "Unknown error")
# humanize error_on
|
# add errors, error_on can be a symbol or object instance
def add(error_on, message = "Unknown error")
# humanize error_on
|
if error_on.is_a?(Symbol)
error_on_str = error_on.to_s
else
error_on_str = underscore(error_on.class.name)
end
error_on_str = error_on_str.gsub(/\//, '_')
error_on_str = error_on_str.gsub(/_/, ' ')
error_on_str = error_on_str.gsub(/^revenc/, '').strip
#error_on_str = error_on_str.capitalize
@errors[error_on_str] ||= []
@errors[error_on_str] << message.to_s
end
|
arnab/game_of_life
|
06a5dd4c21610bab1df2a21ca6b723922dfd5a6a
|
lib/game_of_life/board.rb
|
https://github.com/arnab/game_of_life/blob/06a5dd4c21610bab1df2a21ca6b723922dfd5a6a/lib/game_of_life/board.rb#L68-L71
|
ruby
|
test
|
# Finds the neighbors of a given {Cell}'s co-ordinates. The neighbors are the eight cells
# that surround the given one.
# @param [Integer] x the x-coordinate of the cell you find the neighbors of
# @param [Integer] y the y-coordinate of the cell you find the neighbors of
# @return [Array<Cell>]
|
def neighbors_of_cell_at(x, y)
|
# Finds the neighbors of a given {Cell}'s co-ordinates. The neighbors are the eight cells
# that surround the given one.
# @param [Integer] x the x-coordinate of the cell you find the neighbors of
# @param [Integer] y the y-coordinate of the cell you find the neighbors of
# @return [Array<Cell>]
def neighbors_of_cell_at(x, y)
|
neighbors = coords_of_neighbors(x, y).map { |x, y| self.cell_at(x, y) }
neighbors.reject {|n| n.nil?}
end
|
arnab/game_of_life
|
06a5dd4c21610bab1df2a21ca6b723922dfd5a6a
|
lib/game_of_life/board.rb
|
https://github.com/arnab/game_of_life/blob/06a5dd4c21610bab1df2a21ca6b723922dfd5a6a/lib/game_of_life/board.rb#L75-L90
|
ruby
|
test
|
# This is the first stage in a Game's #tick.
# @see Game#tick
|
def reformat_for_next_generation!
# create an array of dead cells and insert it as the first and last row of cells
|
# This is the first stage in a Game's #tick.
# @see Game#tick
def reformat_for_next_generation!
# create an array of dead cells and insert it as the first and last row of cells
|
dead_cells = ([email protected]).map { Cell.new }
# don't forget to deep copy the dead_cells
@cells.unshift Marshal.load(Marshal.dump(dead_cells))
@cells.push Marshal.load(Marshal.dump(dead_cells))
# also insert a dead cell at the left and right of each row
@cells.each do |row|
row.unshift Cell.new
row.push Cell.new
end
# validate to see if we broke the board
validate
end
|
arnab/game_of_life
|
06a5dd4c21610bab1df2a21ca6b723922dfd5a6a
|
lib/game_of_life/board.rb
|
https://github.com/arnab/game_of_life/blob/06a5dd4c21610bab1df2a21ca6b723922dfd5a6a/lib/game_of_life/board.rb#L105-L123
|
ruby
|
test
|
# This is the third and last stage in a Game's #tick.
# @see Game#tick
|
def shed_dead_weight!
# Remove the first and last rows if all cells are dead
|
# This is the third and last stage in a Game's #tick.
# @see Game#tick
def shed_dead_weight!
# Remove the first and last rows if all cells are dead
|
@cells.shift if @cells.first.all? { |cell| cell.dead? }
@cells.pop if @cells.last.all? { |cell| cell.dead? }
# Remove the first cell of every row, if they are all dead
first_columns = @cells.map { |row| row.first }
if first_columns.all? { |cell| cell.dead? }
@cells.each { |row| row.shift }
end
# Remove the last cell of every row, if they are all dead
last_columns = @cells.map { |row| row.last }
if last_columns.all? { |cell| cell.dead? }
@cells.each { |row| row.pop }
end
validate
end
|
arnab/game_of_life
|
06a5dd4c21610bab1df2a21ca6b723922dfd5a6a
|
lib/game_of_life/board.rb
|
https://github.com/arnab/game_of_life/blob/06a5dd4c21610bab1df2a21ca6b723922dfd5a6a/lib/game_of_life/board.rb#L179-L188
|
ruby
|
test
|
# Calculates the co-ordinates of neighbors of a given pair of co-ordinates.
# @param [Integer] x the x-coordinate
# @param [Integer] y the y-coordinate
# @return [Array<Integer, Integer>] the list of neighboring co-ordinates
# @example
# coords_of_neighbors(1,1) =>
# [
# [0, 0], [0, 1], [0, 2],
# [1, 0], [1, 2],
# [2, 0], [2, 1], [2, 2],
# ]
# @note This method returns all possible co-ordinate pairs of neighbors,
# so it can contain coordinates of cells not in the board, or negative ones.
# @see #neighbors_of_cell_at
|
def coords_of_neighbors(x, y)
|
# Calculates the co-ordinates of neighbors of a given pair of co-ordinates.
# @param [Integer] x the x-coordinate
# @param [Integer] y the y-coordinate
# @return [Array<Integer, Integer>] the list of neighboring co-ordinates
# @example
# coords_of_neighbors(1,1) =>
# [
# [0, 0], [0, 1], [0, 2],
# [1, 0], [1, 2],
# [2, 0], [2, 1], [2, 2],
# ]
# @note This method returns all possible co-ordinate pairs of neighbors,
# so it can contain coordinates of cells not in the board, or negative ones.
# @see #neighbors_of_cell_at
def coords_of_neighbors(x, y)
|
coords_of_neighbors = []
(x - 1).upto(x + 1).each do |neighbors_x|
(y - 1).upto(y + 1).each do |neighbors_y|
next if (x == neighbors_x) && (y == neighbors_y)
coords_of_neighbors << [neighbors_x, neighbors_y]
end
end
coords_of_neighbors
end
|
lyfeyaj/rsqoot
|
0b3157f55f3a1fa2b21ac5389fe1686a77e6a4fd
|
lib/rsqoot/merchant.rb
|
https://github.com/lyfeyaj/rsqoot/blob/0b3157f55f3a1fa2b21ac5389fe1686a77e6a4fd/lib/rsqoot/merchant.rb#L9-L17
|
ruby
|
test
|
# Retrieve a list of merchants base on the following parameters
#
# @param [String] id (The merchant's ID, Use the Sqoot ID or ID for any supported namespace. Must supply namespace if we don't use Sqoot)
# @param [String] namespace (One of the supported namespaces. Factual, Foursquare, Facebook, Google, CitySearch, Yelp.)
|
def merchant(id, options = {})
|
# Retrieve a list of merchants base on the following parameters
#
# @param [String] id (The merchant's ID, Use the Sqoot ID or ID for any supported namespace. Must supply namespace if we don't use Sqoot)
# @param [String] namespace (One of the supported namespaces. Factual, Foursquare, Facebook, Google, CitySearch, Yelp.)
def merchant(id, options = {})
|
options = update_by_expire_time options
if merchant_not_latest?(id)
@rsqoot_merchant = get("merchants/#{id}", options, SqootMerchant)
@rsqoot_merchant = @rsqoot_merchant.merchant if @rsqoot_merchant
end
logger(uri: sqoot_query_uri, records: [@rsqoot_merchant], type: 'merchants', opts: options)
@rsqoot_merchant
end
|
dansimpson/em-ws-client
|
6499762a21ed3087ede7b99c6594ed83ae53d0f7
|
lib/em-ws-client/encoder.rb
|
https://github.com/dansimpson/em-ws-client/blob/6499762a21ed3087ede7b99c6594ed83ae53d0f7/lib/em-ws-client/encoder.rb#L13-L55
|
ruby
|
test
|
# Encode a standard payload to a hybi10
# WebSocket frame
|
def encode data, opcode=TEXT_FRAME
|
# Encode a standard payload to a hybi10
# WebSocket frame
def encode data, opcode=TEXT_FRAME
|
frame = []
frame << (opcode | 0x80)
packr = "CC"
if opcode == TEXT_FRAME
data.force_encoding("UTF-8")
if !data.valid_encoding?
raise "Invalid UTF!"
end
end
# append frame length and mask bit 0x80
len = data ? data.bytesize : 0
if len <= 125
frame << (len | 0x80)
elsif len < 65536
frame << (126 | 0x80)
frame << len
packr << "n"
else
frame << (127 | 0x80)
frame << len
packr << "L!>"
end
# generate a masking key
key = rand(2 ** 31)
# mask each byte with the key
frame << key
packr << "N"
#puts "op #{opcode} len #{len} bytes #{data}"
# Apply the masking key to every byte
len.times do |i|
frame << ((data.getbyte(i) ^ (key >> ((3 - (i % 4)) * 8))) & 0xFF)
end
frame.pack("#{packr}C*")
end
|
jdtornow/challah-rolls
|
ba235d5f0f1e65210907b1e4d3dcb0a7d765077a
|
lib/challah/rolls/permission.rb
|
https://github.com/jdtornow/challah-rolls/blob/ba235d5f0f1e65210907b1e4d3dcb0a7d765077a/lib/challah/rolls/permission.rb#L55-L77
|
ruby
|
test
|
# This method sets up the +Permission+ class with all baked in methods.
#
# A permission requires the presence of the +name+, +key+ and +description+
#
# Once this method has been called, the {InstanceMethods} module
# will be accessibile within the Permission model.
|
def challah_permission
|
# This method sets up the +Permission+ class with all baked in methods.
#
# A permission requires the presence of the +name+, +key+ and +description+
#
# Once this method has been called, the {InstanceMethods} module
# will be accessibile within the Permission model.
def challah_permission
|
unless included_modules.include?(InstanceMethods)
include InstanceMethods
extend ClassMethods
end
class_eval do
validates_presence_of :name, :key
validates_uniqueness_of :name, :key
validates_format_of :key, :with => /^([a-z0-9_])*$/, :message => :invalid_key
has_many :permission_roles, :dependent => :destroy
has_many :roles, :through => :permission_roles, :order => 'roles.name'
has_many :permission_users, :dependent => :destroy
has_many :users, :through => :permission_users, :order => 'users.last_name, users.first_name'
default_scope order('permissions.name')
attr_accessible :name, :description, :key, :locked
after_create :add_to_admin_role
end
end
|
progressions/epic
|
171353cc39c130b338a073ebdfa995483d3523e5
|
lib/epic/base.rb
|
https://github.com/progressions/epic/blob/171353cc39c130b338a073ebdfa995483d3523e5/lib/epic/base.rb#L24-L28
|
ruby
|
test
|
# Parses out the <tt>base_path</tt> setting from a path to display it in a
# less verbose way.
|
def display_path(filename=nil)
|
# Parses out the <tt>base_path</tt> setting from a path to display it in a
# less verbose way.
def display_path(filename=nil)
|
filename ||= path
display_path = File.expand_path(filename)
display_path.gsub(base_path.to_s, "")
end
|
Juanchote/api_connectors
|
f8bdb71647ddd96dd9408c39181bab8ac834f5fd
|
lib/api_connector/api_connector.rb
|
https://github.com/Juanchote/api_connectors/blob/f8bdb71647ddd96dd9408c39181bab8ac834f5fd/lib/api_connector/api_connector.rb#L44-L49
|
ruby
|
test
|
# makes a POST request
#
# ==== Attributes
# * +hash+ - Hash of parameters
# ** +endpoint+ - Url endpoint ex. /product/createOrUpdate
# ** +args+ - Request arguments, (add headers key for extra headers options) ex. hash[:headers] = { 'content-type' => 'xml' }
# * +payload+ - Data for the request ex. { merchantId: 'asdasdsadas', products: [{ ... },{ ...}...]}
|
def post hash={}, payload
|
# makes a POST request
#
# ==== Attributes
# * +hash+ - Hash of parameters
# ** +endpoint+ - Url endpoint ex. /product/createOrUpdate
# ** +args+ - Request arguments, (add headers key for extra headers options) ex. hash[:headers] = { 'content-type' => 'xml' }
# * +payload+ - Data for the request ex. { merchantId: 'asdasdsadas', products: [{ ... },{ ...}...]}
def post hash={}, payload
|
raise 'Payload cannot be blank' if payload.nil? || payload.empty?
hash.symbolize_keys!
call(:post, hash[:endpoint], (hash[:args]||{}).merge({:method => :post}), payload)
end
|
Juanchote/api_connectors
|
f8bdb71647ddd96dd9408c39181bab8ac834f5fd
|
lib/api_connector/api_connector.rb
|
https://github.com/Juanchote/api_connectors/blob/f8bdb71647ddd96dd9408c39181bab8ac834f5fd/lib/api_connector/api_connector.rb#L57-L73
|
ruby
|
test
|
# low level api for request (needed por PUT, PATCH & DELETE methods)
#
# ==== Attributes
# * +endpoint+ - Url endpoint ex. /merchant/get
# * +args+ - Request arguments, (add headers key for extra headers options) ex. { method: :get, headers: { 'content-type' => 'xml' } } (method key is needed, otherwise :get will be setted)
# * +params+ - Request parameters / payload data
|
def call method, endpoint, args={}, params
|
# low level api for request (needed por PUT, PATCH & DELETE methods)
#
# ==== Attributes
# * +endpoint+ - Url endpoint ex. /merchant/get
# * +args+ - Request arguments, (add headers key for extra headers options) ex. { method: :get, headers: { 'content-type' => 'xml' } } (method key is needed, otherwise :get will be setted)
# * +params+ - Request parameters / payload data
def call method, endpoint, args={}, params
|
raise "Endpoint can't be blank" unless endpoint
raise "Method is missing" unless method
url = (method == :get || method == :delete) ? url(endpoint,params) : url(endpoint)
RestClient::Request.execute(method: method,
url: url,
headers: header(args[:headers]),
payload: params || {}
) do |response, request, result|
#status = response.code == 200 ? :debug : :error
#print(status, request, response.body)
parse(response, endpoint)
end
end
|
CiscoSystems/ropenstack
|
77dcb332711da2a35fe5abf2b6c63a0415c0bf69
|
lib/ropenstack/networking.rb
|
https://github.com/CiscoSystems/ropenstack/blob/77dcb332711da2a35fe5abf2b6c63a0415c0bf69/lib/ropenstack/networking.rb#L27-L33
|
ruby
|
test
|
# Networks
#
# Get a list of a tenants networks
#
# :call-seq:
# networks(id) => A single network with the id matching the parameter
# networks => All networks visible to the tenant making the request
|
def networks(id = nil)
|
# Networks
#
# Get a list of a tenants networks
#
# :call-seq:
# networks(id) => A single network with the id matching the parameter
# networks => All networks visible to the tenant making the request
def networks(id = nil)
|
endpoint = "networks"
unless id.nil?
endpoint = endpoint + "/" + id
end
return get_request(address(endpoint), @token)
end
|
CiscoSystems/ropenstack
|
77dcb332711da2a35fe5abf2b6c63a0415c0bf69
|
lib/ropenstack/networking.rb
|
https://github.com/CiscoSystems/ropenstack/blob/77dcb332711da2a35fe5abf2b6c63a0415c0bf69/lib/ropenstack/networking.rb#L38-L47
|
ruby
|
test
|
# Create a new network on Openstack given a name and tenant id.
|
def create_network(name, tenant, admin_state_up = true)
|
# Create a new network on Openstack given a name and tenant id.
def create_network(name, tenant, admin_state_up = true)
|
data = {
'network' => {
'name' => name,
'tenant_id' => tenant,
'admin_state_up' => admin_state_up
}
}
return post_request(address("networks"), data, @token)
end
|
CiscoSystems/ropenstack
|
77dcb332711da2a35fe5abf2b6c63a0415c0bf69
|
lib/ropenstack/networking.rb
|
https://github.com/CiscoSystems/ropenstack/blob/77dcb332711da2a35fe5abf2b6c63a0415c0bf69/lib/ropenstack/networking.rb#L107-L126
|
ruby
|
test
|
# Create a new port given network and device ids, optional
# parameter subnet id allows for scoping the port to a single subnet.
|
def create_port(network, subnet = nil, device = nil, device_owner = nil)
|
# Create a new port given network and device ids, optional
# parameter subnet id allows for scoping the port to a single subnet.
def create_port(network, subnet = nil, device = nil, device_owner = nil)
|
data = {
'port' => {
'network_id' => network,
}
}
unless device_owner.nil?
data['port']['device_owner'] = device_owner
end
unless device.nil?
data['port']['device_id'] = device
end
unless subnet.nil?
data['port']['fixed_ips'] = [{'subnet_id' => subnet}]
end
puts data
return post_request(address("ports"), data, @token)
end
|
CiscoSystems/ropenstack
|
77dcb332711da2a35fe5abf2b6c63a0415c0bf69
|
lib/ropenstack/networking.rb
|
https://github.com/CiscoSystems/ropenstack/blob/77dcb332711da2a35fe5abf2b6c63a0415c0bf69/lib/ropenstack/networking.rb#L139-L145
|
ruby
|
test
|
# Weird function for adding a port to multiple subnets if nessessary.
|
def move_port_to_subnets(port_id, subnet_ids)
|
# Weird function for adding a port to multiple subnets if nessessary.
def move_port_to_subnets(port_id, subnet_ids)
|
id_list = Array.new()
subnet_ids.each do |id|
id_list << { "subnet_id" => id }
end
return update_port(port_id, id_list)
end
|
pjb3/rack-action
|
7f0f78c0ffe34fc5c067df6f65c24e114b1a608b
|
lib/rack/action.rb
|
https://github.com/pjb3/rack-action/blob/7f0f78c0ffe34fc5c067df6f65c24e114b1a608b/lib/rack/action.rb#L108-L112
|
ruby
|
test
|
# This is a convenience method that sets the Content-Type headers
# and writes the JSON String to the response.
#
# @param [Hash] data The data
# @param [Hash] options The options
# @option options [Fixnum] :status The response status code
# @return [String] The JSON
|
def json(data={}, options={})
|
# This is a convenience method that sets the Content-Type headers
# and writes the JSON String to the response.
#
# @param [Hash] data The data
# @param [Hash] options The options
# @option options [Fixnum] :status The response status code
# @return [String] The JSON
def json(data={}, options={})
|
response[CONTENT_TYPE] = APPLICATION_JSON
response.status = options[:status] if options.has_key?(:status)
response.write self.class.json_serializer.dump(data)
end
|
pjb3/rack-action
|
7f0f78c0ffe34fc5c067df6f65c24e114b1a608b
|
lib/rack/action.rb
|
https://github.com/pjb3/rack-action/blob/7f0f78c0ffe34fc5c067df6f65c24e114b1a608b/lib/rack/action.rb#L120-L125
|
ruby
|
test
|
# This is a convenience method that forms an absolute URL based on the
# url parameter, which can be a relative or absolute URL, and then
# sets the headers and the body appropriately to do a 302 redirect.
#
# @see #absolute_url
# @return [String] The absolute url
|
def redirect_to(url, options={})
|
# This is a convenience method that forms an absolute URL based on the
# url parameter, which can be a relative or absolute URL, and then
# sets the headers and the body appropriately to do a 302 redirect.
#
# @see #absolute_url
# @return [String] The absolute url
def redirect_to(url, options={})
|
full_url = absolute_url(url, options)
response[LOCATION] = full_url
respond_with 302
full_url
end
|
fntz/ov
|
b1d954c3a3e7deb4130adb704bd4b62d329769ca
|
lib/ov/ov_method.rb
|
https://github.com/fntz/ov/blob/b1d954c3a3e7deb4130adb704bd4b62d329769ca/lib/ov/ov_method.rb#L20-L26
|
ruby
|
test
|
# +name+ (Symbol) : name for method
# +types+ (Array) : array with types, for method arguments
# +body+ (Proc) : block called with method
|
def eql0?(other) #:nodoc:
|
# +name+ (Symbol) : name for method
# +types+ (Array) : array with types, for method arguments
# +body+ (Proc) : block called with method
def eql0?(other) #:nodoc:
|
@ancestors.find{|a|
a.__overload_methods.find{|m|
m.name == other.name && m.types == other.types
}
}
end
|
pithyless/lego
|
dfc2f3f125197bfcbb30edb60af58595019f0b14
|
lib/lego/model.rb
|
https://github.com/pithyless/lego/blob/dfc2f3f125197bfcbb30edb60af58595019f0b14/lib/lego/model.rb#L132-L139
|
ruby
|
test
|
# Serialize
|
def as_json(opts={})
|
# Serialize
def as_json(opts={})
|
raise NotImplementedError, 'as_json with arguments' unless opts.empty?
{}.tap do |h|
attributes.each do |attr, val|
h[attr] = val.as_json
end
end
end
|
CiscoSystems/ropenstack
|
77dcb332711da2a35fe5abf2b6c63a0415c0bf69
|
lib/ropenstack/compute.rb
|
https://github.com/CiscoSystems/ropenstack/blob/77dcb332711da2a35fe5abf2b6c63a0415c0bf69/lib/ropenstack/compute.rb#L24-L30
|
ruby
|
test
|
# Gets a list of servers from OpenStack
#
# :call-seq:
# servers(id) => A single server with the id matching the parameter
# servers() => All servers visible to the tenant making the request
|
def servers(id)
|
# Gets a list of servers from OpenStack
#
# :call-seq:
# servers(id) => A single server with the id matching the parameter
# servers() => All servers visible to the tenant making the request
def servers(id)
|
endpoint = "/servers"
unless id.nil?
endpoint = endpoint + "/" + id
end
return get_request(address(endpoint), @token)
end
|
CiscoSystems/ropenstack
|
77dcb332711da2a35fe5abf2b6c63a0415c0bf69
|
lib/ropenstack/compute.rb
|
https://github.com/CiscoSystems/ropenstack/blob/77dcb332711da2a35fe5abf2b6c63a0415c0bf69/lib/ropenstack/compute.rb#L42-L60
|
ruby
|
test
|
# Creates a server on OpenStack.
|
def create_server(name, image, flavor, networks = nil, keypair = nil, security_group = nil, metadata = nil)
|
# Creates a server on OpenStack.
def create_server(name, image, flavor, networks = nil, keypair = nil, security_group = nil, metadata = nil)
|
data = {
"server" => {
"name" => name,
"imageRef" => image,
"flavorRef" => flavor,
}
}
unless networks.nil?
data["server"]["networks"] = networks
end
unless keypair.nil?
data["server"]["key_name"] = keypair
end
unless security_group.nil?
data["server"]["security_group"] = security_group
end
return post_request(address("/servers"), data, @token)
end
|
CiscoSystems/ropenstack
|
77dcb332711da2a35fe5abf2b6c63a0415c0bf69
|
lib/ropenstack/compute.rb
|
https://github.com/CiscoSystems/ropenstack/blob/77dcb332711da2a35fe5abf2b6c63a0415c0bf69/lib/ropenstack/compute.rb#L75-L89
|
ruby
|
test
|
# Perform an action on a server on Openstack, by passing an id,
# and an action, some actions require more data.
#
# E.g. action(id, "reboot", "hard")
|
def action(id, act, *args)
|
# Perform an action on a server on Openstack, by passing an id,
# and an action, some actions require more data.
#
# E.g. action(id, "reboot", "hard")
def action(id, act, *args)
|
data = case act
when "reboot" then {'reboot' =>{"type" => args[0]}}
when "vnc" then {'os-getVNCConsole' => { "type" => "novnc" }}
when "stop" then {'os-stop' => 'null'}
when "start" then {'os-start' => 'null'}
when "pause" then {'pause' => 'null'}
when "unpause" then {'unpause' => 'null'}
when "suspend" then {'suspend' => 'null'}
when "resume" then {'resume' => 'null'}
when "create_image" then {'createImage' => {'name' => args[0], 'metadata' => args[1]}}
else raise "Invalid Action"
end
return post_request(address("/servers/" + id + "/action"), data, @token)
end
|
CiscoSystems/ropenstack
|
77dcb332711da2a35fe5abf2b6c63a0415c0bf69
|
lib/ropenstack/compute.rb
|
https://github.com/CiscoSystems/ropenstack/blob/77dcb332711da2a35fe5abf2b6c63a0415c0bf69/lib/ropenstack/compute.rb#L102-L105
|
ruby
|
test
|
# Delete an image stored on Openstack through the nova endpoint
|
def delete_image(id)
|
# Delete an image stored on Openstack through the nova endpoint
def delete_image(id)
|
uri = URI.parse("http://" + @location.host + ":" + @location.port.to_s + "/v2/images/" + id)
return delete_request(uri, @token)
end
|
lyfeyaj/rsqoot
|
0b3157f55f3a1fa2b21ac5389fe1686a77e6a4fd
|
lib/rsqoot/request.rb
|
https://github.com/lyfeyaj/rsqoot/blob/0b3157f55f3a1fa2b21ac5389fe1686a77e6a4fd/lib/rsqoot/request.rb#L10-L21
|
ruby
|
test
|
# Get method, use by all other API qeury methods, fetch records
# from the Sqoot API V2 url, and provide wrapper functionality
|
def get(path, opts = {}, wrapper = ::Hashie::Mash)
|
# Get method, use by all other API qeury methods, fetch records
# from the Sqoot API V2 url, and provide wrapper functionality
def get(path, opts = {}, wrapper = ::Hashie::Mash)
|
uri, headers = url_generator(path, opts)
begin
json = JSON.parse uri.open(headers).read
result = wrapper.new json
@query_options = result.query
result
rescue => e
logger(error: e)
nil
end
end
|
lyfeyaj/rsqoot
|
0b3157f55f3a1fa2b21ac5389fe1686a77e6a4fd
|
lib/rsqoot/request.rb
|
https://github.com/lyfeyaj/rsqoot/blob/0b3157f55f3a1fa2b21ac5389fe1686a77e6a4fd/lib/rsqoot/request.rb#L26-L42
|
ruby
|
test
|
# Generate valid Sqoot API V2 url and provide two different way of
# authentication: :header, :parameter
|
def url_generator(path, opts = {}, require_key = false)
|
# Generate valid Sqoot API V2 url and provide two different way of
# authentication: :header, :parameter
def url_generator(path, opts = {}, require_key = false)
|
uri = URI.parse base_api_url
headers = { read_timeout: read_timeout }
uri.path = '/v2/' + path
query = options_parser opts
endpoint = path.split('/')[0]
case authentication_method
when :header
headers.merge! 'Authorization' => "api_key #{api_key(endpoint)}"
query += "&api_key=#{api_key(endpoint)}" if require_key
when :parameter
query += "&api_key=#{api_key(endpoint)}"
end
uri.query = query
@sqoot_query_uri = uri
[uri, headers]
end
|
lyfeyaj/rsqoot
|
0b3157f55f3a1fa2b21ac5389fe1686a77e6a4fd
|
lib/rsqoot/request.rb
|
https://github.com/lyfeyaj/rsqoot/blob/0b3157f55f3a1fa2b21ac5389fe1686a77e6a4fd/lib/rsqoot/request.rb#L59-L67
|
ruby
|
test
|
# Decide which api key should be used: private, public
|
def api_key(endpoint = '')
|
# Decide which api key should be used: private, public
def api_key(endpoint = '')
|
if private_endpoints.include? endpoint
private_api_key
elsif public_endpoints.include? endpoint
public_api_key
else
fail "No such endpoint #{endpoint} available."
end
end
|
lyfeyaj/rsqoot
|
0b3157f55f3a1fa2b21ac5389fe1686a77e6a4fd
|
lib/rsqoot/request.rb
|
https://github.com/lyfeyaj/rsqoot/blob/0b3157f55f3a1fa2b21ac5389fe1686a77e6a4fd/lib/rsqoot/request.rb#L73-L78
|
ruby
|
test
|
# Example: options = {per_page: 10, page: 1}
# Options should be parsed as http query: per_page=10&page=1
#
# @return [String]
|
def options_parser(options = {})
|
# Example: options = {per_page: 10, page: 1}
# Options should be parsed as http query: per_page=10&page=1
#
# @return [String]
def options_parser(options = {})
|
query = options.map do |key, value|
[key, value].map(&:to_s).join('=')
end.join('&')
URI.encode query
end
|
maxivak/optimacms
|
1e71d98b67cfe06d977102823b296b3010b10a83
|
app/models/optimacms/template.rb
|
https://github.com/maxivak/optimacms/blob/1e71d98b67cfe06d977102823b296b3010b10a83/app/models/optimacms/template.rb#L96-L111
|
ruby
|
test
|
# translations
|
def build_translations
#
|
# translations
def build_translations
#
|
if is_translated
langs = Language.list_with_default
else
langs = ['']
end
#
langs_missing = langs - self.translations.all.map{|r| r.lang}
langs_missing.each do |lang|
self.translations.new(:lang=>lang)
end
end
|
maxivak/optimacms
|
1e71d98b67cfe06d977102823b296b3010b10a83
|
app/models/optimacms/template.rb
|
https://github.com/maxivak/optimacms/blob/1e71d98b67cfe06d977102823b296b3010b10a83/app/models/optimacms/template.rb#L195-L200
|
ruby
|
test
|
# content
|
def content(lang='')
|
# content
def content(lang='')
|
filename = fullpath(lang)
return nil if filename.nil?
return '' if !File.exists? filename
File.read(filename)
end
|
maxivak/optimacms
|
1e71d98b67cfe06d977102823b296b3010b10a83
|
app/models/optimacms/template.rb
|
https://github.com/maxivak/optimacms/blob/1e71d98b67cfe06d977102823b296b3010b10a83/app/models/optimacms/template.rb#L240-L249
|
ruby
|
test
|
# operations with path
|
def set_basepath
|
# operations with path
def set_basepath
|
if self.parent.nil?
self.basepath = self.basename
self.basedirpath ||= ''
else
self.basepath = self.parent.basepath+'/'+self.basename
self.basedirpath ||= self.parent.basepath+'/'
end
end
|
maxivak/optimacms
|
1e71d98b67cfe06d977102823b296b3010b10a83
|
app/models/optimacms/template.rb
|
https://github.com/maxivak/optimacms/blob/1e71d98b67cfe06d977102823b296b3010b10a83/app/models/optimacms/template.rb#L288-L299
|
ruby
|
test
|
# callbacks
|
def _before_validation
|
# callbacks
def _before_validation
|
fix_basedirpath
# parent, basedirpath
if self.parent_id.nil? && !self.basedirpath.blank?
set_parent_from_basedirpath
elsif self.basedirpath.nil? && !self.parent_id.nil?
set_basedirpath_from_parent
end
set_basepath
end
|
lyfeyaj/rsqoot
|
0b3157f55f3a1fa2b21ac5389fe1686a77e6a4fd
|
lib/rsqoot/commission.rb
|
https://github.com/lyfeyaj/rsqoot/blob/0b3157f55f3a1fa2b21ac5389fe1686a77e6a4fd/lib/rsqoot/commission.rb#L10-L18
|
ruby
|
test
|
# Retrieve information of commissions based on the following parameters
#
# @param [String] :to Start date
# @param [String] :from End date
#
# @return [RSqoot::SqootCommission]
|
def commissions(options = {})
|
# Retrieve information of commissions based on the following parameters
#
# @param [String] :to Start date
# @param [String] :from End date
#
# @return [RSqoot::SqootCommission]
def commissions(options = {})
|
options = update_by_expire_time options
if commissions_not_latest?(options)
@rsqoot_commissions = get('commissions', options, SqootCommission)
@rsqoot_commissions = @rsqoot_commissions.commissions if @rsqoot_commissions
end
logger(uri: sqoot_query_uri, records: @rsqoot_commissions, type: 'commissions', opts: options)
@rsqoot_commissions
end
|
maxivak/optimacms
|
1e71d98b67cfe06d977102823b296b3010b10a83
|
app/controllers/optimacms/admin/backup_metadata_controller.rb
|
https://github.com/maxivak/optimacms/blob/1e71d98b67cfe06d977102823b296b3010b10a83/app/controllers/optimacms/admin/backup_metadata_controller.rb#L72-L81
|
ruby
|
test
|
# import templates
|
def reviewimport_templates
# input
|
# import templates
def reviewimport_templates
# input
|
@dirname = params[:dirname]
# work
@backup_basedir = Optimacms::BackupMetadata::Backup.make_backup_dir_path @dirname
@backup_templates_dirpath = File.join(@backup_basedir, "templates")
@analysis = Optimacms::BackupMetadata::TemplateImport.analyze_data_dir(@backup_templates_dirpath)
end
|
maxivak/optimacms
|
1e71d98b67cfe06d977102823b296b3010b10a83
|
app/controllers/optimacms/admin/backup_metadata_controller.rb
|
https://github.com/maxivak/optimacms/blob/1e71d98b67cfe06d977102823b296b3010b10a83/app/controllers/optimacms/admin/backup_metadata_controller.rb#L104-L114
|
ruby
|
test
|
# import pages
|
def reviewimport_pages
# input
|
# import pages
def reviewimport_pages
# input
|
@dirname = params[:dirname]
# work
@backup_basedir = Optimacms::BackupMetadata::Backup.make_backup_dir_path @dirname
@backup_templates_dirpath = File.join(@backup_basedir, "pages")
@analysis = Optimacms::BackupMetadata::PageImport.analyze_data_dir(@backup_templates_dirpath)
end
|
Saidbek/football_ruby
|
7b3f0a3b6836431766ccbd6e5e7ceeb70f4c23aa
|
lib/football_ruby/client.rb
|
https://github.com/Saidbek/football_ruby/blob/7b3f0a3b6836431766ccbd6e5e7ceeb70f4c23aa/lib/football_ruby/client.rb#L7-L11
|
ruby
|
test
|
# List all available leagues.
|
def leagues(opts={})
|
# List all available leagues.
def leagues(opts={})
|
season = opts.fetch(:season) { Time.now.year }
json_response get("competitions/?season=#{season}")
end
|
Saidbek/football_ruby
|
7b3f0a3b6836431766ccbd6e5e7ceeb70f4c23aa
|
lib/football_ruby/client.rb
|
https://github.com/Saidbek/football_ruby/blob/7b3f0a3b6836431766ccbd6e5e7ceeb70f4c23aa/lib/football_ruby/client.rb#L25-L34
|
ruby
|
test
|
# Show League Table / current standing.
# Filters:
#
# match_day=/\d+/
|
def league_table(id, opts={})
|
# Show League Table / current standing.
# Filters:
#
# match_day=/\d+/
def league_table(id, opts={})
|
raise IdMissingError, 'missing id' if id.nil?
match_day = opts[:match_day]
uri = "competitions/#{id}/leagueTable/"
url = match_day.nil? ? uri : "#{uri}?matchday=#{match_day}"
json_response get(url)
end
|
Saidbek/football_ruby
|
7b3f0a3b6836431766ccbd6e5e7ceeb70f4c23aa
|
lib/football_ruby/client.rb
|
https://github.com/Saidbek/football_ruby/blob/7b3f0a3b6836431766ccbd6e5e7ceeb70f4c23aa/lib/football_ruby/client.rb#L42-L53
|
ruby
|
test
|
# List all fixtures for a certain league.
# Filters:
#
# time_frame=/p|n[1-9]{1,2}/
# match_day=/\d+/
|
def league_fixtures(id, opts={})
|
# List all fixtures for a certain league.
# Filters:
#
# time_frame=/p|n[1-9]{1,2}/
# match_day=/\d+/
def league_fixtures(id, opts={})
|
raise IdMissingError, 'missing id' if id.nil?
time_frame = opts[:time_frame]
match_day = opts[:match_day]
uri = "competitions/#{id}/fixtures/"
url = time_frame.nil? ? uri : "#{uri}?timeFrame=#{time_frame}"
url = match_day.nil? ? url : "#{url}?matchday=#{match_day}"
json_response get(url)
end
|
Saidbek/football_ruby
|
7b3f0a3b6836431766ccbd6e5e7ceeb70f4c23aa
|
lib/football_ruby/client.rb
|
https://github.com/Saidbek/football_ruby/blob/7b3f0a3b6836431766ccbd6e5e7ceeb70f4c23aa/lib/football_ruby/client.rb#L61-L70
|
ruby
|
test
|
# List fixtures across a set of leagues.
# Filters:
#
# time_frame=/p|n[1-9]{1,2}/
# league=leagueCode
|
def fixtures(opts={})
|
# List fixtures across a set of leagues.
# Filters:
#
# time_frame=/p|n[1-9]{1,2}/
# league=leagueCode
def fixtures(opts={})
|
time_frame = opts[:time_frame]
league = opts[:league]
uri = "fixtures/"
url = time_frame.nil? ? uri : "#{uri}?timeFrame=#{time_frame}"
url = league.nil? ? url : "#{url}?league=#{league}"
json_response get(url)
end
|
Saidbek/football_ruby
|
7b3f0a3b6836431766ccbd6e5e7ceeb70f4c23aa
|
lib/football_ruby/client.rb
|
https://github.com/Saidbek/football_ruby/blob/7b3f0a3b6836431766ccbd6e5e7ceeb70f4c23aa/lib/football_ruby/client.rb#L77-L86
|
ruby
|
test
|
# Show one fixture.
# Filters:
#
# head2head=/\d+/
|
def fixture(id, opts={})
|
# Show one fixture.
# Filters:
#
# head2head=/\d+/
def fixture(id, opts={})
|
raise IdMissingError, 'missing id' if id.nil?
head2head = opts[:head2head]
uri = "fixtures/#{id}/"
url = head2head.nil? ? uri : "#{uri}?head2head=#{head2head}"
json_response get(url)
end
|
Saidbek/football_ruby
|
7b3f0a3b6836431766ccbd6e5e7ceeb70f4c23aa
|
lib/football_ruby/client.rb
|
https://github.com/Saidbek/football_ruby/blob/7b3f0a3b6836431766ccbd6e5e7ceeb70f4c23aa/lib/football_ruby/client.rb#L95-L108
|
ruby
|
test
|
# Show all fixtures for a certain team.
# Filters:
#
# season=/\d\d\d\d/
# time_frame=/p|n[1-9]{1,2}/
# venue=/home|away/
|
def team_fixtures(id, opts={})
|
# Show all fixtures for a certain team.
# Filters:
#
# season=/\d\d\d\d/
# time_frame=/p|n[1-9]{1,2}/
# venue=/home|away/
def team_fixtures(id, opts={})
|
raise IdMissingError, 'missing id' if id.nil?
season = opts[:season]
time_frame = opts[:time_frame]
venue = opts[:venue]
uri = "teams/#{id}/fixtures/"
url = season.nil? ? uri : "#{uri}?season=#{season}"
url = time_frame.nil? ? url : "#{url}?timeFrame=#{time_frame}"
url = venue.nil? ? url : "#{url}?venue=#{venue}"
json_response get(url)
end
|
fntz/ov
|
b1d954c3a3e7deb4130adb704bd4b62d329769ca
|
lib/ov/ext/matching.rb
|
https://github.com/fntz/ov/blob/b1d954c3a3e7deb4130adb704bd4b62d329769ca/lib/ov/ext/matching.rb#L17-L34
|
ruby
|
test
|
# Add `match` method, which work like `case` statement but for types
#
# == Usage
#
# include Ov::Ext
#
# match("String", "dsa") do
# try(String, Array) {|str, arr| "#{str} #{arr}" }
# try(String) {|str| "#{str}" }
# otherwise { "none" }
# end
|
def match(*args, &block)
|
# Add `match` method, which work like `case` statement but for types
#
# == Usage
#
# include Ov::Ext
#
# match("String", "dsa") do
# try(String, Array) {|str, arr| "#{str} #{arr}" }
# try(String) {|str| "#{str}" }
# otherwise { "none" }
# end
def match(*args, &block)
|
z = Module.new do
include Ov
extend self
def try(*args, &block)
let :anon_method, *args, &block
end
def otherwise(&block)
let :otherwise, &block
end
instance_eval &block
end
begin
z.anon_method(*args)
rescue Ov::NotImplementError => e
z.otherwise
end
end
|
woto/ckpages
|
c258fe291e6215d72904dc71b7cf60f17e7dbdd4
|
app/controllers/ckpages/pages_controller.rb
|
https://github.com/woto/ckpages/blob/c258fe291e6215d72904dc71b7cf60f17e7dbdd4/app/controllers/ckpages/pages_controller.rb#L17-L23
|
ruby
|
test
|
# GET /pages/new
|
def new
|
# GET /pages/new
def new
|
@page = Page.new(path: '/')
if params[:path].present?
@page.path = CGI::unescape(params[:path])
end
end
|
apeiros/tabledata
|
e277b6a1fdb567a6d73f42349bb9946ffad67134
|
lib/tabledata/row.rb
|
https://github.com/apeiros/tabledata/blob/e277b6a1fdb567a6d73f42349bb9946ffad67134/lib/tabledata/row.rb#L58-L69
|
ruby
|
test
|
# Tries to return the value of the column identified by index, corresponding accessor or header.
# It throws an IndexError exception if the referenced index lies outside of the array bounds.
# This error can be prevented by supplying a second argument, which will act as a default value.
#
# Alternatively, if a block is given it will only be executed when an invalid
# index is referenced. Negative values of index count from the end of the
# array.
|
def fetch(column, *default_value, &default_block)
|
# Tries to return the value of the column identified by index, corresponding accessor or header.
# It throws an IndexError exception if the referenced index lies outside of the array bounds.
# This error can be prevented by supplying a second argument, which will act as a default value.
#
# Alternatively, if a block is given it will only be executed when an invalid
# index is referenced. Negative values of index count from the end of the
# array.
def fetch(column, *default_value, &default_block)
|
raise ArgumentError, "Must only provide at max one default value or one default block" if default_value.size > (block_given? ? 0 : 1)
index = case column
when Symbol then @table.index_for_accessor(column)
when String then @table.index_for_header(column)
when Integer then column
else raise InvalidColumnSpecifier, "Invalid index type, expected Symbol, String or Integer, but got #{column.class}"
end
@data.fetch(index, *default_value, &default_block)
end
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.