id
int32 0
24.9k
| repo
stringlengths 5
58
| path
stringlengths 9
168
| func_name
stringlengths 9
130
| original_string
stringlengths 66
10.5k
| language
stringclasses 1
value | code
stringlengths 66
10.5k
| code_tokens
list | docstring
stringlengths 8
16k
| docstring_tokens
list | sha
stringlengths 40
40
| url
stringlengths 94
266
|
|---|---|---|---|---|---|---|---|---|---|---|---|
12,400
|
meew0/discordrb
|
lib/discordrb/commands/command_bot.rb
|
Discordrb::Commands.CommandBot.trigger?
|
def trigger?(message)
if @prefix.is_a? String
standard_prefix_trigger(message.content, @prefix)
elsif @prefix.is_a? Array
@prefix.map { |e| standard_prefix_trigger(message.content, e) }.reduce { |m, e| m || e }
elsif @prefix.respond_to? :call
@prefix.call(message)
end
end
|
ruby
|
def trigger?(message)
if @prefix.is_a? String
standard_prefix_trigger(message.content, @prefix)
elsif @prefix.is_a? Array
@prefix.map { |e| standard_prefix_trigger(message.content, e) }.reduce { |m, e| m || e }
elsif @prefix.respond_to? :call
@prefix.call(message)
end
end
|
[
"def",
"trigger?",
"(",
"message",
")",
"if",
"@prefix",
".",
"is_a?",
"String",
"standard_prefix_trigger",
"(",
"message",
".",
"content",
",",
"@prefix",
")",
"elsif",
"@prefix",
".",
"is_a?",
"Array",
"@prefix",
".",
"map",
"{",
"|",
"e",
"|",
"standard_prefix_trigger",
"(",
"message",
".",
"content",
",",
"e",
")",
"}",
".",
"reduce",
"{",
"|",
"m",
",",
"e",
"|",
"m",
"||",
"e",
"}",
"elsif",
"@prefix",
".",
"respond_to?",
":call",
"@prefix",
".",
"call",
"(",
"message",
")",
"end",
"end"
] |
Check whether a message should trigger command execution, and if it does, return the raw chain
|
[
"Check",
"whether",
"a",
"message",
"should",
"trigger",
"command",
"execution",
"and",
"if",
"it",
"does",
"return",
"the",
"raw",
"chain"
] |
764298a1ff0be69a1853b510d736f21c2b91a2fe
|
https://github.com/meew0/discordrb/blob/764298a1ff0be69a1853b510d736f21c2b91a2fe/lib/discordrb/commands/command_bot.rb#L426-L434
|
12,401
|
meew0/discordrb
|
lib/discordrb/voice/voice_bot.rb
|
Discordrb::Voice.VoiceBot.stop_playing
|
def stop_playing(wait_for_confirmation = false)
@was_playing_before = @playing
@speaking = false
@playing = false
sleep IDEAL_LENGTH / 1000.0 if @was_playing_before
return unless wait_for_confirmation
@has_stopped_playing = false
sleep IDEAL_LENGTH / 1000.0 until @has_stopped_playing
@has_stopped_playing = false
end
|
ruby
|
def stop_playing(wait_for_confirmation = false)
@was_playing_before = @playing
@speaking = false
@playing = false
sleep IDEAL_LENGTH / 1000.0 if @was_playing_before
return unless wait_for_confirmation
@has_stopped_playing = false
sleep IDEAL_LENGTH / 1000.0 until @has_stopped_playing
@has_stopped_playing = false
end
|
[
"def",
"stop_playing",
"(",
"wait_for_confirmation",
"=",
"false",
")",
"@was_playing_before",
"=",
"@playing",
"@speaking",
"=",
"false",
"@playing",
"=",
"false",
"sleep",
"IDEAL_LENGTH",
"/",
"1000.0",
"if",
"@was_playing_before",
"return",
"unless",
"wait_for_confirmation",
"@has_stopped_playing",
"=",
"false",
"sleep",
"IDEAL_LENGTH",
"/",
"1000.0",
"until",
"@has_stopped_playing",
"@has_stopped_playing",
"=",
"false",
"end"
] |
Stops the current playback entirely.
@param wait_for_confirmation [true, false] Whether the method should wait for confirmation from the playback
method that the playback has actually stopped.
|
[
"Stops",
"the",
"current",
"playback",
"entirely",
"."
] |
764298a1ff0be69a1853b510d736f21c2b91a2fe
|
https://github.com/meew0/discordrb/blob/764298a1ff0be69a1853b510d736f21c2b91a2fe/lib/discordrb/voice/voice_bot.rb#L157-L168
|
12,402
|
meew0/discordrb
|
lib/discordrb/voice/voice_bot.rb
|
Discordrb::Voice.VoiceBot.play_dca
|
def play_dca(file)
stop_playing(true) if @playing
@bot.debug "Reading DCA file #{file}"
input_stream = File.open(file)
magic = input_stream.read(4)
raise ArgumentError, 'Not a DCA1 file! The file might have been corrupted, please recreate it.' unless magic == 'DCA1'
# Read the metadata header, then read the metadata and discard it as we don't care about it
metadata_header = input_stream.read(4).unpack1('l<')
input_stream.read(metadata_header)
# Play the data, without re-encoding it to opus
play_internal do
begin
# Read header
header_str = input_stream.read(2)
unless header_str
@bot.debug 'Finished DCA parsing (header is nil)'
next :stop
end
header = header_str.unpack1('s<')
raise 'Negative header in DCA file! Your file is likely corrupted.' if header.negative?
rescue EOFError
@bot.debug 'Finished DCA parsing (EOFError)'
next :stop
end
# Read bytes
input_stream.read(header)
end
end
|
ruby
|
def play_dca(file)
stop_playing(true) if @playing
@bot.debug "Reading DCA file #{file}"
input_stream = File.open(file)
magic = input_stream.read(4)
raise ArgumentError, 'Not a DCA1 file! The file might have been corrupted, please recreate it.' unless magic == 'DCA1'
# Read the metadata header, then read the metadata and discard it as we don't care about it
metadata_header = input_stream.read(4).unpack1('l<')
input_stream.read(metadata_header)
# Play the data, without re-encoding it to opus
play_internal do
begin
# Read header
header_str = input_stream.read(2)
unless header_str
@bot.debug 'Finished DCA parsing (header is nil)'
next :stop
end
header = header_str.unpack1('s<')
raise 'Negative header in DCA file! Your file is likely corrupted.' if header.negative?
rescue EOFError
@bot.debug 'Finished DCA parsing (EOFError)'
next :stop
end
# Read bytes
input_stream.read(header)
end
end
|
[
"def",
"play_dca",
"(",
"file",
")",
"stop_playing",
"(",
"true",
")",
"if",
"@playing",
"@bot",
".",
"debug",
"\"Reading DCA file #{file}\"",
"input_stream",
"=",
"File",
".",
"open",
"(",
"file",
")",
"magic",
"=",
"input_stream",
".",
"read",
"(",
"4",
")",
"raise",
"ArgumentError",
",",
"'Not a DCA1 file! The file might have been corrupted, please recreate it.'",
"unless",
"magic",
"==",
"'DCA1'",
"# Read the metadata header, then read the metadata and discard it as we don't care about it",
"metadata_header",
"=",
"input_stream",
".",
"read",
"(",
"4",
")",
".",
"unpack1",
"(",
"'l<'",
")",
"input_stream",
".",
"read",
"(",
"metadata_header",
")",
"# Play the data, without re-encoding it to opus",
"play_internal",
"do",
"begin",
"# Read header",
"header_str",
"=",
"input_stream",
".",
"read",
"(",
"2",
")",
"unless",
"header_str",
"@bot",
".",
"debug",
"'Finished DCA parsing (header is nil)'",
"next",
":stop",
"end",
"header",
"=",
"header_str",
".",
"unpack1",
"(",
"'s<'",
")",
"raise",
"'Negative header in DCA file! Your file is likely corrupted.'",
"if",
"header",
".",
"negative?",
"rescue",
"EOFError",
"@bot",
".",
"debug",
"'Finished DCA parsing (EOFError)'",
"next",
":stop",
"end",
"# Read bytes",
"input_stream",
".",
"read",
"(",
"header",
")",
"end",
"end"
] |
Plays a stream of audio data in the DCA format. This format has the advantage that no recoding has to be
done - the file contains the data exactly as Discord needs it.
@note DCA playback will not be affected by the volume modifier ({#volume}) because the modifier operates on raw
PCM, not opus data. Modifying the volume of DCA data would involve decoding it, multiplying the samples and
re-encoding it, which defeats its entire purpose (no recoding).
@see https://github.com/bwmarrin/dca
@see #play
|
[
"Plays",
"a",
"stream",
"of",
"audio",
"data",
"in",
"the",
"DCA",
"format",
".",
"This",
"format",
"has",
"the",
"advantage",
"that",
"no",
"recoding",
"has",
"to",
"be",
"done",
"-",
"the",
"file",
"contains",
"the",
"data",
"exactly",
"as",
"Discord",
"needs",
"it",
"."
] |
764298a1ff0be69a1853b510d736f21c2b91a2fe
|
https://github.com/meew0/discordrb/blob/764298a1ff0be69a1853b510d736f21c2b91a2fe/lib/discordrb/voice/voice_bot.rb#L255-L290
|
12,403
|
meew0/discordrb
|
lib/discordrb/voice/voice_bot.rb
|
Discordrb::Voice.VoiceBot.play_internal
|
def play_internal
count = 0
@playing = true
# Default play length (ms), will be adjusted later
@length = IDEAL_LENGTH
self.speaking = true
loop do
# Starting from the tenth packet, perform length adjustment every 100 packets (2 seconds)
should_adjust_this_packet = (count % @adjust_interval == @adjust_offset)
# If we should adjust, start now
@length_adjust = Time.now.nsec if should_adjust_this_packet
break unless @playing
# If we should skip, get some data, discard it and go to the next iteration
if @skips.positive?
@skips -= 1
yield
next
end
# Track packet count, sequence and time (Discord requires this)
count += 1
increment_packet_headers
# Get packet data
buf = yield
# Stop doing anything if the stop signal was sent
break if buf == :stop
# Proceed to the next packet if we got nil
next unless buf
# Track intermediate adjustment so we can measure how much encoding contributes to the total time
@intermediate_adjust = Time.now.nsec if should_adjust_this_packet
# Send the packet
@udp.send_audio(buf, @sequence, @time)
# Set the stream time (for tracking how long we've been playing)
@stream_time = count * @length / 1000
if @length_override # Don't do adjustment because the user has manually specified an override value
@length = @length_override
elsif @length_adjust # Perform length adjustment
# Define the time once so it doesn't get inaccurate
now = Time.now.nsec
# Difference between length_adjust and now in ms
ms_diff = (now - @length_adjust) / 1_000_000.0
if ms_diff >= 0
@length = if @adjust_average
(IDEAL_LENGTH - ms_diff + @length) / 2.0
else
IDEAL_LENGTH - ms_diff
end
# Track the time it took to encode
encode_ms = (@intermediate_adjust - @length_adjust) / 1_000_000.0
@bot.debug("Length adjustment: new length #{@length} (measured #{ms_diff}, #{(100 * encode_ms) / ms_diff}% encoding)") if @adjust_debug
end
@length_adjust = nil
end
# If paused, wait
sleep 0.1 while @paused
if @length.positive?
# Wait `length` ms, then send the next packet
sleep @length / 1000.0
else
Discordrb::LOGGER.warn('Audio encoding and sending together took longer than Discord expects one packet to be (20 ms)! This may be indicative of network problems.')
end
end
@bot.debug('Sending five silent frames to clear out buffers')
5.times do
increment_packet_headers
@udp.send_audio(Encoder::OPUS_SILENCE, @sequence, @time)
# Length adjustments don't matter here, we can just wait 20 ms since nobody is going to hear it anyway
sleep IDEAL_LENGTH / 1000.0
end
@bot.debug('Performing final cleanup after stream ended')
# Final cleanup
stop_playing
# Notify any stop_playing methods running right now that we have actually stopped
@has_stopped_playing = true
end
|
ruby
|
def play_internal
count = 0
@playing = true
# Default play length (ms), will be adjusted later
@length = IDEAL_LENGTH
self.speaking = true
loop do
# Starting from the tenth packet, perform length adjustment every 100 packets (2 seconds)
should_adjust_this_packet = (count % @adjust_interval == @adjust_offset)
# If we should adjust, start now
@length_adjust = Time.now.nsec if should_adjust_this_packet
break unless @playing
# If we should skip, get some data, discard it and go to the next iteration
if @skips.positive?
@skips -= 1
yield
next
end
# Track packet count, sequence and time (Discord requires this)
count += 1
increment_packet_headers
# Get packet data
buf = yield
# Stop doing anything if the stop signal was sent
break if buf == :stop
# Proceed to the next packet if we got nil
next unless buf
# Track intermediate adjustment so we can measure how much encoding contributes to the total time
@intermediate_adjust = Time.now.nsec if should_adjust_this_packet
# Send the packet
@udp.send_audio(buf, @sequence, @time)
# Set the stream time (for tracking how long we've been playing)
@stream_time = count * @length / 1000
if @length_override # Don't do adjustment because the user has manually specified an override value
@length = @length_override
elsif @length_adjust # Perform length adjustment
# Define the time once so it doesn't get inaccurate
now = Time.now.nsec
# Difference between length_adjust and now in ms
ms_diff = (now - @length_adjust) / 1_000_000.0
if ms_diff >= 0
@length = if @adjust_average
(IDEAL_LENGTH - ms_diff + @length) / 2.0
else
IDEAL_LENGTH - ms_diff
end
# Track the time it took to encode
encode_ms = (@intermediate_adjust - @length_adjust) / 1_000_000.0
@bot.debug("Length adjustment: new length #{@length} (measured #{ms_diff}, #{(100 * encode_ms) / ms_diff}% encoding)") if @adjust_debug
end
@length_adjust = nil
end
# If paused, wait
sleep 0.1 while @paused
if @length.positive?
# Wait `length` ms, then send the next packet
sleep @length / 1000.0
else
Discordrb::LOGGER.warn('Audio encoding and sending together took longer than Discord expects one packet to be (20 ms)! This may be indicative of network problems.')
end
end
@bot.debug('Sending five silent frames to clear out buffers')
5.times do
increment_packet_headers
@udp.send_audio(Encoder::OPUS_SILENCE, @sequence, @time)
# Length adjustments don't matter here, we can just wait 20 ms since nobody is going to hear it anyway
sleep IDEAL_LENGTH / 1000.0
end
@bot.debug('Performing final cleanup after stream ended')
# Final cleanup
stop_playing
# Notify any stop_playing methods running right now that we have actually stopped
@has_stopped_playing = true
end
|
[
"def",
"play_internal",
"count",
"=",
"0",
"@playing",
"=",
"true",
"# Default play length (ms), will be adjusted later",
"@length",
"=",
"IDEAL_LENGTH",
"self",
".",
"speaking",
"=",
"true",
"loop",
"do",
"# Starting from the tenth packet, perform length adjustment every 100 packets (2 seconds)",
"should_adjust_this_packet",
"=",
"(",
"count",
"%",
"@adjust_interval",
"==",
"@adjust_offset",
")",
"# If we should adjust, start now",
"@length_adjust",
"=",
"Time",
".",
"now",
".",
"nsec",
"if",
"should_adjust_this_packet",
"break",
"unless",
"@playing",
"# If we should skip, get some data, discard it and go to the next iteration",
"if",
"@skips",
".",
"positive?",
"@skips",
"-=",
"1",
"yield",
"next",
"end",
"# Track packet count, sequence and time (Discord requires this)",
"count",
"+=",
"1",
"increment_packet_headers",
"# Get packet data",
"buf",
"=",
"yield",
"# Stop doing anything if the stop signal was sent",
"break",
"if",
"buf",
"==",
":stop",
"# Proceed to the next packet if we got nil",
"next",
"unless",
"buf",
"# Track intermediate adjustment so we can measure how much encoding contributes to the total time",
"@intermediate_adjust",
"=",
"Time",
".",
"now",
".",
"nsec",
"if",
"should_adjust_this_packet",
"# Send the packet",
"@udp",
".",
"send_audio",
"(",
"buf",
",",
"@sequence",
",",
"@time",
")",
"# Set the stream time (for tracking how long we've been playing)",
"@stream_time",
"=",
"count",
"*",
"@length",
"/",
"1000",
"if",
"@length_override",
"# Don't do adjustment because the user has manually specified an override value",
"@length",
"=",
"@length_override",
"elsif",
"@length_adjust",
"# Perform length adjustment",
"# Define the time once so it doesn't get inaccurate",
"now",
"=",
"Time",
".",
"now",
".",
"nsec",
"# Difference between length_adjust and now in ms",
"ms_diff",
"=",
"(",
"now",
"-",
"@length_adjust",
")",
"/",
"1_000_000.0",
"if",
"ms_diff",
">=",
"0",
"@length",
"=",
"if",
"@adjust_average",
"(",
"IDEAL_LENGTH",
"-",
"ms_diff",
"+",
"@length",
")",
"/",
"2.0",
"else",
"IDEAL_LENGTH",
"-",
"ms_diff",
"end",
"# Track the time it took to encode",
"encode_ms",
"=",
"(",
"@intermediate_adjust",
"-",
"@length_adjust",
")",
"/",
"1_000_000.0",
"@bot",
".",
"debug",
"(",
"\"Length adjustment: new length #{@length} (measured #{ms_diff}, #{(100 * encode_ms) / ms_diff}% encoding)\"",
")",
"if",
"@adjust_debug",
"end",
"@length_adjust",
"=",
"nil",
"end",
"# If paused, wait",
"sleep",
"0.1",
"while",
"@paused",
"if",
"@length",
".",
"positive?",
"# Wait `length` ms, then send the next packet",
"sleep",
"@length",
"/",
"1000.0",
"else",
"Discordrb",
"::",
"LOGGER",
".",
"warn",
"(",
"'Audio encoding and sending together took longer than Discord expects one packet to be (20 ms)! This may be indicative of network problems.'",
")",
"end",
"end",
"@bot",
".",
"debug",
"(",
"'Sending five silent frames to clear out buffers'",
")",
"5",
".",
"times",
"do",
"increment_packet_headers",
"@udp",
".",
"send_audio",
"(",
"Encoder",
"::",
"OPUS_SILENCE",
",",
"@sequence",
",",
"@time",
")",
"# Length adjustments don't matter here, we can just wait 20 ms since nobody is going to hear it anyway",
"sleep",
"IDEAL_LENGTH",
"/",
"1000.0",
"end",
"@bot",
".",
"debug",
"(",
"'Performing final cleanup after stream ended'",
")",
"# Final cleanup",
"stop_playing",
"# Notify any stop_playing methods running right now that we have actually stopped",
"@has_stopped_playing",
"=",
"true",
"end"
] |
Plays the data from the @io stream as Discord requires it
|
[
"Plays",
"the",
"data",
"from",
"the"
] |
764298a1ff0be69a1853b510d736f21c2b91a2fe
|
https://github.com/meew0/discordrb/blob/764298a1ff0be69a1853b510d736f21c2b91a2fe/lib/discordrb/voice/voice_bot.rb#L297-L393
|
12,404
|
meew0/discordrb
|
lib/discordrb/webhooks/client.rb
|
Discordrb::Webhooks.Client.execute
|
def execute(builder = nil, wait = false)
raise TypeError, 'builder needs to be nil or like a Discordrb::Webhooks::Builder!' unless
builder.respond_to?(:file) && builder.respond_to?(:to_multipart_hash) || builder.respond_to?(:to_json_hash) || builder.nil?
builder ||= Builder.new
yield builder if block_given?
if builder.file
post_multipart(builder, wait)
else
post_json(builder, wait)
end
end
|
ruby
|
def execute(builder = nil, wait = false)
raise TypeError, 'builder needs to be nil or like a Discordrb::Webhooks::Builder!' unless
builder.respond_to?(:file) && builder.respond_to?(:to_multipart_hash) || builder.respond_to?(:to_json_hash) || builder.nil?
builder ||= Builder.new
yield builder if block_given?
if builder.file
post_multipart(builder, wait)
else
post_json(builder, wait)
end
end
|
[
"def",
"execute",
"(",
"builder",
"=",
"nil",
",",
"wait",
"=",
"false",
")",
"raise",
"TypeError",
",",
"'builder needs to be nil or like a Discordrb::Webhooks::Builder!'",
"unless",
"builder",
".",
"respond_to?",
"(",
":file",
")",
"&&",
"builder",
".",
"respond_to?",
"(",
":to_multipart_hash",
")",
"||",
"builder",
".",
"respond_to?",
"(",
":to_json_hash",
")",
"||",
"builder",
".",
"nil?",
"builder",
"||=",
"Builder",
".",
"new",
"yield",
"builder",
"if",
"block_given?",
"if",
"builder",
".",
"file",
"post_multipart",
"(",
"builder",
",",
"wait",
")",
"else",
"post_json",
"(",
"builder",
",",
"wait",
")",
"end",
"end"
] |
Create a new webhook
@param url [String] The URL to post messages to.
@param id [Integer] The webhook's ID. Will only be used if `url` is not
set.
@param token [String] The webhook's authorisation token. Will only be used
if `url` is not set.
Executes the webhook this client points to with the given data.
@param builder [Builder, nil] The builder to start out with, or nil if one should be created anew.
@param wait [true, false] Whether Discord should wait for the message to be successfully received by clients, or
whether it should return immediately after sending the message.
@yield [builder] Gives the builder to the block to add additional steps, or to do the entire building process.
@yieldparam builder [Builder] The builder given as a parameter which is used as the initial step to start from.
@example Execute the webhook with an already existing builder
builder = Discordrb::Webhooks::Builder.new # ...
client.execute(builder)
@example Execute the webhook by building a new message
client.execute do |builder|
builder.content = 'Testing'
builder.username = 'discordrb'
builder.add_embed do |embed|
embed.timestamp = Time.now
embed.title = 'Testing'
embed.image = Discordrb::Webhooks::EmbedImage.new(url: 'https://i.imgur.com/PcMltU7.jpg')
end
end
@return [RestClient::Response] the response returned by Discord.
|
[
"Create",
"a",
"new",
"webhook"
] |
764298a1ff0be69a1853b510d736f21c2b91a2fe
|
https://github.com/meew0/discordrb/blob/764298a1ff0be69a1853b510d736f21c2b91a2fe/lib/discordrb/webhooks/client.rb#L41-L54
|
12,405
|
meew0/discordrb
|
lib/discordrb/await.rb
|
Discordrb.Await.match
|
def match(event)
dummy_handler = EventContainer.handler_class(@type).new(@attributes, @bot)
return [nil, nil] unless event.instance_of?(@type) && dummy_handler.matches?(event)
should_delete = nil
should_delete = true if (@block && @block.call(event) != false) || !@block
[@key, should_delete]
end
|
ruby
|
def match(event)
dummy_handler = EventContainer.handler_class(@type).new(@attributes, @bot)
return [nil, nil] unless event.instance_of?(@type) && dummy_handler.matches?(event)
should_delete = nil
should_delete = true if (@block && @block.call(event) != false) || !@block
[@key, should_delete]
end
|
[
"def",
"match",
"(",
"event",
")",
"dummy_handler",
"=",
"EventContainer",
".",
"handler_class",
"(",
"@type",
")",
".",
"new",
"(",
"@attributes",
",",
"@bot",
")",
"return",
"[",
"nil",
",",
"nil",
"]",
"unless",
"event",
".",
"instance_of?",
"(",
"@type",
")",
"&&",
"dummy_handler",
".",
"matches?",
"(",
"event",
")",
"should_delete",
"=",
"nil",
"should_delete",
"=",
"true",
"if",
"(",
"@block",
"&&",
"@block",
".",
"call",
"(",
"event",
")",
"!=",
"false",
")",
"||",
"!",
"@block",
"[",
"@key",
",",
"should_delete",
"]",
"end"
] |
Makes a new await. For internal use only.
@!visibility private
Checks whether the await can be triggered by the given event, and if it can, execute the block
and return its result along with this await's key.
@param event [Event] An event to check for.
@return [Array] This await's key and whether or not it should be deleted. If there was no match, both are nil.
|
[
"Makes",
"a",
"new",
"await",
".",
"For",
"internal",
"use",
"only",
"."
] |
764298a1ff0be69a1853b510d736f21c2b91a2fe
|
https://github.com/meew0/discordrb/blob/764298a1ff0be69a1853b510d736f21c2b91a2fe/lib/discordrb/await.rb#L42-L50
|
12,406
|
meew0/discordrb
|
lib/discordrb/events/message.rb
|
Discordrb::Events.Respondable.drain_into
|
def drain_into(result)
return if result.is_a?(Discordrb::Message)
result = (@saved_message.nil? ? '' : @saved_message.to_s) + (result.nil? ? '' : result.to_s)
drain
result
end
|
ruby
|
def drain_into(result)
return if result.is_a?(Discordrb::Message)
result = (@saved_message.nil? ? '' : @saved_message.to_s) + (result.nil? ? '' : result.to_s)
drain
result
end
|
[
"def",
"drain_into",
"(",
"result",
")",
"return",
"if",
"result",
".",
"is_a?",
"(",
"Discordrb",
"::",
"Message",
")",
"result",
"=",
"(",
"@saved_message",
".",
"nil?",
"?",
"''",
":",
"@saved_message",
".",
"to_s",
")",
"+",
"(",
"result",
".",
"nil?",
"?",
"''",
":",
"result",
".",
"to_s",
")",
"drain",
"result",
"end"
] |
Drains the currently saved message into a result string. This prepends it before that string, clears the saved
message and returns the concatenation.
@param result [String] The result string to drain into.
@return [String] a string formed by concatenating the saved message and the argument.
|
[
"Drains",
"the",
"currently",
"saved",
"message",
"into",
"a",
"result",
"string",
".",
"This",
"prepends",
"it",
"before",
"that",
"string",
"clears",
"the",
"saved",
"message",
"and",
"returns",
"the",
"concatenation",
"."
] |
764298a1ff0be69a1853b510d736f21c2b91a2fe
|
https://github.com/meew0/discordrb/blob/764298a1ff0be69a1853b510d736f21c2b91a2fe/lib/discordrb/events/message.rb#L62-L68
|
12,407
|
meew0/discordrb
|
lib/discordrb/events/message.rb
|
Discordrb::Events.MessageEvent.attach_file
|
def attach_file(file, filename: nil, spoiler: nil)
raise ArgumentError, 'Argument is not a file!' unless file.is_a?(File)
@file = file
@filename = filename
@file_spoiler = spoiler
nil
end
|
ruby
|
def attach_file(file, filename: nil, spoiler: nil)
raise ArgumentError, 'Argument is not a file!' unless file.is_a?(File)
@file = file
@filename = filename
@file_spoiler = spoiler
nil
end
|
[
"def",
"attach_file",
"(",
"file",
",",
"filename",
":",
"nil",
",",
"spoiler",
":",
"nil",
")",
"raise",
"ArgumentError",
",",
"'Argument is not a file!'",
"unless",
"file",
".",
"is_a?",
"(",
"File",
")",
"@file",
"=",
"file",
"@filename",
"=",
"filename",
"@file_spoiler",
"=",
"spoiler",
"nil",
"end"
] |
Attaches a file to the message event and converts the message into
a caption.
@param file [File] The file to be attached
@param filename [String] Overrides the filename of the uploaded file
@param spoiler [true, false] Whether or not this file should appear as a spoiler.
|
[
"Attaches",
"a",
"file",
"to",
"the",
"message",
"event",
"and",
"converts",
"the",
"message",
"into",
"a",
"caption",
"."
] |
764298a1ff0be69a1853b510d736f21c2b91a2fe
|
https://github.com/meew0/discordrb/blob/764298a1ff0be69a1853b510d736f21c2b91a2fe/lib/discordrb/events/message.rb#L142-L149
|
12,408
|
meew0/discordrb
|
lib/discordrb/data/server.rb
|
Discordrb.Server.role
|
def role(id)
id = id.resolve_id
@roles.find { |e| e.id == id }
end
|
ruby
|
def role(id)
id = id.resolve_id
@roles.find { |e| e.id == id }
end
|
[
"def",
"role",
"(",
"id",
")",
"id",
"=",
"id",
".",
"resolve_id",
"@roles",
".",
"find",
"{",
"|",
"e",
"|",
"e",
".",
"id",
"==",
"id",
"}",
"end"
] |
Gets a role on this server based on its ID.
@param id [Integer, String, #resolve_id] The role ID to look for.
|
[
"Gets",
"a",
"role",
"on",
"this",
"server",
"based",
"on",
"its",
"ID",
"."
] |
764298a1ff0be69a1853b510d736f21c2b91a2fe
|
https://github.com/meew0/discordrb/blob/764298a1ff0be69a1853b510d736f21c2b91a2fe/lib/discordrb/data/server.rb#L114-L117
|
12,409
|
meew0/discordrb
|
lib/discordrb/data/server.rb
|
Discordrb.Server.member
|
def member(id, request = true)
id = id.resolve_id
return @members[id] if member_cached?(id)
return nil unless request
member = @bot.member(self, id)
@members[id] = member unless member.nil?
rescue StandardError
nil
end
|
ruby
|
def member(id, request = true)
id = id.resolve_id
return @members[id] if member_cached?(id)
return nil unless request
member = @bot.member(self, id)
@members[id] = member unless member.nil?
rescue StandardError
nil
end
|
[
"def",
"member",
"(",
"id",
",",
"request",
"=",
"true",
")",
"id",
"=",
"id",
".",
"resolve_id",
"return",
"@members",
"[",
"id",
"]",
"if",
"member_cached?",
"(",
"id",
")",
"return",
"nil",
"unless",
"request",
"member",
"=",
"@bot",
".",
"member",
"(",
"self",
",",
"id",
")",
"@members",
"[",
"id",
"]",
"=",
"member",
"unless",
"member",
".",
"nil?",
"rescue",
"StandardError",
"nil",
"end"
] |
Gets a member on this server based on user ID
@param id [Integer] The user ID to look for
@param request [true, false] Whether the member should be requested from Discord if it's not cached
|
[
"Gets",
"a",
"member",
"on",
"this",
"server",
"based",
"on",
"user",
"ID"
] |
764298a1ff0be69a1853b510d736f21c2b91a2fe
|
https://github.com/meew0/discordrb/blob/764298a1ff0be69a1853b510d736f21c2b91a2fe/lib/discordrb/data/server.rb#L122-L131
|
12,410
|
meew0/discordrb
|
lib/discordrb/data/server.rb
|
Discordrb.Server.prune_count
|
def prune_count(days)
raise ArgumentError, 'Days must be between 1 and 30' unless days.between?(1, 30)
response = JSON.parse API::Server.prune_count(@bot.token, @id, days)
response['pruned']
end
|
ruby
|
def prune_count(days)
raise ArgumentError, 'Days must be between 1 and 30' unless days.between?(1, 30)
response = JSON.parse API::Server.prune_count(@bot.token, @id, days)
response['pruned']
end
|
[
"def",
"prune_count",
"(",
"days",
")",
"raise",
"ArgumentError",
",",
"'Days must be between 1 and 30'",
"unless",
"days",
".",
"between?",
"(",
"1",
",",
"30",
")",
"response",
"=",
"JSON",
".",
"parse",
"API",
"::",
"Server",
".",
"prune_count",
"(",
"@bot",
".",
"token",
",",
"@id",
",",
"days",
")",
"response",
"[",
"'pruned'",
"]",
"end"
] |
Returns the amount of members that are candidates for pruning
@param days [Integer] the number of days to consider for inactivity
@return [Integer] number of members to be removed
@raise [ArgumentError] if days is not between 1 and 30 (inclusive)
|
[
"Returns",
"the",
"amount",
"of",
"members",
"that",
"are",
"candidates",
"for",
"pruning"
] |
764298a1ff0be69a1853b510d736f21c2b91a2fe
|
https://github.com/meew0/discordrb/blob/764298a1ff0be69a1853b510d736f21c2b91a2fe/lib/discordrb/data/server.rb#L276-L281
|
12,411
|
meew0/discordrb
|
lib/discordrb/data/server.rb
|
Discordrb.Server.delete_role
|
def delete_role(role_id)
@roles.reject! { |r| r.id == role_id }
@members.each do |_, member|
new_roles = member.roles.reject { |r| r.id == role_id }
member.update_roles(new_roles)
end
@channels.each do |channel|
overwrites = channel.permission_overwrites.reject { |id, _| id == role_id }
channel.update_overwrites(overwrites)
end
end
|
ruby
|
def delete_role(role_id)
@roles.reject! { |r| r.id == role_id }
@members.each do |_, member|
new_roles = member.roles.reject { |r| r.id == role_id }
member.update_roles(new_roles)
end
@channels.each do |channel|
overwrites = channel.permission_overwrites.reject { |id, _| id == role_id }
channel.update_overwrites(overwrites)
end
end
|
[
"def",
"delete_role",
"(",
"role_id",
")",
"@roles",
".",
"reject!",
"{",
"|",
"r",
"|",
"r",
".",
"id",
"==",
"role_id",
"}",
"@members",
".",
"each",
"do",
"|",
"_",
",",
"member",
"|",
"new_roles",
"=",
"member",
".",
"roles",
".",
"reject",
"{",
"|",
"r",
"|",
"r",
".",
"id",
"==",
"role_id",
"}",
"member",
".",
"update_roles",
"(",
"new_roles",
")",
"end",
"@channels",
".",
"each",
"do",
"|",
"channel",
"|",
"overwrites",
"=",
"channel",
".",
"permission_overwrites",
".",
"reject",
"{",
"|",
"id",
",",
"_",
"|",
"id",
"==",
"role_id",
"}",
"channel",
".",
"update_overwrites",
"(",
"overwrites",
")",
"end",
"end"
] |
Removes a role from the role cache
@note For internal use only
@!visibility private
|
[
"Removes",
"a",
"role",
"from",
"the",
"role",
"cache"
] |
764298a1ff0be69a1853b510d736f21c2b91a2fe
|
https://github.com/meew0/discordrb/blob/764298a1ff0be69a1853b510d736f21c2b91a2fe/lib/discordrb/data/server.rb#L365-L375
|
12,412
|
meew0/discordrb
|
lib/discordrb/data/server.rb
|
Discordrb.Server.update_role_positions
|
def update_role_positions(role_positions)
response = JSON.parse(API::Server.update_role_positions(@bot.token, @id, role_positions))
response.each do |data|
updated_role = Role.new(data, @bot, self)
role(updated_role.id).update_from(updated_role)
end
end
|
ruby
|
def update_role_positions(role_positions)
response = JSON.parse(API::Server.update_role_positions(@bot.token, @id, role_positions))
response.each do |data|
updated_role = Role.new(data, @bot, self)
role(updated_role.id).update_from(updated_role)
end
end
|
[
"def",
"update_role_positions",
"(",
"role_positions",
")",
"response",
"=",
"JSON",
".",
"parse",
"(",
"API",
"::",
"Server",
".",
"update_role_positions",
"(",
"@bot",
".",
"token",
",",
"@id",
",",
"role_positions",
")",
")",
"response",
".",
"each",
"do",
"|",
"data",
"|",
"updated_role",
"=",
"Role",
".",
"new",
"(",
"data",
",",
"@bot",
",",
"self",
")",
"role",
"(",
"updated_role",
".",
"id",
")",
".",
"update_from",
"(",
"updated_role",
")",
"end",
"end"
] |
Updates the positions of all roles on the server
@note For internal use only
@!visibility private
|
[
"Updates",
"the",
"positions",
"of",
"all",
"roles",
"on",
"the",
"server"
] |
764298a1ff0be69a1853b510d736f21c2b91a2fe
|
https://github.com/meew0/discordrb/blob/764298a1ff0be69a1853b510d736f21c2b91a2fe/lib/discordrb/data/server.rb#L380-L386
|
12,413
|
meew0/discordrb
|
lib/discordrb/data/server.rb
|
Discordrb.Server.update_voice_state
|
def update_voice_state(data)
user_id = data['user_id'].to_i
if data['channel_id']
unless @voice_states[user_id]
# Create a new voice state for the user
@voice_states[user_id] = VoiceState.new(user_id)
end
# Update the existing voice state (or the one we just created)
channel = @channels_by_id[data['channel_id'].to_i]
@voice_states[user_id].update(
channel,
data['mute'],
data['deaf'],
data['self_mute'],
data['self_deaf']
)
else
# The user is not in a voice channel anymore, so delete its voice state
@voice_states.delete(user_id)
end
end
|
ruby
|
def update_voice_state(data)
user_id = data['user_id'].to_i
if data['channel_id']
unless @voice_states[user_id]
# Create a new voice state for the user
@voice_states[user_id] = VoiceState.new(user_id)
end
# Update the existing voice state (or the one we just created)
channel = @channels_by_id[data['channel_id'].to_i]
@voice_states[user_id].update(
channel,
data['mute'],
data['deaf'],
data['self_mute'],
data['self_deaf']
)
else
# The user is not in a voice channel anymore, so delete its voice state
@voice_states.delete(user_id)
end
end
|
[
"def",
"update_voice_state",
"(",
"data",
")",
"user_id",
"=",
"data",
"[",
"'user_id'",
"]",
".",
"to_i",
"if",
"data",
"[",
"'channel_id'",
"]",
"unless",
"@voice_states",
"[",
"user_id",
"]",
"# Create a new voice state for the user",
"@voice_states",
"[",
"user_id",
"]",
"=",
"VoiceState",
".",
"new",
"(",
"user_id",
")",
"end",
"# Update the existing voice state (or the one we just created)",
"channel",
"=",
"@channels_by_id",
"[",
"data",
"[",
"'channel_id'",
"]",
".",
"to_i",
"]",
"@voice_states",
"[",
"user_id",
"]",
".",
"update",
"(",
"channel",
",",
"data",
"[",
"'mute'",
"]",
",",
"data",
"[",
"'deaf'",
"]",
",",
"data",
"[",
"'self_mute'",
"]",
",",
"data",
"[",
"'self_deaf'",
"]",
")",
"else",
"# The user is not in a voice channel anymore, so delete its voice state",
"@voice_states",
".",
"delete",
"(",
"user_id",
")",
"end",
"end"
] |
Updates a member's voice state
@note For internal use only
@!visibility private
|
[
"Updates",
"a",
"member",
"s",
"voice",
"state"
] |
764298a1ff0be69a1853b510d736f21c2b91a2fe
|
https://github.com/meew0/discordrb/blob/764298a1ff0be69a1853b510d736f21c2b91a2fe/lib/discordrb/data/server.rb#L421-L443
|
12,414
|
meew0/discordrb
|
lib/discordrb/data/server.rb
|
Discordrb.Server.create_role
|
def create_role(name: 'new role', colour: 0, hoist: false, mentionable: false, permissions: 104_324_161, reason: nil)
colour = colour.respond_to?(:combined) ? colour.combined : colour
permissions = if permissions.is_a?(Array)
Permissions.bits(permissions)
elsif permissions.respond_to?(:bits)
permissions.bits
else
permissions
end
response = API::Server.create_role(@bot.token, @id, name, colour, hoist, mentionable, permissions, reason)
role = Role.new(JSON.parse(response), @bot, self)
@roles << role
role
end
|
ruby
|
def create_role(name: 'new role', colour: 0, hoist: false, mentionable: false, permissions: 104_324_161, reason: nil)
colour = colour.respond_to?(:combined) ? colour.combined : colour
permissions = if permissions.is_a?(Array)
Permissions.bits(permissions)
elsif permissions.respond_to?(:bits)
permissions.bits
else
permissions
end
response = API::Server.create_role(@bot.token, @id, name, colour, hoist, mentionable, permissions, reason)
role = Role.new(JSON.parse(response), @bot, self)
@roles << role
role
end
|
[
"def",
"create_role",
"(",
"name",
":",
"'new role'",
",",
"colour",
":",
"0",
",",
"hoist",
":",
"false",
",",
"mentionable",
":",
"false",
",",
"permissions",
":",
"104_324_161",
",",
"reason",
":",
"nil",
")",
"colour",
"=",
"colour",
".",
"respond_to?",
"(",
":combined",
")",
"?",
"colour",
".",
"combined",
":",
"colour",
"permissions",
"=",
"if",
"permissions",
".",
"is_a?",
"(",
"Array",
")",
"Permissions",
".",
"bits",
"(",
"permissions",
")",
"elsif",
"permissions",
".",
"respond_to?",
"(",
":bits",
")",
"permissions",
".",
"bits",
"else",
"permissions",
"end",
"response",
"=",
"API",
"::",
"Server",
".",
"create_role",
"(",
"@bot",
".",
"token",
",",
"@id",
",",
"name",
",",
"colour",
",",
"hoist",
",",
"mentionable",
",",
"permissions",
",",
"reason",
")",
"role",
"=",
"Role",
".",
"new",
"(",
"JSON",
".",
"parse",
"(",
"response",
")",
",",
"@bot",
",",
"self",
")",
"@roles",
"<<",
"role",
"role",
"end"
] |
Creates a role on this server which can then be modified. It will be initialized
with the regular role defaults the client uses unless specified, i.e. name is "new role",
permissions are the default, colour is the default etc.
@param name [String] Name of the role to create
@param colour [Integer, ColourRGB, #combined] The roles colour
@param hoist [true, false]
@param mentionable [true, false]
@param permissions [Integer, Array<Symbol>, Permissions, #bits] The permissions to write to the new role.
@param reason [String] The reason the for the creation of this role.
@return [Role] the created role.
|
[
"Creates",
"a",
"role",
"on",
"this",
"server",
"which",
"can",
"then",
"be",
"modified",
".",
"It",
"will",
"be",
"initialized",
"with",
"the",
"regular",
"role",
"defaults",
"the",
"client",
"uses",
"unless",
"specified",
"i",
".",
"e",
".",
"name",
"is",
"new",
"role",
"permissions",
"are",
"the",
"default",
"colour",
"is",
"the",
"default",
"etc",
"."
] |
764298a1ff0be69a1853b510d736f21c2b91a2fe
|
https://github.com/meew0/discordrb/blob/764298a1ff0be69a1853b510d736f21c2b91a2fe/lib/discordrb/data/server.rb#L484-L500
|
12,415
|
meew0/discordrb
|
lib/discordrb/data/server.rb
|
Discordrb.Server.add_emoji
|
def add_emoji(name, image, roles = [], reason: nil)
image_string = image
if image.respond_to? :read
image_string = 'data:image/jpg;base64,'
image_string += Base64.strict_encode64(image.read)
end
data = JSON.parse(API::Server.add_emoji(@bot.token, @id, image_string, name, roles.map(&:resolve_id), reason))
new_emoji = Emoji.new(data)
@emoji[new_emoji.id] = new_emoji
end
|
ruby
|
def add_emoji(name, image, roles = [], reason: nil)
image_string = image
if image.respond_to? :read
image_string = 'data:image/jpg;base64,'
image_string += Base64.strict_encode64(image.read)
end
data = JSON.parse(API::Server.add_emoji(@bot.token, @id, image_string, name, roles.map(&:resolve_id), reason))
new_emoji = Emoji.new(data)
@emoji[new_emoji.id] = new_emoji
end
|
[
"def",
"add_emoji",
"(",
"name",
",",
"image",
",",
"roles",
"=",
"[",
"]",
",",
"reason",
":",
"nil",
")",
"image_string",
"=",
"image",
"if",
"image",
".",
"respond_to?",
":read",
"image_string",
"=",
"'data:image/jpg;base64,'",
"image_string",
"+=",
"Base64",
".",
"strict_encode64",
"(",
"image",
".",
"read",
")",
"end",
"data",
"=",
"JSON",
".",
"parse",
"(",
"API",
"::",
"Server",
".",
"add_emoji",
"(",
"@bot",
".",
"token",
",",
"@id",
",",
"image_string",
",",
"name",
",",
"roles",
".",
"map",
"(",
":resolve_id",
")",
",",
"reason",
")",
")",
"new_emoji",
"=",
"Emoji",
".",
"new",
"(",
"data",
")",
"@emoji",
"[",
"new_emoji",
".",
"id",
"]",
"=",
"new_emoji",
"end"
] |
Adds a new custom emoji on this server.
@param name [String] The name of emoji to create.
@param image [String, #read] A base64 encoded string with the image data, or an object that responds to `#read`, such as `File`.
@param roles [Array<Role, String, Integer>] An array of roles, or role IDs to be whitelisted for this emoji.
@param reason [String] The reason the for the creation of this emoji.
@return [Emoji] The emoji that has been added.
|
[
"Adds",
"a",
"new",
"custom",
"emoji",
"on",
"this",
"server",
"."
] |
764298a1ff0be69a1853b510d736f21c2b91a2fe
|
https://github.com/meew0/discordrb/blob/764298a1ff0be69a1853b510d736f21c2b91a2fe/lib/discordrb/data/server.rb#L508-L518
|
12,416
|
meew0/discordrb
|
lib/discordrb/data/server.rb
|
Discordrb.Server.delete_emoji
|
def delete_emoji(emoji, reason: nil)
API::Server.delete_emoji(@bot.token, @id, emoji.resolve_id, reason)
end
|
ruby
|
def delete_emoji(emoji, reason: nil)
API::Server.delete_emoji(@bot.token, @id, emoji.resolve_id, reason)
end
|
[
"def",
"delete_emoji",
"(",
"emoji",
",",
"reason",
":",
"nil",
")",
"API",
"::",
"Server",
".",
"delete_emoji",
"(",
"@bot",
".",
"token",
",",
"@id",
",",
"emoji",
".",
"resolve_id",
",",
"reason",
")",
"end"
] |
Delete a custom emoji on this server
@param emoji [Emoji, Integer, String] The emoji or emoji ID to be deleted.
@param reason [String] The reason the for the deletion of this emoji.
|
[
"Delete",
"a",
"custom",
"emoji",
"on",
"this",
"server"
] |
764298a1ff0be69a1853b510d736f21c2b91a2fe
|
https://github.com/meew0/discordrb/blob/764298a1ff0be69a1853b510d736f21c2b91a2fe/lib/discordrb/data/server.rb#L523-L525
|
12,417
|
meew0/discordrb
|
lib/discordrb/data/server.rb
|
Discordrb.Server.ban
|
def ban(user, message_days = 0, reason: nil)
API::Server.ban_user(@bot.token, @id, user.resolve_id, message_days, reason)
end
|
ruby
|
def ban(user, message_days = 0, reason: nil)
API::Server.ban_user(@bot.token, @id, user.resolve_id, message_days, reason)
end
|
[
"def",
"ban",
"(",
"user",
",",
"message_days",
"=",
"0",
",",
"reason",
":",
"nil",
")",
"API",
"::",
"Server",
".",
"ban_user",
"(",
"@bot",
".",
"token",
",",
"@id",
",",
"user",
".",
"resolve_id",
",",
"message_days",
",",
"reason",
")",
"end"
] |
Bans a user from this server.
@param user [User, #resolve_id] The user to ban.
@param message_days [Integer] How many days worth of messages sent by the user should be deleted.
@param reason [String] The reason the user is being banned.
|
[
"Bans",
"a",
"user",
"from",
"this",
"server",
"."
] |
764298a1ff0be69a1853b510d736f21c2b91a2fe
|
https://github.com/meew0/discordrb/blob/764298a1ff0be69a1853b510d736f21c2b91a2fe/lib/discordrb/data/server.rb#L552-L554
|
12,418
|
meew0/discordrb
|
lib/discordrb/data/server.rb
|
Discordrb.Server.unban
|
def unban(user, reason = nil)
API::Server.unban_user(@bot.token, @id, user.resolve_id, reason)
end
|
ruby
|
def unban(user, reason = nil)
API::Server.unban_user(@bot.token, @id, user.resolve_id, reason)
end
|
[
"def",
"unban",
"(",
"user",
",",
"reason",
"=",
"nil",
")",
"API",
"::",
"Server",
".",
"unban_user",
"(",
"@bot",
".",
"token",
",",
"@id",
",",
"user",
".",
"resolve_id",
",",
"reason",
")",
"end"
] |
Unbans a previously banned user from this server.
@param user [User, #resolve_id] The user to unban.
@param reason [String] The reason the user is being unbanned.
|
[
"Unbans",
"a",
"previously",
"banned",
"user",
"from",
"this",
"server",
"."
] |
764298a1ff0be69a1853b510d736f21c2b91a2fe
|
https://github.com/meew0/discordrb/blob/764298a1ff0be69a1853b510d736f21c2b91a2fe/lib/discordrb/data/server.rb#L559-L561
|
12,419
|
meew0/discordrb
|
lib/discordrb/data/server.rb
|
Discordrb.Server.kick
|
def kick(user, reason = nil)
API::Server.remove_member(@bot.token, @id, user.resolve_id, reason)
end
|
ruby
|
def kick(user, reason = nil)
API::Server.remove_member(@bot.token, @id, user.resolve_id, reason)
end
|
[
"def",
"kick",
"(",
"user",
",",
"reason",
"=",
"nil",
")",
"API",
"::",
"Server",
".",
"remove_member",
"(",
"@bot",
".",
"token",
",",
"@id",
",",
"user",
".",
"resolve_id",
",",
"reason",
")",
"end"
] |
Kicks a user from this server.
@param user [User, #resolve_id] The user to kick.
@param reason [String] The reason the user is being kicked.
|
[
"Kicks",
"a",
"user",
"from",
"this",
"server",
"."
] |
764298a1ff0be69a1853b510d736f21c2b91a2fe
|
https://github.com/meew0/discordrb/blob/764298a1ff0be69a1853b510d736f21c2b91a2fe/lib/discordrb/data/server.rb#L566-L568
|
12,420
|
meew0/discordrb
|
lib/discordrb/data/server.rb
|
Discordrb.Server.move
|
def move(user, channel)
API::Server.update_member(@bot.token, @id, user.resolve_id, channel_id: channel.resolve_id)
end
|
ruby
|
def move(user, channel)
API::Server.update_member(@bot.token, @id, user.resolve_id, channel_id: channel.resolve_id)
end
|
[
"def",
"move",
"(",
"user",
",",
"channel",
")",
"API",
"::",
"Server",
".",
"update_member",
"(",
"@bot",
".",
"token",
",",
"@id",
",",
"user",
".",
"resolve_id",
",",
"channel_id",
":",
"channel",
".",
"resolve_id",
")",
"end"
] |
Forcibly moves a user into a different voice channel. Only works if the bot has the permission needed.
@param user [User, #resolve_id] The user to move.
@param channel [Channel, #resolve_id] The voice channel to move into.
|
[
"Forcibly",
"moves",
"a",
"user",
"into",
"a",
"different",
"voice",
"channel",
".",
"Only",
"works",
"if",
"the",
"bot",
"has",
"the",
"permission",
"needed",
"."
] |
764298a1ff0be69a1853b510d736f21c2b91a2fe
|
https://github.com/meew0/discordrb/blob/764298a1ff0be69a1853b510d736f21c2b91a2fe/lib/discordrb/data/server.rb#L573-L575
|
12,421
|
meew0/discordrb
|
lib/discordrb/data/server.rb
|
Discordrb.Server.icon=
|
def icon=(icon)
if icon.respond_to? :read
icon_string = 'data:image/jpg;base64,'
icon_string += Base64.strict_encode64(icon.read)
update_server_data(icon_id: icon_string)
else
update_server_data(icon_id: icon)
end
end
|
ruby
|
def icon=(icon)
if icon.respond_to? :read
icon_string = 'data:image/jpg;base64,'
icon_string += Base64.strict_encode64(icon.read)
update_server_data(icon_id: icon_string)
else
update_server_data(icon_id: icon)
end
end
|
[
"def",
"icon",
"=",
"(",
"icon",
")",
"if",
"icon",
".",
"respond_to?",
":read",
"icon_string",
"=",
"'data:image/jpg;base64,'",
"icon_string",
"+=",
"Base64",
".",
"strict_encode64",
"(",
"icon",
".",
"read",
")",
"update_server_data",
"(",
"icon_id",
":",
"icon_string",
")",
"else",
"update_server_data",
"(",
"icon_id",
":",
"icon",
")",
"end",
"end"
] |
Sets the server's icon.
@param icon [String, #read] The new icon, in base64-encoded JPG format.
|
[
"Sets",
"the",
"server",
"s",
"icon",
"."
] |
764298a1ff0be69a1853b510d736f21c2b91a2fe
|
https://github.com/meew0/discordrb/blob/764298a1ff0be69a1853b510d736f21c2b91a2fe/lib/discordrb/data/server.rb#L623-L631
|
12,422
|
meew0/discordrb
|
lib/discordrb/data/server.rb
|
Discordrb.Server.verification_level=
|
def verification_level=(level)
level = VERIFICATION_LEVELS[level] if level.is_a?(Symbol)
update_server_data(verification_level: level)
end
|
ruby
|
def verification_level=(level)
level = VERIFICATION_LEVELS[level] if level.is_a?(Symbol)
update_server_data(verification_level: level)
end
|
[
"def",
"verification_level",
"=",
"(",
"level",
")",
"level",
"=",
"VERIFICATION_LEVELS",
"[",
"level",
"]",
"if",
"level",
".",
"is_a?",
"(",
"Symbol",
")",
"update_server_data",
"(",
"verification_level",
":",
"level",
")",
"end"
] |
Sets the verification level of the server
@param level [Integer, Symbol] The verification level from 0-4 or Symbol (see {VERIFICATION_LEVELS})
|
[
"Sets",
"the",
"verification",
"level",
"of",
"the",
"server"
] |
764298a1ff0be69a1853b510d736f21c2b91a2fe
|
https://github.com/meew0/discordrb/blob/764298a1ff0be69a1853b510d736f21c2b91a2fe/lib/discordrb/data/server.rb#L667-L671
|
12,423
|
meew0/discordrb
|
lib/discordrb/data/server.rb
|
Discordrb.Server.default_message_notifications=
|
def default_message_notifications=(notification_level)
notification_level = NOTIFICATION_LEVELS[notification_level] if notification_level.is_a?(Symbol)
update_server_data(default_message_notifications: notification_level)
end
|
ruby
|
def default_message_notifications=(notification_level)
notification_level = NOTIFICATION_LEVELS[notification_level] if notification_level.is_a?(Symbol)
update_server_data(default_message_notifications: notification_level)
end
|
[
"def",
"default_message_notifications",
"=",
"(",
"notification_level",
")",
"notification_level",
"=",
"NOTIFICATION_LEVELS",
"[",
"notification_level",
"]",
"if",
"notification_level",
".",
"is_a?",
"(",
"Symbol",
")",
"update_server_data",
"(",
"default_message_notifications",
":",
"notification_level",
")",
"end"
] |
Sets the default message notification level
@param notification_level [Integer, Symbol] The default message notificiation 0-1 or Symbol (see {NOTIFICATION_LEVELS})
|
[
"Sets",
"the",
"default",
"message",
"notification",
"level"
] |
764298a1ff0be69a1853b510d736f21c2b91a2fe
|
https://github.com/meew0/discordrb/blob/764298a1ff0be69a1853b510d736f21c2b91a2fe/lib/discordrb/data/server.rb#L686-L690
|
12,424
|
meew0/discordrb
|
lib/discordrb/data/server.rb
|
Discordrb.Server.explicit_content_filter=
|
def explicit_content_filter=(filter_level)
filter_level = FILTER_LEVELS[filter_level] if filter_level.is_a?(Symbol)
update_server_data(explicit_content_filter: filter_level)
end
|
ruby
|
def explicit_content_filter=(filter_level)
filter_level = FILTER_LEVELS[filter_level] if filter_level.is_a?(Symbol)
update_server_data(explicit_content_filter: filter_level)
end
|
[
"def",
"explicit_content_filter",
"=",
"(",
"filter_level",
")",
"filter_level",
"=",
"FILTER_LEVELS",
"[",
"filter_level",
"]",
"if",
"filter_level",
".",
"is_a?",
"(",
"Symbol",
")",
"update_server_data",
"(",
"explicit_content_filter",
":",
"filter_level",
")",
"end"
] |
Sets the server content filter.
@param filter_level [Integer, Symbol] The content filter from 0-2 or Symbol (see {FILTER_LEVELS})
|
[
"Sets",
"the",
"server",
"content",
"filter",
"."
] |
764298a1ff0be69a1853b510d736f21c2b91a2fe
|
https://github.com/meew0/discordrb/blob/764298a1ff0be69a1853b510d736f21c2b91a2fe/lib/discordrb/data/server.rb#L716-L720
|
12,425
|
meew0/discordrb
|
lib/discordrb/data/server.rb
|
Discordrb.Server.webhooks
|
def webhooks
webhooks = JSON.parse(API::Server.webhooks(@bot.token, @id))
webhooks.map { |webhook| Webhook.new(webhook, @bot) }
end
|
ruby
|
def webhooks
webhooks = JSON.parse(API::Server.webhooks(@bot.token, @id))
webhooks.map { |webhook| Webhook.new(webhook, @bot) }
end
|
[
"def",
"webhooks",
"webhooks",
"=",
"JSON",
".",
"parse",
"(",
"API",
"::",
"Server",
".",
"webhooks",
"(",
"@bot",
".",
"token",
",",
"@id",
")",
")",
"webhooks",
".",
"map",
"{",
"|",
"webhook",
"|",
"Webhook",
".",
"new",
"(",
"webhook",
",",
"@bot",
")",
"}",
"end"
] |
Requests a list of Webhooks on the server.
@return [Array<Webhook>] webhooks on the server.
|
[
"Requests",
"a",
"list",
"of",
"Webhooks",
"on",
"the",
"server",
"."
] |
764298a1ff0be69a1853b510d736f21c2b91a2fe
|
https://github.com/meew0/discordrb/blob/764298a1ff0be69a1853b510d736f21c2b91a2fe/lib/discordrb/data/server.rb#L732-L735
|
12,426
|
meew0/discordrb
|
lib/discordrb/data/server.rb
|
Discordrb.Server.invites
|
def invites
invites = JSON.parse(API::Server.invites(@bot.token, @id))
invites.map { |invite| Invite.new(invite, @bot) }
end
|
ruby
|
def invites
invites = JSON.parse(API::Server.invites(@bot.token, @id))
invites.map { |invite| Invite.new(invite, @bot) }
end
|
[
"def",
"invites",
"invites",
"=",
"JSON",
".",
"parse",
"(",
"API",
"::",
"Server",
".",
"invites",
"(",
"@bot",
".",
"token",
",",
"@id",
")",
")",
"invites",
".",
"map",
"{",
"|",
"invite",
"|",
"Invite",
".",
"new",
"(",
"invite",
",",
"@bot",
")",
"}",
"end"
] |
Requests a list of Invites to the server.
@return [Array<Invite>] invites to the server.
|
[
"Requests",
"a",
"list",
"of",
"Invites",
"to",
"the",
"server",
"."
] |
764298a1ff0be69a1853b510d736f21c2b91a2fe
|
https://github.com/meew0/discordrb/blob/764298a1ff0be69a1853b510d736f21c2b91a2fe/lib/discordrb/data/server.rb#L739-L742
|
12,427
|
meew0/discordrb
|
lib/discordrb/data/server.rb
|
Discordrb.Server.process_chunk
|
def process_chunk(members)
process_members(members)
@processed_chunk_members += members.length
LOGGER.debug("Processed one chunk on server #{@id} - length #{members.length}")
# Don't bother with the rest of the method if it's not truly the last packet
return unless @processed_chunk_members == @member_count
LOGGER.debug("Finished chunking server #{@id}")
# Reset everything to normal
@chunked = true
@processed_chunk_members = 0
end
|
ruby
|
def process_chunk(members)
process_members(members)
@processed_chunk_members += members.length
LOGGER.debug("Processed one chunk on server #{@id} - length #{members.length}")
# Don't bother with the rest of the method if it's not truly the last packet
return unless @processed_chunk_members == @member_count
LOGGER.debug("Finished chunking server #{@id}")
# Reset everything to normal
@chunked = true
@processed_chunk_members = 0
end
|
[
"def",
"process_chunk",
"(",
"members",
")",
"process_members",
"(",
"members",
")",
"@processed_chunk_members",
"+=",
"members",
".",
"length",
"LOGGER",
".",
"debug",
"(",
"\"Processed one chunk on server #{@id} - length #{members.length}\"",
")",
"# Don't bother with the rest of the method if it's not truly the last packet",
"return",
"unless",
"@processed_chunk_members",
"==",
"@member_count",
"LOGGER",
".",
"debug",
"(",
"\"Finished chunking server #{@id}\"",
")",
"# Reset everything to normal",
"@chunked",
"=",
"true",
"@processed_chunk_members",
"=",
"0",
"end"
] |
Processes a GUILD_MEMBERS_CHUNK packet, specifically the members field
@note For internal use only
@!visibility private
|
[
"Processes",
"a",
"GUILD_MEMBERS_CHUNK",
"packet",
"specifically",
"the",
"members",
"field"
] |
764298a1ff0be69a1853b510d736f21c2b91a2fe
|
https://github.com/meew0/discordrb/blob/764298a1ff0be69a1853b510d736f21c2b91a2fe/lib/discordrb/data/server.rb#L747-L760
|
12,428
|
meew0/discordrb
|
lib/discordrb/voice/encoder.rb
|
Discordrb::Voice.Encoder.adjust_volume
|
def adjust_volume(buf, mult)
# We don't need to adjust anything if the buf is nil so just return in that case
return unless buf
# buf is s16le so use 's<' for signed, 16 bit, LE
result = buf.unpack('s<*').map do |sample|
sample *= mult
# clamp to s16 range
[32_767, [-32_768, sample].max].min
end
# After modification, make it s16le again
result.pack('s<*')
end
|
ruby
|
def adjust_volume(buf, mult)
# We don't need to adjust anything if the buf is nil so just return in that case
return unless buf
# buf is s16le so use 's<' for signed, 16 bit, LE
result = buf.unpack('s<*').map do |sample|
sample *= mult
# clamp to s16 range
[32_767, [-32_768, sample].max].min
end
# After modification, make it s16le again
result.pack('s<*')
end
|
[
"def",
"adjust_volume",
"(",
"buf",
",",
"mult",
")",
"# We don't need to adjust anything if the buf is nil so just return in that case",
"return",
"unless",
"buf",
"# buf is s16le so use 's<' for signed, 16 bit, LE",
"result",
"=",
"buf",
".",
"unpack",
"(",
"'s<*'",
")",
".",
"map",
"do",
"|",
"sample",
"|",
"sample",
"*=",
"mult",
"# clamp to s16 range",
"[",
"32_767",
",",
"[",
"-",
"32_768",
",",
"sample",
"]",
".",
"max",
"]",
".",
"min",
"end",
"# After modification, make it s16le again",
"result",
".",
"pack",
"(",
"'s<*'",
")",
"end"
] |
Adjusts the volume of a given buffer of s16le PCM data.
@param buf [String] An unencoded PCM (s16le) buffer.
@param mult [Float] The volume multiplier, 1 for same volume.
@return [String] The buffer with adjusted volume, s16le again
|
[
"Adjusts",
"the",
"volume",
"of",
"a",
"given",
"buffer",
"of",
"s16le",
"PCM",
"data",
"."
] |
764298a1ff0be69a1853b510d736f21c2b91a2fe
|
https://github.com/meew0/discordrb/blob/764298a1ff0be69a1853b510d736f21c2b91a2fe/lib/discordrb/voice/encoder.rb#L57-L71
|
12,429
|
meew0/discordrb
|
lib/discordrb/commands/container.rb
|
Discordrb::Commands.CommandContainer.command
|
def command(name, attributes = {}, &block)
@commands ||= {}
if name.is_a? Array
new_command = nil
name.each do |e|
new_command = Command.new(e, attributes, &block)
@commands[e] = new_command
end
new_command
else
new_command = Command.new(name, attributes, &block)
new_command.attributes[:aliases].each do |aliased_name|
@commands[aliased_name] = CommandAlias.new(aliased_name, new_command)
end
@commands[name] = new_command
end
end
|
ruby
|
def command(name, attributes = {}, &block)
@commands ||= {}
if name.is_a? Array
new_command = nil
name.each do |e|
new_command = Command.new(e, attributes, &block)
@commands[e] = new_command
end
new_command
else
new_command = Command.new(name, attributes, &block)
new_command.attributes[:aliases].each do |aliased_name|
@commands[aliased_name] = CommandAlias.new(aliased_name, new_command)
end
@commands[name] = new_command
end
end
|
[
"def",
"command",
"(",
"name",
",",
"attributes",
"=",
"{",
"}",
",",
"&",
"block",
")",
"@commands",
"||=",
"{",
"}",
"if",
"name",
".",
"is_a?",
"Array",
"new_command",
"=",
"nil",
"name",
".",
"each",
"do",
"|",
"e",
"|",
"new_command",
"=",
"Command",
".",
"new",
"(",
"e",
",",
"attributes",
",",
"block",
")",
"@commands",
"[",
"e",
"]",
"=",
"new_command",
"end",
"new_command",
"else",
"new_command",
"=",
"Command",
".",
"new",
"(",
"name",
",",
"attributes",
",",
"block",
")",
"new_command",
".",
"attributes",
"[",
":aliases",
"]",
".",
"each",
"do",
"|",
"aliased_name",
"|",
"@commands",
"[",
"aliased_name",
"]",
"=",
"CommandAlias",
".",
"new",
"(",
"aliased_name",
",",
"new_command",
")",
"end",
"@commands",
"[",
"name",
"]",
"=",
"new_command",
"end",
"end"
] |
Adds a new command to the container.
@param name [Symbol, Array<Symbol>] The name of the command to add, or an array of multiple names for the command
@param attributes [Hash] The attributes to initialize the command with.
@option attributes [Integer] :permission_level The minimum permission level that can use this command, inclusive.
See {CommandBot#set_user_permission} and {CommandBot#set_role_permission}.
@option attributes [String, false] :permission_message Message to display when a user does not have sufficient
permissions to execute a command. %name% in the message will be replaced with the name of the command. Disable
the message by setting this option to false.
@option attributes [Array<Symbol>] :required_permissions Discord action permissions (e.g. `:kick_members`) that
should be required to use this command. See {Discordrb::Permissions::FLAGS} for a list.
@option attributes [Array<Role>, Array<#resolve_id>] :required_roles Roles that user must have to use this command
(user must have all of them).
@option attributes [Array<Role>, Array<#resolve_id>] :allowed_roles Roles that user should have to use this command
(user should have at least one of them).
@option attributes [Array<String, Integer, Channel>] :channels The channels that this command can be used on. An
empty array indicates it can be used on any channel. Supersedes the command bot attribute.
@option attributes [true, false] :chain_usable Whether this command is able to be used inside of a command chain
or sub-chain. Typically used for administrative commands that shouldn't be done carelessly.
@option attributes [true, false] :help_available Whether this command is visible in the help command. See the
:help_command attribute of {CommandBot#initialize}.
@option attributes [String] :description A short description of what this command does. Will be shown in the help
command if the user asks for it.
@option attributes [String] :usage A short description of how this command should be used. Will be displayed in
the help command or if the user uses it wrong.
@option attributes [Array<Class>] :arg_types An array of argument classes which will be used for type-checking.
Hard-coded for some native classes, but can be used with any class that implements static
method `from_argument`.
@option attributes [Integer] :min_args The minimum number of arguments this command should have. If a user
attempts to call the command with fewer arguments, the usage information will be displayed, if it exists.
@option attributes [Integer] :max_args The maximum number of arguments the command should have.
@option attributes [String] :rate_limit_message The message that should be displayed if the command hits a rate
limit. None if unspecified or nil. %time% in the message will be replaced with the time in seconds when the
command will be available again.
@option attributes [Symbol] :bucket The rate limit bucket that should be used for rate limiting. No rate limiting
will be done if unspecified or nil.
@option attributes [String, #call] :rescue A string to respond with, or a block to be called in the event an exception
is raised internally. If given a String, `%exception%` will be substituted with the exception's `#message`. If given
a `Proc`, it will be passed the `CommandEvent` along with the `Exception`.
@yield The block is executed when the command is executed.
@yieldparam event [CommandEvent] The event of the message that contained the command.
@note `LocalJumpError`s are rescued from internally, giving bots the opportunity to use `return` or `break` in
their blocks without propagating an exception.
@return [Command] The command that was added.
@deprecated The command name argument will no longer support arrays in the next release.
Use the `aliases` attribute instead.
|
[
"Adds",
"a",
"new",
"command",
"to",
"the",
"container",
"."
] |
764298a1ff0be69a1853b510d736f21c2b91a2fe
|
https://github.com/meew0/discordrb/blob/764298a1ff0be69a1853b510d736f21c2b91a2fe/lib/discordrb/commands/container.rb#L60-L78
|
12,430
|
meew0/discordrb
|
lib/discordrb/data/profile.rb
|
Discordrb.Profile.avatar=
|
def avatar=(avatar)
if avatar.respond_to? :read
# Set the file to binary mode if supported, so we don't get problems with Windows
avatar.binmode if avatar.respond_to?(:binmode)
avatar_string = 'data:image/jpg;base64,'
avatar_string += Base64.strict_encode64(avatar.read)
update_profile_data(avatar: avatar_string)
else
update_profile_data(avatar: avatar)
end
end
|
ruby
|
def avatar=(avatar)
if avatar.respond_to? :read
# Set the file to binary mode if supported, so we don't get problems with Windows
avatar.binmode if avatar.respond_to?(:binmode)
avatar_string = 'data:image/jpg;base64,'
avatar_string += Base64.strict_encode64(avatar.read)
update_profile_data(avatar: avatar_string)
else
update_profile_data(avatar: avatar)
end
end
|
[
"def",
"avatar",
"=",
"(",
"avatar",
")",
"if",
"avatar",
".",
"respond_to?",
":read",
"# Set the file to binary mode if supported, so we don't get problems with Windows",
"avatar",
".",
"binmode",
"if",
"avatar",
".",
"respond_to?",
"(",
":binmode",
")",
"avatar_string",
"=",
"'data:image/jpg;base64,'",
"avatar_string",
"+=",
"Base64",
".",
"strict_encode64",
"(",
"avatar",
".",
"read",
")",
"update_profile_data",
"(",
"avatar",
":",
"avatar_string",
")",
"else",
"update_profile_data",
"(",
"avatar",
":",
"avatar",
")",
"end",
"end"
] |
Changes the bot's avatar.
@param avatar [String, #read] A JPG file to be used as the avatar, either
something readable (e.g. File Object) or as a data URL.
|
[
"Changes",
"the",
"bot",
"s",
"avatar",
"."
] |
764298a1ff0be69a1853b510d736f21c2b91a2fe
|
https://github.com/meew0/discordrb/blob/764298a1ff0be69a1853b510d736f21c2b91a2fe/lib/discordrb/data/profile.rb#L28-L39
|
12,431
|
meew0/discordrb
|
lib/discordrb/voice/network.rb
|
Discordrb::Voice.VoiceUDP.connect
|
def connect(endpoint, port, ssrc)
@endpoint = endpoint
@endpoint = @endpoint[6..-1] if @endpoint.start_with? 'wss://'
@endpoint = @endpoint.gsub(':80', '') # The endpoint may contain a port, we don't want that
@endpoint = Resolv.getaddress @endpoint
@port = port
@ssrc = ssrc
end
|
ruby
|
def connect(endpoint, port, ssrc)
@endpoint = endpoint
@endpoint = @endpoint[6..-1] if @endpoint.start_with? 'wss://'
@endpoint = @endpoint.gsub(':80', '') # The endpoint may contain a port, we don't want that
@endpoint = Resolv.getaddress @endpoint
@port = port
@ssrc = ssrc
end
|
[
"def",
"connect",
"(",
"endpoint",
",",
"port",
",",
"ssrc",
")",
"@endpoint",
"=",
"endpoint",
"@endpoint",
"=",
"@endpoint",
"[",
"6",
"..",
"-",
"1",
"]",
"if",
"@endpoint",
".",
"start_with?",
"'wss://'",
"@endpoint",
"=",
"@endpoint",
".",
"gsub",
"(",
"':80'",
",",
"''",
")",
"# The endpoint may contain a port, we don't want that",
"@endpoint",
"=",
"Resolv",
".",
"getaddress",
"@endpoint",
"@port",
"=",
"port",
"@ssrc",
"=",
"ssrc",
"end"
] |
Creates a new UDP connection. Only creates a socket as the discovery reply may come before the data is
initialized.
Initializes the UDP socket with data obtained from opcode 2.
@param endpoint [String] The voice endpoint to connect to.
@param port [Integer] The port to connect to.
@param ssrc [Integer] The Super Secret Relay Code (SSRC). Discord uses this to identify different voice users
on the same endpoint.
|
[
"Creates",
"a",
"new",
"UDP",
"connection",
".",
"Only",
"creates",
"a",
"socket",
"as",
"the",
"discovery",
"reply",
"may",
"come",
"before",
"the",
"data",
"is",
"initialized",
".",
"Initializes",
"the",
"UDP",
"socket",
"with",
"data",
"obtained",
"from",
"opcode",
"2",
"."
] |
764298a1ff0be69a1853b510d736f21c2b91a2fe
|
https://github.com/meew0/discordrb/blob/764298a1ff0be69a1853b510d736f21c2b91a2fe/lib/discordrb/voice/network.rb#L50-L58
|
12,432
|
meew0/discordrb
|
lib/discordrb/voice/network.rb
|
Discordrb::Voice.VoiceUDP.receive_discovery_reply
|
def receive_discovery_reply
# Wait for a UDP message
message = @socket.recv(70)
ip = message[4..-3].delete("\0")
port = message[-2..-1].to_i
[ip, port]
end
|
ruby
|
def receive_discovery_reply
# Wait for a UDP message
message = @socket.recv(70)
ip = message[4..-3].delete("\0")
port = message[-2..-1].to_i
[ip, port]
end
|
[
"def",
"receive_discovery_reply",
"# Wait for a UDP message",
"message",
"=",
"@socket",
".",
"recv",
"(",
"70",
")",
"ip",
"=",
"message",
"[",
"4",
"..",
"-",
"3",
"]",
".",
"delete",
"(",
"\"\\0\"",
")",
"port",
"=",
"message",
"[",
"-",
"2",
"..",
"-",
"1",
"]",
".",
"to_i",
"[",
"ip",
",",
"port",
"]",
"end"
] |
Waits for a UDP discovery reply, and returns the sent data.
@return [Array(String, Integer)] the IP and port received from the discovery reply.
|
[
"Waits",
"for",
"a",
"UDP",
"discovery",
"reply",
"and",
"returns",
"the",
"sent",
"data",
"."
] |
764298a1ff0be69a1853b510d736f21c2b91a2fe
|
https://github.com/meew0/discordrb/blob/764298a1ff0be69a1853b510d736f21c2b91a2fe/lib/discordrb/voice/network.rb#L62-L68
|
12,433
|
meew0/discordrb
|
lib/discordrb/voice/network.rb
|
Discordrb::Voice.VoiceUDP.send_audio
|
def send_audio(buf, sequence, time)
# Header of the audio packet
header = [0x80, 0x78, sequence, time, @ssrc].pack('CCnNN')
# Encrypt data, if necessary
buf = encrypt_audio(header, buf) if encrypted?
send_packet(header + buf)
end
|
ruby
|
def send_audio(buf, sequence, time)
# Header of the audio packet
header = [0x80, 0x78, sequence, time, @ssrc].pack('CCnNN')
# Encrypt data, if necessary
buf = encrypt_audio(header, buf) if encrypted?
send_packet(header + buf)
end
|
[
"def",
"send_audio",
"(",
"buf",
",",
"sequence",
",",
"time",
")",
"# Header of the audio packet",
"header",
"=",
"[",
"0x80",
",",
"0x78",
",",
"sequence",
",",
"time",
",",
"@ssrc",
"]",
".",
"pack",
"(",
"'CCnNN'",
")",
"# Encrypt data, if necessary",
"buf",
"=",
"encrypt_audio",
"(",
"header",
",",
"buf",
")",
"if",
"encrypted?",
"send_packet",
"(",
"header",
"+",
"buf",
")",
"end"
] |
Makes an audio packet from a buffer and sends it to Discord.
@param buf [String] The audio data to send, must be exactly one Opus frame
@param sequence [Integer] The packet sequence number, incremented by one for subsequent packets
@param time [Integer] When this packet should be played back, in no particular unit (essentially just the
sequence number multiplied by 960)
|
[
"Makes",
"an",
"audio",
"packet",
"from",
"a",
"buffer",
"and",
"sends",
"it",
"to",
"Discord",
"."
] |
764298a1ff0be69a1853b510d736f21c2b91a2fe
|
https://github.com/meew0/discordrb/blob/764298a1ff0be69a1853b510d736f21c2b91a2fe/lib/discordrb/voice/network.rb#L75-L83
|
12,434
|
meew0/discordrb
|
lib/discordrb/voice/network.rb
|
Discordrb::Voice.VoiceUDP.encrypt_audio
|
def encrypt_audio(header, buf)
raise 'No secret key found, despite encryption being enabled!' unless @secret_key
box = RbNaCl::SecretBox.new(@secret_key)
# The nonce is the header of the voice packet with 12 null bytes appended
nonce = header + ([0] * 12).pack('C*')
box.encrypt(nonce, buf)
end
|
ruby
|
def encrypt_audio(header, buf)
raise 'No secret key found, despite encryption being enabled!' unless @secret_key
box = RbNaCl::SecretBox.new(@secret_key)
# The nonce is the header of the voice packet with 12 null bytes appended
nonce = header + ([0] * 12).pack('C*')
box.encrypt(nonce, buf)
end
|
[
"def",
"encrypt_audio",
"(",
"header",
",",
"buf",
")",
"raise",
"'No secret key found, despite encryption being enabled!'",
"unless",
"@secret_key",
"box",
"=",
"RbNaCl",
"::",
"SecretBox",
".",
"new",
"(",
"@secret_key",
")",
"# The nonce is the header of the voice packet with 12 null bytes appended",
"nonce",
"=",
"header",
"+",
"(",
"[",
"0",
"]",
"*",
"12",
")",
".",
"pack",
"(",
"'C*'",
")",
"box",
".",
"encrypt",
"(",
"nonce",
",",
"buf",
")",
"end"
] |
Encrypts audio data using RbNaCl
@param header [String] The header of the packet, to be used as the nonce
@param buf [String] The encoded audio data to be encrypted
@return [String] the audio data, encrypted
|
[
"Encrypts",
"audio",
"data",
"using",
"RbNaCl"
] |
764298a1ff0be69a1853b510d736f21c2b91a2fe
|
https://github.com/meew0/discordrb/blob/764298a1ff0be69a1853b510d736f21c2b91a2fe/lib/discordrb/voice/network.rb#L101-L110
|
12,435
|
meew0/discordrb
|
lib/discordrb/commands/rate_limiter.rb
|
Discordrb::Commands.RateLimiter.rate_limited?
|
def rate_limited?(key, thing, increment: 1)
# Check whether the bucket actually exists
return false unless @buckets && @buckets[key]
@buckets[key].rate_limited?(thing, increment: increment)
end
|
ruby
|
def rate_limited?(key, thing, increment: 1)
# Check whether the bucket actually exists
return false unless @buckets && @buckets[key]
@buckets[key].rate_limited?(thing, increment: increment)
end
|
[
"def",
"rate_limited?",
"(",
"key",
",",
"thing",
",",
"increment",
":",
"1",
")",
"# Check whether the bucket actually exists",
"return",
"false",
"unless",
"@buckets",
"&&",
"@buckets",
"[",
"key",
"]",
"@buckets",
"[",
"key",
"]",
".",
"rate_limited?",
"(",
"thing",
",",
"increment",
":",
"increment",
")",
"end"
] |
Performs a rate limit request.
@param key [Symbol] Which bucket to perform the request for.
@param thing [#resolve_id, Integer, Symbol] What should be rate-limited.
@param increment (see Bucket#rate_limited?)
@see Bucket#rate_limited?
@return [Integer, false] How much time to wait or false if the request succeeded.
|
[
"Performs",
"a",
"rate",
"limit",
"request",
"."
] |
764298a1ff0be69a1853b510d736f21c2b91a2fe
|
https://github.com/meew0/discordrb/blob/764298a1ff0be69a1853b510d736f21c2b91a2fe/lib/discordrb/commands/rate_limiter.rb#L112-L117
|
12,436
|
meew0/discordrb
|
lib/discordrb/commands/rate_limiter.rb
|
Discordrb::Commands.Bucket.clean
|
def clean(rate_limit_time = nil)
rate_limit_time ||= Time.now
@bucket.delete_if do |_, limit_hash|
# Time limit has not run out
return false if @time_span && rate_limit_time < (limit_hash[:set_time] + @time_span)
# Delay has not run out
return false if @delay && rate_limit_time < (limit_hash[:last_time] + @delay)
true
end
end
|
ruby
|
def clean(rate_limit_time = nil)
rate_limit_time ||= Time.now
@bucket.delete_if do |_, limit_hash|
# Time limit has not run out
return false if @time_span && rate_limit_time < (limit_hash[:set_time] + @time_span)
# Delay has not run out
return false if @delay && rate_limit_time < (limit_hash[:last_time] + @delay)
true
end
end
|
[
"def",
"clean",
"(",
"rate_limit_time",
"=",
"nil",
")",
"rate_limit_time",
"||=",
"Time",
".",
"now",
"@bucket",
".",
"delete_if",
"do",
"|",
"_",
",",
"limit_hash",
"|",
"# Time limit has not run out",
"return",
"false",
"if",
"@time_span",
"&&",
"rate_limit_time",
"<",
"(",
"limit_hash",
"[",
":set_time",
"]",
"+",
"@time_span",
")",
"# Delay has not run out",
"return",
"false",
"if",
"@delay",
"&&",
"rate_limit_time",
"<",
"(",
"limit_hash",
"[",
":last_time",
"]",
"+",
"@delay",
")",
"true",
"end",
"end"
] |
Makes a new bucket
@param limit [Integer, nil] How many requests the user may perform in the given time_span, or nil if there should be no limit.
@param time_span [Integer, nil] The time span after which the request count is reset, in seconds, or nil if the bucket should never be reset. (If this is nil, limit should be nil too)
@param delay [Integer, nil] The delay for which the user has to wait after performing a request, in seconds, or nil if the user shouldn't have to wait.
Cleans the bucket, removing all elements that aren't necessary anymore
@param rate_limit_time [Time] The time to base the cleaning on, only useful for testing.
|
[
"Makes",
"a",
"new",
"bucket"
] |
764298a1ff0be69a1853b510d736f21c2b91a2fe
|
https://github.com/meew0/discordrb/blob/764298a1ff0be69a1853b510d736f21c2b91a2fe/lib/discordrb/commands/rate_limiter.rb#L23-L35
|
12,437
|
meew0/discordrb
|
lib/discordrb/commands/rate_limiter.rb
|
Discordrb::Commands.Bucket.rate_limited?
|
def rate_limited?(thing, rate_limit_time = nil, increment: 1)
key = resolve_key thing
limit_hash = @bucket[key]
# First case: limit_hash doesn't exist yet
unless limit_hash
@bucket[key] = {
last_time: Time.now,
set_time: Time.now,
count: increment
}
return false
end
# Define the time at which we're being rate limited once so it doesn't get inaccurate
rate_limit_time ||= Time.now
if @limit && (limit_hash[:count] + increment) > @limit
# Second case: Count is over the limit and the time has not run out yet
return (limit_hash[:set_time] + @time_span) - rate_limit_time if @time_span && rate_limit_time < (limit_hash[:set_time] + @time_span)
# Third case: Count is over the limit but the time has run out
# Don't return anything here because there may still be delay-based limiting
limit_hash[:set_time] = rate_limit_time
limit_hash[:count] = 0
end
if @delay && rate_limit_time < (limit_hash[:last_time] + @delay)
# Fourth case: we're being delayed
(limit_hash[:last_time] + @delay) - rate_limit_time
else
# Fifth case: no rate limiting at all! Increment the count, set the last_time, and return false
limit_hash[:last_time] = rate_limit_time
limit_hash[:count] += increment
false
end
end
|
ruby
|
def rate_limited?(thing, rate_limit_time = nil, increment: 1)
key = resolve_key thing
limit_hash = @bucket[key]
# First case: limit_hash doesn't exist yet
unless limit_hash
@bucket[key] = {
last_time: Time.now,
set_time: Time.now,
count: increment
}
return false
end
# Define the time at which we're being rate limited once so it doesn't get inaccurate
rate_limit_time ||= Time.now
if @limit && (limit_hash[:count] + increment) > @limit
# Second case: Count is over the limit and the time has not run out yet
return (limit_hash[:set_time] + @time_span) - rate_limit_time if @time_span && rate_limit_time < (limit_hash[:set_time] + @time_span)
# Third case: Count is over the limit but the time has run out
# Don't return anything here because there may still be delay-based limiting
limit_hash[:set_time] = rate_limit_time
limit_hash[:count] = 0
end
if @delay && rate_limit_time < (limit_hash[:last_time] + @delay)
# Fourth case: we're being delayed
(limit_hash[:last_time] + @delay) - rate_limit_time
else
# Fifth case: no rate limiting at all! Increment the count, set the last_time, and return false
limit_hash[:last_time] = rate_limit_time
limit_hash[:count] += increment
false
end
end
|
[
"def",
"rate_limited?",
"(",
"thing",
",",
"rate_limit_time",
"=",
"nil",
",",
"increment",
":",
"1",
")",
"key",
"=",
"resolve_key",
"thing",
"limit_hash",
"=",
"@bucket",
"[",
"key",
"]",
"# First case: limit_hash doesn't exist yet",
"unless",
"limit_hash",
"@bucket",
"[",
"key",
"]",
"=",
"{",
"last_time",
":",
"Time",
".",
"now",
",",
"set_time",
":",
"Time",
".",
"now",
",",
"count",
":",
"increment",
"}",
"return",
"false",
"end",
"# Define the time at which we're being rate limited once so it doesn't get inaccurate",
"rate_limit_time",
"||=",
"Time",
".",
"now",
"if",
"@limit",
"&&",
"(",
"limit_hash",
"[",
":count",
"]",
"+",
"increment",
")",
">",
"@limit",
"# Second case: Count is over the limit and the time has not run out yet",
"return",
"(",
"limit_hash",
"[",
":set_time",
"]",
"+",
"@time_span",
")",
"-",
"rate_limit_time",
"if",
"@time_span",
"&&",
"rate_limit_time",
"<",
"(",
"limit_hash",
"[",
":set_time",
"]",
"+",
"@time_span",
")",
"# Third case: Count is over the limit but the time has run out",
"# Don't return anything here because there may still be delay-based limiting",
"limit_hash",
"[",
":set_time",
"]",
"=",
"rate_limit_time",
"limit_hash",
"[",
":count",
"]",
"=",
"0",
"end",
"if",
"@delay",
"&&",
"rate_limit_time",
"<",
"(",
"limit_hash",
"[",
":last_time",
"]",
"+",
"@delay",
")",
"# Fourth case: we're being delayed",
"(",
"limit_hash",
"[",
":last_time",
"]",
"+",
"@delay",
")",
"-",
"rate_limit_time",
"else",
"# Fifth case: no rate limiting at all! Increment the count, set the last_time, and return false",
"limit_hash",
"[",
":last_time",
"]",
"=",
"rate_limit_time",
"limit_hash",
"[",
":count",
"]",
"+=",
"increment",
"false",
"end",
"end"
] |
Performs a rate limiting request
@param thing [#resolve_id, Integer, Symbol] The particular thing that should be rate-limited (usually a user/channel, but you can also choose arbitrary integers or symbols)
@param rate_limit_time [Time] The time to base the rate limiting on, only useful for testing.
@param increment [Integer] How much to increment the rate-limit counter. Default is 1.
@return [Integer, false] the waiting time until the next request, in seconds, or false if the request succeeded
|
[
"Performs",
"a",
"rate",
"limiting",
"request"
] |
764298a1ff0be69a1853b510d736f21c2b91a2fe
|
https://github.com/meew0/discordrb/blob/764298a1ff0be69a1853b510d736f21c2b91a2fe/lib/discordrb/commands/rate_limiter.rb#L42-L79
|
12,438
|
meew0/discordrb
|
lib/discordrb/gateway.rb
|
Discordrb.Gateway.run_async
|
def run_async
@ws_thread = Thread.new do
Thread.current[:discordrb_name] = 'websocket'
connect_loop
LOGGER.warn('The WS loop exited! Not sure if this is a good thing')
end
LOGGER.debug('WS thread created! Now waiting for confirmation that everything worked')
sleep(0.5) until @ws_success
LOGGER.debug('Confirmation received! Exiting run.')
end
|
ruby
|
def run_async
@ws_thread = Thread.new do
Thread.current[:discordrb_name] = 'websocket'
connect_loop
LOGGER.warn('The WS loop exited! Not sure if this is a good thing')
end
LOGGER.debug('WS thread created! Now waiting for confirmation that everything worked')
sleep(0.5) until @ws_success
LOGGER.debug('Confirmation received! Exiting run.')
end
|
[
"def",
"run_async",
"@ws_thread",
"=",
"Thread",
".",
"new",
"do",
"Thread",
".",
"current",
"[",
":discordrb_name",
"]",
"=",
"'websocket'",
"connect_loop",
"LOGGER",
".",
"warn",
"(",
"'The WS loop exited! Not sure if this is a good thing'",
")",
"end",
"LOGGER",
".",
"debug",
"(",
"'WS thread created! Now waiting for confirmation that everything worked'",
")",
"sleep",
"(",
"0.5",
")",
"until",
"@ws_success",
"LOGGER",
".",
"debug",
"(",
"'Confirmation received! Exiting run.'",
")",
"end"
] |
Connect to the gateway server in a separate thread
|
[
"Connect",
"to",
"the",
"gateway",
"server",
"in",
"a",
"separate",
"thread"
] |
764298a1ff0be69a1853b510d736f21c2b91a2fe
|
https://github.com/meew0/discordrb/blob/764298a1ff0be69a1853b510d736f21c2b91a2fe/lib/discordrb/gateway.rb#L163-L173
|
12,439
|
meew0/discordrb
|
lib/discordrb/gateway.rb
|
Discordrb.Gateway.send_packet
|
def send_packet(opcode, packet)
data = {
op: opcode,
d: packet
}
send(data.to_json)
end
|
ruby
|
def send_packet(opcode, packet)
data = {
op: opcode,
d: packet
}
send(data.to_json)
end
|
[
"def",
"send_packet",
"(",
"opcode",
",",
"packet",
")",
"data",
"=",
"{",
"op",
":",
"opcode",
",",
"d",
":",
"packet",
"}",
"send",
"(",
"data",
".",
"to_json",
")",
"end"
] |
Sends a custom packet over the connection. This can be useful to implement future yet unimplemented functionality
or for testing. You probably shouldn't use this unless you know what you're doing.
@param opcode [Integer] The opcode the packet should be sent as. Can be one of {Opcodes} or a custom value if
necessary.
@param packet [Object] Some arbitrary JSON-serialisable data that should be sent as the `d` field.
|
[
"Sends",
"a",
"custom",
"packet",
"over",
"the",
"connection",
".",
"This",
"can",
"be",
"useful",
"to",
"implement",
"future",
"yet",
"unimplemented",
"functionality",
"or",
"for",
"testing",
".",
"You",
"probably",
"shouldn",
"t",
"use",
"this",
"unless",
"you",
"know",
"what",
"you",
"re",
"doing",
"."
] |
764298a1ff0be69a1853b510d736f21c2b91a2fe
|
https://github.com/meew0/discordrb/blob/764298a1ff0be69a1853b510d736f21c2b91a2fe/lib/discordrb/gateway.rb#L406-L413
|
12,440
|
meew0/discordrb
|
lib/discordrb/gateway.rb
|
Discordrb.Gateway.obtain_socket
|
def obtain_socket(uri)
socket = TCPSocket.new(uri.host, uri.port || socket_port(uri))
if secure_uri?(uri)
ctx = OpenSSL::SSL::SSLContext.new
if ENV['DISCORDRB_SSL_VERIFY_NONE']
ctx.ssl_version = 'SSLv23'
ctx.verify_mode = OpenSSL::SSL::VERIFY_NONE # use VERIFY_PEER for verification
cert_store = OpenSSL::X509::Store.new
cert_store.set_default_paths
ctx.cert_store = cert_store
else
ctx.set_params ssl_version: :TLSv1_2
end
socket = OpenSSL::SSL::SSLSocket.new(socket, ctx)
socket.connect
end
socket
end
|
ruby
|
def obtain_socket(uri)
socket = TCPSocket.new(uri.host, uri.port || socket_port(uri))
if secure_uri?(uri)
ctx = OpenSSL::SSL::SSLContext.new
if ENV['DISCORDRB_SSL_VERIFY_NONE']
ctx.ssl_version = 'SSLv23'
ctx.verify_mode = OpenSSL::SSL::VERIFY_NONE # use VERIFY_PEER for verification
cert_store = OpenSSL::X509::Store.new
cert_store.set_default_paths
ctx.cert_store = cert_store
else
ctx.set_params ssl_version: :TLSv1_2
end
socket = OpenSSL::SSL::SSLSocket.new(socket, ctx)
socket.connect
end
socket
end
|
[
"def",
"obtain_socket",
"(",
"uri",
")",
"socket",
"=",
"TCPSocket",
".",
"new",
"(",
"uri",
".",
"host",
",",
"uri",
".",
"port",
"||",
"socket_port",
"(",
"uri",
")",
")",
"if",
"secure_uri?",
"(",
"uri",
")",
"ctx",
"=",
"OpenSSL",
"::",
"SSL",
"::",
"SSLContext",
".",
"new",
"if",
"ENV",
"[",
"'DISCORDRB_SSL_VERIFY_NONE'",
"]",
"ctx",
".",
"ssl_version",
"=",
"'SSLv23'",
"ctx",
".",
"verify_mode",
"=",
"OpenSSL",
"::",
"SSL",
"::",
"VERIFY_NONE",
"# use VERIFY_PEER for verification",
"cert_store",
"=",
"OpenSSL",
"::",
"X509",
"::",
"Store",
".",
"new",
"cert_store",
".",
"set_default_paths",
"ctx",
".",
"cert_store",
"=",
"cert_store",
"else",
"ctx",
".",
"set_params",
"ssl_version",
":",
":TLSv1_2",
"end",
"socket",
"=",
"OpenSSL",
"::",
"SSL",
"::",
"SSLSocket",
".",
"new",
"(",
"socket",
",",
"ctx",
")",
"socket",
".",
"connect",
"end",
"socket",
"end"
] |
Create and connect a socket using a URI
|
[
"Create",
"and",
"connect",
"a",
"socket",
"using",
"a",
"URI"
] |
764298a1ff0be69a1853b510d736f21c2b91a2fe
|
https://github.com/meew0/discordrb/blob/764298a1ff0be69a1853b510d736f21c2b91a2fe/lib/discordrb/gateway.rb#L489-L511
|
12,441
|
interagent/committee
|
lib/committee/schema_validator/hyper_schema/response_validator.rb
|
Committee.SchemaValidator::HyperSchema::ResponseValidator.target_schema
|
def target_schema(link)
if link.target_schema
link.target_schema
elsif legacy_hyper_schema_rel?(link)
link.parent
end
end
|
ruby
|
def target_schema(link)
if link.target_schema
link.target_schema
elsif legacy_hyper_schema_rel?(link)
link.parent
end
end
|
[
"def",
"target_schema",
"(",
"link",
")",
"if",
"link",
".",
"target_schema",
"link",
".",
"target_schema",
"elsif",
"legacy_hyper_schema_rel?",
"(",
"link",
")",
"link",
".",
"parent",
"end",
"end"
] |
Gets the target schema of a link. This is normally just the standard
response schema, but we allow some legacy behavior for hyper-schema links
tagged with rel=instances to instead use the schema of their parent
resource.
|
[
"Gets",
"the",
"target",
"schema",
"of",
"a",
"link",
".",
"This",
"is",
"normally",
"just",
"the",
"standard",
"response",
"schema",
"but",
"we",
"allow",
"some",
"legacy",
"behavior",
"for",
"hyper",
"-",
"schema",
"links",
"tagged",
"with",
"rel",
"=",
"instances",
"to",
"instead",
"use",
"the",
"schema",
"of",
"their",
"parent",
"resource",
"."
] |
810fadcea1bc1c529627d47325c1008b5c33b0a4
|
https://github.com/interagent/committee/blob/810fadcea1bc1c529627d47325c1008b5c33b0a4/lib/committee/schema_validator/hyper_schema/response_validator.rb#L69-L75
|
12,442
|
ffaker/ffaker
|
lib/ffaker/name_mx.rb
|
FFaker.NameMX.name
|
def name(gender = :any)
case gender
when :any then rand(0..1) == 0 ? name(:male) : name(:female)
when :male then fetch_sample(MALE_FIRST_NAMES)
when :female then fetch_sample(FEMALE_FIRST_NAMES)
else raise ArgumentError, 'Invalid gender, must be one of :any, :male, :female'
end
end
|
ruby
|
def name(gender = :any)
case gender
when :any then rand(0..1) == 0 ? name(:male) : name(:female)
when :male then fetch_sample(MALE_FIRST_NAMES)
when :female then fetch_sample(FEMALE_FIRST_NAMES)
else raise ArgumentError, 'Invalid gender, must be one of :any, :male, :female'
end
end
|
[
"def",
"name",
"(",
"gender",
"=",
":any",
")",
"case",
"gender",
"when",
":any",
"then",
"rand",
"(",
"0",
"..",
"1",
")",
"==",
"0",
"?",
"name",
"(",
":male",
")",
":",
"name",
"(",
":female",
")",
"when",
":male",
"then",
"fetch_sample",
"(",
"MALE_FIRST_NAMES",
")",
"when",
":female",
"then",
"fetch_sample",
"(",
"FEMALE_FIRST_NAMES",
")",
"else",
"raise",
"ArgumentError",
",",
"'Invalid gender, must be one of :any, :male, :female'",
"end",
"end"
] |
A single name according to gender parameter
|
[
"A",
"single",
"name",
"according",
"to",
"gender",
"parameter"
] |
9570ac54874fec66a99b9c86401fb878f1e3e951
|
https://github.com/ffaker/ffaker/blob/9570ac54874fec66a99b9c86401fb878f1e3e951/lib/ffaker/name_mx.rb#L71-L78
|
12,443
|
ffaker/ffaker
|
lib/ffaker/phone_number_de.rb
|
FFaker.PhoneNumberDE.mobile_prefix
|
def mobile_prefix(leading_zero = true)
mobile_prefix = '1' + rand(5..7).to_s + rand(0..9).to_s
mobile_prefix = '0' + mobile_prefix if leading_zero
mobile_prefix
end
|
ruby
|
def mobile_prefix(leading_zero = true)
mobile_prefix = '1' + rand(5..7).to_s + rand(0..9).to_s
mobile_prefix = '0' + mobile_prefix if leading_zero
mobile_prefix
end
|
[
"def",
"mobile_prefix",
"(",
"leading_zero",
"=",
"true",
")",
"mobile_prefix",
"=",
"'1'",
"+",
"rand",
"(",
"5",
"..",
"7",
")",
".",
"to_s",
"+",
"rand",
"(",
"0",
"..",
"9",
")",
".",
"to_s",
"mobile_prefix",
"=",
"'0'",
"+",
"mobile_prefix",
"if",
"leading_zero",
"mobile_prefix",
"end"
] |
Mobile prefixes are in the 015x, 016x, 017x ranges
|
[
"Mobile",
"prefixes",
"are",
"in",
"the",
"015x",
"016x",
"017x",
"ranges"
] |
9570ac54874fec66a99b9c86401fb878f1e3e951
|
https://github.com/ffaker/ffaker/blob/9570ac54874fec66a99b9c86401fb878f1e3e951/lib/ffaker/phone_number_de.rb#L10-L14
|
12,444
|
minimagick/minimagick
|
lib/mini_magick/image.rb
|
MiniMagick.Image.validate!
|
def validate!
identify
rescue MiniMagick::Error => error
raise MiniMagick::Invalid, error.message
end
|
ruby
|
def validate!
identify
rescue MiniMagick::Error => error
raise MiniMagick::Invalid, error.message
end
|
[
"def",
"validate!",
"identify",
"rescue",
"MiniMagick",
"::",
"Error",
"=>",
"error",
"raise",
"MiniMagick",
"::",
"Invalid",
",",
"error",
".",
"message",
"end"
] |
Runs `identify` on the current image, and raises an error if it doesn't
pass.
@raise [MiniMagick::Invalid]
|
[
"Runs",
"identify",
"on",
"the",
"current",
"image",
"and",
"raises",
"an",
"error",
"if",
"it",
"doesn",
"t",
"pass",
"."
] |
d484786f35e91f107836d3c86aca61d50a35820b
|
https://github.com/minimagick/minimagick/blob/d484786f35e91f107836d3c86aca61d50a35820b/lib/mini_magick/image.rb#L205-L209
|
12,445
|
minimagick/minimagick
|
lib/mini_magick/image.rb
|
MiniMagick.Image.format
|
def format(format, page = 0, read_opts={})
if @tempfile
new_tempfile = MiniMagick::Utilities.tempfile(".#{format}")
new_path = new_tempfile.path
else
new_path = Pathname(path).sub_ext(".#{format}").to_s
end
input_path = path.dup
input_path << "[#{page}]" if page && !layer?
MiniMagick::Tool::Convert.new do |convert|
read_opts.each do |opt, val|
convert.send(opt.to_s, val)
end
convert << input_path
yield convert if block_given?
convert << new_path
end
if @tempfile
destroy!
@tempfile = new_tempfile
else
File.delete(path) unless path == new_path || layer?
end
path.replace new_path
@info.clear
self
end
|
ruby
|
def format(format, page = 0, read_opts={})
if @tempfile
new_tempfile = MiniMagick::Utilities.tempfile(".#{format}")
new_path = new_tempfile.path
else
new_path = Pathname(path).sub_ext(".#{format}").to_s
end
input_path = path.dup
input_path << "[#{page}]" if page && !layer?
MiniMagick::Tool::Convert.new do |convert|
read_opts.each do |opt, val|
convert.send(opt.to_s, val)
end
convert << input_path
yield convert if block_given?
convert << new_path
end
if @tempfile
destroy!
@tempfile = new_tempfile
else
File.delete(path) unless path == new_path || layer?
end
path.replace new_path
@info.clear
self
end
|
[
"def",
"format",
"(",
"format",
",",
"page",
"=",
"0",
",",
"read_opts",
"=",
"{",
"}",
")",
"if",
"@tempfile",
"new_tempfile",
"=",
"MiniMagick",
"::",
"Utilities",
".",
"tempfile",
"(",
"\".#{format}\"",
")",
"new_path",
"=",
"new_tempfile",
".",
"path",
"else",
"new_path",
"=",
"Pathname",
"(",
"path",
")",
".",
"sub_ext",
"(",
"\".#{format}\"",
")",
".",
"to_s",
"end",
"input_path",
"=",
"path",
".",
"dup",
"input_path",
"<<",
"\"[#{page}]\"",
"if",
"page",
"&&",
"!",
"layer?",
"MiniMagick",
"::",
"Tool",
"::",
"Convert",
".",
"new",
"do",
"|",
"convert",
"|",
"read_opts",
".",
"each",
"do",
"|",
"opt",
",",
"val",
"|",
"convert",
".",
"send",
"(",
"opt",
".",
"to_s",
",",
"val",
")",
"end",
"convert",
"<<",
"input_path",
"yield",
"convert",
"if",
"block_given?",
"convert",
"<<",
"new_path",
"end",
"if",
"@tempfile",
"destroy!",
"@tempfile",
"=",
"new_tempfile",
"else",
"File",
".",
"delete",
"(",
"path",
")",
"unless",
"path",
"==",
"new_path",
"||",
"layer?",
"end",
"path",
".",
"replace",
"new_path",
"@info",
".",
"clear",
"self",
"end"
] |
This is used to change the format of the image. That is, from "tiff to
jpg" or something like that. Once you run it, the instance is pointing to
a new file with a new extension!
*DANGER*: This renames the file that the instance is pointing to. So, if
you manually opened the file with Image.new(file_path)... Then that file
is DELETED! If you used Image.open(file) then you are OK. The original
file will still be there. But, any changes to it might not be...
Formatting an animation into a non-animated type will result in
ImageMagick creating multiple pages (starting with 0). You can choose
which page you want to manipulate. We default to the first page.
If you would like to convert between animated formats, pass nil as your
page and ImageMagick will copy all of the pages.
@param format [String] The target format... Like 'jpg', 'gif', 'tiff' etc.
@param page [Integer] If this is an animated gif, say which 'page' you
want with an integer. Default 0 will convert only the first page; 'nil'
will convert all pages.
@param read_opts [Hash] Any read options to be passed to ImageMagick
for example: image.format('jpg', page, {density: '300'})
@yield [MiniMagick::Tool::Convert] It optionally yields the command,
if you want to add something.
@return [self]
|
[
"This",
"is",
"used",
"to",
"change",
"the",
"format",
"of",
"the",
"image",
".",
"That",
"is",
"from",
"tiff",
"to",
"jpg",
"or",
"something",
"like",
"that",
".",
"Once",
"you",
"run",
"it",
"the",
"instance",
"is",
"pointing",
"to",
"a",
"new",
"file",
"with",
"a",
"new",
"extension!"
] |
d484786f35e91f107836d3c86aca61d50a35820b
|
https://github.com/minimagick/minimagick/blob/d484786f35e91f107836d3c86aca61d50a35820b/lib/mini_magick/image.rb#L395-L426
|
12,446
|
minimagick/minimagick
|
lib/mini_magick/image.rb
|
MiniMagick.Image.identify
|
def identify
MiniMagick::Tool::Identify.new do |builder|
yield builder if block_given?
builder << path
end
end
|
ruby
|
def identify
MiniMagick::Tool::Identify.new do |builder|
yield builder if block_given?
builder << path
end
end
|
[
"def",
"identify",
"MiniMagick",
"::",
"Tool",
"::",
"Identify",
".",
"new",
"do",
"|",
"builder",
"|",
"yield",
"builder",
"if",
"block_given?",
"builder",
"<<",
"path",
"end",
"end"
] |
Runs `identify` on itself. Accepts an optional block for adding more
options to `identify`.
@example
image = MiniMagick::Image.open("image.jpg")
image.identify do |b|
b.verbose
end # runs `identify -verbose image.jpg`
@return [String] Output from `identify`
@yield [MiniMagick::Tool::Identify]
|
[
"Runs",
"identify",
"on",
"itself",
".",
"Accepts",
"an",
"optional",
"block",
"for",
"adding",
"more",
"options",
"to",
"identify",
"."
] |
d484786f35e91f107836d3c86aca61d50a35820b
|
https://github.com/minimagick/minimagick/blob/d484786f35e91f107836d3c86aca61d50a35820b/lib/mini_magick/image.rb#L547-L552
|
12,447
|
excon/excon
|
lib/excon/utils.rb
|
Excon.Utils.redact
|
def redact(datum)
datum = datum.dup
if datum.has_key?(:headers) && datum[:headers].has_key?('Authorization')
datum[:headers] = datum[:headers].dup
datum[:headers]['Authorization'] = REDACTED
end
if datum.has_key?(:password)
datum[:password] = REDACTED
end
datum
end
|
ruby
|
def redact(datum)
datum = datum.dup
if datum.has_key?(:headers) && datum[:headers].has_key?('Authorization')
datum[:headers] = datum[:headers].dup
datum[:headers]['Authorization'] = REDACTED
end
if datum.has_key?(:password)
datum[:password] = REDACTED
end
datum
end
|
[
"def",
"redact",
"(",
"datum",
")",
"datum",
"=",
"datum",
".",
"dup",
"if",
"datum",
".",
"has_key?",
"(",
":headers",
")",
"&&",
"datum",
"[",
":headers",
"]",
".",
"has_key?",
"(",
"'Authorization'",
")",
"datum",
"[",
":headers",
"]",
"=",
"datum",
"[",
":headers",
"]",
".",
"dup",
"datum",
"[",
":headers",
"]",
"[",
"'Authorization'",
"]",
"=",
"REDACTED",
"end",
"if",
"datum",
".",
"has_key?",
"(",
":password",
")",
"datum",
"[",
":password",
"]",
"=",
"REDACTED",
"end",
"datum",
"end"
] |
Redact sensitive info from provided data
|
[
"Redact",
"sensitive",
"info",
"from",
"provided",
"data"
] |
d4975a8a5b49d5901a769b289fb5054a6d064f6d
|
https://github.com/excon/excon/blob/d4975a8a5b49d5901a769b289fb5054a6d064f6d/lib/excon/utils.rb#L31-L41
|
12,448
|
excon/excon
|
lib/excon/utils.rb
|
Excon.Utils.split_header_value
|
def split_header_value(str)
return [] if str.nil?
str = str.dup.strip
binary_encode(str)
str.scan(%r'\G((?:"(?:\\.|[^"])+?"|[^",]+)+)
(?:,\s*|\Z)'xn).flatten
end
|
ruby
|
def split_header_value(str)
return [] if str.nil?
str = str.dup.strip
binary_encode(str)
str.scan(%r'\G((?:"(?:\\.|[^"])+?"|[^",]+)+)
(?:,\s*|\Z)'xn).flatten
end
|
[
"def",
"split_header_value",
"(",
"str",
")",
"return",
"[",
"]",
"if",
"str",
".",
"nil?",
"str",
"=",
"str",
".",
"dup",
".",
"strip",
"binary_encode",
"(",
"str",
")",
"str",
".",
"scan",
"(",
"%r'",
"\\G",
"\\\\",
"\\s",
"\\Z",
"'xn",
")",
".",
"flatten",
"end"
] |
Splits a header value +str+ according to HTTP specification.
|
[
"Splits",
"a",
"header",
"value",
"+",
"str",
"+",
"according",
"to",
"HTTP",
"specification",
"."
] |
d4975a8a5b49d5901a769b289fb5054a6d064f6d
|
https://github.com/excon/excon/blob/d4975a8a5b49d5901a769b289fb5054a6d064f6d/lib/excon/utils.rb#L78-L84
|
12,449
|
excon/excon
|
lib/excon/utils.rb
|
Excon.Utils.escape_uri
|
def escape_uri(str)
str = str.dup
binary_encode(str)
str.gsub(UNESCAPED) { "%%%02X" % $1[0].ord }
end
|
ruby
|
def escape_uri(str)
str = str.dup
binary_encode(str)
str.gsub(UNESCAPED) { "%%%02X" % $1[0].ord }
end
|
[
"def",
"escape_uri",
"(",
"str",
")",
"str",
"=",
"str",
".",
"dup",
"binary_encode",
"(",
"str",
")",
"str",
".",
"gsub",
"(",
"UNESCAPED",
")",
"{",
"\"%%%02X\"",
"%",
"$1",
"[",
"0",
"]",
".",
"ord",
"}",
"end"
] |
Escapes HTTP reserved and unwise characters in +str+
|
[
"Escapes",
"HTTP",
"reserved",
"and",
"unwise",
"characters",
"in",
"+",
"str",
"+"
] |
d4975a8a5b49d5901a769b289fb5054a6d064f6d
|
https://github.com/excon/excon/blob/d4975a8a5b49d5901a769b289fb5054a6d064f6d/lib/excon/utils.rb#L87-L91
|
12,450
|
excon/excon
|
lib/excon/utils.rb
|
Excon.Utils.unescape_uri
|
def unescape_uri(str)
str = str.dup
binary_encode(str)
str.gsub(ESCAPED) { $1.hex.chr }
end
|
ruby
|
def unescape_uri(str)
str = str.dup
binary_encode(str)
str.gsub(ESCAPED) { $1.hex.chr }
end
|
[
"def",
"unescape_uri",
"(",
"str",
")",
"str",
"=",
"str",
".",
"dup",
"binary_encode",
"(",
"str",
")",
"str",
".",
"gsub",
"(",
"ESCAPED",
")",
"{",
"$1",
".",
"hex",
".",
"chr",
"}",
"end"
] |
Unescapes HTTP reserved and unwise characters in +str+
|
[
"Unescapes",
"HTTP",
"reserved",
"and",
"unwise",
"characters",
"in",
"+",
"str",
"+"
] |
d4975a8a5b49d5901a769b289fb5054a6d064f6d
|
https://github.com/excon/excon/blob/d4975a8a5b49d5901a769b289fb5054a6d064f6d/lib/excon/utils.rb#L94-L98
|
12,451
|
excon/excon
|
lib/excon/utils.rb
|
Excon.Utils.unescape_form
|
def unescape_form(str)
str = str.dup
binary_encode(str)
str.gsub!(/\+/, ' ')
str.gsub(ESCAPED) { $1.hex.chr }
end
|
ruby
|
def unescape_form(str)
str = str.dup
binary_encode(str)
str.gsub!(/\+/, ' ')
str.gsub(ESCAPED) { $1.hex.chr }
end
|
[
"def",
"unescape_form",
"(",
"str",
")",
"str",
"=",
"str",
".",
"dup",
"binary_encode",
"(",
"str",
")",
"str",
".",
"gsub!",
"(",
"/",
"\\+",
"/",
",",
"' '",
")",
"str",
".",
"gsub",
"(",
"ESCAPED",
")",
"{",
"$1",
".",
"hex",
".",
"chr",
"}",
"end"
] |
Unescape form encoded values in +str+
|
[
"Unescape",
"form",
"encoded",
"values",
"in",
"+",
"str",
"+"
] |
d4975a8a5b49d5901a769b289fb5054a6d064f6d
|
https://github.com/excon/excon/blob/d4975a8a5b49d5901a769b289fb5054a6d064f6d/lib/excon/utils.rb#L101-L106
|
12,452
|
excon/excon
|
lib/excon/connection.rb
|
Excon.Connection.request
|
def request(params={}, &block)
# @data has defaults, merge in new params to override
datum = @data.merge(params)
datum[:headers] = @data[:headers].merge(datum[:headers] || {})
validate_params(:request, params, datum[:middlewares])
# If the user passed in new middleware, we want to validate that the original connection parameters
# are still valid with the provided middleware.
if params[:middlewares]
validate_params(:connection, @data, datum[:middlewares])
end
if datum[:user] || datum[:password]
user, pass = Utils.unescape_uri(datum[:user].to_s), Utils.unescape_uri(datum[:password].to_s)
datum[:headers]['Authorization'] ||= 'Basic ' + ["#{user}:#{pass}"].pack('m').delete(Excon::CR_NL)
end
if datum[:scheme] == UNIX
datum[:headers]['Host'] ||= ''
else
datum[:headers]['Host'] ||= datum[:host] + port_string(datum)
end
# if path is empty or doesn't start with '/', insert one
unless datum[:path][0, 1] == '/'
datum[:path] = datum[:path].dup.insert(0, '/')
end
if block_given?
Excon.display_warning('Excon requests with a block are deprecated, pass :response_block instead.')
datum[:response_block] = Proc.new
end
datum[:connection] = self
datum[:stack] = datum[:middlewares].map do |middleware|
lambda {|stack| middleware.new(stack)}
end.reverse.inject(self) do |middlewares, middleware|
middleware.call(middlewares)
end
datum = datum[:stack].request_call(datum)
unless datum[:pipeline]
datum = response(datum)
if datum[:persistent]
if key = datum[:response][:headers].keys.detect {|k| k.casecmp('Connection') == 0 }
if datum[:response][:headers][key].casecmp('close') == 0
reset
end
end
else
reset
end
Excon::Response.new(datum[:response])
else
datum
end
rescue => error
reset
# If we didn't get far enough to initialize datum and the middleware stack, just raise
raise error if !datum
datum[:error] = error
if datum[:stack]
datum[:stack].error_call(datum)
else
raise error
end
end
|
ruby
|
def request(params={}, &block)
# @data has defaults, merge in new params to override
datum = @data.merge(params)
datum[:headers] = @data[:headers].merge(datum[:headers] || {})
validate_params(:request, params, datum[:middlewares])
# If the user passed in new middleware, we want to validate that the original connection parameters
# are still valid with the provided middleware.
if params[:middlewares]
validate_params(:connection, @data, datum[:middlewares])
end
if datum[:user] || datum[:password]
user, pass = Utils.unescape_uri(datum[:user].to_s), Utils.unescape_uri(datum[:password].to_s)
datum[:headers]['Authorization'] ||= 'Basic ' + ["#{user}:#{pass}"].pack('m').delete(Excon::CR_NL)
end
if datum[:scheme] == UNIX
datum[:headers]['Host'] ||= ''
else
datum[:headers]['Host'] ||= datum[:host] + port_string(datum)
end
# if path is empty or doesn't start with '/', insert one
unless datum[:path][0, 1] == '/'
datum[:path] = datum[:path].dup.insert(0, '/')
end
if block_given?
Excon.display_warning('Excon requests with a block are deprecated, pass :response_block instead.')
datum[:response_block] = Proc.new
end
datum[:connection] = self
datum[:stack] = datum[:middlewares].map do |middleware|
lambda {|stack| middleware.new(stack)}
end.reverse.inject(self) do |middlewares, middleware|
middleware.call(middlewares)
end
datum = datum[:stack].request_call(datum)
unless datum[:pipeline]
datum = response(datum)
if datum[:persistent]
if key = datum[:response][:headers].keys.detect {|k| k.casecmp('Connection') == 0 }
if datum[:response][:headers][key].casecmp('close') == 0
reset
end
end
else
reset
end
Excon::Response.new(datum[:response])
else
datum
end
rescue => error
reset
# If we didn't get far enough to initialize datum and the middleware stack, just raise
raise error if !datum
datum[:error] = error
if datum[:stack]
datum[:stack].error_call(datum)
else
raise error
end
end
|
[
"def",
"request",
"(",
"params",
"=",
"{",
"}",
",",
"&",
"block",
")",
"# @data has defaults, merge in new params to override",
"datum",
"=",
"@data",
".",
"merge",
"(",
"params",
")",
"datum",
"[",
":headers",
"]",
"=",
"@data",
"[",
":headers",
"]",
".",
"merge",
"(",
"datum",
"[",
":headers",
"]",
"||",
"{",
"}",
")",
"validate_params",
"(",
":request",
",",
"params",
",",
"datum",
"[",
":middlewares",
"]",
")",
"# If the user passed in new middleware, we want to validate that the original connection parameters",
"# are still valid with the provided middleware.",
"if",
"params",
"[",
":middlewares",
"]",
"validate_params",
"(",
":connection",
",",
"@data",
",",
"datum",
"[",
":middlewares",
"]",
")",
"end",
"if",
"datum",
"[",
":user",
"]",
"||",
"datum",
"[",
":password",
"]",
"user",
",",
"pass",
"=",
"Utils",
".",
"unescape_uri",
"(",
"datum",
"[",
":user",
"]",
".",
"to_s",
")",
",",
"Utils",
".",
"unescape_uri",
"(",
"datum",
"[",
":password",
"]",
".",
"to_s",
")",
"datum",
"[",
":headers",
"]",
"[",
"'Authorization'",
"]",
"||=",
"'Basic '",
"+",
"[",
"\"#{user}:#{pass}\"",
"]",
".",
"pack",
"(",
"'m'",
")",
".",
"delete",
"(",
"Excon",
"::",
"CR_NL",
")",
"end",
"if",
"datum",
"[",
":scheme",
"]",
"==",
"UNIX",
"datum",
"[",
":headers",
"]",
"[",
"'Host'",
"]",
"||=",
"''",
"else",
"datum",
"[",
":headers",
"]",
"[",
"'Host'",
"]",
"||=",
"datum",
"[",
":host",
"]",
"+",
"port_string",
"(",
"datum",
")",
"end",
"# if path is empty or doesn't start with '/', insert one",
"unless",
"datum",
"[",
":path",
"]",
"[",
"0",
",",
"1",
"]",
"==",
"'/'",
"datum",
"[",
":path",
"]",
"=",
"datum",
"[",
":path",
"]",
".",
"dup",
".",
"insert",
"(",
"0",
",",
"'/'",
")",
"end",
"if",
"block_given?",
"Excon",
".",
"display_warning",
"(",
"'Excon requests with a block are deprecated, pass :response_block instead.'",
")",
"datum",
"[",
":response_block",
"]",
"=",
"Proc",
".",
"new",
"end",
"datum",
"[",
":connection",
"]",
"=",
"self",
"datum",
"[",
":stack",
"]",
"=",
"datum",
"[",
":middlewares",
"]",
".",
"map",
"do",
"|",
"middleware",
"|",
"lambda",
"{",
"|",
"stack",
"|",
"middleware",
".",
"new",
"(",
"stack",
")",
"}",
"end",
".",
"reverse",
".",
"inject",
"(",
"self",
")",
"do",
"|",
"middlewares",
",",
"middleware",
"|",
"middleware",
".",
"call",
"(",
"middlewares",
")",
"end",
"datum",
"=",
"datum",
"[",
":stack",
"]",
".",
"request_call",
"(",
"datum",
")",
"unless",
"datum",
"[",
":pipeline",
"]",
"datum",
"=",
"response",
"(",
"datum",
")",
"if",
"datum",
"[",
":persistent",
"]",
"if",
"key",
"=",
"datum",
"[",
":response",
"]",
"[",
":headers",
"]",
".",
"keys",
".",
"detect",
"{",
"|",
"k",
"|",
"k",
".",
"casecmp",
"(",
"'Connection'",
")",
"==",
"0",
"}",
"if",
"datum",
"[",
":response",
"]",
"[",
":headers",
"]",
"[",
"key",
"]",
".",
"casecmp",
"(",
"'close'",
")",
"==",
"0",
"reset",
"end",
"end",
"else",
"reset",
"end",
"Excon",
"::",
"Response",
".",
"new",
"(",
"datum",
"[",
":response",
"]",
")",
"else",
"datum",
"end",
"rescue",
"=>",
"error",
"reset",
"# If we didn't get far enough to initialize datum and the middleware stack, just raise",
"raise",
"error",
"if",
"!",
"datum",
"datum",
"[",
":error",
"]",
"=",
"error",
"if",
"datum",
"[",
":stack",
"]",
"datum",
"[",
":stack",
"]",
".",
"error_call",
"(",
"datum",
")",
"else",
"raise",
"error",
"end",
"end"
] |
Sends the supplied request to the destination host.
@yield [chunk] @see Response#self.parse
@param [Hash<Symbol, >] params One or more optional params, override defaults set in Connection.new
@option params [String] :body text to be sent over a socket
@option params [Hash<Symbol, String>] :headers The default headers to supply in a request
@option params [String] :path appears after 'scheme://host:port/'
@option params [Hash] :query appended to the 'scheme://host:port/path/' in the form of '?key=value'
|
[
"Sends",
"the",
"supplied",
"request",
"to",
"the",
"destination",
"host",
"."
] |
d4975a8a5b49d5901a769b289fb5054a6d064f6d
|
https://github.com/excon/excon/blob/d4975a8a5b49d5901a769b289fb5054a6d064f6d/lib/excon/connection.rb#L230-L301
|
12,453
|
excon/excon
|
lib/excon/connection.rb
|
Excon.Connection.requests
|
def requests(pipeline_params)
pipeline_params.each {|params| params.merge!(:pipeline => true, :persistent => true) }
pipeline_params.last.merge!(:persistent => @data[:persistent])
responses = pipeline_params.map do |params|
request(params)
end.map do |datum|
Excon::Response.new(response(datum)[:response])
end
if @data[:persistent]
if key = responses.last[:headers].keys.detect {|k| k.casecmp('Connection') == 0 }
if responses.last[:headers][key].casecmp('close') == 0
reset
end
end
else
reset
end
responses
end
|
ruby
|
def requests(pipeline_params)
pipeline_params.each {|params| params.merge!(:pipeline => true, :persistent => true) }
pipeline_params.last.merge!(:persistent => @data[:persistent])
responses = pipeline_params.map do |params|
request(params)
end.map do |datum|
Excon::Response.new(response(datum)[:response])
end
if @data[:persistent]
if key = responses.last[:headers].keys.detect {|k| k.casecmp('Connection') == 0 }
if responses.last[:headers][key].casecmp('close') == 0
reset
end
end
else
reset
end
responses
end
|
[
"def",
"requests",
"(",
"pipeline_params",
")",
"pipeline_params",
".",
"each",
"{",
"|",
"params",
"|",
"params",
".",
"merge!",
"(",
":pipeline",
"=>",
"true",
",",
":persistent",
"=>",
"true",
")",
"}",
"pipeline_params",
".",
"last",
".",
"merge!",
"(",
":persistent",
"=>",
"@data",
"[",
":persistent",
"]",
")",
"responses",
"=",
"pipeline_params",
".",
"map",
"do",
"|",
"params",
"|",
"request",
"(",
"params",
")",
"end",
".",
"map",
"do",
"|",
"datum",
"|",
"Excon",
"::",
"Response",
".",
"new",
"(",
"response",
"(",
"datum",
")",
"[",
":response",
"]",
")",
"end",
"if",
"@data",
"[",
":persistent",
"]",
"if",
"key",
"=",
"responses",
".",
"last",
"[",
":headers",
"]",
".",
"keys",
".",
"detect",
"{",
"|",
"k",
"|",
"k",
".",
"casecmp",
"(",
"'Connection'",
")",
"==",
"0",
"}",
"if",
"responses",
".",
"last",
"[",
":headers",
"]",
"[",
"key",
"]",
".",
"casecmp",
"(",
"'close'",
")",
"==",
"0",
"reset",
"end",
"end",
"else",
"reset",
"end",
"responses",
"end"
] |
Sends the supplied requests to the destination host using pipelining.
@pipeline_params [Array<Hash>] pipeline_params An array of one or more optional params, override defaults set in Connection.new, see #request for details
|
[
"Sends",
"the",
"supplied",
"requests",
"to",
"the",
"destination",
"host",
"using",
"pipelining",
"."
] |
d4975a8a5b49d5901a769b289fb5054a6d064f6d
|
https://github.com/excon/excon/blob/d4975a8a5b49d5901a769b289fb5054a6d064f6d/lib/excon/connection.rb#L305-L326
|
12,454
|
excon/excon
|
lib/excon/connection.rb
|
Excon.Connection.batch_requests
|
def batch_requests(pipeline_params, limit = nil)
limit ||= Process.respond_to?(:getrlimit) ? Process.getrlimit(:NOFILE).first : 256
responses = []
pipeline_params.each_slice(limit) do |params|
responses.concat(requests(params))
end
responses
end
|
ruby
|
def batch_requests(pipeline_params, limit = nil)
limit ||= Process.respond_to?(:getrlimit) ? Process.getrlimit(:NOFILE).first : 256
responses = []
pipeline_params.each_slice(limit) do |params|
responses.concat(requests(params))
end
responses
end
|
[
"def",
"batch_requests",
"(",
"pipeline_params",
",",
"limit",
"=",
"nil",
")",
"limit",
"||=",
"Process",
".",
"respond_to?",
"(",
":getrlimit",
")",
"?",
"Process",
".",
"getrlimit",
"(",
":NOFILE",
")",
".",
"first",
":",
"256",
"responses",
"=",
"[",
"]",
"pipeline_params",
".",
"each_slice",
"(",
"limit",
")",
"do",
"|",
"params",
"|",
"responses",
".",
"concat",
"(",
"requests",
"(",
"params",
")",
")",
"end",
"responses",
"end"
] |
Sends the supplied requests to the destination host using pipelining in
batches of @limit [Numeric] requests. This is your soft file descriptor
limit by default, typically 256.
@pipeline_params [Array<Hash>] pipeline_params An array of one or more optional params, override defaults set in Connection.new, see #request for details
|
[
"Sends",
"the",
"supplied",
"requests",
"to",
"the",
"destination",
"host",
"using",
"pipelining",
"in",
"batches",
"of"
] |
d4975a8a5b49d5901a769b289fb5054a6d064f6d
|
https://github.com/excon/excon/blob/d4975a8a5b49d5901a769b289fb5054a6d064f6d/lib/excon/connection.rb#L332-L341
|
12,455
|
cucumber/aruba
|
lib/aruba/console.rb
|
Aruba.Console.start
|
def start
# Start IRB with current context:
# http://stackoverflow.com/questions/4189818/how-to-run-irb-start-in-context-of-current-class
ARGV.clear
IRB.setup nil
IRB.conf[:IRB_NAME] = 'aruba'
IRB.conf[:PROMPT] = {}
IRB.conf[:PROMPT][:ARUBA] = {
PROMPT_I: '%N:%03n:%i> ',
PROMPT_S: '%N:%03n:%i%l ',
PROMPT_C: '%N:%03n:%i* ',
RETURN: "# => %s\n"
}
IRB.conf[:PROMPT_MODE] = :ARUBA
IRB.conf[:RC] = false
require 'irb/completion'
require 'irb/ext/save-history'
IRB.conf[:READLINE] = true
IRB.conf[:SAVE_HISTORY] = 1000
IRB.conf[:HISTORY_FILE] = Aruba.config.console_history_file
context = Class.new do
include Aruba::Api
include Aruba::Console::Help
def initialize
setup_aruba
end
def inspect
'nil'
end
end
irb = IRB::Irb.new(IRB::WorkSpace.new(context.new))
IRB.conf[:MAIN_CONTEXT] = irb.context
trap("SIGINT") do
irb.signal_handle
end
begin
catch(:IRB_EXIT) do
irb.eval_input
end
ensure
IRB.irb_at_exit
end
end
|
ruby
|
def start
# Start IRB with current context:
# http://stackoverflow.com/questions/4189818/how-to-run-irb-start-in-context-of-current-class
ARGV.clear
IRB.setup nil
IRB.conf[:IRB_NAME] = 'aruba'
IRB.conf[:PROMPT] = {}
IRB.conf[:PROMPT][:ARUBA] = {
PROMPT_I: '%N:%03n:%i> ',
PROMPT_S: '%N:%03n:%i%l ',
PROMPT_C: '%N:%03n:%i* ',
RETURN: "# => %s\n"
}
IRB.conf[:PROMPT_MODE] = :ARUBA
IRB.conf[:RC] = false
require 'irb/completion'
require 'irb/ext/save-history'
IRB.conf[:READLINE] = true
IRB.conf[:SAVE_HISTORY] = 1000
IRB.conf[:HISTORY_FILE] = Aruba.config.console_history_file
context = Class.new do
include Aruba::Api
include Aruba::Console::Help
def initialize
setup_aruba
end
def inspect
'nil'
end
end
irb = IRB::Irb.new(IRB::WorkSpace.new(context.new))
IRB.conf[:MAIN_CONTEXT] = irb.context
trap("SIGINT") do
irb.signal_handle
end
begin
catch(:IRB_EXIT) do
irb.eval_input
end
ensure
IRB.irb_at_exit
end
end
|
[
"def",
"start",
"# Start IRB with current context:",
"# http://stackoverflow.com/questions/4189818/how-to-run-irb-start-in-context-of-current-class",
"ARGV",
".",
"clear",
"IRB",
".",
"setup",
"nil",
"IRB",
".",
"conf",
"[",
":IRB_NAME",
"]",
"=",
"'aruba'",
"IRB",
".",
"conf",
"[",
":PROMPT",
"]",
"=",
"{",
"}",
"IRB",
".",
"conf",
"[",
":PROMPT",
"]",
"[",
":ARUBA",
"]",
"=",
"{",
"PROMPT_I",
":",
"'%N:%03n:%i> '",
",",
"PROMPT_S",
":",
"'%N:%03n:%i%l '",
",",
"PROMPT_C",
":",
"'%N:%03n:%i* '",
",",
"RETURN",
":",
"\"# => %s\\n\"",
"}",
"IRB",
".",
"conf",
"[",
":PROMPT_MODE",
"]",
"=",
":ARUBA",
"IRB",
".",
"conf",
"[",
":RC",
"]",
"=",
"false",
"require",
"'irb/completion'",
"require",
"'irb/ext/save-history'",
"IRB",
".",
"conf",
"[",
":READLINE",
"]",
"=",
"true",
"IRB",
".",
"conf",
"[",
":SAVE_HISTORY",
"]",
"=",
"1000",
"IRB",
".",
"conf",
"[",
":HISTORY_FILE",
"]",
"=",
"Aruba",
".",
"config",
".",
"console_history_file",
"context",
"=",
"Class",
".",
"new",
"do",
"include",
"Aruba",
"::",
"Api",
"include",
"Aruba",
"::",
"Console",
"::",
"Help",
"def",
"initialize",
"setup_aruba",
"end",
"def",
"inspect",
"'nil'",
"end",
"end",
"irb",
"=",
"IRB",
"::",
"Irb",
".",
"new",
"(",
"IRB",
"::",
"WorkSpace",
".",
"new",
"(",
"context",
".",
"new",
")",
")",
"IRB",
".",
"conf",
"[",
":MAIN_CONTEXT",
"]",
"=",
"irb",
".",
"context",
"trap",
"(",
"\"SIGINT\"",
")",
"do",
"irb",
".",
"signal_handle",
"end",
"begin",
"catch",
"(",
":IRB_EXIT",
")",
"do",
"irb",
".",
"eval_input",
"end",
"ensure",
"IRB",
".",
"irb_at_exit",
"end",
"end"
] |
Start the aruba console
rubocop:disable Metrics/MethodLength
|
[
"Start",
"the",
"aruba",
"console"
] |
add17615322f575588aef1fccce875396cdf36e9
|
https://github.com/cucumber/aruba/blob/add17615322f575588aef1fccce875396cdf36e9/lib/aruba/console.rb#L13-L65
|
12,456
|
cucumber/aruba
|
lib/aruba/basic_configuration.rb
|
Aruba.BasicConfiguration.make_copy
|
def make_copy
obj = self.dup
obj.local_options = Marshal.load(Marshal.dump(local_options))
obj.hooks = @hooks
obj
end
|
ruby
|
def make_copy
obj = self.dup
obj.local_options = Marshal.load(Marshal.dump(local_options))
obj.hooks = @hooks
obj
end
|
[
"def",
"make_copy",
"obj",
"=",
"self",
".",
"dup",
"obj",
".",
"local_options",
"=",
"Marshal",
".",
"load",
"(",
"Marshal",
".",
"dump",
"(",
"local_options",
")",
")",
"obj",
".",
"hooks",
"=",
"@hooks",
"obj",
"end"
] |
Make deep dup copy of configuration
|
[
"Make",
"deep",
"dup",
"copy",
"of",
"configuration"
] |
add17615322f575588aef1fccce875396cdf36e9
|
https://github.com/cucumber/aruba/blob/add17615322f575588aef1fccce875396cdf36e9/lib/aruba/basic_configuration.rb#L116-L122
|
12,457
|
cucumber/aruba
|
lib/aruba/basic_configuration.rb
|
Aruba.BasicConfiguration.before
|
def before(name, context = proc {}, *args, &block)
name = format('%s_%s', 'before_', name.to_s).to_sym
if block_given?
@hooks.append(name, block)
self
else
@hooks.execute(name, context, *args)
end
end
|
ruby
|
def before(name, context = proc {}, *args, &block)
name = format('%s_%s', 'before_', name.to_s).to_sym
if block_given?
@hooks.append(name, block)
self
else
@hooks.execute(name, context, *args)
end
end
|
[
"def",
"before",
"(",
"name",
",",
"context",
"=",
"proc",
"{",
"}",
",",
"*",
"args",
",",
"&",
"block",
")",
"name",
"=",
"format",
"(",
"'%s_%s'",
",",
"'before_'",
",",
"name",
".",
"to_s",
")",
".",
"to_sym",
"if",
"block_given?",
"@hooks",
".",
"append",
"(",
"name",
",",
"block",
")",
"self",
"else",
"@hooks",
".",
"execute",
"(",
"name",
",",
"context",
",",
"args",
")",
"end",
"end"
] |
Define or run before-hook
@param [Symbol, String] name
The name of the hook
@param [Proc] context
The context a hook should run in. This is a runtime only option.
@param [Array] args
Arguments for the run of hook. This is a runtime only option.
@yield
The code block which should be run. This is a configure time only option
|
[
"Define",
"or",
"run",
"before",
"-",
"hook"
] |
add17615322f575588aef1fccce875396cdf36e9
|
https://github.com/cucumber/aruba/blob/add17615322f575588aef1fccce875396cdf36e9/lib/aruba/basic_configuration.rb#L137-L147
|
12,458
|
cucumber/aruba
|
lib/aruba/event_bus.rb
|
Aruba.EventBus.notify
|
def notify(event)
fail NoEventError, 'Please pass an event object, not a class' if event.is_a?(Class)
@handlers[event.class.to_s].each { |handler| handler.call(event) }
end
|
ruby
|
def notify(event)
fail NoEventError, 'Please pass an event object, not a class' if event.is_a?(Class)
@handlers[event.class.to_s].each { |handler| handler.call(event) }
end
|
[
"def",
"notify",
"(",
"event",
")",
"fail",
"NoEventError",
",",
"'Please pass an event object, not a class'",
"if",
"event",
".",
"is_a?",
"(",
"Class",
")",
"@handlers",
"[",
"event",
".",
"class",
".",
"to_s",
"]",
".",
"each",
"{",
"|",
"handler",
"|",
"handler",
".",
"call",
"(",
"event",
")",
"}",
"end"
] |
Broadcast an event
@param [Object] event
An object of registered event class. This object is passed to the event
handler.
|
[
"Broadcast",
"an",
"event"
] |
add17615322f575588aef1fccce875396cdf36e9
|
https://github.com/cucumber/aruba/blob/add17615322f575588aef1fccce875396cdf36e9/lib/aruba/event_bus.rb#L53-L57
|
12,459
|
cucumber/aruba
|
lib/aruba/runtime.rb
|
Aruba.Runtime.fixtures_directory
|
def fixtures_directory
@fixtures_directory ||= begin
candidates = config.fixtures_directories.map { |dir| File.join(root_directory, dir) }
directory = candidates.find { |d| Aruba.platform.directory? d }
fail "No existing fixtures directory found in #{candidates.map { |d| format('"%s"', d) }.join(', ')}." unless directory
directory
end
fail %(Fixtures directory "#{@fixtures_directory}" is not a directory) unless Aruba.platform.directory?(@fixtures_directory)
ArubaPath.new(@fixtures_directory)
end
|
ruby
|
def fixtures_directory
@fixtures_directory ||= begin
candidates = config.fixtures_directories.map { |dir| File.join(root_directory, dir) }
directory = candidates.find { |d| Aruba.platform.directory? d }
fail "No existing fixtures directory found in #{candidates.map { |d| format('"%s"', d) }.join(', ')}." unless directory
directory
end
fail %(Fixtures directory "#{@fixtures_directory}" is not a directory) unless Aruba.platform.directory?(@fixtures_directory)
ArubaPath.new(@fixtures_directory)
end
|
[
"def",
"fixtures_directory",
"@fixtures_directory",
"||=",
"begin",
"candidates",
"=",
"config",
".",
"fixtures_directories",
".",
"map",
"{",
"|",
"dir",
"|",
"File",
".",
"join",
"(",
"root_directory",
",",
"dir",
")",
"}",
"directory",
"=",
"candidates",
".",
"find",
"{",
"|",
"d",
"|",
"Aruba",
".",
"platform",
".",
"directory?",
"d",
"}",
"fail",
"\"No existing fixtures directory found in #{candidates.map { |d| format('\"%s\"', d) }.join(', ')}.\"",
"unless",
"directory",
"directory",
"end",
"fail",
"%(Fixtures directory \"#{@fixtures_directory}\" is not a directory)",
"unless",
"Aruba",
".",
"platform",
".",
"directory?",
"(",
"@fixtures_directory",
")",
"ArubaPath",
".",
"new",
"(",
"@fixtures_directory",
")",
"end"
] |
The path to the directory which contains fixtures
You might want to overwrite this method to place your data else where.
@return [ArubaPath]
The directory to where your fixtures are stored
|
[
"The",
"path",
"to",
"the",
"directory",
"which",
"contains",
"fixtures",
"You",
"might",
"want",
"to",
"overwrite",
"this",
"method",
"to",
"place",
"your",
"data",
"else",
"where",
"."
] |
add17615322f575588aef1fccce875396cdf36e9
|
https://github.com/cucumber/aruba/blob/add17615322f575588aef1fccce875396cdf36e9/lib/aruba/runtime.rb#L79-L91
|
12,460
|
cucumber/aruba
|
lib/aruba/initializer.rb
|
Aruba.Initializer.call
|
def call(test_framework)
begin
initializers.find { |i| i.match? test_framework }.start [], {}
rescue ArgumentError => e
$stderr.puts e.message
exit 0
end
Initializers::CommonInitializer.start [], {}
end
|
ruby
|
def call(test_framework)
begin
initializers.find { |i| i.match? test_framework }.start [], {}
rescue ArgumentError => e
$stderr.puts e.message
exit 0
end
Initializers::CommonInitializer.start [], {}
end
|
[
"def",
"call",
"(",
"test_framework",
")",
"begin",
"initializers",
".",
"find",
"{",
"|",
"i",
"|",
"i",
".",
"match?",
"test_framework",
"}",
".",
"start",
"[",
"]",
",",
"{",
"}",
"rescue",
"ArgumentError",
"=>",
"e",
"$stderr",
".",
"puts",
"e",
".",
"message",
"exit",
"0",
"end",
"Initializers",
"::",
"CommonInitializer",
".",
"start",
"[",
"]",
",",
"{",
"}",
"end"
] |
Create files etc.
|
[
"Create",
"files",
"etc",
"."
] |
add17615322f575588aef1fccce875396cdf36e9
|
https://github.com/cucumber/aruba/blob/add17615322f575588aef1fccce875396cdf36e9/lib/aruba/initializer.rb#L201-L210
|
12,461
|
cucumber/aruba
|
lib/aruba/hooks.rb
|
Aruba.Hooks.append
|
def append(label, block)
if store.key?(label.to_sym) && store[label.to_sym].respond_to?(:<<)
store[label.to_sym] << block
else
store[label.to_sym] = []
store[label.to_sym] << block
end
end
|
ruby
|
def append(label, block)
if store.key?(label.to_sym) && store[label.to_sym].respond_to?(:<<)
store[label.to_sym] << block
else
store[label.to_sym] = []
store[label.to_sym] << block
end
end
|
[
"def",
"append",
"(",
"label",
",",
"block",
")",
"if",
"store",
".",
"key?",
"(",
"label",
".",
"to_sym",
")",
"&&",
"store",
"[",
"label",
".",
"to_sym",
"]",
".",
"respond_to?",
"(",
":<<",
")",
"store",
"[",
"label",
".",
"to_sym",
"]",
"<<",
"block",
"else",
"store",
"[",
"label",
".",
"to_sym",
"]",
"=",
"[",
"]",
"store",
"[",
"label",
".",
"to_sym",
"]",
"<<",
"block",
"end",
"end"
] |
Create store
Add new hook
@param [String, Symbol] label
The name of the hook
@param [Proc] block
The block which should be run for the hook
|
[
"Create",
"store",
"Add",
"new",
"hook"
] |
add17615322f575588aef1fccce875396cdf36e9
|
https://github.com/cucumber/aruba/blob/add17615322f575588aef1fccce875396cdf36e9/lib/aruba/hooks.rb#L23-L30
|
12,462
|
dblock/fui
|
lib/fui/finder.rb
|
Fui.Finder.find
|
def find(path)
results = []
Find.find(path) do |fpath|
if FileTest.directory?(fpath)
next unless ignores
ignores.each do |ignore|
next unless fpath.include?(ignore.realpath.to_s)
puts "Ignoring Directory: #{fpath}" if options[:verbose]
Find.prune
end
end
results << fpath if yield fpath
end
results
end
|
ruby
|
def find(path)
results = []
Find.find(path) do |fpath|
if FileTest.directory?(fpath)
next unless ignores
ignores.each do |ignore|
next unless fpath.include?(ignore.realpath.to_s)
puts "Ignoring Directory: #{fpath}" if options[:verbose]
Find.prune
end
end
results << fpath if yield fpath
end
results
end
|
[
"def",
"find",
"(",
"path",
")",
"results",
"=",
"[",
"]",
"Find",
".",
"find",
"(",
"path",
")",
"do",
"|",
"fpath",
"|",
"if",
"FileTest",
".",
"directory?",
"(",
"fpath",
")",
"next",
"unless",
"ignores",
"ignores",
".",
"each",
"do",
"|",
"ignore",
"|",
"next",
"unless",
"fpath",
".",
"include?",
"(",
"ignore",
".",
"realpath",
".",
"to_s",
")",
"puts",
"\"Ignoring Directory: #{fpath}\"",
"if",
"options",
"[",
":verbose",
"]",
"Find",
".",
"prune",
"end",
"end",
"results",
"<<",
"fpath",
"if",
"yield",
"fpath",
"end",
"results",
"end"
] |
Find all files for which the block yields.
|
[
"Find",
"all",
"files",
"for",
"which",
"the",
"block",
"yields",
"."
] |
f71efcad7c046849670ae67e8cfb3303ec3e3c7a
|
https://github.com/dblock/fui/blob/f71efcad7c046849670ae67e8cfb3303ec3e3c7a/lib/fui/finder.rb#L54-L70
|
12,463
|
mhenrixon/sidekiq-unique-jobs
|
lib/sidekiq_unique_jobs/util.rb
|
SidekiqUniqueJobs.Util.keys
|
def keys(pattern = SCAN_PATTERN, count = DEFAULT_COUNT)
return redis(&:keys) if pattern.nil?
redis { |conn| conn.scan_each(match: prefix(pattern), count: count).to_a }
end
|
ruby
|
def keys(pattern = SCAN_PATTERN, count = DEFAULT_COUNT)
return redis(&:keys) if pattern.nil?
redis { |conn| conn.scan_each(match: prefix(pattern), count: count).to_a }
end
|
[
"def",
"keys",
"(",
"pattern",
"=",
"SCAN_PATTERN",
",",
"count",
"=",
"DEFAULT_COUNT",
")",
"return",
"redis",
"(",
":keys",
")",
"if",
"pattern",
".",
"nil?",
"redis",
"{",
"|",
"conn",
"|",
"conn",
".",
"scan_each",
"(",
"match",
":",
"prefix",
"(",
"pattern",
")",
",",
"count",
":",
"count",
")",
".",
"to_a",
"}",
"end"
] |
Find unique keys in redis
@param [String] pattern a pattern to scan for in redis
@param [Integer] count the maximum number of keys to delete
@return [Array<String>] an array with active unique keys
|
[
"Find",
"unique",
"keys",
"in",
"redis"
] |
2944b97c720528f53962ccfd17d43ac939a77f46
|
https://github.com/mhenrixon/sidekiq-unique-jobs/blob/2944b97c720528f53962ccfd17d43ac939a77f46/lib/sidekiq_unique_jobs/util.rb#L21-L25
|
12,464
|
mhenrixon/sidekiq-unique-jobs
|
lib/sidekiq_unique_jobs/util.rb
|
SidekiqUniqueJobs.Util.keys_with_ttl
|
def keys_with_ttl(pattern = SCAN_PATTERN, count = DEFAULT_COUNT)
hash = {}
redis do |conn|
conn.scan_each(match: prefix(pattern), count: count).each do |key|
hash[key] = conn.ttl(key)
end
end
hash
end
|
ruby
|
def keys_with_ttl(pattern = SCAN_PATTERN, count = DEFAULT_COUNT)
hash = {}
redis do |conn|
conn.scan_each(match: prefix(pattern), count: count).each do |key|
hash[key] = conn.ttl(key)
end
end
hash
end
|
[
"def",
"keys_with_ttl",
"(",
"pattern",
"=",
"SCAN_PATTERN",
",",
"count",
"=",
"DEFAULT_COUNT",
")",
"hash",
"=",
"{",
"}",
"redis",
"do",
"|",
"conn",
"|",
"conn",
".",
"scan_each",
"(",
"match",
":",
"prefix",
"(",
"pattern",
")",
",",
"count",
":",
"count",
")",
".",
"each",
"do",
"|",
"key",
"|",
"hash",
"[",
"key",
"]",
"=",
"conn",
".",
"ttl",
"(",
"key",
")",
"end",
"end",
"hash",
"end"
] |
Find unique keys with ttl
@param [String] pattern a pattern to scan for in redis
@param [Integer] count the maximum number of keys to delete
@return [Hash<String, Integer>] a hash with active unique keys and corresponding ttl
|
[
"Find",
"unique",
"keys",
"with",
"ttl"
] |
2944b97c720528f53962ccfd17d43ac939a77f46
|
https://github.com/mhenrixon/sidekiq-unique-jobs/blob/2944b97c720528f53962ccfd17d43ac939a77f46/lib/sidekiq_unique_jobs/util.rb#L31-L39
|
12,465
|
mhenrixon/sidekiq-unique-jobs
|
lib/sidekiq_unique_jobs/util.rb
|
SidekiqUniqueJobs.Util.del
|
def del(pattern = SCAN_PATTERN, count = 0)
raise ArgumentError, "Please provide a number of keys to delete greater than zero" if count.zero?
pattern = suffix(pattern)
log_debug { "Deleting keys by: #{pattern}" }
keys, time = timed { keys(pattern, count) }
key_size = keys.size
log_debug { "#{key_size} keys found in #{time} sec." }
_, time = timed { batch_delete(keys) }
log_debug { "Deleted #{key_size} keys in #{time} sec." }
key_size
end
|
ruby
|
def del(pattern = SCAN_PATTERN, count = 0)
raise ArgumentError, "Please provide a number of keys to delete greater than zero" if count.zero?
pattern = suffix(pattern)
log_debug { "Deleting keys by: #{pattern}" }
keys, time = timed { keys(pattern, count) }
key_size = keys.size
log_debug { "#{key_size} keys found in #{time} sec." }
_, time = timed { batch_delete(keys) }
log_debug { "Deleted #{key_size} keys in #{time} sec." }
key_size
end
|
[
"def",
"del",
"(",
"pattern",
"=",
"SCAN_PATTERN",
",",
"count",
"=",
"0",
")",
"raise",
"ArgumentError",
",",
"\"Please provide a number of keys to delete greater than zero\"",
"if",
"count",
".",
"zero?",
"pattern",
"=",
"suffix",
"(",
"pattern",
")",
"log_debug",
"{",
"\"Deleting keys by: #{pattern}\"",
"}",
"keys",
",",
"time",
"=",
"timed",
"{",
"keys",
"(",
"pattern",
",",
"count",
")",
"}",
"key_size",
"=",
"keys",
".",
"size",
"log_debug",
"{",
"\"#{key_size} keys found in #{time} sec.\"",
"}",
"_",
",",
"time",
"=",
"timed",
"{",
"batch_delete",
"(",
"keys",
")",
"}",
"log_debug",
"{",
"\"Deleted #{key_size} keys in #{time} sec.\"",
"}",
"key_size",
"end"
] |
Deletes unique keys from redis
@param [String] pattern a pattern to scan for in redis
@param [Integer] count the maximum number of keys to delete
@return [Integer] the number of keys deleted
|
[
"Deletes",
"unique",
"keys",
"from",
"redis"
] |
2944b97c720528f53962ccfd17d43ac939a77f46
|
https://github.com/mhenrixon/sidekiq-unique-jobs/blob/2944b97c720528f53962ccfd17d43ac939a77f46/lib/sidekiq_unique_jobs/util.rb#L46-L59
|
12,466
|
mhenrixon/sidekiq-unique-jobs
|
lib/sidekiq_unique_jobs/unlockable.rb
|
SidekiqUniqueJobs.Unlockable.unlock
|
def unlock(item)
SidekiqUniqueJobs::UniqueArgs.digest(item)
SidekiqUniqueJobs::Locksmith.new(item).unlock
end
|
ruby
|
def unlock(item)
SidekiqUniqueJobs::UniqueArgs.digest(item)
SidekiqUniqueJobs::Locksmith.new(item).unlock
end
|
[
"def",
"unlock",
"(",
"item",
")",
"SidekiqUniqueJobs",
"::",
"UniqueArgs",
".",
"digest",
"(",
"item",
")",
"SidekiqUniqueJobs",
"::",
"Locksmith",
".",
"new",
"(",
"item",
")",
".",
"unlock",
"end"
] |
Unlocks a job.
@param [Hash] item a Sidekiq job hash
|
[
"Unlocks",
"a",
"job",
"."
] |
2944b97c720528f53962ccfd17d43ac939a77f46
|
https://github.com/mhenrixon/sidekiq-unique-jobs/blob/2944b97c720528f53962ccfd17d43ac939a77f46/lib/sidekiq_unique_jobs/unlockable.rb#L13-L16
|
12,467
|
mhenrixon/sidekiq-unique-jobs
|
lib/sidekiq_unique_jobs/unlockable.rb
|
SidekiqUniqueJobs.Unlockable.delete
|
def delete(item)
SidekiqUniqueJobs::UniqueArgs.digest(item)
SidekiqUniqueJobs::Locksmith.new(item).delete!
end
|
ruby
|
def delete(item)
SidekiqUniqueJobs::UniqueArgs.digest(item)
SidekiqUniqueJobs::Locksmith.new(item).delete!
end
|
[
"def",
"delete",
"(",
"item",
")",
"SidekiqUniqueJobs",
"::",
"UniqueArgs",
".",
"digest",
"(",
"item",
")",
"SidekiqUniqueJobs",
"::",
"Locksmith",
".",
"new",
"(",
"item",
")",
".",
"delete!",
"end"
] |
Deletes a lock regardless of if it was locked or not.
This is good for situations when a job is locked by another item
@param [Hash] item a Sidekiq job hash
|
[
"Deletes",
"a",
"lock",
"regardless",
"of",
"if",
"it",
"was",
"locked",
"or",
"not",
"."
] |
2944b97c720528f53962ccfd17d43ac939a77f46
|
https://github.com/mhenrixon/sidekiq-unique-jobs/blob/2944b97c720528f53962ccfd17d43ac939a77f46/lib/sidekiq_unique_jobs/unlockable.rb#L22-L25
|
12,468
|
mhenrixon/sidekiq-unique-jobs
|
lib/sidekiq_unique_jobs/scripts.rb
|
SidekiqUniqueJobs.Scripts.call
|
def call(file_name, redis_pool, options = {})
execute_script(file_name, redis_pool, options)
rescue Redis::CommandError => ex
handle_error(ex, file_name) do
call(file_name, redis_pool, options)
end
end
|
ruby
|
def call(file_name, redis_pool, options = {})
execute_script(file_name, redis_pool, options)
rescue Redis::CommandError => ex
handle_error(ex, file_name) do
call(file_name, redis_pool, options)
end
end
|
[
"def",
"call",
"(",
"file_name",
",",
"redis_pool",
",",
"options",
"=",
"{",
"}",
")",
"execute_script",
"(",
"file_name",
",",
"redis_pool",
",",
"options",
")",
"rescue",
"Redis",
"::",
"CommandError",
"=>",
"ex",
"handle_error",
"(",
"ex",
",",
"file_name",
")",
"do",
"call",
"(",
"file_name",
",",
"redis_pool",
",",
"options",
")",
"end",
"end"
] |
Call a lua script with the provided file_name
@note this method is recursive if we need to load a lua script
that wasn't previously loaded.
@param [Symbol] file_name the name of the lua script
@param [Sidekiq::RedisConnection, ConnectionPool] redis_pool the redis connection
@param [Hash] options arguments to pass to the script file
@option options [Array] :keys the array of keys to pass to the script
@option options [Array] :argv the array of arguments to pass to the script
@return value from script
|
[
"Call",
"a",
"lua",
"script",
"with",
"the",
"provided",
"file_name"
] |
2944b97c720528f53962ccfd17d43ac939a77f46
|
https://github.com/mhenrixon/sidekiq-unique-jobs/blob/2944b97c720528f53962ccfd17d43ac939a77f46/lib/sidekiq_unique_jobs/scripts.rb#L33-L39
|
12,469
|
mhenrixon/sidekiq-unique-jobs
|
lib/sidekiq_unique_jobs/scripts.rb
|
SidekiqUniqueJobs.Scripts.execute_script
|
def execute_script(file_name, redis_pool, options = {})
redis(redis_pool) do |conn|
sha = script_sha(conn, file_name)
conn.evalsha(sha, options)
end
end
|
ruby
|
def execute_script(file_name, redis_pool, options = {})
redis(redis_pool) do |conn|
sha = script_sha(conn, file_name)
conn.evalsha(sha, options)
end
end
|
[
"def",
"execute_script",
"(",
"file_name",
",",
"redis_pool",
",",
"options",
"=",
"{",
"}",
")",
"redis",
"(",
"redis_pool",
")",
"do",
"|",
"conn",
"|",
"sha",
"=",
"script_sha",
"(",
"conn",
",",
"file_name",
")",
"conn",
".",
"evalsha",
"(",
"sha",
",",
"options",
")",
"end",
"end"
] |
Execute the script file
@param [Symbol] file_name the name of the lua script
@param [Sidekiq::RedisConnection, ConnectionPool] redis_pool the redis connection
@param [Hash] options arguments to pass to the script file
@option options [Array] :keys the array of keys to pass to the script
@option options [Array] :argv the array of arguments to pass to the script
@return value from script (evalsha)
|
[
"Execute",
"the",
"script",
"file"
] |
2944b97c720528f53962ccfd17d43ac939a77f46
|
https://github.com/mhenrixon/sidekiq-unique-jobs/blob/2944b97c720528f53962ccfd17d43ac939a77f46/lib/sidekiq_unique_jobs/scripts.rb#L52-L57
|
12,470
|
mhenrixon/sidekiq-unique-jobs
|
lib/sidekiq_unique_jobs/scripts.rb
|
SidekiqUniqueJobs.Scripts.script_sha
|
def script_sha(conn, file_name)
if (sha = SCRIPT_SHAS.get(file_name))
return sha
end
sha = conn.script(:load, script_source(file_name))
SCRIPT_SHAS.put(file_name, sha)
sha
end
|
ruby
|
def script_sha(conn, file_name)
if (sha = SCRIPT_SHAS.get(file_name))
return sha
end
sha = conn.script(:load, script_source(file_name))
SCRIPT_SHAS.put(file_name, sha)
sha
end
|
[
"def",
"script_sha",
"(",
"conn",
",",
"file_name",
")",
"if",
"(",
"sha",
"=",
"SCRIPT_SHAS",
".",
"get",
"(",
"file_name",
")",
")",
"return",
"sha",
"end",
"sha",
"=",
"conn",
".",
"script",
"(",
":load",
",",
"script_source",
"(",
"file_name",
")",
")",
"SCRIPT_SHAS",
".",
"put",
"(",
"file_name",
",",
"sha",
")",
"sha",
"end"
] |
Return sha of already loaded lua script or load it and return the sha
@param [Sidekiq::RedisConnection] conn the redis connection
@param [Symbol] file_name the name of the lua script
@return [String] sha of the script file
@return [String] the sha of the script
|
[
"Return",
"sha",
"of",
"already",
"loaded",
"lua",
"script",
"or",
"load",
"it",
"and",
"return",
"the",
"sha"
] |
2944b97c720528f53962ccfd17d43ac939a77f46
|
https://github.com/mhenrixon/sidekiq-unique-jobs/blob/2944b97c720528f53962ccfd17d43ac939a77f46/lib/sidekiq_unique_jobs/scripts.rb#L68-L76
|
12,471
|
mhenrixon/sidekiq-unique-jobs
|
lib/sidekiq_unique_jobs/scripts.rb
|
SidekiqUniqueJobs.Scripts.handle_error
|
def handle_error(ex, file_name)
if ex.message == "NOSCRIPT No matching script. Please use EVAL."
SCRIPT_SHAS.delete(file_name)
return yield if block_given?
end
raise ScriptError, file_name: file_name, source_exception: ex
end
|
ruby
|
def handle_error(ex, file_name)
if ex.message == "NOSCRIPT No matching script. Please use EVAL."
SCRIPT_SHAS.delete(file_name)
return yield if block_given?
end
raise ScriptError, file_name: file_name, source_exception: ex
end
|
[
"def",
"handle_error",
"(",
"ex",
",",
"file_name",
")",
"if",
"ex",
".",
"message",
"==",
"\"NOSCRIPT No matching script. Please use EVAL.\"",
"SCRIPT_SHAS",
".",
"delete",
"(",
"file_name",
")",
"return",
"yield",
"if",
"block_given?",
"end",
"raise",
"ScriptError",
",",
"file_name",
":",
"file_name",
",",
"source_exception",
":",
"ex",
"end"
] |
Handle errors to allow retrying errors that need retrying
@param [Redis::CommandError] ex exception to handle
@param [Symbol] file_name the name of the lua script
@return [void]
@yieldreturn [void] yields back to the caller when NOSCRIPT is raised
|
[
"Handle",
"errors",
"to",
"allow",
"retrying",
"errors",
"that",
"need",
"retrying"
] |
2944b97c720528f53962ccfd17d43ac939a77f46
|
https://github.com/mhenrixon/sidekiq-unique-jobs/blob/2944b97c720528f53962ccfd17d43ac939a77f46/lib/sidekiq_unique_jobs/scripts.rb#L87-L94
|
12,472
|
mhenrixon/sidekiq-unique-jobs
|
lib/sidekiq_unique_jobs/locksmith.rb
|
SidekiqUniqueJobs.Locksmith.delete!
|
def delete!
Scripts.call(
:delete,
redis_pool,
keys: [exists_key, grabbed_key, available_key, version_key, UNIQUE_SET, unique_digest],
)
end
|
ruby
|
def delete!
Scripts.call(
:delete,
redis_pool,
keys: [exists_key, grabbed_key, available_key, version_key, UNIQUE_SET, unique_digest],
)
end
|
[
"def",
"delete!",
"Scripts",
".",
"call",
"(",
":delete",
",",
"redis_pool",
",",
"keys",
":",
"[",
"exists_key",
",",
"grabbed_key",
",",
"available_key",
",",
"version_key",
",",
"UNIQUE_SET",
",",
"unique_digest",
"]",
",",
")",
"end"
] |
Deletes the lock regardless of if it has a ttl set
|
[
"Deletes",
"the",
"lock",
"regardless",
"of",
"if",
"it",
"has",
"a",
"ttl",
"set"
] |
2944b97c720528f53962ccfd17d43ac939a77f46
|
https://github.com/mhenrixon/sidekiq-unique-jobs/blob/2944b97c720528f53962ccfd17d43ac939a77f46/lib/sidekiq_unique_jobs/locksmith.rb#L43-L49
|
12,473
|
mhenrixon/sidekiq-unique-jobs
|
lib/sidekiq_unique_jobs/locksmith.rb
|
SidekiqUniqueJobs.Locksmith.lock
|
def lock(timeout = nil, &block)
Scripts.call(:lock, redis_pool,
keys: [exists_key, grabbed_key, available_key, UNIQUE_SET, unique_digest],
argv: [jid, ttl, lock_type])
grab_token(timeout) do |token|
touch_grabbed_token(token)
return_token_or_block_value(token, &block)
end
end
|
ruby
|
def lock(timeout = nil, &block)
Scripts.call(:lock, redis_pool,
keys: [exists_key, grabbed_key, available_key, UNIQUE_SET, unique_digest],
argv: [jid, ttl, lock_type])
grab_token(timeout) do |token|
touch_grabbed_token(token)
return_token_or_block_value(token, &block)
end
end
|
[
"def",
"lock",
"(",
"timeout",
"=",
"nil",
",",
"&",
"block",
")",
"Scripts",
".",
"call",
"(",
":lock",
",",
"redis_pool",
",",
"keys",
":",
"[",
"exists_key",
",",
"grabbed_key",
",",
"available_key",
",",
"UNIQUE_SET",
",",
"unique_digest",
"]",
",",
"argv",
":",
"[",
"jid",
",",
"ttl",
",",
"lock_type",
"]",
")",
"grab_token",
"(",
"timeout",
")",
"do",
"|",
"token",
"|",
"touch_grabbed_token",
"(",
"token",
")",
"return_token_or_block_value",
"(",
"token",
",",
"block",
")",
"end",
"end"
] |
Create a lock for the item
@param [Integer] timeout the number of seconds to wait for a lock.
@return [String] the Sidekiq job_id (jid)
|
[
"Create",
"a",
"lock",
"for",
"the",
"item"
] |
2944b97c720528f53962ccfd17d43ac939a77f46
|
https://github.com/mhenrixon/sidekiq-unique-jobs/blob/2944b97c720528f53962ccfd17d43ac939a77f46/lib/sidekiq_unique_jobs/locksmith.rb#L58-L67
|
12,474
|
mhenrixon/sidekiq-unique-jobs
|
lib/sidekiq_unique_jobs/locksmith.rb
|
SidekiqUniqueJobs.Locksmith.unlock!
|
def unlock!(token = nil)
token ||= jid
Scripts.call(
:unlock,
redis_pool,
keys: [exists_key, grabbed_key, available_key, version_key, UNIQUE_SET, unique_digest],
argv: [token, ttl, lock_type],
)
end
|
ruby
|
def unlock!(token = nil)
token ||= jid
Scripts.call(
:unlock,
redis_pool,
keys: [exists_key, grabbed_key, available_key, version_key, UNIQUE_SET, unique_digest],
argv: [token, ttl, lock_type],
)
end
|
[
"def",
"unlock!",
"(",
"token",
"=",
"nil",
")",
"token",
"||=",
"jid",
"Scripts",
".",
"call",
"(",
":unlock",
",",
"redis_pool",
",",
"keys",
":",
"[",
"exists_key",
",",
"grabbed_key",
",",
"available_key",
",",
"version_key",
",",
"UNIQUE_SET",
",",
"unique_digest",
"]",
",",
"argv",
":",
"[",
"token",
",",
"ttl",
",",
"lock_type",
"]",
",",
")",
"end"
] |
Removes the lock keys from Redis
@param [String] token the token to unlock (defaults to jid)
@return [false] unless locked?
@return [String] Sidekiq job_id (jid) if successful
|
[
"Removes",
"the",
"lock",
"keys",
"from",
"Redis"
] |
2944b97c720528f53962ccfd17d43ac939a77f46
|
https://github.com/mhenrixon/sidekiq-unique-jobs/blob/2944b97c720528f53962ccfd17d43ac939a77f46/lib/sidekiq_unique_jobs/locksmith.rb#L91-L100
|
12,475
|
mhenrixon/sidekiq-unique-jobs
|
lib/sidekiq_unique_jobs/connection.rb
|
SidekiqUniqueJobs.Connection.redis
|
def redis(redis_pool = nil)
if redis_pool
redis_pool.with { |conn| yield conn }
else
Sidekiq.redis { |conn| yield conn }
end
end
|
ruby
|
def redis(redis_pool = nil)
if redis_pool
redis_pool.with { |conn| yield conn }
else
Sidekiq.redis { |conn| yield conn }
end
end
|
[
"def",
"redis",
"(",
"redis_pool",
"=",
"nil",
")",
"if",
"redis_pool",
"redis_pool",
".",
"with",
"{",
"|",
"conn",
"|",
"yield",
"conn",
"}",
"else",
"Sidekiq",
".",
"redis",
"{",
"|",
"conn",
"|",
"yield",
"conn",
"}",
"end",
"end"
] |
Creates a connection to redis
@return [Sidekiq::RedisConnection, ConnectionPool] a connection to redis
|
[
"Creates",
"a",
"connection",
"to",
"redis"
] |
2944b97c720528f53962ccfd17d43ac939a77f46
|
https://github.com/mhenrixon/sidekiq-unique-jobs/blob/2944b97c720528f53962ccfd17d43ac939a77f46/lib/sidekiq_unique_jobs/connection.rb#L14-L20
|
12,476
|
mhenrixon/sidekiq-unique-jobs
|
lib/sidekiq_unique_jobs/digests.rb
|
SidekiqUniqueJobs.Digests.all
|
def all(pattern: SCAN_PATTERN, count: DEFAULT_COUNT)
redis { |conn| conn.sscan_each(UNIQUE_SET, match: pattern, count: count).to_a }
end
|
ruby
|
def all(pattern: SCAN_PATTERN, count: DEFAULT_COUNT)
redis { |conn| conn.sscan_each(UNIQUE_SET, match: pattern, count: count).to_a }
end
|
[
"def",
"all",
"(",
"pattern",
":",
"SCAN_PATTERN",
",",
"count",
":",
"DEFAULT_COUNT",
")",
"redis",
"{",
"|",
"conn",
"|",
"conn",
".",
"sscan_each",
"(",
"UNIQUE_SET",
",",
"match",
":",
"pattern",
",",
"count",
":",
"count",
")",
".",
"to_a",
"}",
"end"
] |
Return unique digests matching pattern
@param [String] pattern a pattern to match with
@param [Integer] count the maximum number to match
@return [Array<String>] with unique digests
|
[
"Return",
"unique",
"digests",
"matching",
"pattern"
] |
2944b97c720528f53962ccfd17d43ac939a77f46
|
https://github.com/mhenrixon/sidekiq-unique-jobs/blob/2944b97c720528f53962ccfd17d43ac939a77f46/lib/sidekiq_unique_jobs/digests.rb#L21-L23
|
12,477
|
mhenrixon/sidekiq-unique-jobs
|
lib/sidekiq_unique_jobs/digests.rb
|
SidekiqUniqueJobs.Digests.page
|
def page(pattern: SCAN_PATTERN, cursor: 0, page_size: 100)
redis do |conn|
total_size, digests = conn.multi do
conn.scard(UNIQUE_SET)
conn.sscan(UNIQUE_SET, cursor, match: pattern, count: page_size)
end
[total_size, digests[0], digests[1]]
end
end
|
ruby
|
def page(pattern: SCAN_PATTERN, cursor: 0, page_size: 100)
redis do |conn|
total_size, digests = conn.multi do
conn.scard(UNIQUE_SET)
conn.sscan(UNIQUE_SET, cursor, match: pattern, count: page_size)
end
[total_size, digests[0], digests[1]]
end
end
|
[
"def",
"page",
"(",
"pattern",
":",
"SCAN_PATTERN",
",",
"cursor",
":",
"0",
",",
"page_size",
":",
"100",
")",
"redis",
"do",
"|",
"conn",
"|",
"total_size",
",",
"digests",
"=",
"conn",
".",
"multi",
"do",
"conn",
".",
"scard",
"(",
"UNIQUE_SET",
")",
"conn",
".",
"sscan",
"(",
"UNIQUE_SET",
",",
"cursor",
",",
"match",
":",
"pattern",
",",
"count",
":",
"page_size",
")",
"end",
"[",
"total_size",
",",
"digests",
"[",
"0",
"]",
",",
"digests",
"[",
"1",
"]",
"]",
"end",
"end"
] |
Paginate unique digests
@param [String] pattern a pattern to match with
@param [Integer] cursor the maximum number to match
@param [Integer] page_size the current cursor position
@return [Array<String>] with unique digests
|
[
"Paginate",
"unique",
"digests"
] |
2944b97c720528f53962ccfd17d43ac939a77f46
|
https://github.com/mhenrixon/sidekiq-unique-jobs/blob/2944b97c720528f53962ccfd17d43ac939a77f46/lib/sidekiq_unique_jobs/digests.rb#L32-L41
|
12,478
|
mhenrixon/sidekiq-unique-jobs
|
lib/sidekiq_unique_jobs/digests.rb
|
SidekiqUniqueJobs.Digests.del
|
def del(digest: nil, pattern: nil, count: DEFAULT_COUNT)
return delete_by_pattern(pattern, count: count) if pattern
return delete_by_digest(digest) if digest
raise ArgumentError, "either digest or pattern need to be provided"
end
|
ruby
|
def del(digest: nil, pattern: nil, count: DEFAULT_COUNT)
return delete_by_pattern(pattern, count: count) if pattern
return delete_by_digest(digest) if digest
raise ArgumentError, "either digest or pattern need to be provided"
end
|
[
"def",
"del",
"(",
"digest",
":",
"nil",
",",
"pattern",
":",
"nil",
",",
"count",
":",
"DEFAULT_COUNT",
")",
"return",
"delete_by_pattern",
"(",
"pattern",
",",
"count",
":",
"count",
")",
"if",
"pattern",
"return",
"delete_by_digest",
"(",
"digest",
")",
"if",
"digest",
"raise",
"ArgumentError",
",",
"\"either digest or pattern need to be provided\"",
"end"
] |
Deletes unique digest either by a digest or pattern
@param [String] digest the full digest to delete
@param [String] pattern a key pattern to match with
@param [Integer] count the maximum number
@raise [ArgumentError] when both pattern and digest are nil
@return [Array<String>] with unique digests
|
[
"Deletes",
"unique",
"digest",
"either",
"by",
"a",
"digest",
"or",
"pattern"
] |
2944b97c720528f53962ccfd17d43ac939a77f46
|
https://github.com/mhenrixon/sidekiq-unique-jobs/blob/2944b97c720528f53962ccfd17d43ac939a77f46/lib/sidekiq_unique_jobs/digests.rb#L57-L62
|
12,479
|
mhenrixon/sidekiq-unique-jobs
|
lib/sidekiq_unique_jobs/digests.rb
|
SidekiqUniqueJobs.Digests.delete_by_pattern
|
def delete_by_pattern(pattern, count: DEFAULT_COUNT)
result, elapsed = timed do
digests = all(pattern: pattern, count: count)
batch_delete(digests)
digests.size
end
log_info("#{__method__}(#{pattern}, count: #{count}) completed in #{elapsed}ms")
result
end
|
ruby
|
def delete_by_pattern(pattern, count: DEFAULT_COUNT)
result, elapsed = timed do
digests = all(pattern: pattern, count: count)
batch_delete(digests)
digests.size
end
log_info("#{__method__}(#{pattern}, count: #{count}) completed in #{elapsed}ms")
result
end
|
[
"def",
"delete_by_pattern",
"(",
"pattern",
",",
"count",
":",
"DEFAULT_COUNT",
")",
"result",
",",
"elapsed",
"=",
"timed",
"do",
"digests",
"=",
"all",
"(",
"pattern",
":",
"pattern",
",",
"count",
":",
"count",
")",
"batch_delete",
"(",
"digests",
")",
"digests",
".",
"size",
"end",
"log_info",
"(",
"\"#{__method__}(#{pattern}, count: #{count}) completed in #{elapsed}ms\"",
")",
"result",
"end"
] |
Deletes unique digests by pattern
@param [String] pattern a key pattern to match with
@param [Integer] count the maximum number
@return [Array<String>] with unique digests
|
[
"Deletes",
"unique",
"digests",
"by",
"pattern"
] |
2944b97c720528f53962ccfd17d43ac939a77f46
|
https://github.com/mhenrixon/sidekiq-unique-jobs/blob/2944b97c720528f53962ccfd17d43ac939a77f46/lib/sidekiq_unique_jobs/digests.rb#L71-L81
|
12,480
|
mhenrixon/sidekiq-unique-jobs
|
lib/sidekiq_unique_jobs/digests.rb
|
SidekiqUniqueJobs.Digests.delete_by_digest
|
def delete_by_digest(digest)
result, elapsed = timed do
Scripts.call(:delete_by_digest, nil, keys: [UNIQUE_SET, digest])
count
end
log_info("#{__method__}(#{digest}) completed in #{elapsed}ms")
result
end
|
ruby
|
def delete_by_digest(digest)
result, elapsed = timed do
Scripts.call(:delete_by_digest, nil, keys: [UNIQUE_SET, digest])
count
end
log_info("#{__method__}(#{digest}) completed in #{elapsed}ms")
result
end
|
[
"def",
"delete_by_digest",
"(",
"digest",
")",
"result",
",",
"elapsed",
"=",
"timed",
"do",
"Scripts",
".",
"call",
"(",
":delete_by_digest",
",",
"nil",
",",
"keys",
":",
"[",
"UNIQUE_SET",
",",
"digest",
"]",
")",
"count",
"end",
"log_info",
"(",
"\"#{__method__}(#{digest}) completed in #{elapsed}ms\"",
")",
"result",
"end"
] |
Get a total count of unique digests
@param [String] digest a key pattern to match with
|
[
"Get",
"a",
"total",
"count",
"of",
"unique",
"digests"
] |
2944b97c720528f53962ccfd17d43ac939a77f46
|
https://github.com/mhenrixon/sidekiq-unique-jobs/blob/2944b97c720528f53962ccfd17d43ac939a77f46/lib/sidekiq_unique_jobs/digests.rb#L86-L95
|
12,481
|
mhenrixon/sidekiq-unique-jobs
|
lib/sidekiq_unique_jobs/sidekiq_worker_methods.rb
|
SidekiqUniqueJobs.SidekiqWorkerMethods.worker_class_constantize
|
def worker_class_constantize(klazz = @worker_class)
return klazz unless klazz.is_a?(String)
Object.const_get(klazz)
rescue NameError => ex
case ex.message
when /uninitialized constant/
klazz
else
raise
end
end
|
ruby
|
def worker_class_constantize(klazz = @worker_class)
return klazz unless klazz.is_a?(String)
Object.const_get(klazz)
rescue NameError => ex
case ex.message
when /uninitialized constant/
klazz
else
raise
end
end
|
[
"def",
"worker_class_constantize",
"(",
"klazz",
"=",
"@worker_class",
")",
"return",
"klazz",
"unless",
"klazz",
".",
"is_a?",
"(",
"String",
")",
"Object",
".",
"const_get",
"(",
"klazz",
")",
"rescue",
"NameError",
"=>",
"ex",
"case",
"ex",
".",
"message",
"when",
"/",
"/",
"klazz",
"else",
"raise",
"end",
"end"
] |
Attempt to constantize a string worker_class argument, always
failing back to the original argument when the constant can't be found
@return [Sidekiq::Worker]
|
[
"Attempt",
"to",
"constantize",
"a",
"string",
"worker_class",
"argument",
"always",
"failing",
"back",
"to",
"the",
"original",
"argument",
"when",
"the",
"constant",
"can",
"t",
"be",
"found"
] |
2944b97c720528f53962ccfd17d43ac939a77f46
|
https://github.com/mhenrixon/sidekiq-unique-jobs/blob/2944b97c720528f53962ccfd17d43ac939a77f46/lib/sidekiq_unique_jobs/sidekiq_worker_methods.rb#L45-L56
|
12,482
|
mhenrixon/sidekiq-unique-jobs
|
lib/sidekiq_unique_jobs/config.rb
|
SidekiqUniqueJobs.Config.add_lock
|
def add_lock(name, klass)
raise ArgumentError, "Lock #{name} already defined, please use another name" if locks.key?(name.to_sym)
new_locks = locks.dup.merge(name.to_sym => klass).freeze
self.locks = new_locks
end
|
ruby
|
def add_lock(name, klass)
raise ArgumentError, "Lock #{name} already defined, please use another name" if locks.key?(name.to_sym)
new_locks = locks.dup.merge(name.to_sym => klass).freeze
self.locks = new_locks
end
|
[
"def",
"add_lock",
"(",
"name",
",",
"klass",
")",
"raise",
"ArgumentError",
",",
"\"Lock #{name} already defined, please use another name\"",
"if",
"locks",
".",
"key?",
"(",
"name",
".",
"to_sym",
")",
"new_locks",
"=",
"locks",
".",
"dup",
".",
"merge",
"(",
"name",
".",
"to_sym",
"=>",
"klass",
")",
".",
"freeze",
"self",
".",
"locks",
"=",
"new_locks",
"end"
] |
Adds a lock type to the configuration. It will raise if the lock exists already
@param [String] name the name of the lock
@param [Class] klass the class describing the lock
|
[
"Adds",
"a",
"lock",
"type",
"to",
"the",
"configuration",
".",
"It",
"will",
"raise",
"if",
"the",
"lock",
"exists",
"already"
] |
2944b97c720528f53962ccfd17d43ac939a77f46
|
https://github.com/mhenrixon/sidekiq-unique-jobs/blob/2944b97c720528f53962ccfd17d43ac939a77f46/lib/sidekiq_unique_jobs/config.rb#L50-L55
|
12,483
|
mhenrixon/sidekiq-unique-jobs
|
lib/sidekiq_unique_jobs/config.rb
|
SidekiqUniqueJobs.Config.add_strategy
|
def add_strategy(name, klass)
raise ArgumentError, "strategy #{name} already defined, please use another name" if strategies.key?(name.to_sym)
new_strategies = strategies.dup.merge(name.to_sym => klass).freeze
self.strategies = new_strategies
end
|
ruby
|
def add_strategy(name, klass)
raise ArgumentError, "strategy #{name} already defined, please use another name" if strategies.key?(name.to_sym)
new_strategies = strategies.dup.merge(name.to_sym => klass).freeze
self.strategies = new_strategies
end
|
[
"def",
"add_strategy",
"(",
"name",
",",
"klass",
")",
"raise",
"ArgumentError",
",",
"\"strategy #{name} already defined, please use another name\"",
"if",
"strategies",
".",
"key?",
"(",
"name",
".",
"to_sym",
")",
"new_strategies",
"=",
"strategies",
".",
"dup",
".",
"merge",
"(",
"name",
".",
"to_sym",
"=>",
"klass",
")",
".",
"freeze",
"self",
".",
"strategies",
"=",
"new_strategies",
"end"
] |
Adds an on_conflict strategy to the configuration.
It will raise if the strategy exists already
@param [String] name the name of the custom strategy
@param [Class] klass the class describing the strategy
|
[
"Adds",
"an",
"on_conflict",
"strategy",
"to",
"the",
"configuration",
".",
"It",
"will",
"raise",
"if",
"the",
"strategy",
"exists",
"already"
] |
2944b97c720528f53962ccfd17d43ac939a77f46
|
https://github.com/mhenrixon/sidekiq-unique-jobs/blob/2944b97c720528f53962ccfd17d43ac939a77f46/lib/sidekiq_unique_jobs/config.rb#L62-L67
|
12,484
|
mhenrixon/sidekiq-unique-jobs
|
lib/sidekiq_unique_jobs/unique_args.rb
|
SidekiqUniqueJobs.UniqueArgs.digestable_hash
|
def digestable_hash
@item.slice(CLASS_KEY, QUEUE_KEY, UNIQUE_ARGS_KEY).tap do |hash|
hash.delete(QUEUE_KEY) if unique_across_queues?
hash.delete(CLASS_KEY) if unique_across_workers?
end
end
|
ruby
|
def digestable_hash
@item.slice(CLASS_KEY, QUEUE_KEY, UNIQUE_ARGS_KEY).tap do |hash|
hash.delete(QUEUE_KEY) if unique_across_queues?
hash.delete(CLASS_KEY) if unique_across_workers?
end
end
|
[
"def",
"digestable_hash",
"@item",
".",
"slice",
"(",
"CLASS_KEY",
",",
"QUEUE_KEY",
",",
"UNIQUE_ARGS_KEY",
")",
".",
"tap",
"do",
"|",
"hash",
"|",
"hash",
".",
"delete",
"(",
"QUEUE_KEY",
")",
"if",
"unique_across_queues?",
"hash",
".",
"delete",
"(",
"CLASS_KEY",
")",
"if",
"unique_across_workers?",
"end",
"end"
] |
Filter a hash to use for digest
@return [Hash] to use for digest
|
[
"Filter",
"a",
"hash",
"to",
"use",
"for",
"digest"
] |
2944b97c720528f53962ccfd17d43ac939a77f46
|
https://github.com/mhenrixon/sidekiq-unique-jobs/blob/2944b97c720528f53962ccfd17d43ac939a77f46/lib/sidekiq_unique_jobs/unique_args.rb#L62-L67
|
12,485
|
mhenrixon/sidekiq-unique-jobs
|
lib/sidekiq_unique_jobs/unique_args.rb
|
SidekiqUniqueJobs.UniqueArgs.filtered_args
|
def filtered_args(args)
return args if args.empty?
json_args = Normalizer.jsonify(args)
case unique_args_method
when Proc
filter_by_proc(json_args)
when Symbol
filter_by_symbol(json_args)
else
log_debug("#{__method__} arguments not filtered (using all arguments for uniqueness)")
json_args
end
end
|
ruby
|
def filtered_args(args)
return args if args.empty?
json_args = Normalizer.jsonify(args)
case unique_args_method
when Proc
filter_by_proc(json_args)
when Symbol
filter_by_symbol(json_args)
else
log_debug("#{__method__} arguments not filtered (using all arguments for uniqueness)")
json_args
end
end
|
[
"def",
"filtered_args",
"(",
"args",
")",
"return",
"args",
"if",
"args",
".",
"empty?",
"json_args",
"=",
"Normalizer",
".",
"jsonify",
"(",
"args",
")",
"case",
"unique_args_method",
"when",
"Proc",
"filter_by_proc",
"(",
"json_args",
")",
"when",
"Symbol",
"filter_by_symbol",
"(",
"json_args",
")",
"else",
"log_debug",
"(",
"\"#{__method__} arguments not filtered (using all arguments for uniqueness)\"",
")",
"json_args",
"end",
"end"
] |
Filters unique arguments by proc or symbol
@param [Array] args the arguments passed to the sidekiq worker
@return [Array] {#filter_by_proc} when {#unique_args_method} is a Proc
@return [Array] {#filter_by_symbol} when {#unique_args_method} is a Symbol
@return [Array] args unfiltered when neither of the above
|
[
"Filters",
"unique",
"arguments",
"by",
"proc",
"or",
"symbol"
] |
2944b97c720528f53962ccfd17d43ac939a77f46
|
https://github.com/mhenrixon/sidekiq-unique-jobs/blob/2944b97c720528f53962ccfd17d43ac939a77f46/lib/sidekiq_unique_jobs/unique_args.rb#L101-L115
|
12,486
|
mhenrixon/sidekiq-unique-jobs
|
lib/sidekiq_unique_jobs/unique_args.rb
|
SidekiqUniqueJobs.UniqueArgs.filter_by_symbol
|
def filter_by_symbol(args)
return args unless worker_method_defined?(unique_args_method)
worker_class.send(unique_args_method, args)
rescue ArgumentError => ex
log_fatal(ex)
args
end
|
ruby
|
def filter_by_symbol(args)
return args unless worker_method_defined?(unique_args_method)
worker_class.send(unique_args_method, args)
rescue ArgumentError => ex
log_fatal(ex)
args
end
|
[
"def",
"filter_by_symbol",
"(",
"args",
")",
"return",
"args",
"unless",
"worker_method_defined?",
"(",
"unique_args_method",
")",
"worker_class",
".",
"send",
"(",
"unique_args_method",
",",
"args",
")",
"rescue",
"ArgumentError",
"=>",
"ex",
"log_fatal",
"(",
"ex",
")",
"args",
"end"
] |
Filters unique arguments by method configured in the sidekiq worker
@param [Array] args the arguments passed to the sidekiq worker
@return [Array] unfiltered unless {#worker_method_defined?}
@return [Array] with the filtered arguments
|
[
"Filters",
"unique",
"arguments",
"by",
"method",
"configured",
"in",
"the",
"sidekiq",
"worker"
] |
2944b97c720528f53962ccfd17d43ac939a77f46
|
https://github.com/mhenrixon/sidekiq-unique-jobs/blob/2944b97c720528f53962ccfd17d43ac939a77f46/lib/sidekiq_unique_jobs/unique_args.rb#L128-L135
|
12,487
|
k1LoW/awspec
|
lib/awspec/helper/client_wrap.rb
|
Awspec::Helper.ClientWrap.method_missing
|
def method_missing(m, *args, &block)
begin
results = client.send(m, *args, &block)
rescue Exception => e # rubocop:disable Lint/RescueException
raise unless e.class.to_s == symbol.to_s && backoff < backoff_limit
@backoff = backoff + (iteration * iteration * 0.5)
@iteration += 1
sleep backoff
results = self.send(m, *args, &block)
end
reset_backoff
results
end
|
ruby
|
def method_missing(m, *args, &block)
begin
results = client.send(m, *args, &block)
rescue Exception => e # rubocop:disable Lint/RescueException
raise unless e.class.to_s == symbol.to_s && backoff < backoff_limit
@backoff = backoff + (iteration * iteration * 0.5)
@iteration += 1
sleep backoff
results = self.send(m, *args, &block)
end
reset_backoff
results
end
|
[
"def",
"method_missing",
"(",
"m",
",",
"*",
"args",
",",
"&",
"block",
")",
"begin",
"results",
"=",
"client",
".",
"send",
"(",
"m",
",",
"args",
",",
"block",
")",
"rescue",
"Exception",
"=>",
"e",
"# rubocop:disable Lint/RescueException",
"raise",
"unless",
"e",
".",
"class",
".",
"to_s",
"==",
"symbol",
".",
"to_s",
"&&",
"backoff",
"<",
"backoff_limit",
"@backoff",
"=",
"backoff",
"+",
"(",
"iteration",
"*",
"iteration",
"*",
"0.5",
")",
"@iteration",
"+=",
"1",
"sleep",
"backoff",
"results",
"=",
"self",
".",
"send",
"(",
"m",
",",
"args",
",",
"block",
")",
"end",
"reset_backoff",
"results",
"end"
] |
used to capture only the "RequestLimitExceeded" error from an aws
client api call. In the case of matching it we want to try again,
backing off successively each time, until the backoff_limit is reached or
exceeded, in which case, the error will be re-raised and it should fail
as expected.
|
[
"used",
"to",
"capture",
"only",
"the",
"RequestLimitExceeded",
"error",
"from",
"an",
"aws",
"client",
"api",
"call",
".",
"In",
"the",
"case",
"of",
"matching",
"it",
"we",
"want",
"to",
"try",
"again",
"backing",
"off",
"successively",
"each",
"time",
"until",
"the",
"backoff_limit",
"is",
"reached",
"or",
"exceeded",
"in",
"which",
"case",
"the",
"error",
"will",
"be",
"re",
"-",
"raised",
"and",
"it",
"should",
"fail",
"as",
"expected",
"."
] |
d33365040c42c79fa4c8233451d7fe8f24f2c503
|
https://github.com/k1LoW/awspec/blob/d33365040c42c79fa4c8233451d7fe8f24f2c503/lib/awspec/helper/client_wrap.rb#L24-L39
|
12,488
|
palkan/logidze
|
lib/logidze/history.rb
|
Logidze.History.changes_to
|
def changes_to(time: nil, version: nil, data: {}, from: 0)
raise ArgumentError, "Time or version must be specified" if time.nil? && version.nil?
filter = time.nil? ? method(:version_filter) : method(:time_filter)
versions.each_with_object(data.dup) do |v, acc|
next if v.version < from
break acc if filter.call(v, version, time)
acc.merge!(v.changes)
end
end
|
ruby
|
def changes_to(time: nil, version: nil, data: {}, from: 0)
raise ArgumentError, "Time or version must be specified" if time.nil? && version.nil?
filter = time.nil? ? method(:version_filter) : method(:time_filter)
versions.each_with_object(data.dup) do |v, acc|
next if v.version < from
break acc if filter.call(v, version, time)
acc.merge!(v.changes)
end
end
|
[
"def",
"changes_to",
"(",
"time",
":",
"nil",
",",
"version",
":",
"nil",
",",
"data",
":",
"{",
"}",
",",
"from",
":",
"0",
")",
"raise",
"ArgumentError",
",",
"\"Time or version must be specified\"",
"if",
"time",
".",
"nil?",
"&&",
"version",
".",
"nil?",
"filter",
"=",
"time",
".",
"nil?",
"?",
"method",
"(",
":version_filter",
")",
":",
"method",
"(",
":time_filter",
")",
"versions",
".",
"each_with_object",
"(",
"data",
".",
"dup",
")",
"do",
"|",
"v",
",",
"acc",
"|",
"next",
"if",
"v",
".",
"version",
"<",
"from",
"break",
"acc",
"if",
"filter",
".",
"call",
"(",
"v",
",",
"version",
",",
"time",
")",
"acc",
".",
"merge!",
"(",
"v",
".",
"changes",
")",
"end",
"end"
] |
Return diff from the initial state to specified time or version.
Optional `data` paramater can be used as initial diff state.
|
[
"Return",
"diff",
"from",
"the",
"initial",
"state",
"to",
"specified",
"time",
"or",
"version",
".",
"Optional",
"data",
"paramater",
"can",
"be",
"used",
"as",
"initial",
"diff",
"state",
"."
] |
ffa0f793cb9c6fab96fa67a285341ca9aaa7ded8
|
https://github.com/palkan/logidze/blob/ffa0f793cb9c6fab96fa67a285341ca9aaa7ded8/lib/logidze/history.rb#L60-L70
|
12,489
|
palkan/logidze
|
lib/logidze/history.rb
|
Logidze.History.diff_from
|
def diff_from(time: nil, version: nil)
raise ArgumentError, "Time or version must be specified" if time.nil? && version.nil?
from_version = version.nil? ? find_by_time(time) : find_by_version(version)
from_version ||= versions.first
base = changes_to(version: from_version.version)
diff = changes_to(version: self.version, data: base, from: from_version.version + 1)
build_changes(base, diff)
end
|
ruby
|
def diff_from(time: nil, version: nil)
raise ArgumentError, "Time or version must be specified" if time.nil? && version.nil?
from_version = version.nil? ? find_by_time(time) : find_by_version(version)
from_version ||= versions.first
base = changes_to(version: from_version.version)
diff = changes_to(version: self.version, data: base, from: from_version.version + 1)
build_changes(base, diff)
end
|
[
"def",
"diff_from",
"(",
"time",
":",
"nil",
",",
"version",
":",
"nil",
")",
"raise",
"ArgumentError",
",",
"\"Time or version must be specified\"",
"if",
"time",
".",
"nil?",
"&&",
"version",
".",
"nil?",
"from_version",
"=",
"version",
".",
"nil?",
"?",
"find_by_time",
"(",
"time",
")",
":",
"find_by_version",
"(",
"version",
")",
"from_version",
"||=",
"versions",
".",
"first",
"base",
"=",
"changes_to",
"(",
"version",
":",
"from_version",
".",
"version",
")",
"diff",
"=",
"changes_to",
"(",
"version",
":",
"self",
".",
"version",
",",
"data",
":",
"base",
",",
"from",
":",
"from_version",
".",
"version",
"+",
"1",
")",
"build_changes",
"(",
"base",
",",
"diff",
")",
"end"
] |
Return diff object representing changes since specified time or version.
@example
diff_from(time: 2.days.ago)
#=> { "id" => 1, "changes" => { "title" => { "old" => "Hello!", "new" => "World" } } }
rubocop:disable Metrics/AbcSize
|
[
"Return",
"diff",
"object",
"representing",
"changes",
"since",
"specified",
"time",
"or",
"version",
"."
] |
ffa0f793cb9c6fab96fa67a285341ca9aaa7ded8
|
https://github.com/palkan/logidze/blob/ffa0f793cb9c6fab96fa67a285341ca9aaa7ded8/lib/logidze/history.rb#L79-L89
|
12,490
|
palkan/logidze
|
lib/logidze/history.rb
|
Logidze.History.current_ts?
|
def current_ts?(time)
(current_version.time <= time) &&
(next_version.nil? || (next_version.time < time))
end
|
ruby
|
def current_ts?(time)
(current_version.time <= time) &&
(next_version.nil? || (next_version.time < time))
end
|
[
"def",
"current_ts?",
"(",
"time",
")",
"(",
"current_version",
".",
"time",
"<=",
"time",
")",
"&&",
"(",
"next_version",
".",
"nil?",
"||",
"(",
"next_version",
".",
"time",
"<",
"time",
")",
")",
"end"
] |
Return true iff time corresponds to current version
|
[
"Return",
"true",
"iff",
"time",
"corresponds",
"to",
"current",
"version"
] |
ffa0f793cb9c6fab96fa67a285341ca9aaa7ded8
|
https://github.com/palkan/logidze/blob/ffa0f793cb9c6fab96fa67a285341ca9aaa7ded8/lib/logidze/history.rb#L98-L101
|
12,491
|
palkan/logidze
|
lib/logidze/model.rb
|
Logidze.Model.at_version
|
def at_version(version)
return self if log_data.version == version
log_entry = log_data.find_by_version(version)
return nil unless log_entry
build_dup(log_entry)
end
|
ruby
|
def at_version(version)
return self if log_data.version == version
log_entry = log_data.find_by_version(version)
return nil unless log_entry
build_dup(log_entry)
end
|
[
"def",
"at_version",
"(",
"version",
")",
"return",
"self",
"if",
"log_data",
".",
"version",
"==",
"version",
"log_entry",
"=",
"log_data",
".",
"find_by_version",
"(",
"version",
")",
"return",
"nil",
"unless",
"log_entry",
"build_dup",
"(",
"log_entry",
")",
"end"
] |
Return a dirty copy of specified version of record
|
[
"Return",
"a",
"dirty",
"copy",
"of",
"specified",
"version",
"of",
"record"
] |
ffa0f793cb9c6fab96fa67a285341ca9aaa7ded8
|
https://github.com/palkan/logidze/blob/ffa0f793cb9c6fab96fa67a285341ca9aaa7ded8/lib/logidze/model.rb#L111-L118
|
12,492
|
palkan/logidze
|
lib/logidze/model.rb
|
Logidze.Model.diff_from
|
def diff_from(ts = nil, version: nil, time: nil)
Deprecations.show_ts_deprecation_for("#diff_from") if ts
time ||= ts
time = parse_time(time) if time
changes = log_data.diff_from(time: time, version: version).tap do |v|
deserialize_changes!(v)
end
changes.delete_if { |k, _v| deleted_column?(k) }
{ "id" => id, "changes" => changes }
end
|
ruby
|
def diff_from(ts = nil, version: nil, time: nil)
Deprecations.show_ts_deprecation_for("#diff_from") if ts
time ||= ts
time = parse_time(time) if time
changes = log_data.diff_from(time: time, version: version).tap do |v|
deserialize_changes!(v)
end
changes.delete_if { |k, _v| deleted_column?(k) }
{ "id" => id, "changes" => changes }
end
|
[
"def",
"diff_from",
"(",
"ts",
"=",
"nil",
",",
"version",
":",
"nil",
",",
"time",
":",
"nil",
")",
"Deprecations",
".",
"show_ts_deprecation_for",
"(",
"\"#diff_from\"",
")",
"if",
"ts",
"time",
"||=",
"ts",
"time",
"=",
"parse_time",
"(",
"time",
")",
"if",
"time",
"changes",
"=",
"log_data",
".",
"diff_from",
"(",
"time",
":",
"time",
",",
"version",
":",
"version",
")",
".",
"tap",
"do",
"|",
"v",
"|",
"deserialize_changes!",
"(",
"v",
")",
"end",
"changes",
".",
"delete_if",
"{",
"|",
"k",
",",
"_v",
"|",
"deleted_column?",
"(",
"k",
")",
"}",
"{",
"\"id\"",
"=>",
"id",
",",
"\"changes\"",
"=>",
"changes",
"}",
"end"
] |
Return diff object representing changes since specified time.
@example
post.diff_from(time: 2.days.ago) # or post.diff_from(version: 2)
#=> { "id" => 1, "changes" => { "title" => { "old" => "Hello!", "new" => "World" } } }
|
[
"Return",
"diff",
"object",
"representing",
"changes",
"since",
"specified",
"time",
"."
] |
ffa0f793cb9c6fab96fa67a285341ca9aaa7ded8
|
https://github.com/palkan/logidze/blob/ffa0f793cb9c6fab96fa67a285341ca9aaa7ded8/lib/logidze/model.rb#L134-L145
|
12,493
|
palkan/logidze
|
lib/logidze/model.rb
|
Logidze.Model.undo!
|
def undo!(append: Logidze.append_on_undo)
version = log_data.previous_version
return false if version.nil?
switch_to!(version.version, append: append)
end
|
ruby
|
def undo!(append: Logidze.append_on_undo)
version = log_data.previous_version
return false if version.nil?
switch_to!(version.version, append: append)
end
|
[
"def",
"undo!",
"(",
"append",
":",
"Logidze",
".",
"append_on_undo",
")",
"version",
"=",
"log_data",
".",
"previous_version",
"return",
"false",
"if",
"version",
".",
"nil?",
"switch_to!",
"(",
"version",
".",
"version",
",",
"append",
":",
"append",
")",
"end"
] |
Restore record to the previous version.
Return false if no previous version found, otherwise return updated record.
|
[
"Restore",
"record",
"to",
"the",
"previous",
"version",
".",
"Return",
"false",
"if",
"no",
"previous",
"version",
"found",
"otherwise",
"return",
"updated",
"record",
"."
] |
ffa0f793cb9c6fab96fa67a285341ca9aaa7ded8
|
https://github.com/palkan/logidze/blob/ffa0f793cb9c6fab96fa67a285341ca9aaa7ded8/lib/logidze/model.rb#L149-L154
|
12,494
|
palkan/logidze
|
lib/logidze/model.rb
|
Logidze.Model.switch_to!
|
def switch_to!(version, append: Logidze.append_on_undo)
return false unless at_version(version)
if append && version < log_version
update!(log_data.changes_to(version: version))
else
at_version!(version)
self.class.without_logging { save! }
end
end
|
ruby
|
def switch_to!(version, append: Logidze.append_on_undo)
return false unless at_version(version)
if append && version < log_version
update!(log_data.changes_to(version: version))
else
at_version!(version)
self.class.without_logging { save! }
end
end
|
[
"def",
"switch_to!",
"(",
"version",
",",
"append",
":",
"Logidze",
".",
"append_on_undo",
")",
"return",
"false",
"unless",
"at_version",
"(",
"version",
")",
"if",
"append",
"&&",
"version",
"<",
"log_version",
"update!",
"(",
"log_data",
".",
"changes_to",
"(",
"version",
":",
"version",
")",
")",
"else",
"at_version!",
"(",
"version",
")",
"self",
".",
"class",
".",
"without_logging",
"{",
"save!",
"}",
"end",
"end"
] |
Restore record to the specified version.
Return false if version is unknown.
|
[
"Restore",
"record",
"to",
"the",
"specified",
"version",
".",
"Return",
"false",
"if",
"version",
"is",
"unknown",
"."
] |
ffa0f793cb9c6fab96fa67a285341ca9aaa7ded8
|
https://github.com/palkan/logidze/blob/ffa0f793cb9c6fab96fa67a285341ca9aaa7ded8/lib/logidze/model.rb#L167-L176
|
12,495
|
markdownlint/markdownlint
|
lib/mdl/doc.rb
|
MarkdownLint.Doc.find_type
|
def find_type(type, nested=true)
find_type_elements(type, nested).map { |e| e.options }
end
|
ruby
|
def find_type(type, nested=true)
find_type_elements(type, nested).map { |e| e.options }
end
|
[
"def",
"find_type",
"(",
"type",
",",
"nested",
"=",
"true",
")",
"find_type_elements",
"(",
"type",
",",
"nested",
")",
".",
"map",
"{",
"|",
"e",
"|",
"e",
".",
"options",
"}",
"end"
] |
Find all elements of a given type, returning their options hash. The
options hash has most of the useful data about an element and often you
can just use this in your rules.
# Returns [ { :location => 1, :element_level => 2 }, ... ]
elements = find_type(:li)
If +nested+ is set to false, this returns only top level elements of a
given type.
|
[
"Find",
"all",
"elements",
"of",
"a",
"given",
"type",
"returning",
"their",
"options",
"hash",
".",
"The",
"options",
"hash",
"has",
"most",
"of",
"the",
"useful",
"data",
"about",
"an",
"element",
"and",
"often",
"you",
"can",
"just",
"use",
"this",
"in",
"your",
"rules",
"."
] |
a9e80fcf3989d73b654b00bb2225a00be53983e8
|
https://github.com/markdownlint/markdownlint/blob/a9e80fcf3989d73b654b00bb2225a00be53983e8/lib/mdl/doc.rb#L72-L74
|
12,496
|
markdownlint/markdownlint
|
lib/mdl/doc.rb
|
MarkdownLint.Doc.find_type_elements
|
def find_type_elements(type, nested=true, elements=@elements)
results = []
if type.class == Symbol
type = [type]
end
elements.each do |e|
results.push(e) if type.include?(e.type)
if nested and not e.children.empty?
results.concat(find_type_elements(type, nested, e.children))
end
end
results
end
|
ruby
|
def find_type_elements(type, nested=true, elements=@elements)
results = []
if type.class == Symbol
type = [type]
end
elements.each do |e|
results.push(e) if type.include?(e.type)
if nested and not e.children.empty?
results.concat(find_type_elements(type, nested, e.children))
end
end
results
end
|
[
"def",
"find_type_elements",
"(",
"type",
",",
"nested",
"=",
"true",
",",
"elements",
"=",
"@elements",
")",
"results",
"=",
"[",
"]",
"if",
"type",
".",
"class",
"==",
"Symbol",
"type",
"=",
"[",
"type",
"]",
"end",
"elements",
".",
"each",
"do",
"|",
"e",
"|",
"results",
".",
"push",
"(",
"e",
")",
"if",
"type",
".",
"include?",
"(",
"e",
".",
"type",
")",
"if",
"nested",
"and",
"not",
"e",
".",
"children",
".",
"empty?",
"results",
".",
"concat",
"(",
"find_type_elements",
"(",
"type",
",",
"nested",
",",
"e",
".",
"children",
")",
")",
"end",
"end",
"results",
"end"
] |
Find all elements of a given type, returning a list of the element
objects themselves.
Instead of a single type, a list of types can be provided instead to
find all types.
If +nested+ is set to false, this returns only top level elements of a
given type.
|
[
"Find",
"all",
"elements",
"of",
"a",
"given",
"type",
"returning",
"a",
"list",
"of",
"the",
"element",
"objects",
"themselves",
"."
] |
a9e80fcf3989d73b654b00bb2225a00be53983e8
|
https://github.com/markdownlint/markdownlint/blob/a9e80fcf3989d73b654b00bb2225a00be53983e8/lib/mdl/doc.rb#L86-L98
|
12,497
|
markdownlint/markdownlint
|
lib/mdl/doc.rb
|
MarkdownLint.Doc.find_type_elements_except
|
def find_type_elements_except(type, nested_except=[], elements=@elements)
results = []
if type.class == Symbol
type = [type]
end
if nested_except.class == Symbol
nested_except = [nested_except]
end
elements.each do |e|
results.push(e) if type.include?(e.type)
unless nested_except.include?(e.type) or e.children.empty?
results.concat(find_type_elements_except(type, nested_except, e.children))
end
end
results
end
|
ruby
|
def find_type_elements_except(type, nested_except=[], elements=@elements)
results = []
if type.class == Symbol
type = [type]
end
if nested_except.class == Symbol
nested_except = [nested_except]
end
elements.each do |e|
results.push(e) if type.include?(e.type)
unless nested_except.include?(e.type) or e.children.empty?
results.concat(find_type_elements_except(type, nested_except, e.children))
end
end
results
end
|
[
"def",
"find_type_elements_except",
"(",
"type",
",",
"nested_except",
"=",
"[",
"]",
",",
"elements",
"=",
"@elements",
")",
"results",
"=",
"[",
"]",
"if",
"type",
".",
"class",
"==",
"Symbol",
"type",
"=",
"[",
"type",
"]",
"end",
"if",
"nested_except",
".",
"class",
"==",
"Symbol",
"nested_except",
"=",
"[",
"nested_except",
"]",
"end",
"elements",
".",
"each",
"do",
"|",
"e",
"|",
"results",
".",
"push",
"(",
"e",
")",
"if",
"type",
".",
"include?",
"(",
"e",
".",
"type",
")",
"unless",
"nested_except",
".",
"include?",
"(",
"e",
".",
"type",
")",
"or",
"e",
".",
"children",
".",
"empty?",
"results",
".",
"concat",
"(",
"find_type_elements_except",
"(",
"type",
",",
"nested_except",
",",
"e",
".",
"children",
")",
")",
"end",
"end",
"results",
"end"
] |
A variation on find_type_elements that allows you to skip drilling down
into children of specific element types.
Instead of a single type, a list of types can be provided instead to
find all types.
Unlike find_type_elements, this method will always search for nested
elements, and skip the element types given to nested_except.
|
[
"A",
"variation",
"on",
"find_type_elements",
"that",
"allows",
"you",
"to",
"skip",
"drilling",
"down",
"into",
"children",
"of",
"specific",
"element",
"types",
"."
] |
a9e80fcf3989d73b654b00bb2225a00be53983e8
|
https://github.com/markdownlint/markdownlint/blob/a9e80fcf3989d73b654b00bb2225a00be53983e8/lib/mdl/doc.rb#L110-L125
|
12,498
|
markdownlint/markdownlint
|
lib/mdl/doc.rb
|
MarkdownLint.Doc.element_linenumber
|
def element_linenumber(element)
element = element.options if element.is_a?(Kramdown::Element)
element[:location]
end
|
ruby
|
def element_linenumber(element)
element = element.options if element.is_a?(Kramdown::Element)
element[:location]
end
|
[
"def",
"element_linenumber",
"(",
"element",
")",
"element",
"=",
"element",
".",
"options",
"if",
"element",
".",
"is_a?",
"(",
"Kramdown",
"::",
"Element",
")",
"element",
"[",
":location",
"]",
"end"
] |
Returns the line number a given element is located on in the source
file. You can pass in either an element object or an options hash here.
|
[
"Returns",
"the",
"line",
"number",
"a",
"given",
"element",
"is",
"located",
"on",
"in",
"the",
"source",
"file",
".",
"You",
"can",
"pass",
"in",
"either",
"an",
"element",
"object",
"or",
"an",
"options",
"hash",
"here",
"."
] |
a9e80fcf3989d73b654b00bb2225a00be53983e8
|
https://github.com/markdownlint/markdownlint/blob/a9e80fcf3989d73b654b00bb2225a00be53983e8/lib/mdl/doc.rb#L131-L134
|
12,499
|
markdownlint/markdownlint
|
lib/mdl/doc.rb
|
MarkdownLint.Doc.matching_lines
|
def matching_lines(re)
@lines.each_with_index.select{|text, linenum| re.match(text)}.map{
|i| i[1]+1}
end
|
ruby
|
def matching_lines(re)
@lines.each_with_index.select{|text, linenum| re.match(text)}.map{
|i| i[1]+1}
end
|
[
"def",
"matching_lines",
"(",
"re",
")",
"@lines",
".",
"each_with_index",
".",
"select",
"{",
"|",
"text",
",",
"linenum",
"|",
"re",
".",
"match",
"(",
"text",
")",
"}",
".",
"map",
"{",
"|",
"i",
"|",
"i",
"[",
"1",
"]",
"+",
"1",
"}",
"end"
] |
Returns line numbers for lines that match the given regular expression
|
[
"Returns",
"line",
"numbers",
"for",
"lines",
"that",
"match",
"the",
"given",
"regular",
"expression"
] |
a9e80fcf3989d73b654b00bb2225a00be53983e8
|
https://github.com/markdownlint/markdownlint/blob/a9e80fcf3989d73b654b00bb2225a00be53983e8/lib/mdl/doc.rb#L220-L223
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.