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,900
|
seejohnrun/ice_cube
|
lib/ice_cube/validations/fixed_value.rb
|
IceCube.Validations::FixedValue.validate_day_lock
|
def validate_day_lock(time, start_time)
days_in_month = TimeUtil.days_in_month(time)
date = Date.new(time.year, time.month, time.day)
if value && value < 0
start = TimeUtil.day_of_month(value, date)
month_overflow = days_in_month - TimeUtil.days_in_next_month(time)
elsif value && value > 0
start = value
month_overflow = 0
else
start = TimeUtil.day_of_month(start_time.day, date)
month_overflow = 0
end
sleeps = start - date.day
if value && value > 0
until_next_month = days_in_month + sleeps
else
until_next_month = start < 28 ? days_in_month : TimeUtil.days_to_next_month(date)
until_next_month += sleeps - month_overflow
end
sleeps >= 0 ? sleeps : until_next_month
end
|
ruby
|
def validate_day_lock(time, start_time)
days_in_month = TimeUtil.days_in_month(time)
date = Date.new(time.year, time.month, time.day)
if value && value < 0
start = TimeUtil.day_of_month(value, date)
month_overflow = days_in_month - TimeUtil.days_in_next_month(time)
elsif value && value > 0
start = value
month_overflow = 0
else
start = TimeUtil.day_of_month(start_time.day, date)
month_overflow = 0
end
sleeps = start - date.day
if value && value > 0
until_next_month = days_in_month + sleeps
else
until_next_month = start < 28 ? days_in_month : TimeUtil.days_to_next_month(date)
until_next_month += sleeps - month_overflow
end
sleeps >= 0 ? sleeps : until_next_month
end
|
[
"def",
"validate_day_lock",
"(",
"time",
",",
"start_time",
")",
"days_in_month",
"=",
"TimeUtil",
".",
"days_in_month",
"(",
"time",
")",
"date",
"=",
"Date",
".",
"new",
"(",
"time",
".",
"year",
",",
"time",
".",
"month",
",",
"time",
".",
"day",
")",
"if",
"value",
"&&",
"value",
"<",
"0",
"start",
"=",
"TimeUtil",
".",
"day_of_month",
"(",
"value",
",",
"date",
")",
"month_overflow",
"=",
"days_in_month",
"-",
"TimeUtil",
".",
"days_in_next_month",
"(",
"time",
")",
"elsif",
"value",
"&&",
"value",
">",
"0",
"start",
"=",
"value",
"month_overflow",
"=",
"0",
"else",
"start",
"=",
"TimeUtil",
".",
"day_of_month",
"(",
"start_time",
".",
"day",
",",
"date",
")",
"month_overflow",
"=",
"0",
"end",
"sleeps",
"=",
"start",
"-",
"date",
".",
"day",
"if",
"value",
"&&",
"value",
">",
"0",
"until_next_month",
"=",
"days_in_month",
"+",
"sleeps",
"else",
"until_next_month",
"=",
"start",
"<",
"28",
"?",
"days_in_month",
":",
"TimeUtil",
".",
"days_to_next_month",
"(",
"date",
")",
"until_next_month",
"+=",
"sleeps",
"-",
"month_overflow",
"end",
"sleeps",
">=",
"0",
"?",
"sleeps",
":",
"until_next_month",
"end"
] |
For monthly rules that have no specified day value, the validation relies
on the schedule start time and jumps to include every month even if it
has fewer days than the schedule's start day.
Negative day values (from month end) also include all months.
Positive day values are taken literally so months with fewer days will
be skipped.
|
[
"For",
"monthly",
"rules",
"that",
"have",
"no",
"specified",
"day",
"value",
"the",
"validation",
"relies",
"on",
"the",
"schedule",
"start",
"time",
"and",
"jumps",
"to",
"include",
"every",
"month",
"even",
"if",
"it",
"has",
"fewer",
"days",
"than",
"the",
"schedule",
"s",
"start",
"day",
"."
] |
fb6c657bdc4f87dfda2bf83f15c5f487b78ccabd
|
https://github.com/seejohnrun/ice_cube/blob/fb6c657bdc4f87dfda2bf83f15c5f487b78ccabd/lib/ice_cube/validations/fixed_value.rb#L60-L85
|
12,901
|
seejohnrun/ice_cube
|
lib/ice_cube/builders/ical_builder.rb
|
IceCube.IcalBuilder.to_s
|
def to_s
arr = []
if freq = @hash.delete('FREQ')
arr << "FREQ=#{freq.join(',')}"
end
arr.concat(@hash.map do |key, value|
if value.is_a?(Array)
"#{key}=#{value.join(',')}"
end
end.compact)
arr.join(';')
end
|
ruby
|
def to_s
arr = []
if freq = @hash.delete('FREQ')
arr << "FREQ=#{freq.join(',')}"
end
arr.concat(@hash.map do |key, value|
if value.is_a?(Array)
"#{key}=#{value.join(',')}"
end
end.compact)
arr.join(';')
end
|
[
"def",
"to_s",
"arr",
"=",
"[",
"]",
"if",
"freq",
"=",
"@hash",
".",
"delete",
"(",
"'FREQ'",
")",
"arr",
"<<",
"\"FREQ=#{freq.join(',')}\"",
"end",
"arr",
".",
"concat",
"(",
"@hash",
".",
"map",
"do",
"|",
"key",
",",
"value",
"|",
"if",
"value",
".",
"is_a?",
"(",
"Array",
")",
"\"#{key}=#{value.join(',')}\"",
"end",
"end",
".",
"compact",
")",
"arr",
".",
"join",
"(",
"';'",
")",
"end"
] |
Build for a single rule entry
|
[
"Build",
"for",
"a",
"single",
"rule",
"entry"
] |
fb6c657bdc4f87dfda2bf83f15c5f487b78ccabd
|
https://github.com/seejohnrun/ice_cube/blob/fb6c657bdc4f87dfda2bf83f15c5f487b78ccabd/lib/ice_cube/builders/ical_builder.rb#L20-L31
|
12,902
|
seejohnrun/ice_cube
|
lib/ice_cube/validations/hour_of_day.rb
|
IceCube.Validations::HourOfDay.hour_of_day
|
def hour_of_day(*hours)
hours.flatten.each do |hour|
unless hour.is_a?(Integer)
raise ArgumentError, "expecting Integer value for hour, got #{hour.inspect}"
end
verify_alignment(hour, :hour, :hour_of_day) { |error| raise error }
validations_for(:hour_of_day) << Validation.new(hour)
end
clobber_base_validations(:hour)
self
end
|
ruby
|
def hour_of_day(*hours)
hours.flatten.each do |hour|
unless hour.is_a?(Integer)
raise ArgumentError, "expecting Integer value for hour, got #{hour.inspect}"
end
verify_alignment(hour, :hour, :hour_of_day) { |error| raise error }
validations_for(:hour_of_day) << Validation.new(hour)
end
clobber_base_validations(:hour)
self
end
|
[
"def",
"hour_of_day",
"(",
"*",
"hours",
")",
"hours",
".",
"flatten",
".",
"each",
"do",
"|",
"hour",
"|",
"unless",
"hour",
".",
"is_a?",
"(",
"Integer",
")",
"raise",
"ArgumentError",
",",
"\"expecting Integer value for hour, got #{hour.inspect}\"",
"end",
"verify_alignment",
"(",
"hour",
",",
":hour",
",",
":hour_of_day",
")",
"{",
"|",
"error",
"|",
"raise",
"error",
"}",
"validations_for",
"(",
":hour_of_day",
")",
"<<",
"Validation",
".",
"new",
"(",
"hour",
")",
"end",
"clobber_base_validations",
"(",
":hour",
")",
"self",
"end"
] |
Add hour of day validations
|
[
"Add",
"hour",
"of",
"day",
"validations"
] |
fb6c657bdc4f87dfda2bf83f15c5f487b78ccabd
|
https://github.com/seejohnrun/ice_cube/blob/fb6c657bdc4f87dfda2bf83f15c5f487b78ccabd/lib/ice_cube/validations/hour_of_day.rb#L6-L18
|
12,903
|
seejohnrun/ice_cube
|
lib/ice_cube/schedule.rb
|
IceCube.Schedule.add_recurrence_time
|
def add_recurrence_time(time)
return if time.nil?
rule = SingleOccurrenceRule.new(time)
add_recurrence_rule rule
time
end
|
ruby
|
def add_recurrence_time(time)
return if time.nil?
rule = SingleOccurrenceRule.new(time)
add_recurrence_rule rule
time
end
|
[
"def",
"add_recurrence_time",
"(",
"time",
")",
"return",
"if",
"time",
".",
"nil?",
"rule",
"=",
"SingleOccurrenceRule",
".",
"new",
"(",
"time",
")",
"add_recurrence_rule",
"rule",
"time",
"end"
] |
Add a recurrence time to the schedule
|
[
"Add",
"a",
"recurrence",
"time",
"to",
"the",
"schedule"
] |
fb6c657bdc4f87dfda2bf83f15c5f487b78ccabd
|
https://github.com/seejohnrun/ice_cube/blob/fb6c657bdc4f87dfda2bf83f15c5f487b78ccabd/lib/ice_cube/schedule.rb#L48-L53
|
12,904
|
seejohnrun/ice_cube
|
lib/ice_cube/schedule.rb
|
IceCube.Schedule.add_exception_time
|
def add_exception_time(time)
return if time.nil?
rule = SingleOccurrenceRule.new(time)
add_exception_rule rule
time
end
|
ruby
|
def add_exception_time(time)
return if time.nil?
rule = SingleOccurrenceRule.new(time)
add_exception_rule rule
time
end
|
[
"def",
"add_exception_time",
"(",
"time",
")",
"return",
"if",
"time",
".",
"nil?",
"rule",
"=",
"SingleOccurrenceRule",
".",
"new",
"(",
"time",
")",
"add_exception_rule",
"rule",
"time",
"end"
] |
Add an exception time to the schedule
|
[
"Add",
"an",
"exception",
"time",
"to",
"the",
"schedule"
] |
fb6c657bdc4f87dfda2bf83f15c5f487b78ccabd
|
https://github.com/seejohnrun/ice_cube/blob/fb6c657bdc4f87dfda2bf83f15c5f487b78ccabd/lib/ice_cube/schedule.rb#L59-L64
|
12,905
|
seejohnrun/ice_cube
|
lib/ice_cube/schedule.rb
|
IceCube.Schedule.remove_recurrence_time
|
def remove_recurrence_time(time)
found = false
@all_recurrence_rules.delete_if do |rule|
found = true if rule.is_a?(SingleOccurrenceRule) && rule.time == time
end
time if found
end
|
ruby
|
def remove_recurrence_time(time)
found = false
@all_recurrence_rules.delete_if do |rule|
found = true if rule.is_a?(SingleOccurrenceRule) && rule.time == time
end
time if found
end
|
[
"def",
"remove_recurrence_time",
"(",
"time",
")",
"found",
"=",
"false",
"@all_recurrence_rules",
".",
"delete_if",
"do",
"|",
"rule",
"|",
"found",
"=",
"true",
"if",
"rule",
".",
"is_a?",
"(",
"SingleOccurrenceRule",
")",
"&&",
"rule",
".",
"time",
"==",
"time",
"end",
"time",
"if",
"found",
"end"
] |
Remove a recurrence time
|
[
"Remove",
"a",
"recurrence",
"time"
] |
fb6c657bdc4f87dfda2bf83f15c5f487b78ccabd
|
https://github.com/seejohnrun/ice_cube/blob/fb6c657bdc4f87dfda2bf83f15c5f487b78ccabd/lib/ice_cube/schedule.rb#L116-L122
|
12,906
|
seejohnrun/ice_cube
|
lib/ice_cube/schedule.rb
|
IceCube.Schedule.next_occurrences
|
def next_occurrences(num, from = nil, options = {})
from = TimeUtil.match_zone(from, start_time) || TimeUtil.now(start_time)
enumerate_occurrences(from + 1, nil, options).take(num)
end
|
ruby
|
def next_occurrences(num, from = nil, options = {})
from = TimeUtil.match_zone(from, start_time) || TimeUtil.now(start_time)
enumerate_occurrences(from + 1, nil, options).take(num)
end
|
[
"def",
"next_occurrences",
"(",
"num",
",",
"from",
"=",
"nil",
",",
"options",
"=",
"{",
"}",
")",
"from",
"=",
"TimeUtil",
".",
"match_zone",
"(",
"from",
",",
"start_time",
")",
"||",
"TimeUtil",
".",
"now",
"(",
"start_time",
")",
"enumerate_occurrences",
"(",
"from",
"+",
"1",
",",
"nil",
",",
"options",
")",
".",
"take",
"(",
"num",
")",
"end"
] |
The next n occurrences after now
|
[
"The",
"next",
"n",
"occurrences",
"after",
"now"
] |
fb6c657bdc4f87dfda2bf83f15c5f487b78ccabd
|
https://github.com/seejohnrun/ice_cube/blob/fb6c657bdc4f87dfda2bf83f15c5f487b78ccabd/lib/ice_cube/schedule.rb#L171-L174
|
12,907
|
seejohnrun/ice_cube
|
lib/ice_cube/schedule.rb
|
IceCube.Schedule.previous_occurrence
|
def previous_occurrence(from)
from = TimeUtil.match_zone(from, start_time) or raise ArgumentError, "Time required, got #{from.inspect}"
return nil if from <= start_time
enumerate_occurrences(start_time, from - 1).to_a.last
end
|
ruby
|
def previous_occurrence(from)
from = TimeUtil.match_zone(from, start_time) or raise ArgumentError, "Time required, got #{from.inspect}"
return nil if from <= start_time
enumerate_occurrences(start_time, from - 1).to_a.last
end
|
[
"def",
"previous_occurrence",
"(",
"from",
")",
"from",
"=",
"TimeUtil",
".",
"match_zone",
"(",
"from",
",",
"start_time",
")",
"or",
"raise",
"ArgumentError",
",",
"\"Time required, got #{from.inspect}\"",
"return",
"nil",
"if",
"from",
"<=",
"start_time",
"enumerate_occurrences",
"(",
"start_time",
",",
"from",
"-",
"1",
")",
".",
"to_a",
".",
"last",
"end"
] |
The previous occurrence from a given time
|
[
"The",
"previous",
"occurrence",
"from",
"a",
"given",
"time"
] |
fb6c657bdc4f87dfda2bf83f15c5f487b78ccabd
|
https://github.com/seejohnrun/ice_cube/blob/fb6c657bdc4f87dfda2bf83f15c5f487b78ccabd/lib/ice_cube/schedule.rb#L185-L189
|
12,908
|
seejohnrun/ice_cube
|
lib/ice_cube/schedule.rb
|
IceCube.Schedule.previous_occurrences
|
def previous_occurrences(num, from)
from = TimeUtil.match_zone(from, start_time) or raise ArgumentError, "Time required, got #{from.inspect}"
return [] if from <= start_time
a = enumerate_occurrences(start_time, from - 1).to_a
a.size > num ? a[-1*num,a.size] : a
end
|
ruby
|
def previous_occurrences(num, from)
from = TimeUtil.match_zone(from, start_time) or raise ArgumentError, "Time required, got #{from.inspect}"
return [] if from <= start_time
a = enumerate_occurrences(start_time, from - 1).to_a
a.size > num ? a[-1*num,a.size] : a
end
|
[
"def",
"previous_occurrences",
"(",
"num",
",",
"from",
")",
"from",
"=",
"TimeUtil",
".",
"match_zone",
"(",
"from",
",",
"start_time",
")",
"or",
"raise",
"ArgumentError",
",",
"\"Time required, got #{from.inspect}\"",
"return",
"[",
"]",
"if",
"from",
"<=",
"start_time",
"a",
"=",
"enumerate_occurrences",
"(",
"start_time",
",",
"from",
"-",
"1",
")",
".",
"to_a",
"a",
".",
"size",
">",
"num",
"?",
"a",
"[",
"-",
"1",
"*",
"num",
",",
"a",
".",
"size",
"]",
":",
"a",
"end"
] |
The previous n occurrences before a given time
|
[
"The",
"previous",
"n",
"occurrences",
"before",
"a",
"given",
"time"
] |
fb6c657bdc4f87dfda2bf83f15c5f487b78ccabd
|
https://github.com/seejohnrun/ice_cube/blob/fb6c657bdc4f87dfda2bf83f15c5f487b78ccabd/lib/ice_cube/schedule.rb#L192-L197
|
12,909
|
seejohnrun/ice_cube
|
lib/ice_cube/schedule.rb
|
IceCube.Schedule.occurs_between?
|
def occurs_between?(begin_time, closing_time, options = {})
enumerate_occurrences(begin_time, closing_time, options).next
true
rescue StopIteration
false
end
|
ruby
|
def occurs_between?(begin_time, closing_time, options = {})
enumerate_occurrences(begin_time, closing_time, options).next
true
rescue StopIteration
false
end
|
[
"def",
"occurs_between?",
"(",
"begin_time",
",",
"closing_time",
",",
"options",
"=",
"{",
"}",
")",
"enumerate_occurrences",
"(",
"begin_time",
",",
"closing_time",
",",
"options",
")",
".",
"next",
"true",
"rescue",
"StopIteration",
"false",
"end"
] |
Return a boolean indicating if an occurrence falls between two times
|
[
"Return",
"a",
"boolean",
"indicating",
"if",
"an",
"occurrence",
"falls",
"between",
"two",
"times"
] |
fb6c657bdc4f87dfda2bf83f15c5f487b78ccabd
|
https://github.com/seejohnrun/ice_cube/blob/fb6c657bdc4f87dfda2bf83f15c5f487b78ccabd/lib/ice_cube/schedule.rb#L218-L223
|
12,910
|
seejohnrun/ice_cube
|
lib/ice_cube/schedule.rb
|
IceCube.Schedule.occurs_on?
|
def occurs_on?(date)
date = TimeUtil.ensure_date(date)
begin_time = TimeUtil.beginning_of_date(date, start_time)
closing_time = TimeUtil.end_of_date(date, start_time)
occurs_between?(begin_time, closing_time)
end
|
ruby
|
def occurs_on?(date)
date = TimeUtil.ensure_date(date)
begin_time = TimeUtil.beginning_of_date(date, start_time)
closing_time = TimeUtil.end_of_date(date, start_time)
occurs_between?(begin_time, closing_time)
end
|
[
"def",
"occurs_on?",
"(",
"date",
")",
"date",
"=",
"TimeUtil",
".",
"ensure_date",
"(",
"date",
")",
"begin_time",
"=",
"TimeUtil",
".",
"beginning_of_date",
"(",
"date",
",",
"start_time",
")",
"closing_time",
"=",
"TimeUtil",
".",
"end_of_date",
"(",
"date",
",",
"start_time",
")",
"occurs_between?",
"(",
"begin_time",
",",
"closing_time",
")",
"end"
] |
Return a boolean indicating if an occurrence falls on a certain date
|
[
"Return",
"a",
"boolean",
"indicating",
"if",
"an",
"occurrence",
"falls",
"on",
"a",
"certain",
"date"
] |
fb6c657bdc4f87dfda2bf83f15c5f487b78ccabd
|
https://github.com/seejohnrun/ice_cube/blob/fb6c657bdc4f87dfda2bf83f15c5f487b78ccabd/lib/ice_cube/schedule.rb#L235-L240
|
12,911
|
seejohnrun/ice_cube
|
lib/ice_cube/schedule.rb
|
IceCube.Schedule.occurring_at?
|
def occurring_at?(time)
time = TimeUtil.match_zone(time, start_time) or raise ArgumentError, "Time required, got #{time.inspect}"
if duration > 0
return false if exception_time?(time)
occurs_between?(time - duration + 1, time)
else
occurs_at?(time)
end
end
|
ruby
|
def occurring_at?(time)
time = TimeUtil.match_zone(time, start_time) or raise ArgumentError, "Time required, got #{time.inspect}"
if duration > 0
return false if exception_time?(time)
occurs_between?(time - duration + 1, time)
else
occurs_at?(time)
end
end
|
[
"def",
"occurring_at?",
"(",
"time",
")",
"time",
"=",
"TimeUtil",
".",
"match_zone",
"(",
"time",
",",
"start_time",
")",
"or",
"raise",
"ArgumentError",
",",
"\"Time required, got #{time.inspect}\"",
"if",
"duration",
">",
"0",
"return",
"false",
"if",
"exception_time?",
"(",
"time",
")",
"occurs_between?",
"(",
"time",
"-",
"duration",
"+",
"1",
",",
"time",
")",
"else",
"occurs_at?",
"(",
"time",
")",
"end",
"end"
] |
Determine if the schedule is occurring at a given time
|
[
"Determine",
"if",
"the",
"schedule",
"is",
"occurring",
"at",
"a",
"given",
"time"
] |
fb6c657bdc4f87dfda2bf83f15c5f487b78ccabd
|
https://github.com/seejohnrun/ice_cube/blob/fb6c657bdc4f87dfda2bf83f15c5f487b78ccabd/lib/ice_cube/schedule.rb#L243-L251
|
12,912
|
seejohnrun/ice_cube
|
lib/ice_cube/schedule.rb
|
IceCube.Schedule.conflicts_with?
|
def conflicts_with?(other_schedule, closing_time = nil)
closing_time = TimeUtil.ensure_time(closing_time)
unless terminating? || other_schedule.terminating? || closing_time
raise ArgumentError, "One or both schedules must be terminating to use #conflicts_with?"
end
# Pick the terminating schedule, and other schedule
# No need to reverse if terminating? or there is a closing time
terminating_schedule = self
unless terminating? || closing_time
terminating_schedule, other_schedule = other_schedule, terminating_schedule
end
# Go through each occurrence of the terminating schedule and determine
# if the other occurs at that time
#
last_time = nil
terminating_schedule.each_occurrence do |time|
if closing_time && time > closing_time
last_time = closing_time
break
end
last_time = time
return true if other_schedule.occurring_at?(time)
end
# Due to durations, we need to walk up to the end time, and verify in the
# other direction
if last_time
last_time += terminating_schedule.duration
other_schedule.each_occurrence do |time|
break if time > last_time
return true if terminating_schedule.occurring_at?(time)
end
end
# No conflict, return false
false
end
|
ruby
|
def conflicts_with?(other_schedule, closing_time = nil)
closing_time = TimeUtil.ensure_time(closing_time)
unless terminating? || other_schedule.terminating? || closing_time
raise ArgumentError, "One or both schedules must be terminating to use #conflicts_with?"
end
# Pick the terminating schedule, and other schedule
# No need to reverse if terminating? or there is a closing time
terminating_schedule = self
unless terminating? || closing_time
terminating_schedule, other_schedule = other_schedule, terminating_schedule
end
# Go through each occurrence of the terminating schedule and determine
# if the other occurs at that time
#
last_time = nil
terminating_schedule.each_occurrence do |time|
if closing_time && time > closing_time
last_time = closing_time
break
end
last_time = time
return true if other_schedule.occurring_at?(time)
end
# Due to durations, we need to walk up to the end time, and verify in the
# other direction
if last_time
last_time += terminating_schedule.duration
other_schedule.each_occurrence do |time|
break if time > last_time
return true if terminating_schedule.occurring_at?(time)
end
end
# No conflict, return false
false
end
|
[
"def",
"conflicts_with?",
"(",
"other_schedule",
",",
"closing_time",
"=",
"nil",
")",
"closing_time",
"=",
"TimeUtil",
".",
"ensure_time",
"(",
"closing_time",
")",
"unless",
"terminating?",
"||",
"other_schedule",
".",
"terminating?",
"||",
"closing_time",
"raise",
"ArgumentError",
",",
"\"One or both schedules must be terminating to use #conflicts_with?\"",
"end",
"# Pick the terminating schedule, and other schedule",
"# No need to reverse if terminating? or there is a closing time",
"terminating_schedule",
"=",
"self",
"unless",
"terminating?",
"||",
"closing_time",
"terminating_schedule",
",",
"other_schedule",
"=",
"other_schedule",
",",
"terminating_schedule",
"end",
"# Go through each occurrence of the terminating schedule and determine",
"# if the other occurs at that time",
"#",
"last_time",
"=",
"nil",
"terminating_schedule",
".",
"each_occurrence",
"do",
"|",
"time",
"|",
"if",
"closing_time",
"&&",
"time",
">",
"closing_time",
"last_time",
"=",
"closing_time",
"break",
"end",
"last_time",
"=",
"time",
"return",
"true",
"if",
"other_schedule",
".",
"occurring_at?",
"(",
"time",
")",
"end",
"# Due to durations, we need to walk up to the end time, and verify in the",
"# other direction",
"if",
"last_time",
"last_time",
"+=",
"terminating_schedule",
".",
"duration",
"other_schedule",
".",
"each_occurrence",
"do",
"|",
"time",
"|",
"break",
"if",
"time",
">",
"last_time",
"return",
"true",
"if",
"terminating_schedule",
".",
"occurring_at?",
"(",
"time",
")",
"end",
"end",
"# No conflict, return false",
"false",
"end"
] |
Determine if this schedule conflicts with another schedule
@param [IceCube::Schedule] other_schedule - The schedule to compare to
@param [Time] closing_time - the last time to consider
@return [Boolean] whether or not the schedules conflict at all
|
[
"Determine",
"if",
"this",
"schedule",
"conflicts",
"with",
"another",
"schedule"
] |
fb6c657bdc4f87dfda2bf83f15c5f487b78ccabd
|
https://github.com/seejohnrun/ice_cube/blob/fb6c657bdc4f87dfda2bf83f15c5f487b78ccabd/lib/ice_cube/schedule.rb#L257-L291
|
12,913
|
seejohnrun/ice_cube
|
lib/ice_cube/schedule.rb
|
IceCube.Schedule.first
|
def first(n = nil)
occurrences = enumerate_occurrences(start_time).take(n || 1)
n.nil? ? occurrences.first : occurrences
end
|
ruby
|
def first(n = nil)
occurrences = enumerate_occurrences(start_time).take(n || 1)
n.nil? ? occurrences.first : occurrences
end
|
[
"def",
"first",
"(",
"n",
"=",
"nil",
")",
"occurrences",
"=",
"enumerate_occurrences",
"(",
"start_time",
")",
".",
"take",
"(",
"n",
"||",
"1",
")",
"n",
".",
"nil?",
"?",
"occurrences",
".",
"first",
":",
"occurrences",
"end"
] |
Get the first n occurrences, or the first occurrence if n is skipped
|
[
"Get",
"the",
"first",
"n",
"occurrences",
"or",
"the",
"first",
"occurrence",
"if",
"n",
"is",
"skipped"
] |
fb6c657bdc4f87dfda2bf83f15c5f487b78ccabd
|
https://github.com/seejohnrun/ice_cube/blob/fb6c657bdc4f87dfda2bf83f15c5f487b78ccabd/lib/ice_cube/schedule.rb#L299-L302
|
12,914
|
seejohnrun/ice_cube
|
lib/ice_cube/schedule.rb
|
IceCube.Schedule.last
|
def last(n = nil)
require_terminating_rules
occurrences = enumerate_occurrences(start_time).to_a
n.nil? ? occurrences.last : occurrences[-n..-1]
end
|
ruby
|
def last(n = nil)
require_terminating_rules
occurrences = enumerate_occurrences(start_time).to_a
n.nil? ? occurrences.last : occurrences[-n..-1]
end
|
[
"def",
"last",
"(",
"n",
"=",
"nil",
")",
"require_terminating_rules",
"occurrences",
"=",
"enumerate_occurrences",
"(",
"start_time",
")",
".",
"to_a",
"n",
".",
"nil?",
"?",
"occurrences",
".",
"last",
":",
"occurrences",
"[",
"-",
"n",
"..",
"-",
"1",
"]",
"end"
] |
Get the final n occurrences of a terminating schedule
or the final one if no n is given
|
[
"Get",
"the",
"final",
"n",
"occurrences",
"of",
"a",
"terminating",
"schedule",
"or",
"the",
"final",
"one",
"if",
"no",
"n",
"is",
"given"
] |
fb6c657bdc4f87dfda2bf83f15c5f487b78ccabd
|
https://github.com/seejohnrun/ice_cube/blob/fb6c657bdc4f87dfda2bf83f15c5f487b78ccabd/lib/ice_cube/schedule.rb#L306-L310
|
12,915
|
seejohnrun/ice_cube
|
lib/ice_cube/schedule.rb
|
IceCube.Schedule.to_ical
|
def to_ical(force_utc = false)
pieces = []
pieces << "DTSTART#{IcalBuilder.ical_format(start_time, force_utc)}"
pieces.concat recurrence_rules.map { |r| "RRULE:#{r.to_ical}" }
pieces.concat exception_rules.map { |r| "EXRULE:#{r.to_ical}" }
pieces.concat recurrence_times_without_start_time.map { |t| "RDATE#{IcalBuilder.ical_format(t, force_utc)}" }
pieces.concat exception_times.map { |t| "EXDATE#{IcalBuilder.ical_format(t, force_utc)}" }
pieces << "DTEND#{IcalBuilder.ical_format(end_time, force_utc)}" if end_time
pieces.join("\n")
end
|
ruby
|
def to_ical(force_utc = false)
pieces = []
pieces << "DTSTART#{IcalBuilder.ical_format(start_time, force_utc)}"
pieces.concat recurrence_rules.map { |r| "RRULE:#{r.to_ical}" }
pieces.concat exception_rules.map { |r| "EXRULE:#{r.to_ical}" }
pieces.concat recurrence_times_without_start_time.map { |t| "RDATE#{IcalBuilder.ical_format(t, force_utc)}" }
pieces.concat exception_times.map { |t| "EXDATE#{IcalBuilder.ical_format(t, force_utc)}" }
pieces << "DTEND#{IcalBuilder.ical_format(end_time, force_utc)}" if end_time
pieces.join("\n")
end
|
[
"def",
"to_ical",
"(",
"force_utc",
"=",
"false",
")",
"pieces",
"=",
"[",
"]",
"pieces",
"<<",
"\"DTSTART#{IcalBuilder.ical_format(start_time, force_utc)}\"",
"pieces",
".",
"concat",
"recurrence_rules",
".",
"map",
"{",
"|",
"r",
"|",
"\"RRULE:#{r.to_ical}\"",
"}",
"pieces",
".",
"concat",
"exception_rules",
".",
"map",
"{",
"|",
"r",
"|",
"\"EXRULE:#{r.to_ical}\"",
"}",
"pieces",
".",
"concat",
"recurrence_times_without_start_time",
".",
"map",
"{",
"|",
"t",
"|",
"\"RDATE#{IcalBuilder.ical_format(t, force_utc)}\"",
"}",
"pieces",
".",
"concat",
"exception_times",
".",
"map",
"{",
"|",
"t",
"|",
"\"EXDATE#{IcalBuilder.ical_format(t, force_utc)}\"",
"}",
"pieces",
"<<",
"\"DTEND#{IcalBuilder.ical_format(end_time, force_utc)}\"",
"if",
"end_time",
"pieces",
".",
"join",
"(",
"\"\\n\"",
")",
"end"
] |
Serialize this schedule to_ical
|
[
"Serialize",
"this",
"schedule",
"to_ical"
] |
fb6c657bdc4f87dfda2bf83f15c5f487b78ccabd
|
https://github.com/seejohnrun/ice_cube/blob/fb6c657bdc4f87dfda2bf83f15c5f487b78ccabd/lib/ice_cube/schedule.rb#L327-L336
|
12,916
|
seejohnrun/ice_cube
|
lib/ice_cube/schedule.rb
|
IceCube.Schedule.to_hash
|
def to_hash
data = {}
data[:start_time] = TimeUtil.serialize_time(start_time)
data[:start_date] = data[:start_time] if IceCube.compatibility <= 11
data[:end_time] = TimeUtil.serialize_time(end_time) if end_time
data[:rrules] = recurrence_rules.map(&:to_hash)
if IceCube.compatibility <= 11 && exception_rules.any?
data[:exrules] = exception_rules.map(&:to_hash)
end
data[:rtimes] = recurrence_times.map do |rt|
TimeUtil.serialize_time(rt)
end
data[:extimes] = exception_times.map do |et|
TimeUtil.serialize_time(et)
end
data
end
|
ruby
|
def to_hash
data = {}
data[:start_time] = TimeUtil.serialize_time(start_time)
data[:start_date] = data[:start_time] if IceCube.compatibility <= 11
data[:end_time] = TimeUtil.serialize_time(end_time) if end_time
data[:rrules] = recurrence_rules.map(&:to_hash)
if IceCube.compatibility <= 11 && exception_rules.any?
data[:exrules] = exception_rules.map(&:to_hash)
end
data[:rtimes] = recurrence_times.map do |rt|
TimeUtil.serialize_time(rt)
end
data[:extimes] = exception_times.map do |et|
TimeUtil.serialize_time(et)
end
data
end
|
[
"def",
"to_hash",
"data",
"=",
"{",
"}",
"data",
"[",
":start_time",
"]",
"=",
"TimeUtil",
".",
"serialize_time",
"(",
"start_time",
")",
"data",
"[",
":start_date",
"]",
"=",
"data",
"[",
":start_time",
"]",
"if",
"IceCube",
".",
"compatibility",
"<=",
"11",
"data",
"[",
":end_time",
"]",
"=",
"TimeUtil",
".",
"serialize_time",
"(",
"end_time",
")",
"if",
"end_time",
"data",
"[",
":rrules",
"]",
"=",
"recurrence_rules",
".",
"map",
"(",
":to_hash",
")",
"if",
"IceCube",
".",
"compatibility",
"<=",
"11",
"&&",
"exception_rules",
".",
"any?",
"data",
"[",
":exrules",
"]",
"=",
"exception_rules",
".",
"map",
"(",
":to_hash",
")",
"end",
"data",
"[",
":rtimes",
"]",
"=",
"recurrence_times",
".",
"map",
"do",
"|",
"rt",
"|",
"TimeUtil",
".",
"serialize_time",
"(",
"rt",
")",
"end",
"data",
"[",
":extimes",
"]",
"=",
"exception_times",
".",
"map",
"do",
"|",
"et",
"|",
"TimeUtil",
".",
"serialize_time",
"(",
"et",
")",
"end",
"data",
"end"
] |
Convert the schedule to a hash
|
[
"Convert",
"the",
"schedule",
"to",
"a",
"hash"
] |
fb6c657bdc4f87dfda2bf83f15c5f487b78ccabd
|
https://github.com/seejohnrun/ice_cube/blob/fb6c657bdc4f87dfda2bf83f15c5f487b78ccabd/lib/ice_cube/schedule.rb#L357-L373
|
12,917
|
seejohnrun/ice_cube
|
lib/ice_cube/schedule.rb
|
IceCube.Schedule.enumerate_occurrences
|
def enumerate_occurrences(opening_time, closing_time = nil, options = {})
opening_time = TimeUtil.match_zone(opening_time, start_time)
closing_time = TimeUtil.match_zone(closing_time, start_time)
opening_time += TimeUtil.subsec(start_time) - TimeUtil.subsec(opening_time)
opening_time = start_time if opening_time < start_time
spans = options[:spans] == true && duration != 0
Enumerator.new do |yielder|
reset
t1 = full_required? ? start_time : opening_time
t1 -= duration if spans
t1 = start_time if t1 < start_time
loop do
break unless (t0 = next_time(t1, closing_time))
break if closing_time && t0 > closing_time
if (spans ? (t0.end_time > opening_time) : (t0 >= opening_time))
yielder << (block_given? ? yield(t0) : t0)
end
t1 = t0 + 1
end
end
end
|
ruby
|
def enumerate_occurrences(opening_time, closing_time = nil, options = {})
opening_time = TimeUtil.match_zone(opening_time, start_time)
closing_time = TimeUtil.match_zone(closing_time, start_time)
opening_time += TimeUtil.subsec(start_time) - TimeUtil.subsec(opening_time)
opening_time = start_time if opening_time < start_time
spans = options[:spans] == true && duration != 0
Enumerator.new do |yielder|
reset
t1 = full_required? ? start_time : opening_time
t1 -= duration if spans
t1 = start_time if t1 < start_time
loop do
break unless (t0 = next_time(t1, closing_time))
break if closing_time && t0 > closing_time
if (spans ? (t0.end_time > opening_time) : (t0 >= opening_time))
yielder << (block_given? ? yield(t0) : t0)
end
t1 = t0 + 1
end
end
end
|
[
"def",
"enumerate_occurrences",
"(",
"opening_time",
",",
"closing_time",
"=",
"nil",
",",
"options",
"=",
"{",
"}",
")",
"opening_time",
"=",
"TimeUtil",
".",
"match_zone",
"(",
"opening_time",
",",
"start_time",
")",
"closing_time",
"=",
"TimeUtil",
".",
"match_zone",
"(",
"closing_time",
",",
"start_time",
")",
"opening_time",
"+=",
"TimeUtil",
".",
"subsec",
"(",
"start_time",
")",
"-",
"TimeUtil",
".",
"subsec",
"(",
"opening_time",
")",
"opening_time",
"=",
"start_time",
"if",
"opening_time",
"<",
"start_time",
"spans",
"=",
"options",
"[",
":spans",
"]",
"==",
"true",
"&&",
"duration",
"!=",
"0",
"Enumerator",
".",
"new",
"do",
"|",
"yielder",
"|",
"reset",
"t1",
"=",
"full_required?",
"?",
"start_time",
":",
"opening_time",
"t1",
"-=",
"duration",
"if",
"spans",
"t1",
"=",
"start_time",
"if",
"t1",
"<",
"start_time",
"loop",
"do",
"break",
"unless",
"(",
"t0",
"=",
"next_time",
"(",
"t1",
",",
"closing_time",
")",
")",
"break",
"if",
"closing_time",
"&&",
"t0",
">",
"closing_time",
"if",
"(",
"spans",
"?",
"(",
"t0",
".",
"end_time",
">",
"opening_time",
")",
":",
"(",
"t0",
">=",
"opening_time",
")",
")",
"yielder",
"<<",
"(",
"block_given?",
"?",
"yield",
"(",
"t0",
")",
":",
"t0",
")",
"end",
"t1",
"=",
"t0",
"+",
"1",
"end",
"end",
"end"
] |
Find all of the occurrences for the schedule between opening_time
and closing_time
Iteration is unrolled in pairs to skip duplicate times in end of DST
|
[
"Find",
"all",
"of",
"the",
"occurrences",
"for",
"the",
"schedule",
"between",
"opening_time",
"and",
"closing_time",
"Iteration",
"is",
"unrolled",
"in",
"pairs",
"to",
"skip",
"duplicate",
"times",
"in",
"end",
"of",
"DST"
] |
fb6c657bdc4f87dfda2bf83f15c5f487b78ccabd
|
https://github.com/seejohnrun/ice_cube/blob/fb6c657bdc4f87dfda2bf83f15c5f487b78ccabd/lib/ice_cube/schedule.rb#L424-L444
|
12,918
|
seejohnrun/ice_cube
|
lib/ice_cube/rules/weekly_rule.rb
|
IceCube.WeeklyRule.wday_offset
|
def wday_offset(step_time, start_time)
return 0 if step_time == start_time
wday_validations = other_interval_validations.select { |v| v.type == :wday }
return 0 if wday_validations.none?
days = step_time.to_date - start_time.to_date
interval = base_interval_validation.validate(step_time, start_time).to_i
min_wday = wday_validations.map { |v| TimeUtil.normalize_wday(v.day, week_start) }.min
step_wday = TimeUtil.normalize_wday(step_time.wday, week_start)
days + interval - step_wday + min_wday
end
|
ruby
|
def wday_offset(step_time, start_time)
return 0 if step_time == start_time
wday_validations = other_interval_validations.select { |v| v.type == :wday }
return 0 if wday_validations.none?
days = step_time.to_date - start_time.to_date
interval = base_interval_validation.validate(step_time, start_time).to_i
min_wday = wday_validations.map { |v| TimeUtil.normalize_wday(v.day, week_start) }.min
step_wday = TimeUtil.normalize_wday(step_time.wday, week_start)
days + interval - step_wday + min_wday
end
|
[
"def",
"wday_offset",
"(",
"step_time",
",",
"start_time",
")",
"return",
"0",
"if",
"step_time",
"==",
"start_time",
"wday_validations",
"=",
"other_interval_validations",
".",
"select",
"{",
"|",
"v",
"|",
"v",
".",
"type",
"==",
":wday",
"}",
"return",
"0",
"if",
"wday_validations",
".",
"none?",
"days",
"=",
"step_time",
".",
"to_date",
"-",
"start_time",
".",
"to_date",
"interval",
"=",
"base_interval_validation",
".",
"validate",
"(",
"step_time",
",",
"start_time",
")",
".",
"to_i",
"min_wday",
"=",
"wday_validations",
".",
"map",
"{",
"|",
"v",
"|",
"TimeUtil",
".",
"normalize_wday",
"(",
"v",
".",
"day",
",",
"week_start",
")",
"}",
".",
"min",
"step_wday",
"=",
"TimeUtil",
".",
"normalize_wday",
"(",
"step_time",
".",
"wday",
",",
"week_start",
")",
"days",
"+",
"interval",
"-",
"step_wday",
"+",
"min_wday",
"end"
] |
Calculate how many days to the first wday validation in the correct
interval week. This may move backwards within the week if starting in an
interval week with earlier validations.
|
[
"Calculate",
"how",
"many",
"days",
"to",
"the",
"first",
"wday",
"validation",
"in",
"the",
"correct",
"interval",
"week",
".",
"This",
"may",
"move",
"backwards",
"within",
"the",
"week",
"if",
"starting",
"in",
"an",
"interval",
"week",
"with",
"earlier",
"validations",
"."
] |
fb6c657bdc4f87dfda2bf83f15c5f487b78ccabd
|
https://github.com/seejohnrun/ice_cube/blob/fb6c657bdc4f87dfda2bf83f15c5f487b78ccabd/lib/ice_cube/rules/weekly_rule.rb#L47-L59
|
12,919
|
jeremytregunna/ruby-trello
|
lib/trello/client.rb
|
Trello.Client.find
|
def find(path, id, params = {})
response = get("/#{path.to_s.pluralize}/#{id}", params)
trello_class = class_from_path(path)
trello_class.parse response do |data|
data.client = self
end
end
|
ruby
|
def find(path, id, params = {})
response = get("/#{path.to_s.pluralize}/#{id}", params)
trello_class = class_from_path(path)
trello_class.parse response do |data|
data.client = self
end
end
|
[
"def",
"find",
"(",
"path",
",",
"id",
",",
"params",
"=",
"{",
"}",
")",
"response",
"=",
"get",
"(",
"\"/#{path.to_s.pluralize}/#{id}\"",
",",
"params",
")",
"trello_class",
"=",
"class_from_path",
"(",
"path",
")",
"trello_class",
".",
"parse",
"response",
"do",
"|",
"data",
"|",
"data",
".",
"client",
"=",
"self",
"end",
"end"
] |
Finds given resource by id
Examples:
client.find(:board, "board1234")
client.find(:member, "user1234")
|
[
"Finds",
"given",
"resource",
"by",
"id"
] |
ad79c9d8152ad5395b3b61c43170908f1912bfb2
|
https://github.com/jeremytregunna/ruby-trello/blob/ad79c9d8152ad5395b3b61c43170908f1912bfb2/lib/trello/client.rb#L43-L49
|
12,920
|
jeremytregunna/ruby-trello
|
lib/trello/client.rb
|
Trello.Client.find_many
|
def find_many(trello_class, path, params = {})
response = get(path, params)
trello_class.parse_many response do |data|
data.client = self
end
end
|
ruby
|
def find_many(trello_class, path, params = {})
response = get(path, params)
trello_class.parse_many response do |data|
data.client = self
end
end
|
[
"def",
"find_many",
"(",
"trello_class",
",",
"path",
",",
"params",
"=",
"{",
"}",
")",
"response",
"=",
"get",
"(",
"path",
",",
"params",
")",
"trello_class",
".",
"parse_many",
"response",
"do",
"|",
"data",
"|",
"data",
".",
"client",
"=",
"self",
"end",
"end"
] |
Finds given resource by path with params
|
[
"Finds",
"given",
"resource",
"by",
"path",
"with",
"params"
] |
ad79c9d8152ad5395b3b61c43170908f1912bfb2
|
https://github.com/jeremytregunna/ruby-trello/blob/ad79c9d8152ad5395b3b61c43170908f1912bfb2/lib/trello/client.rb#L52-L57
|
12,921
|
jeremytregunna/ruby-trello
|
lib/trello/label_name.rb
|
Trello.LabelName.update_fields
|
def update_fields(fields)
attributes[:yellow] = fields['yellow'] || attributes[:yellow]
attributes[:red] = fields['red'] || attributes[:red]
attributes[:orange] = fields['orange'] || attributes[:orange]
attributes[:green] = fields['green'] || attributes[:green]
attributes[:purple] = fields['purple'] || attributes[:purple]
attributes[:blue] = fields['blue'] || attributes[:blue]
attributes[:sky] = fields['sky'] || attributes[:sky]
attributes[:pink] = fields['pink'] || attributes[:pink]
attributes[:lime] = fields['lime'] || attributes[:lime]
attributes[:black] = fields['black'] || attributes[:black]
self
end
|
ruby
|
def update_fields(fields)
attributes[:yellow] = fields['yellow'] || attributes[:yellow]
attributes[:red] = fields['red'] || attributes[:red]
attributes[:orange] = fields['orange'] || attributes[:orange]
attributes[:green] = fields['green'] || attributes[:green]
attributes[:purple] = fields['purple'] || attributes[:purple]
attributes[:blue] = fields['blue'] || attributes[:blue]
attributes[:sky] = fields['sky'] || attributes[:sky]
attributes[:pink] = fields['pink'] || attributes[:pink]
attributes[:lime] = fields['lime'] || attributes[:lime]
attributes[:black] = fields['black'] || attributes[:black]
self
end
|
[
"def",
"update_fields",
"(",
"fields",
")",
"attributes",
"[",
":yellow",
"]",
"=",
"fields",
"[",
"'yellow'",
"]",
"||",
"attributes",
"[",
":yellow",
"]",
"attributes",
"[",
":red",
"]",
"=",
"fields",
"[",
"'red'",
"]",
"||",
"attributes",
"[",
":red",
"]",
"attributes",
"[",
":orange",
"]",
"=",
"fields",
"[",
"'orange'",
"]",
"||",
"attributes",
"[",
":orange",
"]",
"attributes",
"[",
":green",
"]",
"=",
"fields",
"[",
"'green'",
"]",
"||",
"attributes",
"[",
":green",
"]",
"attributes",
"[",
":purple",
"]",
"=",
"fields",
"[",
"'purple'",
"]",
"||",
"attributes",
"[",
":purple",
"]",
"attributes",
"[",
":blue",
"]",
"=",
"fields",
"[",
"'blue'",
"]",
"||",
"attributes",
"[",
":blue",
"]",
"attributes",
"[",
":sky",
"]",
"=",
"fields",
"[",
"'sky'",
"]",
"||",
"attributes",
"[",
":sky",
"]",
"attributes",
"[",
":pink",
"]",
"=",
"fields",
"[",
"'pink'",
"]",
"||",
"attributes",
"[",
":pink",
"]",
"attributes",
"[",
":lime",
"]",
"=",
"fields",
"[",
"'lime'",
"]",
"||",
"attributes",
"[",
":lime",
"]",
"attributes",
"[",
":black",
"]",
"=",
"fields",
"[",
"'black'",
"]",
"||",
"attributes",
"[",
":black",
"]",
"self",
"end"
] |
Update the fields of a label.
Supply a hash of stringkeyed data retrieved from the Trello API representing
a label.
|
[
"Update",
"the",
"fields",
"of",
"a",
"label",
"."
] |
ad79c9d8152ad5395b3b61c43170908f1912bfb2
|
https://github.com/jeremytregunna/ruby-trello/blob/ad79c9d8152ad5395b3b61c43170908f1912bfb2/lib/trello/label_name.rb#L11-L24
|
12,922
|
jeremytregunna/ruby-trello
|
lib/trello/webhook.rb
|
Trello.Webhook.save
|
def save
# If we have an id, just update our fields.
return update! if id
from_response client.post("/webhooks", {
description: description,
idModel: id_model,
callbackURL: callback_url
})
end
|
ruby
|
def save
# If we have an id, just update our fields.
return update! if id
from_response client.post("/webhooks", {
description: description,
idModel: id_model,
callbackURL: callback_url
})
end
|
[
"def",
"save",
"# If we have an id, just update our fields.",
"return",
"update!",
"if",
"id",
"from_response",
"client",
".",
"post",
"(",
"\"/webhooks\"",
",",
"{",
"description",
":",
"description",
",",
"idModel",
":",
"id_model",
",",
"callbackURL",
":",
"callback_url",
"}",
")",
"end"
] |
Save the webhook.
@raise [Trello::Error] if the Webhook could not be saved.
@return [String] the JSON representation of the saved webhook.
|
[
"Save",
"the",
"webhook",
"."
] |
ad79c9d8152ad5395b3b61c43170908f1912bfb2
|
https://github.com/jeremytregunna/ruby-trello/blob/ad79c9d8152ad5395b3b61c43170908f1912bfb2/lib/trello/webhook.rb#L64-L73
|
12,923
|
jeremytregunna/ruby-trello
|
lib/trello/webhook.rb
|
Trello.Webhook.update!
|
def update!
client.put("/webhooks/#{id}", {
description: description,
idModel: id_model,
callbackURL: callback_url,
active: active
})
end
|
ruby
|
def update!
client.put("/webhooks/#{id}", {
description: description,
idModel: id_model,
callbackURL: callback_url,
active: active
})
end
|
[
"def",
"update!",
"client",
".",
"put",
"(",
"\"/webhooks/#{id}\"",
",",
"{",
"description",
":",
"description",
",",
"idModel",
":",
"id_model",
",",
"callbackURL",
":",
"callback_url",
",",
"active",
":",
"active",
"}",
")",
"end"
] |
Update the webhook.
@raise [Trello::Error] if the Webhook could not be saved.
@return [String] the JSON representation of the updated webhook.
|
[
"Update",
"the",
"webhook",
"."
] |
ad79c9d8152ad5395b3b61c43170908f1912bfb2
|
https://github.com/jeremytregunna/ruby-trello/blob/ad79c9d8152ad5395b3b61c43170908f1912bfb2/lib/trello/webhook.rb#L80-L87
|
12,924
|
jeremytregunna/ruby-trello
|
lib/trello/plugin_datum.rb
|
Trello.PluginDatum.update_fields
|
def update_fields(fields)
attributes[:id] = fields['id'] || attributes[:id]
attributes[:idPlugin] = fields['idPlugin'] || attributes[:idPlugin]
attributes[:scope] = fields['scope'] || attributes[:scope]
attributes[:value] = JSON.parse(fields['value']).presence if fields.has_key?('value')
attributes[:idModel] = fields['idModel'] || attributes[:idModel]
attributes[:access] = fields['access'] || attributes[:access]
self
end
|
ruby
|
def update_fields(fields)
attributes[:id] = fields['id'] || attributes[:id]
attributes[:idPlugin] = fields['idPlugin'] || attributes[:idPlugin]
attributes[:scope] = fields['scope'] || attributes[:scope]
attributes[:value] = JSON.parse(fields['value']).presence if fields.has_key?('value')
attributes[:idModel] = fields['idModel'] || attributes[:idModel]
attributes[:access] = fields['access'] || attributes[:access]
self
end
|
[
"def",
"update_fields",
"(",
"fields",
")",
"attributes",
"[",
":id",
"]",
"=",
"fields",
"[",
"'id'",
"]",
"||",
"attributes",
"[",
":id",
"]",
"attributes",
"[",
":idPlugin",
"]",
"=",
"fields",
"[",
"'idPlugin'",
"]",
"||",
"attributes",
"[",
":idPlugin",
"]",
"attributes",
"[",
":scope",
"]",
"=",
"fields",
"[",
"'scope'",
"]",
"||",
"attributes",
"[",
":scope",
"]",
"attributes",
"[",
":value",
"]",
"=",
"JSON",
".",
"parse",
"(",
"fields",
"[",
"'value'",
"]",
")",
".",
"presence",
"if",
"fields",
".",
"has_key?",
"(",
"'value'",
")",
"attributes",
"[",
":idModel",
"]",
"=",
"fields",
"[",
"'idModel'",
"]",
"||",
"attributes",
"[",
":idModel",
"]",
"attributes",
"[",
":access",
"]",
"=",
"fields",
"[",
"'access'",
"]",
"||",
"attributes",
"[",
":access",
"]",
"self",
"end"
] |
Supply a hash of stringkeyed data retrieved from the Trello API representing
an attachment.
|
[
"Supply",
"a",
"hash",
"of",
"stringkeyed",
"data",
"retrieved",
"from",
"the",
"Trello",
"API",
"representing",
"an",
"attachment",
"."
] |
ad79c9d8152ad5395b3b61c43170908f1912bfb2
|
https://github.com/jeremytregunna/ruby-trello/blob/ad79c9d8152ad5395b3b61c43170908f1912bfb2/lib/trello/plugin_datum.rb#L23-L31
|
12,925
|
jeremytregunna/ruby-trello
|
lib/trello/card.rb
|
Trello.Card.update_fields
|
def update_fields(fields)
attributes[:id] = fields[SYMBOL_TO_STRING[:id]] || attributes[:id]
attributes[:short_id] = fields[SYMBOL_TO_STRING[:short_id]] || attributes[:short_id]
attributes[:name] = fields[SYMBOL_TO_STRING[:name]] || fields[:name] || attributes[:name]
attributes[:desc] = fields[SYMBOL_TO_STRING[:desc]] || fields[:desc] || attributes[:desc]
attributes[:due] = Time.iso8601(fields[SYMBOL_TO_STRING[:due]]) rescue nil if fields.has_key?(SYMBOL_TO_STRING[:due])
attributes[:due] = fields[:due] if fields.has_key?(:due)
attributes[:due_complete] = fields[SYMBOL_TO_STRING[:due_complete]] if fields.has_key?(SYMBOL_TO_STRING[:due_complete])
attributes[:due_complete] ||= false
attributes[:closed] = fields[SYMBOL_TO_STRING[:closed]] if fields.has_key?(SYMBOL_TO_STRING[:closed])
attributes[:url] = fields[SYMBOL_TO_STRING[:url]] || attributes[:url]
attributes[:short_url] = fields[SYMBOL_TO_STRING[:short_url]] || attributes[:short_url]
attributes[:board_id] = fields[SYMBOL_TO_STRING[:board_id]] || attributes[:board_id]
attributes[:member_ids] = fields[SYMBOL_TO_STRING[:member_ids]] || fields[:member_ids] || attributes[:member_ids]
attributes[:list_id] = fields[SYMBOL_TO_STRING[:list_id]] || fields[:list_id] || attributes[:list_id]
attributes[:pos] = fields[SYMBOL_TO_STRING[:pos]] || fields[:pos] || attributes[:pos]
attributes[:labels] = (fields[SYMBOL_TO_STRING[:labels]] || []).map { |lbl| Trello::Label.new(lbl) }.presence || attributes[:labels].presence || []
attributes[:card_labels] = fields[SYMBOL_TO_STRING[:card_labels]] || fields[:card_labels] || attributes[:card_labels]
attributes[:last_activity_date] = Time.iso8601(fields[SYMBOL_TO_STRING[:last_activity_date]]) rescue nil if fields.has_key?(SYMBOL_TO_STRING[:last_activity_date])
attributes[:cover_image_id] = fields[SYMBOL_TO_STRING[:cover_image_id]] || attributes[:cover_image_id]
attributes[:badges] = fields[SYMBOL_TO_STRING[:badges]] || attributes[:badges]
attributes[:card_members] = fields[SYMBOL_TO_STRING[:card_members]] || attributes[:card_members]
attributes[:source_card_id] = fields[SYMBOL_TO_STRING[:source_card_id]] || fields[:source_card_id] || attributes[:source_card_id]
attributes[:source_card_properties] = fields[SYMBOL_TO_STRING[:source_card_properties]] || fields[:source_card_properties] || attributes[:source_card_properties]
self
end
|
ruby
|
def update_fields(fields)
attributes[:id] = fields[SYMBOL_TO_STRING[:id]] || attributes[:id]
attributes[:short_id] = fields[SYMBOL_TO_STRING[:short_id]] || attributes[:short_id]
attributes[:name] = fields[SYMBOL_TO_STRING[:name]] || fields[:name] || attributes[:name]
attributes[:desc] = fields[SYMBOL_TO_STRING[:desc]] || fields[:desc] || attributes[:desc]
attributes[:due] = Time.iso8601(fields[SYMBOL_TO_STRING[:due]]) rescue nil if fields.has_key?(SYMBOL_TO_STRING[:due])
attributes[:due] = fields[:due] if fields.has_key?(:due)
attributes[:due_complete] = fields[SYMBOL_TO_STRING[:due_complete]] if fields.has_key?(SYMBOL_TO_STRING[:due_complete])
attributes[:due_complete] ||= false
attributes[:closed] = fields[SYMBOL_TO_STRING[:closed]] if fields.has_key?(SYMBOL_TO_STRING[:closed])
attributes[:url] = fields[SYMBOL_TO_STRING[:url]] || attributes[:url]
attributes[:short_url] = fields[SYMBOL_TO_STRING[:short_url]] || attributes[:short_url]
attributes[:board_id] = fields[SYMBOL_TO_STRING[:board_id]] || attributes[:board_id]
attributes[:member_ids] = fields[SYMBOL_TO_STRING[:member_ids]] || fields[:member_ids] || attributes[:member_ids]
attributes[:list_id] = fields[SYMBOL_TO_STRING[:list_id]] || fields[:list_id] || attributes[:list_id]
attributes[:pos] = fields[SYMBOL_TO_STRING[:pos]] || fields[:pos] || attributes[:pos]
attributes[:labels] = (fields[SYMBOL_TO_STRING[:labels]] || []).map { |lbl| Trello::Label.new(lbl) }.presence || attributes[:labels].presence || []
attributes[:card_labels] = fields[SYMBOL_TO_STRING[:card_labels]] || fields[:card_labels] || attributes[:card_labels]
attributes[:last_activity_date] = Time.iso8601(fields[SYMBOL_TO_STRING[:last_activity_date]]) rescue nil if fields.has_key?(SYMBOL_TO_STRING[:last_activity_date])
attributes[:cover_image_id] = fields[SYMBOL_TO_STRING[:cover_image_id]] || attributes[:cover_image_id]
attributes[:badges] = fields[SYMBOL_TO_STRING[:badges]] || attributes[:badges]
attributes[:card_members] = fields[SYMBOL_TO_STRING[:card_members]] || attributes[:card_members]
attributes[:source_card_id] = fields[SYMBOL_TO_STRING[:source_card_id]] || fields[:source_card_id] || attributes[:source_card_id]
attributes[:source_card_properties] = fields[SYMBOL_TO_STRING[:source_card_properties]] || fields[:source_card_properties] || attributes[:source_card_properties]
self
end
|
[
"def",
"update_fields",
"(",
"fields",
")",
"attributes",
"[",
":id",
"]",
"=",
"fields",
"[",
"SYMBOL_TO_STRING",
"[",
":id",
"]",
"]",
"||",
"attributes",
"[",
":id",
"]",
"attributes",
"[",
":short_id",
"]",
"=",
"fields",
"[",
"SYMBOL_TO_STRING",
"[",
":short_id",
"]",
"]",
"||",
"attributes",
"[",
":short_id",
"]",
"attributes",
"[",
":name",
"]",
"=",
"fields",
"[",
"SYMBOL_TO_STRING",
"[",
":name",
"]",
"]",
"||",
"fields",
"[",
":name",
"]",
"||",
"attributes",
"[",
":name",
"]",
"attributes",
"[",
":desc",
"]",
"=",
"fields",
"[",
"SYMBOL_TO_STRING",
"[",
":desc",
"]",
"]",
"||",
"fields",
"[",
":desc",
"]",
"||",
"attributes",
"[",
":desc",
"]",
"attributes",
"[",
":due",
"]",
"=",
"Time",
".",
"iso8601",
"(",
"fields",
"[",
"SYMBOL_TO_STRING",
"[",
":due",
"]",
"]",
")",
"rescue",
"nil",
"if",
"fields",
".",
"has_key?",
"(",
"SYMBOL_TO_STRING",
"[",
":due",
"]",
")",
"attributes",
"[",
":due",
"]",
"=",
"fields",
"[",
":due",
"]",
"if",
"fields",
".",
"has_key?",
"(",
":due",
")",
"attributes",
"[",
":due_complete",
"]",
"=",
"fields",
"[",
"SYMBOL_TO_STRING",
"[",
":due_complete",
"]",
"]",
"if",
"fields",
".",
"has_key?",
"(",
"SYMBOL_TO_STRING",
"[",
":due_complete",
"]",
")",
"attributes",
"[",
":due_complete",
"]",
"||=",
"false",
"attributes",
"[",
":closed",
"]",
"=",
"fields",
"[",
"SYMBOL_TO_STRING",
"[",
":closed",
"]",
"]",
"if",
"fields",
".",
"has_key?",
"(",
"SYMBOL_TO_STRING",
"[",
":closed",
"]",
")",
"attributes",
"[",
":url",
"]",
"=",
"fields",
"[",
"SYMBOL_TO_STRING",
"[",
":url",
"]",
"]",
"||",
"attributes",
"[",
":url",
"]",
"attributes",
"[",
":short_url",
"]",
"=",
"fields",
"[",
"SYMBOL_TO_STRING",
"[",
":short_url",
"]",
"]",
"||",
"attributes",
"[",
":short_url",
"]",
"attributes",
"[",
":board_id",
"]",
"=",
"fields",
"[",
"SYMBOL_TO_STRING",
"[",
":board_id",
"]",
"]",
"||",
"attributes",
"[",
":board_id",
"]",
"attributes",
"[",
":member_ids",
"]",
"=",
"fields",
"[",
"SYMBOL_TO_STRING",
"[",
":member_ids",
"]",
"]",
"||",
"fields",
"[",
":member_ids",
"]",
"||",
"attributes",
"[",
":member_ids",
"]",
"attributes",
"[",
":list_id",
"]",
"=",
"fields",
"[",
"SYMBOL_TO_STRING",
"[",
":list_id",
"]",
"]",
"||",
"fields",
"[",
":list_id",
"]",
"||",
"attributes",
"[",
":list_id",
"]",
"attributes",
"[",
":pos",
"]",
"=",
"fields",
"[",
"SYMBOL_TO_STRING",
"[",
":pos",
"]",
"]",
"||",
"fields",
"[",
":pos",
"]",
"||",
"attributes",
"[",
":pos",
"]",
"attributes",
"[",
":labels",
"]",
"=",
"(",
"fields",
"[",
"SYMBOL_TO_STRING",
"[",
":labels",
"]",
"]",
"||",
"[",
"]",
")",
".",
"map",
"{",
"|",
"lbl",
"|",
"Trello",
"::",
"Label",
".",
"new",
"(",
"lbl",
")",
"}",
".",
"presence",
"||",
"attributes",
"[",
":labels",
"]",
".",
"presence",
"||",
"[",
"]",
"attributes",
"[",
":card_labels",
"]",
"=",
"fields",
"[",
"SYMBOL_TO_STRING",
"[",
":card_labels",
"]",
"]",
"||",
"fields",
"[",
":card_labels",
"]",
"||",
"attributes",
"[",
":card_labels",
"]",
"attributes",
"[",
":last_activity_date",
"]",
"=",
"Time",
".",
"iso8601",
"(",
"fields",
"[",
"SYMBOL_TO_STRING",
"[",
":last_activity_date",
"]",
"]",
")",
"rescue",
"nil",
"if",
"fields",
".",
"has_key?",
"(",
"SYMBOL_TO_STRING",
"[",
":last_activity_date",
"]",
")",
"attributes",
"[",
":cover_image_id",
"]",
"=",
"fields",
"[",
"SYMBOL_TO_STRING",
"[",
":cover_image_id",
"]",
"]",
"||",
"attributes",
"[",
":cover_image_id",
"]",
"attributes",
"[",
":badges",
"]",
"=",
"fields",
"[",
"SYMBOL_TO_STRING",
"[",
":badges",
"]",
"]",
"||",
"attributes",
"[",
":badges",
"]",
"attributes",
"[",
":card_members",
"]",
"=",
"fields",
"[",
"SYMBOL_TO_STRING",
"[",
":card_members",
"]",
"]",
"||",
"attributes",
"[",
":card_members",
"]",
"attributes",
"[",
":source_card_id",
"]",
"=",
"fields",
"[",
"SYMBOL_TO_STRING",
"[",
":source_card_id",
"]",
"]",
"||",
"fields",
"[",
":source_card_id",
"]",
"||",
"attributes",
"[",
":source_card_id",
"]",
"attributes",
"[",
":source_card_properties",
"]",
"=",
"fields",
"[",
"SYMBOL_TO_STRING",
"[",
":source_card_properties",
"]",
"]",
"||",
"fields",
"[",
":source_card_properties",
"]",
"||",
"attributes",
"[",
":source_card_properties",
"]",
"self",
"end"
] |
Update the fields of a card.
Supply a hash of string keyed data retrieved from the Trello API representing
a card.
Note that this this method does not save anything new to the Trello API,
it just assigns the input attributes to your local object. If you use
this method to assign attributes, call `save` or `update!` afterwards if
you want to persist your changes to Trello.
@param [Hash] fields
@option fields [String] :id
@option fields [String] :short_id
@option fields [String] :name The new name of the card.
@option fields [String] :desc A string with a length from 0 to
16384.
@option fields [Date] :due A date, or `nil`.
@option fields [Boolean] :due_complete
@option fields [Boolean] :closed
@option fields [String] :url
@option fields [String] :short_url
@option fields [String] :board_id
@option fields [String] :member_ids A comma-separated list of objectIds
(24-character hex strings).
@option fields [String] :pos A position. `"top"`, `"bottom"`, or a
positive number. Defaults to `"bottom"`.
@option fields [Array] :labels An Array of Trello::Label objects
derived from the JSON response
@option fields [String] :card_labels A comma-separated list of
objectIds (24-character hex strings).
@option fields [Object] :cover_image_id
@option fields [Object] :badges
@option fields [Object] :card_members
@option fields [String] :source_card_id
@option fields [Array] :source_card_properties
@return [Trello::Card] self
|
[
"Update",
"the",
"fields",
"of",
"a",
"card",
"."
] |
ad79c9d8152ad5395b3b61c43170908f1912bfb2
|
https://github.com/jeremytregunna/ruby-trello/blob/ad79c9d8152ad5395b3b61c43170908f1912bfb2/lib/trello/card.rb#L171-L196
|
12,926
|
jeremytregunna/ruby-trello
|
lib/trello/card.rb
|
Trello.Card.update!
|
def update!
@previously_changed = changes
# extract only new values to build payload
payload = Hash[changes.map { |key, values| [SYMBOL_TO_STRING[key.to_sym].to_sym, values[1]] }]
@changed_attributes.clear
client.put("/cards/#{id}", payload)
end
|
ruby
|
def update!
@previously_changed = changes
# extract only new values to build payload
payload = Hash[changes.map { |key, values| [SYMBOL_TO_STRING[key.to_sym].to_sym, values[1]] }]
@changed_attributes.clear
client.put("/cards/#{id}", payload)
end
|
[
"def",
"update!",
"@previously_changed",
"=",
"changes",
"# extract only new values to build payload",
"payload",
"=",
"Hash",
"[",
"changes",
".",
"map",
"{",
"|",
"key",
",",
"values",
"|",
"[",
"SYMBOL_TO_STRING",
"[",
"key",
".",
"to_sym",
"]",
".",
"to_sym",
",",
"values",
"[",
"1",
"]",
"]",
"}",
"]",
"@changed_attributes",
".",
"clear",
"client",
".",
"put",
"(",
"\"/cards/#{id}\"",
",",
"payload",
")",
"end"
] |
Update an existing record.
Warning: this updates all fields using values already in memory. If
an external resource has updated these fields, you should refresh!
this object before making your changes, and before updating the record.
@raise [Trello::Error] if the card could not be updated.
@return [String] The JSON representation of the updated card returned by
the Trello API.
|
[
"Update",
"an",
"existing",
"record",
"."
] |
ad79c9d8152ad5395b3b61c43170908f1912bfb2
|
https://github.com/jeremytregunna/ruby-trello/blob/ad79c9d8152ad5395b3b61c43170908f1912bfb2/lib/trello/card.rb#L276-L283
|
12,927
|
jeremytregunna/ruby-trello
|
lib/trello/card.rb
|
Trello.Card.move_to_list
|
def move_to_list(list)
list_number = list.is_a?(String) ? list : list.id
unless list_id == list_number
client.put("/cards/#{id}/idList", {
value: list_number
})
end
end
|
ruby
|
def move_to_list(list)
list_number = list.is_a?(String) ? list : list.id
unless list_id == list_number
client.put("/cards/#{id}/idList", {
value: list_number
})
end
end
|
[
"def",
"move_to_list",
"(",
"list",
")",
"list_number",
"=",
"list",
".",
"is_a?",
"(",
"String",
")",
"?",
"list",
":",
"list",
".",
"id",
"unless",
"list_id",
"==",
"list_number",
"client",
".",
"put",
"(",
"\"/cards/#{id}/idList\"",
",",
"{",
"value",
":",
"list_number",
"}",
")",
"end",
"end"
] |
Move this card to the given list
|
[
"Move",
"this",
"card",
"to",
"the",
"given",
"list"
] |
ad79c9d8152ad5395b3b61c43170908f1912bfb2
|
https://github.com/jeremytregunna/ruby-trello/blob/ad79c9d8152ad5395b3b61c43170908f1912bfb2/lib/trello/card.rb#L338-L345
|
12,928
|
jeremytregunna/ruby-trello
|
lib/trello/card.rb
|
Trello.Card.move_to_list_on_any_board
|
def move_to_list_on_any_board(list_id)
list = List.find(list_id)
if board.id == list.board_id
move_to_list(list_id)
else
move_to_board(Board.find(list.board_id), list)
end
end
|
ruby
|
def move_to_list_on_any_board(list_id)
list = List.find(list_id)
if board.id == list.board_id
move_to_list(list_id)
else
move_to_board(Board.find(list.board_id), list)
end
end
|
[
"def",
"move_to_list_on_any_board",
"(",
"list_id",
")",
"list",
"=",
"List",
".",
"find",
"(",
"list_id",
")",
"if",
"board",
".",
"id",
"==",
"list",
".",
"board_id",
"move_to_list",
"(",
"list_id",
")",
"else",
"move_to_board",
"(",
"Board",
".",
"find",
"(",
"list",
".",
"board_id",
")",
",",
"list",
")",
"end",
"end"
] |
Moves this card to the given list no matter which board it is on
|
[
"Moves",
"this",
"card",
"to",
"the",
"given",
"list",
"no",
"matter",
"which",
"board",
"it",
"is",
"on"
] |
ad79c9d8152ad5395b3b61c43170908f1912bfb2
|
https://github.com/jeremytregunna/ruby-trello/blob/ad79c9d8152ad5395b3b61c43170908f1912bfb2/lib/trello/card.rb#L348-L355
|
12,929
|
jeremytregunna/ruby-trello
|
lib/trello/card.rb
|
Trello.Card.upvote
|
def upvote
begin
client.post("/cards/#{id}/membersVoted", {
value: me.id
})
rescue Trello::Error => e
fail e unless e.message =~ /has already voted/i
end
self
end
|
ruby
|
def upvote
begin
client.post("/cards/#{id}/membersVoted", {
value: me.id
})
rescue Trello::Error => e
fail e unless e.message =~ /has already voted/i
end
self
end
|
[
"def",
"upvote",
"begin",
"client",
".",
"post",
"(",
"\"/cards/#{id}/membersVoted\"",
",",
"{",
"value",
":",
"me",
".",
"id",
"}",
")",
"rescue",
"Trello",
"::",
"Error",
"=>",
"e",
"fail",
"e",
"unless",
"e",
".",
"message",
"=~",
"/",
"/i",
"end",
"self",
"end"
] |
Current authenticated user upvotes a card
|
[
"Current",
"authenticated",
"user",
"upvotes",
"a",
"card"
] |
ad79c9d8152ad5395b3b61c43170908f1912bfb2
|
https://github.com/jeremytregunna/ruby-trello/blob/ad79c9d8152ad5395b3b61c43170908f1912bfb2/lib/trello/card.rb#L379-L389
|
12,930
|
jeremytregunna/ruby-trello
|
lib/trello/card.rb
|
Trello.Card.remove_upvote
|
def remove_upvote
begin
client.delete("/cards/#{id}/membersVoted/#{me.id}")
rescue Trello::Error => e
fail e unless e.message =~ /has not voted/i
end
self
end
|
ruby
|
def remove_upvote
begin
client.delete("/cards/#{id}/membersVoted/#{me.id}")
rescue Trello::Error => e
fail e unless e.message =~ /has not voted/i
end
self
end
|
[
"def",
"remove_upvote",
"begin",
"client",
".",
"delete",
"(",
"\"/cards/#{id}/membersVoted/#{me.id}\"",
")",
"rescue",
"Trello",
"::",
"Error",
"=>",
"e",
"fail",
"e",
"unless",
"e",
".",
"message",
"=~",
"/",
"/i",
"end",
"self",
"end"
] |
Recind upvote. Noop if authenticated user hasn't previously voted
|
[
"Recind",
"upvote",
".",
"Noop",
"if",
"authenticated",
"user",
"hasn",
"t",
"previously",
"voted"
] |
ad79c9d8152ad5395b3b61c43170908f1912bfb2
|
https://github.com/jeremytregunna/ruby-trello/blob/ad79c9d8152ad5395b3b61c43170908f1912bfb2/lib/trello/card.rb#L392-L400
|
12,931
|
jeremytregunna/ruby-trello
|
lib/trello/card.rb
|
Trello.Card.add_label
|
def add_label(label)
unless label.valid?
errors.add(:label, "is not valid.")
return Trello.logger.warn "Label is not valid." unless label.valid?
end
client.post("/cards/#{id}/idLabels", {value: label.id})
end
|
ruby
|
def add_label(label)
unless label.valid?
errors.add(:label, "is not valid.")
return Trello.logger.warn "Label is not valid." unless label.valid?
end
client.post("/cards/#{id}/idLabels", {value: label.id})
end
|
[
"def",
"add_label",
"(",
"label",
")",
"unless",
"label",
".",
"valid?",
"errors",
".",
"add",
"(",
":label",
",",
"\"is not valid.\"",
")",
"return",
"Trello",
".",
"logger",
".",
"warn",
"\"Label is not valid.\"",
"unless",
"label",
".",
"valid?",
"end",
"client",
".",
"post",
"(",
"\"/cards/#{id}/idLabels\"",
",",
"{",
"value",
":",
"label",
".",
"id",
"}",
")",
"end"
] |
Add a label
|
[
"Add",
"a",
"label"
] |
ad79c9d8152ad5395b3b61c43170908f1912bfb2
|
https://github.com/jeremytregunna/ruby-trello/blob/ad79c9d8152ad5395b3b61c43170908f1912bfb2/lib/trello/card.rb#L403-L409
|
12,932
|
jeremytregunna/ruby-trello
|
lib/trello/card.rb
|
Trello.Card.remove_label
|
def remove_label(label)
unless label.valid?
errors.add(:label, "is not valid.")
return Trello.logger.warn "Label is not valid." unless label.valid?
end
client.delete("/cards/#{id}/idLabels/#{label.id}")
end
|
ruby
|
def remove_label(label)
unless label.valid?
errors.add(:label, "is not valid.")
return Trello.logger.warn "Label is not valid." unless label.valid?
end
client.delete("/cards/#{id}/idLabels/#{label.id}")
end
|
[
"def",
"remove_label",
"(",
"label",
")",
"unless",
"label",
".",
"valid?",
"errors",
".",
"add",
"(",
":label",
",",
"\"is not valid.\"",
")",
"return",
"Trello",
".",
"logger",
".",
"warn",
"\"Label is not valid.\"",
"unless",
"label",
".",
"valid?",
"end",
"client",
".",
"delete",
"(",
"\"/cards/#{id}/idLabels/#{label.id}\"",
")",
"end"
] |
Remove a label
|
[
"Remove",
"a",
"label"
] |
ad79c9d8152ad5395b3b61c43170908f1912bfb2
|
https://github.com/jeremytregunna/ruby-trello/blob/ad79c9d8152ad5395b3b61c43170908f1912bfb2/lib/trello/card.rb#L412-L418
|
12,933
|
jeremytregunna/ruby-trello
|
lib/trello/card.rb
|
Trello.Card.add_attachment
|
def add_attachment(attachment, name = '')
# Is it a file object or a string (url)?
if attachment.respond_to?(:path) && attachment.respond_to?(:read)
client.post("/cards/#{id}/attachments", {
file: attachment,
name: name
})
else
client.post("/cards/#{id}/attachments", {
url: attachment,
name: name
})
end
end
|
ruby
|
def add_attachment(attachment, name = '')
# Is it a file object or a string (url)?
if attachment.respond_to?(:path) && attachment.respond_to?(:read)
client.post("/cards/#{id}/attachments", {
file: attachment,
name: name
})
else
client.post("/cards/#{id}/attachments", {
url: attachment,
name: name
})
end
end
|
[
"def",
"add_attachment",
"(",
"attachment",
",",
"name",
"=",
"''",
")",
"# Is it a file object or a string (url)?",
"if",
"attachment",
".",
"respond_to?",
"(",
":path",
")",
"&&",
"attachment",
".",
"respond_to?",
"(",
":read",
")",
"client",
".",
"post",
"(",
"\"/cards/#{id}/attachments\"",
",",
"{",
"file",
":",
"attachment",
",",
"name",
":",
"name",
"}",
")",
"else",
"client",
".",
"post",
"(",
"\"/cards/#{id}/attachments\"",
",",
"{",
"url",
":",
"attachment",
",",
"name",
":",
"name",
"}",
")",
"end",
"end"
] |
Add an attachment to this card
|
[
"Add",
"an",
"attachment",
"to",
"this",
"card"
] |
ad79c9d8152ad5395b3b61c43170908f1912bfb2
|
https://github.com/jeremytregunna/ruby-trello/blob/ad79c9d8152ad5395b3b61c43170908f1912bfb2/lib/trello/card.rb#L421-L434
|
12,934
|
jeremytregunna/ruby-trello
|
lib/trello/card.rb
|
Trello.Card.attachments
|
def attachments
attachments = Attachment.from_response client.get("/cards/#{id}/attachments")
MultiAssociation.new(self, attachments).proxy
end
|
ruby
|
def attachments
attachments = Attachment.from_response client.get("/cards/#{id}/attachments")
MultiAssociation.new(self, attachments).proxy
end
|
[
"def",
"attachments",
"attachments",
"=",
"Attachment",
".",
"from_response",
"client",
".",
"get",
"(",
"\"/cards/#{id}/attachments\"",
")",
"MultiAssociation",
".",
"new",
"(",
"self",
",",
"attachments",
")",
".",
"proxy",
"end"
] |
Retrieve a list of attachments
|
[
"Retrieve",
"a",
"list",
"of",
"attachments"
] |
ad79c9d8152ad5395b3b61c43170908f1912bfb2
|
https://github.com/jeremytregunna/ruby-trello/blob/ad79c9d8152ad5395b3b61c43170908f1912bfb2/lib/trello/card.rb#L437-L440
|
12,935
|
jeremytregunna/ruby-trello
|
lib/trello/organization.rb
|
Trello.Organization.boards
|
def boards
boards = Board.from_response client.get("/organizations/#{id}/boards/all")
MultiAssociation.new(self, boards).proxy
end
|
ruby
|
def boards
boards = Board.from_response client.get("/organizations/#{id}/boards/all")
MultiAssociation.new(self, boards).proxy
end
|
[
"def",
"boards",
"boards",
"=",
"Board",
".",
"from_response",
"client",
".",
"get",
"(",
"\"/organizations/#{id}/boards/all\"",
")",
"MultiAssociation",
".",
"new",
"(",
"self",
",",
"boards",
")",
".",
"proxy",
"end"
] |
Returns a list of boards under this organization.
|
[
"Returns",
"a",
"list",
"of",
"boards",
"under",
"this",
"organization",
"."
] |
ad79c9d8152ad5395b3b61c43170908f1912bfb2
|
https://github.com/jeremytregunna/ruby-trello/blob/ad79c9d8152ad5395b3b61c43170908f1912bfb2/lib/trello/organization.rb#L52-L55
|
12,936
|
jeremytregunna/ruby-trello
|
lib/trello/organization.rb
|
Trello.Organization.members
|
def members(params = {})
members = Member.from_response client.get("/organizations/#{id}/members/all", params)
MultiAssociation.new(self, members).proxy
end
|
ruby
|
def members(params = {})
members = Member.from_response client.get("/organizations/#{id}/members/all", params)
MultiAssociation.new(self, members).proxy
end
|
[
"def",
"members",
"(",
"params",
"=",
"{",
"}",
")",
"members",
"=",
"Member",
".",
"from_response",
"client",
".",
"get",
"(",
"\"/organizations/#{id}/members/all\"",
",",
"params",
")",
"MultiAssociation",
".",
"new",
"(",
"self",
",",
"members",
")",
".",
"proxy",
"end"
] |
Returns an array of members associated with the organization.
|
[
"Returns",
"an",
"array",
"of",
"members",
"associated",
"with",
"the",
"organization",
"."
] |
ad79c9d8152ad5395b3b61c43170908f1912bfb2
|
https://github.com/jeremytregunna/ruby-trello/blob/ad79c9d8152ad5395b3b61c43170908f1912bfb2/lib/trello/organization.rb#L58-L61
|
12,937
|
jeremytregunna/ruby-trello
|
lib/trello/comment.rb
|
Trello.Comment.update_fields
|
def update_fields(fields)
attributes[:action_id] = fields['id'] || attributes[:action_id]
attributes[:text] = fields['data']['text'] || attributes[:text]
attributes[:date] = Time.iso8601(fields['date']) if fields.has_key?('date')
attributes[:member_creator_id] = fields['idMemberCreator'] || attributes[:member_creator_id]
self
end
|
ruby
|
def update_fields(fields)
attributes[:action_id] = fields['id'] || attributes[:action_id]
attributes[:text] = fields['data']['text'] || attributes[:text]
attributes[:date] = Time.iso8601(fields['date']) if fields.has_key?('date')
attributes[:member_creator_id] = fields['idMemberCreator'] || attributes[:member_creator_id]
self
end
|
[
"def",
"update_fields",
"(",
"fields",
")",
"attributes",
"[",
":action_id",
"]",
"=",
"fields",
"[",
"'id'",
"]",
"||",
"attributes",
"[",
":action_id",
"]",
"attributes",
"[",
":text",
"]",
"=",
"fields",
"[",
"'data'",
"]",
"[",
"'text'",
"]",
"||",
"attributes",
"[",
":text",
"]",
"attributes",
"[",
":date",
"]",
"=",
"Time",
".",
"iso8601",
"(",
"fields",
"[",
"'date'",
"]",
")",
"if",
"fields",
".",
"has_key?",
"(",
"'date'",
")",
"attributes",
"[",
":member_creator_id",
"]",
"=",
"fields",
"[",
"'idMemberCreator'",
"]",
"||",
"attributes",
"[",
":member_creator_id",
"]",
"self",
"end"
] |
Update the attributes of a Comment
Supply a hash of string keyed data retrieved from the Trello API representing
a Comment.
|
[
"Update",
"the",
"attributes",
"of",
"a",
"Comment"
] |
ad79c9d8152ad5395b3b61c43170908f1912bfb2
|
https://github.com/jeremytregunna/ruby-trello/blob/ad79c9d8152ad5395b3b61c43170908f1912bfb2/lib/trello/comment.rb#L29-L35
|
12,938
|
jeremytregunna/ruby-trello
|
lib/trello/attachment.rb
|
Trello.Attachment.update_fields
|
def update_fields(fields)
attributes[:name] = fields['name'] || attributes[:name]
attributes[:id] = fields['id'] || attributes[:id]
attributes[:pos] = fields['pos'] || attributes[:pos]
attributes[:url] = fields['url'] || attributes[:url]
attributes[:bytes] = fields['bytes'].to_i || attributes[:bytes]
attributes[:member_id] = fields['idMember'] || attributes[:member_id]
attributes[:date] = Time.parse(fields['date']).presence || attributes[:date]
attributes[:is_upload] = fields['isUpload'] if fields.has_key?('isUpload')
attributes[:mime_type] = fields['mimeType'] || attributes[:mime_type]
attributes[:previews] = fields['previews'] if fields.has_key?('previews')
self
end
|
ruby
|
def update_fields(fields)
attributes[:name] = fields['name'] || attributes[:name]
attributes[:id] = fields['id'] || attributes[:id]
attributes[:pos] = fields['pos'] || attributes[:pos]
attributes[:url] = fields['url'] || attributes[:url]
attributes[:bytes] = fields['bytes'].to_i || attributes[:bytes]
attributes[:member_id] = fields['idMember'] || attributes[:member_id]
attributes[:date] = Time.parse(fields['date']).presence || attributes[:date]
attributes[:is_upload] = fields['isUpload'] if fields.has_key?('isUpload')
attributes[:mime_type] = fields['mimeType'] || attributes[:mime_type]
attributes[:previews] = fields['previews'] if fields.has_key?('previews')
self
end
|
[
"def",
"update_fields",
"(",
"fields",
")",
"attributes",
"[",
":name",
"]",
"=",
"fields",
"[",
"'name'",
"]",
"||",
"attributes",
"[",
":name",
"]",
"attributes",
"[",
":id",
"]",
"=",
"fields",
"[",
"'id'",
"]",
"||",
"attributes",
"[",
":id",
"]",
"attributes",
"[",
":pos",
"]",
"=",
"fields",
"[",
"'pos'",
"]",
"||",
"attributes",
"[",
":pos",
"]",
"attributes",
"[",
":url",
"]",
"=",
"fields",
"[",
"'url'",
"]",
"||",
"attributes",
"[",
":url",
"]",
"attributes",
"[",
":bytes",
"]",
"=",
"fields",
"[",
"'bytes'",
"]",
".",
"to_i",
"||",
"attributes",
"[",
":bytes",
"]",
"attributes",
"[",
":member_id",
"]",
"=",
"fields",
"[",
"'idMember'",
"]",
"||",
"attributes",
"[",
":member_id",
"]",
"attributes",
"[",
":date",
"]",
"=",
"Time",
".",
"parse",
"(",
"fields",
"[",
"'date'",
"]",
")",
".",
"presence",
"||",
"attributes",
"[",
":date",
"]",
"attributes",
"[",
":is_upload",
"]",
"=",
"fields",
"[",
"'isUpload'",
"]",
"if",
"fields",
".",
"has_key?",
"(",
"'isUpload'",
")",
"attributes",
"[",
":mime_type",
"]",
"=",
"fields",
"[",
"'mimeType'",
"]",
"||",
"attributes",
"[",
":mime_type",
"]",
"attributes",
"[",
":previews",
"]",
"=",
"fields",
"[",
"'previews'",
"]",
"if",
"fields",
".",
"has_key?",
"(",
"'previews'",
")",
"self",
"end"
] |
Update the fields of an attachment.
Supply a hash of stringkeyed data retrieved from the Trello API representing
an attachment.
|
[
"Update",
"the",
"fields",
"of",
"an",
"attachment",
"."
] |
ad79c9d8152ad5395b3b61c43170908f1912bfb2
|
https://github.com/jeremytregunna/ruby-trello/blob/ad79c9d8152ad5395b3b61c43170908f1912bfb2/lib/trello/attachment.rb#L26-L38
|
12,939
|
jeremytregunna/ruby-trello
|
lib/trello/custom_field_item.rb
|
Trello.CustomFieldItem.option_value
|
def option_value
if option_id
option_endpoint = "/customFields/#{custom_field_id}/options/#{option_id}"
option = CustomFieldOption.from_response client.get(option_endpoint)
option.value
end
end
|
ruby
|
def option_value
if option_id
option_endpoint = "/customFields/#{custom_field_id}/options/#{option_id}"
option = CustomFieldOption.from_response client.get(option_endpoint)
option.value
end
end
|
[
"def",
"option_value",
"if",
"option_id",
"option_endpoint",
"=",
"\"/customFields/#{custom_field_id}/options/#{option_id}\"",
"option",
"=",
"CustomFieldOption",
".",
"from_response",
"client",
".",
"get",
"(",
"option_endpoint",
")",
"option",
".",
"value",
"end",
"end"
] |
Need to make another call to get the actual value if the custom field type == 'list'
|
[
"Need",
"to",
"make",
"another",
"call",
"to",
"get",
"the",
"actual",
"value",
"if",
"the",
"custom",
"field",
"type",
"==",
"list"
] |
ad79c9d8152ad5395b3b61c43170908f1912bfb2
|
https://github.com/jeremytregunna/ruby-trello/blob/ad79c9d8152ad5395b3b61c43170908f1912bfb2/lib/trello/custom_field_item.rb#L69-L75
|
12,940
|
jeremytregunna/ruby-trello
|
lib/trello/checklist.rb
|
Trello.Checklist.update_fields
|
def update_fields(fields)
attributes[:id] = fields['id'] || attributes[:id]
attributes[:name] = fields['name'] || fields[:name] || attributes[:name]
attributes[:description] = fields['desc'] || attributes[:description]
attributes[:closed] = fields['closed'] if fields.has_key?('closed')
attributes[:url] = fields['url'] || attributes[:url]
attributes[:check_items] = fields['checkItems'] if fields.has_key?('checkItems')
attributes[:position] = fields['pos'] || attributes[:position]
attributes[:board_id] = fields['idBoard'] || attributes[:board_id]
attributes[:card_id] = fields['idCard'] || fields[:card_id] || attributes[:card_id]
attributes[:list_id] = fields['idList'] || attributes[:list_id]
attributes[:member_ids] = fields['idMembers'] || attributes[:member_ids]
self
end
|
ruby
|
def update_fields(fields)
attributes[:id] = fields['id'] || attributes[:id]
attributes[:name] = fields['name'] || fields[:name] || attributes[:name]
attributes[:description] = fields['desc'] || attributes[:description]
attributes[:closed] = fields['closed'] if fields.has_key?('closed')
attributes[:url] = fields['url'] || attributes[:url]
attributes[:check_items] = fields['checkItems'] if fields.has_key?('checkItems')
attributes[:position] = fields['pos'] || attributes[:position]
attributes[:board_id] = fields['idBoard'] || attributes[:board_id]
attributes[:card_id] = fields['idCard'] || fields[:card_id] || attributes[:card_id]
attributes[:list_id] = fields['idList'] || attributes[:list_id]
attributes[:member_ids] = fields['idMembers'] || attributes[:member_ids]
self
end
|
[
"def",
"update_fields",
"(",
"fields",
")",
"attributes",
"[",
":id",
"]",
"=",
"fields",
"[",
"'id'",
"]",
"||",
"attributes",
"[",
":id",
"]",
"attributes",
"[",
":name",
"]",
"=",
"fields",
"[",
"'name'",
"]",
"||",
"fields",
"[",
":name",
"]",
"||",
"attributes",
"[",
":name",
"]",
"attributes",
"[",
":description",
"]",
"=",
"fields",
"[",
"'desc'",
"]",
"||",
"attributes",
"[",
":description",
"]",
"attributes",
"[",
":closed",
"]",
"=",
"fields",
"[",
"'closed'",
"]",
"if",
"fields",
".",
"has_key?",
"(",
"'closed'",
")",
"attributes",
"[",
":url",
"]",
"=",
"fields",
"[",
"'url'",
"]",
"||",
"attributes",
"[",
":url",
"]",
"attributes",
"[",
":check_items",
"]",
"=",
"fields",
"[",
"'checkItems'",
"]",
"if",
"fields",
".",
"has_key?",
"(",
"'checkItems'",
")",
"attributes",
"[",
":position",
"]",
"=",
"fields",
"[",
"'pos'",
"]",
"||",
"attributes",
"[",
":position",
"]",
"attributes",
"[",
":board_id",
"]",
"=",
"fields",
"[",
"'idBoard'",
"]",
"||",
"attributes",
"[",
":board_id",
"]",
"attributes",
"[",
":card_id",
"]",
"=",
"fields",
"[",
"'idCard'",
"]",
"||",
"fields",
"[",
":card_id",
"]",
"||",
"attributes",
"[",
":card_id",
"]",
"attributes",
"[",
":list_id",
"]",
"=",
"fields",
"[",
"'idList'",
"]",
"||",
"attributes",
"[",
":list_id",
"]",
"attributes",
"[",
":member_ids",
"]",
"=",
"fields",
"[",
"'idMembers'",
"]",
"||",
"attributes",
"[",
":member_ids",
"]",
"self",
"end"
] |
Update the fields of a checklist.
Supply a hash of string keyed data retrieved from the Trello API representing
a checklist.
|
[
"Update",
"the",
"fields",
"of",
"a",
"checklist",
"."
] |
ad79c9d8152ad5395b3b61c43170908f1912bfb2
|
https://github.com/jeremytregunna/ruby-trello/blob/ad79c9d8152ad5395b3b61c43170908f1912bfb2/lib/trello/checklist.rb#L47-L60
|
12,941
|
jeremytregunna/ruby-trello
|
lib/trello/checklist.rb
|
Trello.Checklist.save
|
def save
return update! if id
from_response(client.post("/checklists", {
name: name,
idCard: card_id
}))
end
|
ruby
|
def save
return update! if id
from_response(client.post("/checklists", {
name: name,
idCard: card_id
}))
end
|
[
"def",
"save",
"return",
"update!",
"if",
"id",
"from_response",
"(",
"client",
".",
"post",
"(",
"\"/checklists\"",
",",
"{",
"name",
":",
"name",
",",
"idCard",
":",
"card_id",
"}",
")",
")",
"end"
] |
Save a record.
|
[
"Save",
"a",
"record",
"."
] |
ad79c9d8152ad5395b3b61c43170908f1912bfb2
|
https://github.com/jeremytregunna/ruby-trello/blob/ad79c9d8152ad5395b3b61c43170908f1912bfb2/lib/trello/checklist.rb#L68-L75
|
12,942
|
jeremytregunna/ruby-trello
|
lib/trello/checklist.rb
|
Trello.Checklist.members
|
def members
members = member_ids.map do |member_id|
Member.find(member_id)
end
MultiAssociation.new(self, members).proxy
end
|
ruby
|
def members
members = member_ids.map do |member_id|
Member.find(member_id)
end
MultiAssociation.new(self, members).proxy
end
|
[
"def",
"members",
"members",
"=",
"member_ids",
".",
"map",
"do",
"|",
"member_id",
"|",
"Member",
".",
"find",
"(",
"member_id",
")",
"end",
"MultiAssociation",
".",
"new",
"(",
"self",
",",
"members",
")",
".",
"proxy",
"end"
] |
Return a list of members active in this checklist.
|
[
"Return",
"a",
"list",
"of",
"members",
"active",
"in",
"this",
"checklist",
"."
] |
ad79c9d8152ad5395b3b61c43170908f1912bfb2
|
https://github.com/jeremytregunna/ruby-trello/blob/ad79c9d8152ad5395b3b61c43170908f1912bfb2/lib/trello/checklist.rb#L98-L103
|
12,943
|
jeremytregunna/ruby-trello
|
lib/trello/checklist.rb
|
Trello.Checklist.add_item
|
def add_item(name, checked = false, position = 'bottom')
client.post("/checklists/#{id}/checkItems", {name: name, checked: checked, pos: position})
end
|
ruby
|
def add_item(name, checked = false, position = 'bottom')
client.post("/checklists/#{id}/checkItems", {name: name, checked: checked, pos: position})
end
|
[
"def",
"add_item",
"(",
"name",
",",
"checked",
"=",
"false",
",",
"position",
"=",
"'bottom'",
")",
"client",
".",
"post",
"(",
"\"/checklists/#{id}/checkItems\"",
",",
"{",
"name",
":",
"name",
",",
"checked",
":",
"checked",
",",
"pos",
":",
"position",
"}",
")",
"end"
] |
Add an item to the checklist
|
[
"Add",
"an",
"item",
"to",
"the",
"checklist"
] |
ad79c9d8152ad5395b3b61c43170908f1912bfb2
|
https://github.com/jeremytregunna/ruby-trello/blob/ad79c9d8152ad5395b3b61c43170908f1912bfb2/lib/trello/checklist.rb#L106-L108
|
12,944
|
jeremytregunna/ruby-trello
|
lib/trello/has_actions.rb
|
Trello.HasActions.actions
|
def actions(options = {})
actions = Action.from_response client.get("#{request_prefix}/actions", { filter: :all }.merge(options))
MultiAssociation.new(self, actions).proxy
end
|
ruby
|
def actions(options = {})
actions = Action.from_response client.get("#{request_prefix}/actions", { filter: :all }.merge(options))
MultiAssociation.new(self, actions).proxy
end
|
[
"def",
"actions",
"(",
"options",
"=",
"{",
"}",
")",
"actions",
"=",
"Action",
".",
"from_response",
"client",
".",
"get",
"(",
"\"#{request_prefix}/actions\"",
",",
"{",
"filter",
":",
":all",
"}",
".",
"merge",
"(",
"options",
")",
")",
"MultiAssociation",
".",
"new",
"(",
"self",
",",
"actions",
")",
".",
"proxy",
"end"
] |
Returns a list of the actions associated with this object.
|
[
"Returns",
"a",
"list",
"of",
"the",
"actions",
"associated",
"with",
"this",
"object",
"."
] |
ad79c9d8152ad5395b3b61c43170908f1912bfb2
|
https://github.com/jeremytregunna/ruby-trello/blob/ad79c9d8152ad5395b3b61c43170908f1912bfb2/lib/trello/has_actions.rb#L4-L7
|
12,945
|
jeremytregunna/ruby-trello
|
lib/trello/item_state.rb
|
Trello.CheckItemState.update_fields
|
def update_fields(fields)
attributes[:id] = fields['id'] || attributes[:id]
attributes[:state] = fields['state'] || attributes[:state]
attributes[:item_id] = fields['idCheckItem'] || attributes[:item_id]
self
end
|
ruby
|
def update_fields(fields)
attributes[:id] = fields['id'] || attributes[:id]
attributes[:state] = fields['state'] || attributes[:state]
attributes[:item_id] = fields['idCheckItem'] || attributes[:item_id]
self
end
|
[
"def",
"update_fields",
"(",
"fields",
")",
"attributes",
"[",
":id",
"]",
"=",
"fields",
"[",
"'id'",
"]",
"||",
"attributes",
"[",
":id",
"]",
"attributes",
"[",
":state",
"]",
"=",
"fields",
"[",
"'state'",
"]",
"||",
"attributes",
"[",
":state",
"]",
"attributes",
"[",
":item_id",
"]",
"=",
"fields",
"[",
"'idCheckItem'",
"]",
"||",
"attributes",
"[",
":item_id",
"]",
"self",
"end"
] |
Update the fields of an item state.
Supply a hash of string keyed data retrieved from the Trello API representing
an item state.
|
[
"Update",
"the",
"fields",
"of",
"an",
"item",
"state",
"."
] |
ad79c9d8152ad5395b3b61c43170908f1912bfb2
|
https://github.com/jeremytregunna/ruby-trello/blob/ad79c9d8152ad5395b3b61c43170908f1912bfb2/lib/trello/item_state.rb#L18-L23
|
12,946
|
diasks2/pragmatic_segmenter
|
lib/pragmatic_segmenter/cleaner.rb
|
PragmaticSegmenter.Cleaner.clean
|
def clean
return unless text
remove_all_newlines
replace_double_newlines
replace_newlines
replace_escaped_newlines
@text.apply(HTML::All)
replace_punctuation_in_brackets
@text.apply(InlineFormattingRule)
clean_quotations
clean_table_of_contents
check_for_no_space_in_between_sentences
clean_consecutive_characters
end
|
ruby
|
def clean
return unless text
remove_all_newlines
replace_double_newlines
replace_newlines
replace_escaped_newlines
@text.apply(HTML::All)
replace_punctuation_in_brackets
@text.apply(InlineFormattingRule)
clean_quotations
clean_table_of_contents
check_for_no_space_in_between_sentences
clean_consecutive_characters
end
|
[
"def",
"clean",
"return",
"unless",
"text",
"remove_all_newlines",
"replace_double_newlines",
"replace_newlines",
"replace_escaped_newlines",
"@text",
".",
"apply",
"(",
"HTML",
"::",
"All",
")",
"replace_punctuation_in_brackets",
"@text",
".",
"apply",
"(",
"InlineFormattingRule",
")",
"clean_quotations",
"clean_table_of_contents",
"check_for_no_space_in_between_sentences",
"clean_consecutive_characters",
"end"
] |
Clean text of unwanted formatting
Example:
>> text = "This is a sentence\ncut off in the middle because pdf."
>> PragmaticSegmenter::Cleaner(text: text).clean
=> "This is a sentence cut off in the middle because pdf."
Arguments:
text: (String) *required
language: (String) *optional
(two character ISO 639-1 code e.g. 'en')
doc_type: (String) *optional
(e.g. 'pdf')
|
[
"Clean",
"text",
"of",
"unwanted",
"formatting"
] |
bb59de8e46e18d2e0bfee074b7d4cacda9612df2
|
https://github.com/diasks2/pragmatic_segmenter/blob/bb59de8e46e18d2e0bfee074b7d4cacda9612df2/lib/pragmatic_segmenter/cleaner.rb#L33-L48
|
12,947
|
SamSaffron/message_bus
|
lib/message_bus/http_client.rb
|
MessageBus.HTTPClient.subscribe
|
def subscribe(channel, last_message_id: nil, &callback)
raise InvalidChannel unless channel.to_s.start_with?("/")
raise MissingBlock unless block_given?
last_message_id = -1 if last_message_id && !last_message_id.is_a?(Integer)
@channels[channel] ||= Channel.new
channel = @channels[channel]
channel.last_message_id = last_message_id if last_message_id
channel.callbacks.push(callback)
start if stopped?
end
|
ruby
|
def subscribe(channel, last_message_id: nil, &callback)
raise InvalidChannel unless channel.to_s.start_with?("/")
raise MissingBlock unless block_given?
last_message_id = -1 if last_message_id && !last_message_id.is_a?(Integer)
@channels[channel] ||= Channel.new
channel = @channels[channel]
channel.last_message_id = last_message_id if last_message_id
channel.callbacks.push(callback)
start if stopped?
end
|
[
"def",
"subscribe",
"(",
"channel",
",",
"last_message_id",
":",
"nil",
",",
"&",
"callback",
")",
"raise",
"InvalidChannel",
"unless",
"channel",
".",
"to_s",
".",
"start_with?",
"(",
"\"/\"",
")",
"raise",
"MissingBlock",
"unless",
"block_given?",
"last_message_id",
"=",
"-",
"1",
"if",
"last_message_id",
"&&",
"!",
"last_message_id",
".",
"is_a?",
"(",
"Integer",
")",
"@channels",
"[",
"channel",
"]",
"||=",
"Channel",
".",
"new",
"channel",
"=",
"@channels",
"[",
"channel",
"]",
"channel",
".",
"last_message_id",
"=",
"last_message_id",
"if",
"last_message_id",
"channel",
".",
"callbacks",
".",
"push",
"(",
"callback",
")",
"start",
"if",
"stopped?",
"end"
] |
Subscribes to a channel which executes the given callback when a message
is published to the channel
@example Subscribing to a channel for message
client = MessageBus::HTTPClient.new('http://some.test.com')
client.subscribe("/test") do |payload, _message_id, _global_id|
puts payload
end
A last_message_id may be provided.
* -1 will subscribe to all new messages
* -2 will recieve last message + all new messages
* -3 will recieve last 2 message + all new messages
@example Subscribing to a channel with `last_message_id`
client.subscribe("/test", last_message_id: -2) do |payload|
puts payload
end
@param channel [String] channel to listen for messages on
@param last_message_id [Integer] last message id to start polling on.
@yield [data, message_id, global_id]
callback to be executed whenever a message is received
@yieldparam data [Hash] data payload of the message received on the channel
@yieldparam message_id [Integer] id of the message in the channel
@yieldparam global_id [Integer] id of the message in the global backlog
@yieldreturn [void]
@return [Integer] the current status of the client
|
[
"Subscribes",
"to",
"a",
"channel",
"which",
"executes",
"the",
"given",
"callback",
"when",
"a",
"message",
"is",
"published",
"to",
"the",
"channel"
] |
90fba639eb5d332ca8e87fd35f1d603a5743076d
|
https://github.com/SamSaffron/message_bus/blob/90fba639eb5d332ca8e87fd35f1d603a5743076d/lib/message_bus/http_client.rb#L168-L179
|
12,948
|
SamSaffron/message_bus
|
lib/message_bus/http_client.rb
|
MessageBus.HTTPClient.unsubscribe
|
def unsubscribe(channel, &callback)
if callback
@channels[channel].callbacks.delete(callback)
remove_channel(channel) if @channels[channel].callbacks.empty?
else
remove_channel(channel)
end
stop if @channels.empty?
@status
end
|
ruby
|
def unsubscribe(channel, &callback)
if callback
@channels[channel].callbacks.delete(callback)
remove_channel(channel) if @channels[channel].callbacks.empty?
else
remove_channel(channel)
end
stop if @channels.empty?
@status
end
|
[
"def",
"unsubscribe",
"(",
"channel",
",",
"&",
"callback",
")",
"if",
"callback",
"@channels",
"[",
"channel",
"]",
".",
"callbacks",
".",
"delete",
"(",
"callback",
")",
"remove_channel",
"(",
"channel",
")",
"if",
"@channels",
"[",
"channel",
"]",
".",
"callbacks",
".",
"empty?",
"else",
"remove_channel",
"(",
"channel",
")",
"end",
"stop",
"if",
"@channels",
".",
"empty?",
"@status",
"end"
] |
unsubscribes from a channel
@example Unsubscribing from a channel
client = MessageBus::HTTPClient.new('http://some.test.com')
callback = -> { |payload| puts payload }
client.subscribe("/test", &callback)
client.unsubscribe("/test")
If a callback is given, only the specific callback will be unsubscribed.
@example Unsubscribing a callback from a channel
client.unsubscribe("/test", &callback)
When the client does not have any channels left, it will stop polling and
waits until a new subscription is started.
@param channel [String] channel to unsubscribe
@yield [data, global_id, message_id] specific callback to unsubscribe
@return [Integer] the current status of the client
|
[
"unsubscribes",
"from",
"a",
"channel"
] |
90fba639eb5d332ca8e87fd35f1d603a5743076d
|
https://github.com/SamSaffron/message_bus/blob/90fba639eb5d332ca8e87fd35f1d603a5743076d/lib/message_bus/http_client.rb#L201-L211
|
12,949
|
anycable/anycable
|
lib/anycable/rpc_handler.rb
|
AnyCable.RPCHandler.connect
|
def connect(request, _unused_call)
logger.debug("RPC Connect: #{request.inspect}")
socket = build_socket(env: rack_env(request))
connection = factory.call(socket)
connection.handle_open
if socket.closed?
AnyCable::ConnectionResponse.new(status: AnyCable::Status::FAILURE)
else
AnyCable::ConnectionResponse.new(
status: AnyCable::Status::SUCCESS,
identifiers: connection.identifiers_json,
transmissions: socket.transmissions
)
end
rescue StandardError => exp
notify_exception(exp, :connect, request)
AnyCable::ConnectionResponse.new(
status: AnyCable::Status::ERROR,
error_msg: exp.message
)
end
|
ruby
|
def connect(request, _unused_call)
logger.debug("RPC Connect: #{request.inspect}")
socket = build_socket(env: rack_env(request))
connection = factory.call(socket)
connection.handle_open
if socket.closed?
AnyCable::ConnectionResponse.new(status: AnyCable::Status::FAILURE)
else
AnyCable::ConnectionResponse.new(
status: AnyCable::Status::SUCCESS,
identifiers: connection.identifiers_json,
transmissions: socket.transmissions
)
end
rescue StandardError => exp
notify_exception(exp, :connect, request)
AnyCable::ConnectionResponse.new(
status: AnyCable::Status::ERROR,
error_msg: exp.message
)
end
|
[
"def",
"connect",
"(",
"request",
",",
"_unused_call",
")",
"logger",
".",
"debug",
"(",
"\"RPC Connect: #{request.inspect}\"",
")",
"socket",
"=",
"build_socket",
"(",
"env",
":",
"rack_env",
"(",
"request",
")",
")",
"connection",
"=",
"factory",
".",
"call",
"(",
"socket",
")",
"connection",
".",
"handle_open",
"if",
"socket",
".",
"closed?",
"AnyCable",
"::",
"ConnectionResponse",
".",
"new",
"(",
"status",
":",
"AnyCable",
"::",
"Status",
"::",
"FAILURE",
")",
"else",
"AnyCable",
"::",
"ConnectionResponse",
".",
"new",
"(",
"status",
":",
"AnyCable",
"::",
"Status",
"::",
"SUCCESS",
",",
"identifiers",
":",
"connection",
".",
"identifiers_json",
",",
"transmissions",
":",
"socket",
".",
"transmissions",
")",
"end",
"rescue",
"StandardError",
"=>",
"exp",
"notify_exception",
"(",
"exp",
",",
":connect",
",",
"request",
")",
"AnyCable",
"::",
"ConnectionResponse",
".",
"new",
"(",
"status",
":",
"AnyCable",
"::",
"Status",
"::",
"ERROR",
",",
"error_msg",
":",
"exp",
".",
"message",
")",
"end"
] |
Handle connection request from WebSocket server
|
[
"Handle",
"connection",
"request",
"from",
"WebSocket",
"server"
] |
d7515e8e034d42e86ebeb09786a92aad2a11b25f
|
https://github.com/anycable/anycable/blob/d7515e8e034d42e86ebeb09786a92aad2a11b25f/lib/anycable/rpc_handler.rb#L14-L39
|
12,950
|
anycable/anycable
|
lib/anycable/rpc_handler.rb
|
AnyCable.RPCHandler.rack_env
|
def rack_env(request)
uri = URI.parse(request.path)
# Minimum required variables according to Rack Spec
env = {
"REQUEST_METHOD" => "GET",
"SCRIPT_NAME" => "",
"PATH_INFO" => uri.path,
"QUERY_STRING" => uri.query,
"SERVER_NAME" => uri.host,
"SERVER_PORT" => uri.port.to_s,
"HTTP_HOST" => uri.host,
"REMOTE_ADDR" => request.headers.delete("REMOTE_ADDR"),
"rack.url_scheme" => uri.scheme,
"rack.input" => ""
}
env.merge!(build_headers(request.headers))
end
|
ruby
|
def rack_env(request)
uri = URI.parse(request.path)
# Minimum required variables according to Rack Spec
env = {
"REQUEST_METHOD" => "GET",
"SCRIPT_NAME" => "",
"PATH_INFO" => uri.path,
"QUERY_STRING" => uri.query,
"SERVER_NAME" => uri.host,
"SERVER_PORT" => uri.port.to_s,
"HTTP_HOST" => uri.host,
"REMOTE_ADDR" => request.headers.delete("REMOTE_ADDR"),
"rack.url_scheme" => uri.scheme,
"rack.input" => ""
}
env.merge!(build_headers(request.headers))
end
|
[
"def",
"rack_env",
"(",
"request",
")",
"uri",
"=",
"URI",
".",
"parse",
"(",
"request",
".",
"path",
")",
"# Minimum required variables according to Rack Spec",
"env",
"=",
"{",
"\"REQUEST_METHOD\"",
"=>",
"\"GET\"",
",",
"\"SCRIPT_NAME\"",
"=>",
"\"\"",
",",
"\"PATH_INFO\"",
"=>",
"uri",
".",
"path",
",",
"\"QUERY_STRING\"",
"=>",
"uri",
".",
"query",
",",
"\"SERVER_NAME\"",
"=>",
"uri",
".",
"host",
",",
"\"SERVER_PORT\"",
"=>",
"uri",
".",
"port",
".",
"to_s",
",",
"\"HTTP_HOST\"",
"=>",
"uri",
".",
"host",
",",
"\"REMOTE_ADDR\"",
"=>",
"request",
".",
"headers",
".",
"delete",
"(",
"\"REMOTE_ADDR\"",
")",
",",
"\"rack.url_scheme\"",
"=>",
"uri",
".",
"scheme",
",",
"\"rack.input\"",
"=>",
"\"\"",
"}",
"env",
".",
"merge!",
"(",
"build_headers",
"(",
"request",
".",
"headers",
")",
")",
"end"
] |
Build Rack env from request
|
[
"Build",
"Rack",
"env",
"from",
"request"
] |
d7515e8e034d42e86ebeb09786a92aad2a11b25f
|
https://github.com/anycable/anycable/blob/d7515e8e034d42e86ebeb09786a92aad2a11b25f/lib/anycable/rpc_handler.rb#L101-L119
|
12,951
|
anycable/anycable
|
lib/anycable/config.rb
|
AnyCable.Config.to_grpc_params
|
def to_grpc_params
{
pool_size: rpc_pool_size,
max_waiting_requests: rpc_max_waiting_requests,
poll_period: rpc_poll_period,
pool_keep_alive: rpc_pool_keep_alive,
server_args: rpc_server_args
}
end
|
ruby
|
def to_grpc_params
{
pool_size: rpc_pool_size,
max_waiting_requests: rpc_max_waiting_requests,
poll_period: rpc_poll_period,
pool_keep_alive: rpc_pool_keep_alive,
server_args: rpc_server_args
}
end
|
[
"def",
"to_grpc_params",
"{",
"pool_size",
":",
"rpc_pool_size",
",",
"max_waiting_requests",
":",
"rpc_max_waiting_requests",
",",
"poll_period",
":",
"rpc_poll_period",
",",
"pool_keep_alive",
":",
"rpc_pool_keep_alive",
",",
"server_args",
":",
"rpc_server_args",
"}",
"end"
] |
Build gRPC server parameters
|
[
"Build",
"gRPC",
"server",
"parameters"
] |
d7515e8e034d42e86ebeb09786a92aad2a11b25f
|
https://github.com/anycable/anycable/blob/d7515e8e034d42e86ebeb09786a92aad2a11b25f/lib/anycable/config.rb#L62-L70
|
12,952
|
anycable/anycable
|
lib/anycable/config.rb
|
AnyCable.Config.to_redis_params
|
def to_redis_params
{ url: redis_url }.tap do |params|
next if redis_sentinels.nil?
raise ArgumentError, "redis_sentinels must be an array; got #{redis_sentinels}" unless
redis_sentinels.is_a?(Array)
next if redis_sentinels.empty?
params[:sentinels] = redis_sentinels.map(&method(:parse_sentinel))
end
end
|
ruby
|
def to_redis_params
{ url: redis_url }.tap do |params|
next if redis_sentinels.nil?
raise ArgumentError, "redis_sentinels must be an array; got #{redis_sentinels}" unless
redis_sentinels.is_a?(Array)
next if redis_sentinels.empty?
params[:sentinels] = redis_sentinels.map(&method(:parse_sentinel))
end
end
|
[
"def",
"to_redis_params",
"{",
"url",
":",
"redis_url",
"}",
".",
"tap",
"do",
"|",
"params",
"|",
"next",
"if",
"redis_sentinels",
".",
"nil?",
"raise",
"ArgumentError",
",",
"\"redis_sentinels must be an array; got #{redis_sentinels}\"",
"unless",
"redis_sentinels",
".",
"is_a?",
"(",
"Array",
")",
"next",
"if",
"redis_sentinels",
".",
"empty?",
"params",
"[",
":sentinels",
"]",
"=",
"redis_sentinels",
".",
"map",
"(",
"method",
"(",
":parse_sentinel",
")",
")",
"end",
"end"
] |
Build Redis parameters
|
[
"Build",
"Redis",
"parameters"
] |
d7515e8e034d42e86ebeb09786a92aad2a11b25f
|
https://github.com/anycable/anycable/blob/d7515e8e034d42e86ebeb09786a92aad2a11b25f/lib/anycable/config.rb#L73-L84
|
12,953
|
anycable/anycable
|
lib/anycable/server.rb
|
AnyCable.Server.start
|
def start
return if running?
raise "Cannot re-start stopped server" if stopped?
check_default_host
logger.info "RPC server is starting..."
@start_thread = Thread.new { grpc_server.run }
grpc_server.wait_till_running
logger.info "RPC server is listening on #{host}"
end
|
ruby
|
def start
return if running?
raise "Cannot re-start stopped server" if stopped?
check_default_host
logger.info "RPC server is starting..."
@start_thread = Thread.new { grpc_server.run }
grpc_server.wait_till_running
logger.info "RPC server is listening on #{host}"
end
|
[
"def",
"start",
"return",
"if",
"running?",
"raise",
"\"Cannot re-start stopped server\"",
"if",
"stopped?",
"check_default_host",
"logger",
".",
"info",
"\"RPC server is starting...\"",
"@start_thread",
"=",
"Thread",
".",
"new",
"{",
"grpc_server",
".",
"run",
"}",
"grpc_server",
".",
"wait_till_running",
"logger",
".",
"info",
"\"RPC server is listening on #{host}\"",
"end"
] |
Start gRPC server in background and
wait untill it ready to accept connections
|
[
"Start",
"gRPC",
"server",
"in",
"background",
"and",
"wait",
"untill",
"it",
"ready",
"to",
"accept",
"connections"
] |
d7515e8e034d42e86ebeb09786a92aad2a11b25f
|
https://github.com/anycable/anycable/blob/d7515e8e034d42e86ebeb09786a92aad2a11b25f/lib/anycable/server.rb#L76-L90
|
12,954
|
toshimaru/jekyll-toc
|
lib/jekyll-toc.rb
|
Jekyll.TableOfContentsFilter.toc_only
|
def toc_only(html)
Jekyll.logger.warn 'Deprecation: toc_only filter is deprecated and will be remove in jekyll-toc v1.0.',
'Use `{% toc %}` instead of `{{ content | toc_only }}`.'
return '' unless toc_enabled?
TableOfContents::Parser.new(html, toc_config).build_toc
end
|
ruby
|
def toc_only(html)
Jekyll.logger.warn 'Deprecation: toc_only filter is deprecated and will be remove in jekyll-toc v1.0.',
'Use `{% toc %}` instead of `{{ content | toc_only }}`.'
return '' unless toc_enabled?
TableOfContents::Parser.new(html, toc_config).build_toc
end
|
[
"def",
"toc_only",
"(",
"html",
")",
"Jekyll",
".",
"logger",
".",
"warn",
"'Deprecation: toc_only filter is deprecated and will be remove in jekyll-toc v1.0.'",
",",
"'Use `{% toc %}` instead of `{{ content | toc_only }}`.'",
"return",
"''",
"unless",
"toc_enabled?",
"TableOfContents",
"::",
"Parser",
".",
"new",
"(",
"html",
",",
"toc_config",
")",
".",
"build_toc",
"end"
] |
Deprecated method. Removed in v1.0.
|
[
"Deprecated",
"method",
".",
"Removed",
"in",
"v1",
".",
"0",
"."
] |
c36830f0b3d7ddf73793e34f8d498303064c1cef
|
https://github.com/toshimaru/jekyll-toc/blob/c36830f0b3d7ddf73793e34f8d498303064c1cef/lib/jekyll-toc.rb#L22-L28
|
12,955
|
phusion/passenger
|
src/ruby_supportlib/phusion_passenger/utils.rb
|
PhusionPassenger.Utils.generate_random_id
|
def generate_random_id(method)
data = File.open("/dev/urandom", "rb") do |f|
f.read(64)
end
case method
when :base64
data = base64(data)
data.gsub!("+", '')
data.gsub!("/", '')
data.gsub!(/==$/, '')
return data
when :hex
return data.unpack('H*')[0]
else
raise ArgumentError, "Invalid method #{method.inspect}"
end
end
|
ruby
|
def generate_random_id(method)
data = File.open("/dev/urandom", "rb") do |f|
f.read(64)
end
case method
when :base64
data = base64(data)
data.gsub!("+", '')
data.gsub!("/", '')
data.gsub!(/==$/, '')
return data
when :hex
return data.unpack('H*')[0]
else
raise ArgumentError, "Invalid method #{method.inspect}"
end
end
|
[
"def",
"generate_random_id",
"(",
"method",
")",
"data",
"=",
"File",
".",
"open",
"(",
"\"/dev/urandom\"",
",",
"\"rb\"",
")",
"do",
"|",
"f",
"|",
"f",
".",
"read",
"(",
"64",
")",
"end",
"case",
"method",
"when",
":base64",
"data",
"=",
"base64",
"(",
"data",
")",
"data",
".",
"gsub!",
"(",
"\"+\"",
",",
"''",
")",
"data",
".",
"gsub!",
"(",
"\"/\"",
",",
"''",
")",
"data",
".",
"gsub!",
"(",
"/",
"/",
",",
"''",
")",
"return",
"data",
"when",
":hex",
"return",
"data",
".",
"unpack",
"(",
"'H*'",
")",
"[",
"0",
"]",
"else",
"raise",
"ArgumentError",
",",
"\"Invalid method #{method.inspect}\"",
"end",
"end"
] |
Generate a long, cryptographically secure random ID string, which
is also a valid filename.
|
[
"Generate",
"a",
"long",
"cryptographically",
"secure",
"random",
"ID",
"string",
"which",
"is",
"also",
"a",
"valid",
"filename",
"."
] |
970964b53e0ba86959acdf40f06c99b0c4a128ca
|
https://github.com/phusion/passenger/blob/970964b53e0ba86959acdf40f06c99b0c4a128ca/src/ruby_supportlib/phusion_passenger/utils.rb#L44-L60
|
12,956
|
phusion/passenger
|
src/ruby_supportlib/phusion_passenger/utils.rb
|
PhusionPassenger.Utils.print_exception
|
def print_exception(current_location, exception, destination = nil)
if !exception.is_a?(SystemExit)
data = exception.backtrace_string(current_location)
if defined?(DebugLogging) && self.is_a?(DebugLogging)
error(data)
else
destination ||= STDERR
destination.puts(data)
destination.flush if destination.respond_to?(:flush)
end
end
end
|
ruby
|
def print_exception(current_location, exception, destination = nil)
if !exception.is_a?(SystemExit)
data = exception.backtrace_string(current_location)
if defined?(DebugLogging) && self.is_a?(DebugLogging)
error(data)
else
destination ||= STDERR
destination.puts(data)
destination.flush if destination.respond_to?(:flush)
end
end
end
|
[
"def",
"print_exception",
"(",
"current_location",
",",
"exception",
",",
"destination",
"=",
"nil",
")",
"if",
"!",
"exception",
".",
"is_a?",
"(",
"SystemExit",
")",
"data",
"=",
"exception",
".",
"backtrace_string",
"(",
"current_location",
")",
"if",
"defined?",
"(",
"DebugLogging",
")",
"&&",
"self",
".",
"is_a?",
"(",
"DebugLogging",
")",
"error",
"(",
"data",
")",
"else",
"destination",
"||=",
"STDERR",
"destination",
".",
"puts",
"(",
"data",
")",
"destination",
".",
"flush",
"if",
"destination",
".",
"respond_to?",
"(",
":flush",
")",
"end",
"end",
"end"
] |
Print the given exception, including the stack trace, to STDERR.
+current_location+ is a string which describes where the code is
currently at. Usually the current class name will be enough.
It may be nil.
This method requires 'ruby_core_enhancements'. If 'debug_logging'
is loaded and included in the current module, it will use that for
logging.
|
[
"Print",
"the",
"given",
"exception",
"including",
"the",
"stack",
"trace",
"to",
"STDERR",
"."
] |
970964b53e0ba86959acdf40f06c99b0c4a128ca
|
https://github.com/phusion/passenger/blob/970964b53e0ba86959acdf40f06c99b0c4a128ca/src/ruby_supportlib/phusion_passenger/utils.rb#L83-L94
|
12,957
|
phusion/passenger
|
src/ruby_supportlib/phusion_passenger/utils.rb
|
PhusionPassenger.Utils.create_thread_and_abort_on_exception
|
def create_thread_and_abort_on_exception(*args)
Thread.new do
Thread.current.abort_on_exception = true
begin
yield(*args)
rescue SystemExit
raise
rescue Exception => e
print_exception(nil, e)
exit(1)
end
end
end
|
ruby
|
def create_thread_and_abort_on_exception(*args)
Thread.new do
Thread.current.abort_on_exception = true
begin
yield(*args)
rescue SystemExit
raise
rescue Exception => e
print_exception(nil, e)
exit(1)
end
end
end
|
[
"def",
"create_thread_and_abort_on_exception",
"(",
"*",
"args",
")",
"Thread",
".",
"new",
"do",
"Thread",
".",
"current",
".",
"abort_on_exception",
"=",
"true",
"begin",
"yield",
"(",
"args",
")",
"rescue",
"SystemExit",
"raise",
"rescue",
"Exception",
"=>",
"e",
"print_exception",
"(",
"nil",
",",
"e",
")",
"exit",
"(",
"1",
")",
"end",
"end",
"end"
] |
A wrapper around Thread.new that installs a default exception handler.
If an uncaught exception is encountered, it will immediately log the
exception and abort the entire program.
Thread#abort_on_exception is also supposed to do that, but the problem
is that it is implemented by forwarding the uncaught exception
to the main thread, which may not expect that particular exception
and may not handle it properly. The exception could be forwarded to
the main thread during any point of the main thread's execution.
This method requires 'thread' and 'ruby_core_enhancements'.
If 'debug_logging' is loaded and included in the current module,
it will use that for logging.
|
[
"A",
"wrapper",
"around",
"Thread",
".",
"new",
"that",
"installs",
"a",
"default",
"exception",
"handler",
".",
"If",
"an",
"uncaught",
"exception",
"is",
"encountered",
"it",
"will",
"immediately",
"log",
"the",
"exception",
"and",
"abort",
"the",
"entire",
"program",
"."
] |
970964b53e0ba86959acdf40f06c99b0c4a128ca
|
https://github.com/phusion/passenger/blob/970964b53e0ba86959acdf40f06c99b0c4a128ca/src/ruby_supportlib/phusion_passenger/utils.rb#L109-L121
|
12,958
|
phusion/passenger
|
src/ruby_supportlib/phusion_passenger/utils.rb
|
PhusionPassenger.Utils.process_is_alive?
|
def process_is_alive?(pid)
begin
Process.kill(0, pid)
return true
rescue Errno::ESRCH
return false
rescue SystemCallError => e
return true
end
end
|
ruby
|
def process_is_alive?(pid)
begin
Process.kill(0, pid)
return true
rescue Errno::ESRCH
return false
rescue SystemCallError => e
return true
end
end
|
[
"def",
"process_is_alive?",
"(",
"pid",
")",
"begin",
"Process",
".",
"kill",
"(",
"0",
",",
"pid",
")",
"return",
"true",
"rescue",
"Errno",
"::",
"ESRCH",
"return",
"false",
"rescue",
"SystemCallError",
"=>",
"e",
"return",
"true",
"end",
"end"
] |
Checks whether the given process exists.
|
[
"Checks",
"whether",
"the",
"given",
"process",
"exists",
"."
] |
970964b53e0ba86959acdf40f06c99b0c4a128ca
|
https://github.com/phusion/passenger/blob/970964b53e0ba86959acdf40f06c99b0c4a128ca/src/ruby_supportlib/phusion_passenger/utils.rb#L159-L168
|
12,959
|
phusion/passenger
|
src/ruby_supportlib/phusion_passenger/utils.rb
|
PhusionPassenger.Utils.global_backtrace_report
|
def global_backtrace_report
if Kernel.respond_to?(:caller_for_all_threads)
all_thread_stacks = caller_for_all_threads
elsif Thread.respond_to?(:list) && Thread.public_method_defined?(:backtrace)
all_thread_stacks = {}
Thread.list.each do |thread|
all_thread_stacks[thread] = thread.backtrace
end
end
output = "========== Process #{Process.pid}: backtrace dump ==========\n"
if all_thread_stacks
all_thread_stacks.each_pair do |thread, stack|
if thread_name = thread[:name]
thread_name = "(#{thread_name})"
end
stack ||= ["(empty)"]
output << ("-" * 60) << "\n"
output << "# Thread: #{thread.inspect}#{thread_name}, "
if thread == Thread.main
output << "[main thread], "
end
if thread == Thread.current
output << "[current thread], "
end
output << "alive = #{thread.alive?}\n"
output << ("-" * 60) << "\n"
output << " " << stack.join("\n ")
output << "\n\n"
end
else
output << ("-" * 60) << "\n"
output << "# Current thread: #{Thread.current.inspect}\n"
output << ("-" * 60) << "\n"
output << " " << caller.join("\n ")
end
return output
end
|
ruby
|
def global_backtrace_report
if Kernel.respond_to?(:caller_for_all_threads)
all_thread_stacks = caller_for_all_threads
elsif Thread.respond_to?(:list) && Thread.public_method_defined?(:backtrace)
all_thread_stacks = {}
Thread.list.each do |thread|
all_thread_stacks[thread] = thread.backtrace
end
end
output = "========== Process #{Process.pid}: backtrace dump ==========\n"
if all_thread_stacks
all_thread_stacks.each_pair do |thread, stack|
if thread_name = thread[:name]
thread_name = "(#{thread_name})"
end
stack ||= ["(empty)"]
output << ("-" * 60) << "\n"
output << "# Thread: #{thread.inspect}#{thread_name}, "
if thread == Thread.main
output << "[main thread], "
end
if thread == Thread.current
output << "[current thread], "
end
output << "alive = #{thread.alive?}\n"
output << ("-" * 60) << "\n"
output << " " << stack.join("\n ")
output << "\n\n"
end
else
output << ("-" * 60) << "\n"
output << "# Current thread: #{Thread.current.inspect}\n"
output << ("-" * 60) << "\n"
output << " " << caller.join("\n ")
end
return output
end
|
[
"def",
"global_backtrace_report",
"if",
"Kernel",
".",
"respond_to?",
"(",
":caller_for_all_threads",
")",
"all_thread_stacks",
"=",
"caller_for_all_threads",
"elsif",
"Thread",
".",
"respond_to?",
"(",
":list",
")",
"&&",
"Thread",
".",
"public_method_defined?",
"(",
":backtrace",
")",
"all_thread_stacks",
"=",
"{",
"}",
"Thread",
".",
"list",
".",
"each",
"do",
"|",
"thread",
"|",
"all_thread_stacks",
"[",
"thread",
"]",
"=",
"thread",
".",
"backtrace",
"end",
"end",
"output",
"=",
"\"========== Process #{Process.pid}: backtrace dump ==========\\n\"",
"if",
"all_thread_stacks",
"all_thread_stacks",
".",
"each_pair",
"do",
"|",
"thread",
",",
"stack",
"|",
"if",
"thread_name",
"=",
"thread",
"[",
":name",
"]",
"thread_name",
"=",
"\"(#{thread_name})\"",
"end",
"stack",
"||=",
"[",
"\"(empty)\"",
"]",
"output",
"<<",
"(",
"\"-\"",
"*",
"60",
")",
"<<",
"\"\\n\"",
"output",
"<<",
"\"# Thread: #{thread.inspect}#{thread_name}, \"",
"if",
"thread",
"==",
"Thread",
".",
"main",
"output",
"<<",
"\"[main thread], \"",
"end",
"if",
"thread",
"==",
"Thread",
".",
"current",
"output",
"<<",
"\"[current thread], \"",
"end",
"output",
"<<",
"\"alive = #{thread.alive?}\\n\"",
"output",
"<<",
"(",
"\"-\"",
"*",
"60",
")",
"<<",
"\"\\n\"",
"output",
"<<",
"\" \"",
"<<",
"stack",
".",
"join",
"(",
"\"\\n \"",
")",
"output",
"<<",
"\"\\n\\n\"",
"end",
"else",
"output",
"<<",
"(",
"\"-\"",
"*",
"60",
")",
"<<",
"\"\\n\"",
"output",
"<<",
"\"# Current thread: #{Thread.current.inspect}\\n\"",
"output",
"<<",
"(",
"\"-\"",
"*",
"60",
")",
"<<",
"\"\\n\"",
"output",
"<<",
"\" \"",
"<<",
"caller",
".",
"join",
"(",
"\"\\n \"",
")",
"end",
"return",
"output",
"end"
] |
Returns a string which reports the backtraces for all threads,
or if that's not supported the backtrace for the current thread.
|
[
"Returns",
"a",
"string",
"which",
"reports",
"the",
"backtraces",
"for",
"all",
"threads",
"or",
"if",
"that",
"s",
"not",
"supported",
"the",
"backtrace",
"for",
"the",
"current",
"thread",
"."
] |
970964b53e0ba86959acdf40f06c99b0c4a128ca
|
https://github.com/phusion/passenger/blob/970964b53e0ba86959acdf40f06c99b0c4a128ca/src/ruby_supportlib/phusion_passenger/utils.rb#L201-L238
|
12,960
|
phusion/passenger
|
src/ruby_supportlib/phusion_passenger/native_support.rb
|
PhusionPassenger.NativeSupportLoader.current_user_name_or_id
|
def current_user_name_or_id
require 'etc' if !defined?(Etc)
begin
user = Etc.getpwuid(Process.uid)
rescue ArgumentError
user = nil
end
if user
return user.name
else
return "##{Process.uid}"
end
end
|
ruby
|
def current_user_name_or_id
require 'etc' if !defined?(Etc)
begin
user = Etc.getpwuid(Process.uid)
rescue ArgumentError
user = nil
end
if user
return user.name
else
return "##{Process.uid}"
end
end
|
[
"def",
"current_user_name_or_id",
"require",
"'etc'",
"if",
"!",
"defined?",
"(",
"Etc",
")",
"begin",
"user",
"=",
"Etc",
".",
"getpwuid",
"(",
"Process",
".",
"uid",
")",
"rescue",
"ArgumentError",
"user",
"=",
"nil",
"end",
"if",
"user",
"return",
"user",
".",
"name",
"else",
"return",
"\"##{Process.uid}\"",
"end",
"end"
] |
Name of the user under which we are executing, or the id as fallback
N.B. loader_shared_helpers.rb has the same method
|
[
"Name",
"of",
"the",
"user",
"under",
"which",
"we",
"are",
"executing",
"or",
"the",
"id",
"as",
"fallback",
"N",
".",
"B",
".",
"loader_shared_helpers",
".",
"rb",
"has",
"the",
"same",
"method"
] |
970964b53e0ba86959acdf40f06c99b0c4a128ca
|
https://github.com/phusion/passenger/blob/970964b53e0ba86959acdf40f06c99b0c4a128ca/src/ruby_supportlib/phusion_passenger/native_support.rb#L229-L241
|
12,961
|
phusion/passenger
|
src/ruby_supportlib/phusion_passenger/loader_shared_helpers.rb
|
PhusionPassenger.LoaderSharedHelpers.maybe_make_path_relative_to_app_root
|
def maybe_make_path_relative_to_app_root(app_root, abs_path)
if Dir.logical_pwd == app_root && File.dirname(abs_path) == app_root
File.basename(abs_path)
else
abs_path
end
end
|
ruby
|
def maybe_make_path_relative_to_app_root(app_root, abs_path)
if Dir.logical_pwd == app_root && File.dirname(abs_path) == app_root
File.basename(abs_path)
else
abs_path
end
end
|
[
"def",
"maybe_make_path_relative_to_app_root",
"(",
"app_root",
",",
"abs_path",
")",
"if",
"Dir",
".",
"logical_pwd",
"==",
"app_root",
"&&",
"File",
".",
"dirname",
"(",
"abs_path",
")",
"==",
"app_root",
"File",
".",
"basename",
"(",
"abs_path",
")",
"else",
"abs_path",
"end",
"end"
] |
If the current working directory equals `app_root`, and `abs_path` is a
file inside `app_root`, then returns its basename. Otherwise, returns
`abs_path`.
The main use case for this method is to ensure that we load config.ru
with a relative path (only its base name) in most circumstances,
instead of with an absolute path. This is necessary in order to retain
compatibility with apps that expect config.ru's __FILE__ to be relative.
See https://github.com/phusion/passenger/issues/1596
|
[
"If",
"the",
"current",
"working",
"directory",
"equals",
"app_root",
"and",
"abs_path",
"is",
"a",
"file",
"inside",
"app_root",
"then",
"returns",
"its",
"basename",
".",
"Otherwise",
"returns",
"abs_path",
"."
] |
970964b53e0ba86959acdf40f06c99b0c4a128ca
|
https://github.com/phusion/passenger/blob/970964b53e0ba86959acdf40f06c99b0c4a128ca/src/ruby_supportlib/phusion_passenger/loader_shared_helpers.rb#L251-L257
|
12,962
|
phusion/passenger
|
src/ruby_supportlib/phusion_passenger/loader_shared_helpers.rb
|
PhusionPassenger.LoaderSharedHelpers.before_handling_requests
|
def before_handling_requests(forked, options)
if forked
# Reseed pseudo-random number generator for security reasons.
srand
end
if options["process_title"] && !options["process_title"].empty?
$0 = options["process_title"] + ": " + options["app_group_name"]
end
# If we were forked from a preloader process then clear or
# re-establish ActiveRecord database connections. This prevents
# child processes from concurrently accessing the same
# database connection handles.
if forked && defined?(ActiveRecord::Base)
if ActiveRecord::Base.respond_to?(:clear_all_connections!)
ActiveRecord::Base.clear_all_connections!
elsif ActiveRecord::Base.respond_to?(:clear_active_connections!)
ActiveRecord::Base.clear_active_connections!
elsif ActiveRecord::Base.respond_to?(:connected?) &&
ActiveRecord::Base.connected?
ActiveRecord::Base.establish_connection
end
end
# Fire off events.
PhusionPassenger.call_event(:starting_worker_process, forked)
if options["pool_account_username"] && options["pool_account_password_base64"]
password = options["pool_account_password_base64"].unpack('m').first
PhusionPassenger.call_event(:credentials,
options["pool_account_username"], password)
else
PhusionPassenger.call_event(:credentials, nil, nil)
end
end
|
ruby
|
def before_handling_requests(forked, options)
if forked
# Reseed pseudo-random number generator for security reasons.
srand
end
if options["process_title"] && !options["process_title"].empty?
$0 = options["process_title"] + ": " + options["app_group_name"]
end
# If we were forked from a preloader process then clear or
# re-establish ActiveRecord database connections. This prevents
# child processes from concurrently accessing the same
# database connection handles.
if forked && defined?(ActiveRecord::Base)
if ActiveRecord::Base.respond_to?(:clear_all_connections!)
ActiveRecord::Base.clear_all_connections!
elsif ActiveRecord::Base.respond_to?(:clear_active_connections!)
ActiveRecord::Base.clear_active_connections!
elsif ActiveRecord::Base.respond_to?(:connected?) &&
ActiveRecord::Base.connected?
ActiveRecord::Base.establish_connection
end
end
# Fire off events.
PhusionPassenger.call_event(:starting_worker_process, forked)
if options["pool_account_username"] && options["pool_account_password_base64"]
password = options["pool_account_password_base64"].unpack('m').first
PhusionPassenger.call_event(:credentials,
options["pool_account_username"], password)
else
PhusionPassenger.call_event(:credentials, nil, nil)
end
end
|
[
"def",
"before_handling_requests",
"(",
"forked",
",",
"options",
")",
"if",
"forked",
"# Reseed pseudo-random number generator for security reasons.",
"srand",
"end",
"if",
"options",
"[",
"\"process_title\"",
"]",
"&&",
"!",
"options",
"[",
"\"process_title\"",
"]",
".",
"empty?",
"$0",
"=",
"options",
"[",
"\"process_title\"",
"]",
"+",
"\": \"",
"+",
"options",
"[",
"\"app_group_name\"",
"]",
"end",
"# If we were forked from a preloader process then clear or",
"# re-establish ActiveRecord database connections. This prevents",
"# child processes from concurrently accessing the same",
"# database connection handles.",
"if",
"forked",
"&&",
"defined?",
"(",
"ActiveRecord",
"::",
"Base",
")",
"if",
"ActiveRecord",
"::",
"Base",
".",
"respond_to?",
"(",
":clear_all_connections!",
")",
"ActiveRecord",
"::",
"Base",
".",
"clear_all_connections!",
"elsif",
"ActiveRecord",
"::",
"Base",
".",
"respond_to?",
"(",
":clear_active_connections!",
")",
"ActiveRecord",
"::",
"Base",
".",
"clear_active_connections!",
"elsif",
"ActiveRecord",
"::",
"Base",
".",
"respond_to?",
"(",
":connected?",
")",
"&&",
"ActiveRecord",
"::",
"Base",
".",
"connected?",
"ActiveRecord",
"::",
"Base",
".",
"establish_connection",
"end",
"end",
"# Fire off events.",
"PhusionPassenger",
".",
"call_event",
"(",
":starting_worker_process",
",",
"forked",
")",
"if",
"options",
"[",
"\"pool_account_username\"",
"]",
"&&",
"options",
"[",
"\"pool_account_password_base64\"",
"]",
"password",
"=",
"options",
"[",
"\"pool_account_password_base64\"",
"]",
".",
"unpack",
"(",
"'m'",
")",
".",
"first",
"PhusionPassenger",
".",
"call_event",
"(",
":credentials",
",",
"options",
"[",
"\"pool_account_username\"",
"]",
",",
"password",
")",
"else",
"PhusionPassenger",
".",
"call_event",
"(",
":credentials",
",",
"nil",
",",
"nil",
")",
"end",
"end"
] |
To be called before the request handler main loop is entered, but after the app
startup file has been loaded. This function will fire off necessary events
and perform necessary preparation tasks.
+forked+ indicates whether the current worker process is forked off from
an ApplicationSpawner that has preloaded the app code.
+options+ are the spawn options that were passed.
|
[
"To",
"be",
"called",
"before",
"the",
"request",
"handler",
"main",
"loop",
"is",
"entered",
"but",
"after",
"the",
"app",
"startup",
"file",
"has",
"been",
"loaded",
".",
"This",
"function",
"will",
"fire",
"off",
"necessary",
"events",
"and",
"perform",
"necessary",
"preparation",
"tasks",
"."
] |
970964b53e0ba86959acdf40f06c99b0c4a128ca
|
https://github.com/phusion/passenger/blob/970964b53e0ba86959acdf40f06c99b0c4a128ca/src/ruby_supportlib/phusion_passenger/loader_shared_helpers.rb#L300-L334
|
12,963
|
phusion/passenger
|
src/ruby_supportlib/phusion_passenger/message_channel.rb
|
PhusionPassenger.MessageChannel.read_hash
|
def read_hash
buffer = new_buffer
if !@io.read(HEADER_SIZE, buffer)
return nil
end
while buffer.size < HEADER_SIZE
tmp = @io.read(HEADER_SIZE - buffer.size)
if tmp.empty?
return nil
else
buffer << tmp
end
end
chunk_size = buffer.unpack(UINT16_PACK_FORMAT)[0]
if !@io.read(chunk_size, buffer)
return nil
end
while buffer.size < chunk_size
tmp = @io.read(chunk_size - buffer.size)
if tmp.empty?
return nil
else
buffer << tmp
end
end
result = {}
offset = 0
delimiter_pos = buffer.index(DELIMITER, offset)
while !delimiter_pos.nil?
if delimiter_pos == 0
name = ""
else
name = buffer[offset .. delimiter_pos - 1]
end
offset = delimiter_pos + 1
delimiter_pos = buffer.index(DELIMITER, offset)
if delimiter_pos.nil?
raise InvalidHashError
elsif delimiter_pos == 0
value = ""
else
value = buffer[offset .. delimiter_pos - 1]
end
result[name] = value
offset = delimiter_pos + 1
delimiter_pos = buffer.index(DELIMITER, offset)
end
return result
rescue Errno::ECONNRESET
return nil
end
|
ruby
|
def read_hash
buffer = new_buffer
if !@io.read(HEADER_SIZE, buffer)
return nil
end
while buffer.size < HEADER_SIZE
tmp = @io.read(HEADER_SIZE - buffer.size)
if tmp.empty?
return nil
else
buffer << tmp
end
end
chunk_size = buffer.unpack(UINT16_PACK_FORMAT)[0]
if !@io.read(chunk_size, buffer)
return nil
end
while buffer.size < chunk_size
tmp = @io.read(chunk_size - buffer.size)
if tmp.empty?
return nil
else
buffer << tmp
end
end
result = {}
offset = 0
delimiter_pos = buffer.index(DELIMITER, offset)
while !delimiter_pos.nil?
if delimiter_pos == 0
name = ""
else
name = buffer[offset .. delimiter_pos - 1]
end
offset = delimiter_pos + 1
delimiter_pos = buffer.index(DELIMITER, offset)
if delimiter_pos.nil?
raise InvalidHashError
elsif delimiter_pos == 0
value = ""
else
value = buffer[offset .. delimiter_pos - 1]
end
result[name] = value
offset = delimiter_pos + 1
delimiter_pos = buffer.index(DELIMITER, offset)
end
return result
rescue Errno::ECONNRESET
return nil
end
|
[
"def",
"read_hash",
"buffer",
"=",
"new_buffer",
"if",
"!",
"@io",
".",
"read",
"(",
"HEADER_SIZE",
",",
"buffer",
")",
"return",
"nil",
"end",
"while",
"buffer",
".",
"size",
"<",
"HEADER_SIZE",
"tmp",
"=",
"@io",
".",
"read",
"(",
"HEADER_SIZE",
"-",
"buffer",
".",
"size",
")",
"if",
"tmp",
".",
"empty?",
"return",
"nil",
"else",
"buffer",
"<<",
"tmp",
"end",
"end",
"chunk_size",
"=",
"buffer",
".",
"unpack",
"(",
"UINT16_PACK_FORMAT",
")",
"[",
"0",
"]",
"if",
"!",
"@io",
".",
"read",
"(",
"chunk_size",
",",
"buffer",
")",
"return",
"nil",
"end",
"while",
"buffer",
".",
"size",
"<",
"chunk_size",
"tmp",
"=",
"@io",
".",
"read",
"(",
"chunk_size",
"-",
"buffer",
".",
"size",
")",
"if",
"tmp",
".",
"empty?",
"return",
"nil",
"else",
"buffer",
"<<",
"tmp",
"end",
"end",
"result",
"=",
"{",
"}",
"offset",
"=",
"0",
"delimiter_pos",
"=",
"buffer",
".",
"index",
"(",
"DELIMITER",
",",
"offset",
")",
"while",
"!",
"delimiter_pos",
".",
"nil?",
"if",
"delimiter_pos",
"==",
"0",
"name",
"=",
"\"\"",
"else",
"name",
"=",
"buffer",
"[",
"offset",
"..",
"delimiter_pos",
"-",
"1",
"]",
"end",
"offset",
"=",
"delimiter_pos",
"+",
"1",
"delimiter_pos",
"=",
"buffer",
".",
"index",
"(",
"DELIMITER",
",",
"offset",
")",
"if",
"delimiter_pos",
".",
"nil?",
"raise",
"InvalidHashError",
"elsif",
"delimiter_pos",
"==",
"0",
"value",
"=",
"\"\"",
"else",
"value",
"=",
"buffer",
"[",
"offset",
"..",
"delimiter_pos",
"-",
"1",
"]",
"end",
"result",
"[",
"name",
"]",
"=",
"value",
"offset",
"=",
"delimiter_pos",
"+",
"1",
"delimiter_pos",
"=",
"buffer",
".",
"index",
"(",
"DELIMITER",
",",
"offset",
")",
"end",
"return",
"result",
"rescue",
"Errno",
"::",
"ECONNRESET",
"return",
"nil",
"end"
] |
Read an array message from the underlying file descriptor and return the
result as a hash instead of an array. This assumes that the array message
has an even number of elements.
Returns nil when end-of-stream has been reached.
Might raise SystemCallError, IOError or SocketError when something
goes wrong.
|
[
"Read",
"an",
"array",
"message",
"from",
"the",
"underlying",
"file",
"descriptor",
"and",
"return",
"the",
"result",
"as",
"a",
"hash",
"instead",
"of",
"an",
"array",
".",
"This",
"assumes",
"that",
"the",
"array",
"message",
"has",
"an",
"even",
"number",
"of",
"elements",
".",
"Returns",
"nil",
"when",
"end",
"-",
"of",
"-",
"stream",
"has",
"been",
"reached",
"."
] |
970964b53e0ba86959acdf40f06c99b0c4a128ca
|
https://github.com/phusion/passenger/blob/970964b53e0ba86959acdf40f06c99b0c4a128ca/src/ruby_supportlib/phusion_passenger/message_channel.rb#L108-L162
|
12,964
|
phusion/passenger
|
src/ruby_supportlib/phusion_passenger/message_channel.rb
|
PhusionPassenger.MessageChannel.read_scalar
|
def read_scalar(buffer = new_buffer, max_size = nil)
if !@io.read(4, buffer)
return nil
end
while buffer.size < 4
tmp = @io.read(4 - buffer.size)
if tmp.empty?
return nil
else
buffer << tmp
end
end
size = buffer.unpack(UINT32_PACK_FORMAT)[0]
if size == 0
buffer.replace('')
return buffer
else
if !max_size.nil? && size > max_size
raise SecurityError, "Scalar message size (#{size}) " <<
"exceeds maximum allowed size (#{max_size})."
end
if !@io.read(size, buffer)
return nil
end
if buffer.size < size
tmp = ''
while buffer.size < size
if !@io.read(size - buffer.size, tmp)
return nil
else
buffer << tmp
end
end
end
return buffer
end
rescue Errno::ECONNRESET
return nil
end
|
ruby
|
def read_scalar(buffer = new_buffer, max_size = nil)
if !@io.read(4, buffer)
return nil
end
while buffer.size < 4
tmp = @io.read(4 - buffer.size)
if tmp.empty?
return nil
else
buffer << tmp
end
end
size = buffer.unpack(UINT32_PACK_FORMAT)[0]
if size == 0
buffer.replace('')
return buffer
else
if !max_size.nil? && size > max_size
raise SecurityError, "Scalar message size (#{size}) " <<
"exceeds maximum allowed size (#{max_size})."
end
if !@io.read(size, buffer)
return nil
end
if buffer.size < size
tmp = ''
while buffer.size < size
if !@io.read(size - buffer.size, tmp)
return nil
else
buffer << tmp
end
end
end
return buffer
end
rescue Errno::ECONNRESET
return nil
end
|
[
"def",
"read_scalar",
"(",
"buffer",
"=",
"new_buffer",
",",
"max_size",
"=",
"nil",
")",
"if",
"!",
"@io",
".",
"read",
"(",
"4",
",",
"buffer",
")",
"return",
"nil",
"end",
"while",
"buffer",
".",
"size",
"<",
"4",
"tmp",
"=",
"@io",
".",
"read",
"(",
"4",
"-",
"buffer",
".",
"size",
")",
"if",
"tmp",
".",
"empty?",
"return",
"nil",
"else",
"buffer",
"<<",
"tmp",
"end",
"end",
"size",
"=",
"buffer",
".",
"unpack",
"(",
"UINT32_PACK_FORMAT",
")",
"[",
"0",
"]",
"if",
"size",
"==",
"0",
"buffer",
".",
"replace",
"(",
"''",
")",
"return",
"buffer",
"else",
"if",
"!",
"max_size",
".",
"nil?",
"&&",
"size",
">",
"max_size",
"raise",
"SecurityError",
",",
"\"Scalar message size (#{size}) \"",
"<<",
"\"exceeds maximum allowed size (#{max_size}).\"",
"end",
"if",
"!",
"@io",
".",
"read",
"(",
"size",
",",
"buffer",
")",
"return",
"nil",
"end",
"if",
"buffer",
".",
"size",
"<",
"size",
"tmp",
"=",
"''",
"while",
"buffer",
".",
"size",
"<",
"size",
"if",
"!",
"@io",
".",
"read",
"(",
"size",
"-",
"buffer",
".",
"size",
",",
"tmp",
")",
"return",
"nil",
"else",
"buffer",
"<<",
"tmp",
"end",
"end",
"end",
"return",
"buffer",
"end",
"rescue",
"Errno",
"::",
"ECONNRESET",
"return",
"nil",
"end"
] |
Read a scalar message from the underlying IO object. Returns the
read message, or nil on end-of-stream.
Might raise SystemCallError, IOError or SocketError when something
goes wrong.
The +buffer+ argument specifies a buffer in which #read_scalar
stores the read data. It is good practice to reuse existing buffers
in order to minimize stress on the garbage collector.
The +max_size+ argument allows one to specify the maximum allowed
size for the scalar message. If the received scalar message's size
is larger than +max_size+, then a SecurityError will be raised.
|
[
"Read",
"a",
"scalar",
"message",
"from",
"the",
"underlying",
"IO",
"object",
".",
"Returns",
"the",
"read",
"message",
"or",
"nil",
"on",
"end",
"-",
"of",
"-",
"stream",
"."
] |
970964b53e0ba86959acdf40f06c99b0c4a128ca
|
https://github.com/phusion/passenger/blob/970964b53e0ba86959acdf40f06c99b0c4a128ca/src/ruby_supportlib/phusion_passenger/message_channel.rb#L177-L216
|
12,965
|
phusion/passenger
|
src/ruby_supportlib/phusion_passenger/request_handler.rb
|
PhusionPassenger.RequestHandler.cleanup
|
def cleanup
if @main_loop_thread
@main_loop_thread_lock.synchronize do
@graceful_termination_pipe[1].close rescue nil
end
@main_loop_thread.join
end
@server_sockets.each_value do |info|
socket = info[:socket]
type = get_socket_address_type(info[:address])
begin
socket.close if !socket.closed?
rescue Exception => e
# Ignore "stream closed" error, which occurs in some unit tests.
# We catch Exception here instead of IOError because of a Ruby 1.8.7 bug.
if e.to_s !~ /stream closed/ && e.message.to_s !~ /stream closed/
raise e
end
end
if type == :unix
filename = info[:address].sub(/^unix:/, '')
File.unlink(filename) rescue nil
end
end
@owner_pipe.close rescue nil
end
|
ruby
|
def cleanup
if @main_loop_thread
@main_loop_thread_lock.synchronize do
@graceful_termination_pipe[1].close rescue nil
end
@main_loop_thread.join
end
@server_sockets.each_value do |info|
socket = info[:socket]
type = get_socket_address_type(info[:address])
begin
socket.close if !socket.closed?
rescue Exception => e
# Ignore "stream closed" error, which occurs in some unit tests.
# We catch Exception here instead of IOError because of a Ruby 1.8.7 bug.
if e.to_s !~ /stream closed/ && e.message.to_s !~ /stream closed/
raise e
end
end
if type == :unix
filename = info[:address].sub(/^unix:/, '')
File.unlink(filename) rescue nil
end
end
@owner_pipe.close rescue nil
end
|
[
"def",
"cleanup",
"if",
"@main_loop_thread",
"@main_loop_thread_lock",
".",
"synchronize",
"do",
"@graceful_termination_pipe",
"[",
"1",
"]",
".",
"close",
"rescue",
"nil",
"end",
"@main_loop_thread",
".",
"join",
"end",
"@server_sockets",
".",
"each_value",
"do",
"|",
"info",
"|",
"socket",
"=",
"info",
"[",
":socket",
"]",
"type",
"=",
"get_socket_address_type",
"(",
"info",
"[",
":address",
"]",
")",
"begin",
"socket",
".",
"close",
"if",
"!",
"socket",
".",
"closed?",
"rescue",
"Exception",
"=>",
"e",
"# Ignore \"stream closed\" error, which occurs in some unit tests.",
"# We catch Exception here instead of IOError because of a Ruby 1.8.7 bug.",
"if",
"e",
".",
"to_s",
"!~",
"/",
"/",
"&&",
"e",
".",
"message",
".",
"to_s",
"!~",
"/",
"/",
"raise",
"e",
"end",
"end",
"if",
"type",
"==",
":unix",
"filename",
"=",
"info",
"[",
":address",
"]",
".",
"sub",
"(",
"/",
"/",
",",
"''",
")",
"File",
".",
"unlink",
"(",
"filename",
")",
"rescue",
"nil",
"end",
"end",
"@owner_pipe",
".",
"close",
"rescue",
"nil",
"end"
] |
Create a new RequestHandler with the given owner pipe.
+owner_pipe+ must be the readable part of a pipe IO object.
Additionally, the following options may be given:
- connect_password
Clean up temporary stuff created by the request handler.
If the main loop was started by #main_loop, then this method may only
be called after the main loop has exited.
If the main loop was started by #start_main_loop_thread, then this method
may be called at any time, and it will stop the main loop thread.
|
[
"Create",
"a",
"new",
"RequestHandler",
"with",
"the",
"given",
"owner",
"pipe",
".",
"+",
"owner_pipe",
"+",
"must",
"be",
"the",
"readable",
"part",
"of",
"a",
"pipe",
"IO",
"object",
"."
] |
970964b53e0ba86959acdf40f06c99b0c4a128ca
|
https://github.com/phusion/passenger/blob/970964b53e0ba86959acdf40f06c99b0c4a128ca/src/ruby_supportlib/phusion_passenger/request_handler.rb#L140-L166
|
12,966
|
phusion/passenger
|
src/ruby_supportlib/phusion_passenger/request_handler.rb
|
PhusionPassenger.RequestHandler.main_loop
|
def main_loop
debug("Entering request handler main loop")
reset_signal_handlers
begin
@graceful_termination_pipe = IO.pipe
@graceful_termination_pipe[0].close_on_exec!
@graceful_termination_pipe[1].close_on_exec!
@main_loop_thread_lock.synchronize do
@main_loop_generation += 1
@main_loop_running = true
@main_loop_thread_cond.broadcast
@select_timeout = nil
@selectable_sockets = []
@server_sockets.each_value do |value|
socket = value[2]
@selectable_sockets << socket if socket
end
@selectable_sockets << @owner_pipe
@selectable_sockets << @graceful_termination_pipe[0]
end
install_useful_signal_handlers
start_threads
wait_until_termination_requested
wait_until_all_threads_are_idle
terminate_threads
debug("Request handler main loop exited normally")
rescue EOFError
# Exit main loop.
trace(2, "Request handler main loop interrupted by EOFError exception")
rescue Interrupt
# Exit main loop.
trace(2, "Request handler main loop interrupted by Interrupt exception")
rescue SignalException => signal
trace(2, "Request handler main loop interrupted by SignalException")
if signal.message != HARD_TERMINATION_SIGNAL
raise
end
rescue Exception => e
trace(2, "Request handler main loop interrupted by #{e.class} exception")
raise
ensure
debug("Exiting request handler main loop")
revert_signal_handlers
@main_loop_thread_lock.synchronize do
@graceful_termination_pipe[1].close rescue nil
@graceful_termination_pipe[0].close rescue nil
@selectable_sockets = []
@main_loop_generation += 1
@main_loop_running = false
@main_loop_thread_cond.broadcast
end
end
end
|
ruby
|
def main_loop
debug("Entering request handler main loop")
reset_signal_handlers
begin
@graceful_termination_pipe = IO.pipe
@graceful_termination_pipe[0].close_on_exec!
@graceful_termination_pipe[1].close_on_exec!
@main_loop_thread_lock.synchronize do
@main_loop_generation += 1
@main_loop_running = true
@main_loop_thread_cond.broadcast
@select_timeout = nil
@selectable_sockets = []
@server_sockets.each_value do |value|
socket = value[2]
@selectable_sockets << socket if socket
end
@selectable_sockets << @owner_pipe
@selectable_sockets << @graceful_termination_pipe[0]
end
install_useful_signal_handlers
start_threads
wait_until_termination_requested
wait_until_all_threads_are_idle
terminate_threads
debug("Request handler main loop exited normally")
rescue EOFError
# Exit main loop.
trace(2, "Request handler main loop interrupted by EOFError exception")
rescue Interrupt
# Exit main loop.
trace(2, "Request handler main loop interrupted by Interrupt exception")
rescue SignalException => signal
trace(2, "Request handler main loop interrupted by SignalException")
if signal.message != HARD_TERMINATION_SIGNAL
raise
end
rescue Exception => e
trace(2, "Request handler main loop interrupted by #{e.class} exception")
raise
ensure
debug("Exiting request handler main loop")
revert_signal_handlers
@main_loop_thread_lock.synchronize do
@graceful_termination_pipe[1].close rescue nil
@graceful_termination_pipe[0].close rescue nil
@selectable_sockets = []
@main_loop_generation += 1
@main_loop_running = false
@main_loop_thread_cond.broadcast
end
end
end
|
[
"def",
"main_loop",
"debug",
"(",
"\"Entering request handler main loop\"",
")",
"reset_signal_handlers",
"begin",
"@graceful_termination_pipe",
"=",
"IO",
".",
"pipe",
"@graceful_termination_pipe",
"[",
"0",
"]",
".",
"close_on_exec!",
"@graceful_termination_pipe",
"[",
"1",
"]",
".",
"close_on_exec!",
"@main_loop_thread_lock",
".",
"synchronize",
"do",
"@main_loop_generation",
"+=",
"1",
"@main_loop_running",
"=",
"true",
"@main_loop_thread_cond",
".",
"broadcast",
"@select_timeout",
"=",
"nil",
"@selectable_sockets",
"=",
"[",
"]",
"@server_sockets",
".",
"each_value",
"do",
"|",
"value",
"|",
"socket",
"=",
"value",
"[",
"2",
"]",
"@selectable_sockets",
"<<",
"socket",
"if",
"socket",
"end",
"@selectable_sockets",
"<<",
"@owner_pipe",
"@selectable_sockets",
"<<",
"@graceful_termination_pipe",
"[",
"0",
"]",
"end",
"install_useful_signal_handlers",
"start_threads",
"wait_until_termination_requested",
"wait_until_all_threads_are_idle",
"terminate_threads",
"debug",
"(",
"\"Request handler main loop exited normally\"",
")",
"rescue",
"EOFError",
"# Exit main loop.",
"trace",
"(",
"2",
",",
"\"Request handler main loop interrupted by EOFError exception\"",
")",
"rescue",
"Interrupt",
"# Exit main loop.",
"trace",
"(",
"2",
",",
"\"Request handler main loop interrupted by Interrupt exception\"",
")",
"rescue",
"SignalException",
"=>",
"signal",
"trace",
"(",
"2",
",",
"\"Request handler main loop interrupted by SignalException\"",
")",
"if",
"signal",
".",
"message",
"!=",
"HARD_TERMINATION_SIGNAL",
"raise",
"end",
"rescue",
"Exception",
"=>",
"e",
"trace",
"(",
"2",
",",
"\"Request handler main loop interrupted by #{e.class} exception\"",
")",
"raise",
"ensure",
"debug",
"(",
"\"Exiting request handler main loop\"",
")",
"revert_signal_handlers",
"@main_loop_thread_lock",
".",
"synchronize",
"do",
"@graceful_termination_pipe",
"[",
"1",
"]",
".",
"close",
"rescue",
"nil",
"@graceful_termination_pipe",
"[",
"0",
"]",
".",
"close",
"rescue",
"nil",
"@selectable_sockets",
"=",
"[",
"]",
"@main_loop_generation",
"+=",
"1",
"@main_loop_running",
"=",
"false",
"@main_loop_thread_cond",
".",
"broadcast",
"end",
"end",
"end"
] |
Enter the request handler's main loop.
|
[
"Enter",
"the",
"request",
"handler",
"s",
"main",
"loop",
"."
] |
970964b53e0ba86959acdf40f06c99b0c4a128ca
|
https://github.com/phusion/passenger/blob/970964b53e0ba86959acdf40f06c99b0c4a128ca/src/ruby_supportlib/phusion_passenger/request_handler.rb#L176-L233
|
12,967
|
phusion/passenger
|
src/ruby_supportlib/phusion_passenger/request_handler.rb
|
PhusionPassenger.RequestHandler.reset_signal_handlers
|
def reset_signal_handlers
Signal.list_trappable.each_key do |signal|
begin
prev_handler = trap(signal, DEFAULT)
if prev_handler != DEFAULT
@previous_signal_handlers[signal] = prev_handler
end
rescue ArgumentError
# Signal cannot be trapped; ignore it.
end
end
trap('HUP', IGNORE)
PhusionPassenger.call_event(:after_installing_signal_handlers)
end
|
ruby
|
def reset_signal_handlers
Signal.list_trappable.each_key do |signal|
begin
prev_handler = trap(signal, DEFAULT)
if prev_handler != DEFAULT
@previous_signal_handlers[signal] = prev_handler
end
rescue ArgumentError
# Signal cannot be trapped; ignore it.
end
end
trap('HUP', IGNORE)
PhusionPassenger.call_event(:after_installing_signal_handlers)
end
|
[
"def",
"reset_signal_handlers",
"Signal",
".",
"list_trappable",
".",
"each_key",
"do",
"|",
"signal",
"|",
"begin",
"prev_handler",
"=",
"trap",
"(",
"signal",
",",
"DEFAULT",
")",
"if",
"prev_handler",
"!=",
"DEFAULT",
"@previous_signal_handlers",
"[",
"signal",
"]",
"=",
"prev_handler",
"end",
"rescue",
"ArgumentError",
"# Signal cannot be trapped; ignore it.",
"end",
"end",
"trap",
"(",
"'HUP'",
",",
"IGNORE",
")",
"PhusionPassenger",
".",
"call_event",
"(",
":after_installing_signal_handlers",
")",
"end"
] |
Reset signal handlers to their default handler, and install some
special handlers for a few signals. The previous signal handlers
will be put back by calling revert_signal_handlers.
|
[
"Reset",
"signal",
"handlers",
"to",
"their",
"default",
"handler",
"and",
"install",
"some",
"special",
"handlers",
"for",
"a",
"few",
"signals",
".",
"The",
"previous",
"signal",
"handlers",
"will",
"be",
"put",
"back",
"by",
"calling",
"revert_signal_handlers",
"."
] |
970964b53e0ba86959acdf40f06c99b0c4a128ca
|
https://github.com/phusion/passenger/blob/970964b53e0ba86959acdf40f06c99b0c4a128ca/src/ruby_supportlib/phusion_passenger/request_handler.rb#L328-L341
|
12,968
|
AaronLasseigne/active_interaction
|
lib/active_interaction/filter.rb
|
ActiveInteraction.Filter.default
|
def default(context = nil)
raise NoDefaultError, name unless default?
value = raw_default(context)
raise InvalidValueError if value.is_a?(GroupedInput)
cast(value, context)
rescue InvalidNestedValueError => error
raise InvalidDefaultError, "#{name}: #{value.inspect} (#{error})"
rescue InvalidValueError, MissingValueError
raise InvalidDefaultError, "#{name}: #{value.inspect}"
end
|
ruby
|
def default(context = nil)
raise NoDefaultError, name unless default?
value = raw_default(context)
raise InvalidValueError if value.is_a?(GroupedInput)
cast(value, context)
rescue InvalidNestedValueError => error
raise InvalidDefaultError, "#{name}: #{value.inspect} (#{error})"
rescue InvalidValueError, MissingValueError
raise InvalidDefaultError, "#{name}: #{value.inspect}"
end
|
[
"def",
"default",
"(",
"context",
"=",
"nil",
")",
"raise",
"NoDefaultError",
",",
"name",
"unless",
"default?",
"value",
"=",
"raw_default",
"(",
"context",
")",
"raise",
"InvalidValueError",
"if",
"value",
".",
"is_a?",
"(",
"GroupedInput",
")",
"cast",
"(",
"value",
",",
"context",
")",
"rescue",
"InvalidNestedValueError",
"=>",
"error",
"raise",
"InvalidDefaultError",
",",
"\"#{name}: #{value.inspect} (#{error})\"",
"rescue",
"InvalidValueError",
",",
"MissingValueError",
"raise",
"InvalidDefaultError",
",",
"\"#{name}: #{value.inspect}\"",
"end"
] |
Get the default value.
@example
ActiveInteraction::Filter.new(:example).default
# => ActiveInteraction::NoDefaultError: example
@example
ActiveInteraction::Filter.new(:example, default: nil).default
# => nil
@example
ActiveInteraction::Filter.new(:example, default: 0).default
# => ActiveInteraction::InvalidDefaultError: example: 0
@param context [Base, nil]
@return (see #raw_default)
@raise [NoDefaultError] If the default is missing.
@raise [InvalidDefaultError] If the default is invalid.
|
[
"Get",
"the",
"default",
"value",
"."
] |
fdc00a041e939ef48948baa2f7fd1ce2e4d66982
|
https://github.com/AaronLasseigne/active_interaction/blob/fdc00a041e939ef48948baa2f7fd1ce2e4d66982/lib/active_interaction/filter.rb#L127-L138
|
12,969
|
AaronLasseigne/active_interaction
|
lib/active_interaction/concerns/active_recordable.rb
|
ActiveInteraction.ActiveRecordable.column_for_attribute
|
def column_for_attribute(name)
filter = self.class.filters[name]
FilterColumn.intern(filter.database_column_type) if filter
end
|
ruby
|
def column_for_attribute(name)
filter = self.class.filters[name]
FilterColumn.intern(filter.database_column_type) if filter
end
|
[
"def",
"column_for_attribute",
"(",
"name",
")",
"filter",
"=",
"self",
".",
"class",
".",
"filters",
"[",
"name",
"]",
"FilterColumn",
".",
"intern",
"(",
"filter",
".",
"database_column_type",
")",
"if",
"filter",
"end"
] |
Returns the column object for the named filter.
@param name [Symbol] The name of a filter.
@example
class Interaction < ActiveInteraction::Base
string :email, default: nil
def execute; end
end
Interaction.new.column_for_attribute(:email)
# => #<ActiveInteraction::FilterColumn:0x007faebeb2a6c8 @type=:string>
Interaction.new.column_for_attribute(:not_a_filter)
# => nil
@return [FilterColumn, nil]
@since 1.2.0
|
[
"Returns",
"the",
"column",
"object",
"for",
"the",
"named",
"filter",
"."
] |
fdc00a041e939ef48948baa2f7fd1ce2e4d66982
|
https://github.com/AaronLasseigne/active_interaction/blob/fdc00a041e939ef48948baa2f7fd1ce2e4d66982/lib/active_interaction/concerns/active_recordable.rb#L29-L32
|
12,970
|
gocardless/business
|
lib/business/calendar.rb
|
Business.Calendar.add_business_days
|
def add_business_days(date, delta)
date = roll_forward(date)
delta.times do
begin
date += day_interval_for(date)
end until business_day?(date)
end
date
end
|
ruby
|
def add_business_days(date, delta)
date = roll_forward(date)
delta.times do
begin
date += day_interval_for(date)
end until business_day?(date)
end
date
end
|
[
"def",
"add_business_days",
"(",
"date",
",",
"delta",
")",
"date",
"=",
"roll_forward",
"(",
"date",
")",
"delta",
".",
"times",
"do",
"begin",
"date",
"+=",
"day_interval_for",
"(",
"date",
")",
"end",
"until",
"business_day?",
"(",
"date",
")",
"end",
"date",
"end"
] |
Add a number of business days to a date. If a non-business day is given,
counting will start from the next business day. So,
monday + 1 = tuesday
friday + 1 = monday
sunday + 1 = tuesday
|
[
"Add",
"a",
"number",
"of",
"business",
"days",
"to",
"a",
"date",
".",
"If",
"a",
"non",
"-",
"business",
"day",
"is",
"given",
"counting",
"will",
"start",
"from",
"the",
"next",
"business",
"day",
".",
"So",
"monday",
"+",
"1",
"=",
"tuesday",
"friday",
"+",
"1",
"=",
"monday",
"sunday",
"+",
"1",
"=",
"tuesday"
] |
62a2a09008095403bafa78033a8be1afe6debbf6
|
https://github.com/gocardless/business/blob/62a2a09008095403bafa78033a8be1afe6debbf6/lib/business/calendar.rb#L102-L110
|
12,971
|
gocardless/business
|
lib/business/calendar.rb
|
Business.Calendar.subtract_business_days
|
def subtract_business_days(date, delta)
date = roll_backward(date)
delta.times do
begin
date -= day_interval_for(date)
end until business_day?(date)
end
date
end
|
ruby
|
def subtract_business_days(date, delta)
date = roll_backward(date)
delta.times do
begin
date -= day_interval_for(date)
end until business_day?(date)
end
date
end
|
[
"def",
"subtract_business_days",
"(",
"date",
",",
"delta",
")",
"date",
"=",
"roll_backward",
"(",
"date",
")",
"delta",
".",
"times",
"do",
"begin",
"date",
"-=",
"day_interval_for",
"(",
"date",
")",
"end",
"until",
"business_day?",
"(",
"date",
")",
"end",
"date",
"end"
] |
Subtract a number of business days to a date. If a non-business day is
given, counting will start from the previous business day. So,
friday - 1 = thursday
monday - 1 = friday
sunday - 1 = thursday
|
[
"Subtract",
"a",
"number",
"of",
"business",
"days",
"to",
"a",
"date",
".",
"If",
"a",
"non",
"-",
"business",
"day",
"is",
"given",
"counting",
"will",
"start",
"from",
"the",
"previous",
"business",
"day",
".",
"So",
"friday",
"-",
"1",
"=",
"thursday",
"monday",
"-",
"1",
"=",
"friday",
"sunday",
"-",
"1",
"=",
"thursday"
] |
62a2a09008095403bafa78033a8be1afe6debbf6
|
https://github.com/gocardless/business/blob/62a2a09008095403bafa78033a8be1afe6debbf6/lib/business/calendar.rb#L117-L125
|
12,972
|
gocardless/business
|
lib/business/calendar.rb
|
Business.Calendar.set_working_days
|
def set_working_days(working_days)
@working_days = (working_days || default_working_days).map do |day|
day.downcase.strip[0..2].tap do |normalised_day|
raise "Invalid day #{day}" unless DAY_NAMES.include?(normalised_day)
end
end
extra_working_dates_names = @extra_working_dates.map { |d| d.strftime("%a").downcase }
return if (extra_working_dates_names & @working_days).none?
raise ArgumentError, 'Extra working dates cannot be on working days'
end
|
ruby
|
def set_working_days(working_days)
@working_days = (working_days || default_working_days).map do |day|
day.downcase.strip[0..2].tap do |normalised_day|
raise "Invalid day #{day}" unless DAY_NAMES.include?(normalised_day)
end
end
extra_working_dates_names = @extra_working_dates.map { |d| d.strftime("%a").downcase }
return if (extra_working_dates_names & @working_days).none?
raise ArgumentError, 'Extra working dates cannot be on working days'
end
|
[
"def",
"set_working_days",
"(",
"working_days",
")",
"@working_days",
"=",
"(",
"working_days",
"||",
"default_working_days",
")",
".",
"map",
"do",
"|",
"day",
"|",
"day",
".",
"downcase",
".",
"strip",
"[",
"0",
"..",
"2",
"]",
".",
"tap",
"do",
"|",
"normalised_day",
"|",
"raise",
"\"Invalid day #{day}\"",
"unless",
"DAY_NAMES",
".",
"include?",
"(",
"normalised_day",
")",
"end",
"end",
"extra_working_dates_names",
"=",
"@extra_working_dates",
".",
"map",
"{",
"|",
"d",
"|",
"d",
".",
"strftime",
"(",
"\"%a\"",
")",
".",
"downcase",
"}",
"return",
"if",
"(",
"extra_working_dates_names",
"&",
"@working_days",
")",
".",
"none?",
"raise",
"ArgumentError",
",",
"'Extra working dates cannot be on working days'",
"end"
] |
Internal method for assigning working days from a calendar config.
|
[
"Internal",
"method",
"for",
"assigning",
"working",
"days",
"from",
"a",
"calendar",
"config",
"."
] |
62a2a09008095403bafa78033a8be1afe6debbf6
|
https://github.com/gocardless/business/blob/62a2a09008095403bafa78033a8be1afe6debbf6/lib/business/calendar.rb#L167-L176
|
12,973
|
stevegraham/slanger
|
lib/slanger/channel.rb
|
Slanger.Channel.dispatch
|
def dispatch(message, channel)
push(Oj.dump(message, mode: :compat)) unless channel =~ /\Aslanger:/
perform_client_webhook!(message)
end
|
ruby
|
def dispatch(message, channel)
push(Oj.dump(message, mode: :compat)) unless channel =~ /\Aslanger:/
perform_client_webhook!(message)
end
|
[
"def",
"dispatch",
"(",
"message",
",",
"channel",
")",
"push",
"(",
"Oj",
".",
"dump",
"(",
"message",
",",
"mode",
":",
":compat",
")",
")",
"unless",
"channel",
"=~",
"/",
"\\A",
"/",
"perform_client_webhook!",
"(",
"message",
")",
"end"
] |
Send an event received from Redis to the EventMachine channel
which will send it to subscribed clients.
|
[
"Send",
"an",
"event",
"received",
"from",
"Redis",
"to",
"the",
"EventMachine",
"channel",
"which",
"will",
"send",
"it",
"to",
"subscribed",
"clients",
"."
] |
f26f80c675dc4d853bce401743779a6959981af1
|
https://github.com/stevegraham/slanger/blob/f26f80c675dc4d853bce401743779a6959981af1/lib/slanger/channel.rb#L84-L88
|
12,974
|
stevegraham/slanger
|
lib/slanger/handler.rb
|
Slanger.Handler.onmessage
|
def onmessage(msg)
msg = Oj.strict_load(msg)
msg['data'] = Oj.strict_load(msg['data']) if msg['data'].is_a? String
event = msg['event'].gsub(/\Apusher:/, 'pusher_')
if event =~ /\Aclient-/
msg['socket_id'] = connection.socket_id
Channel.send_client_message msg
elsif respond_to? event, true
send event, msg
end
rescue JSON::ParserError
error({ code: 5001, message: "Invalid JSON" })
rescue Exception => e
error({ code: 500, message: "#{e.message}\n #{e.backtrace.join "\n"}" })
end
|
ruby
|
def onmessage(msg)
msg = Oj.strict_load(msg)
msg['data'] = Oj.strict_load(msg['data']) if msg['data'].is_a? String
event = msg['event'].gsub(/\Apusher:/, 'pusher_')
if event =~ /\Aclient-/
msg['socket_id'] = connection.socket_id
Channel.send_client_message msg
elsif respond_to? event, true
send event, msg
end
rescue JSON::ParserError
error({ code: 5001, message: "Invalid JSON" })
rescue Exception => e
error({ code: 500, message: "#{e.message}\n #{e.backtrace.join "\n"}" })
end
|
[
"def",
"onmessage",
"(",
"msg",
")",
"msg",
"=",
"Oj",
".",
"strict_load",
"(",
"msg",
")",
"msg",
"[",
"'data'",
"]",
"=",
"Oj",
".",
"strict_load",
"(",
"msg",
"[",
"'data'",
"]",
")",
"if",
"msg",
"[",
"'data'",
"]",
".",
"is_a?",
"String",
"event",
"=",
"msg",
"[",
"'event'",
"]",
".",
"gsub",
"(",
"/",
"\\A",
"/",
",",
"'pusher_'",
")",
"if",
"event",
"=~",
"/",
"\\A",
"/",
"msg",
"[",
"'socket_id'",
"]",
"=",
"connection",
".",
"socket_id",
"Channel",
".",
"send_client_message",
"msg",
"elsif",
"respond_to?",
"event",
",",
"true",
"send",
"event",
",",
"msg",
"end",
"rescue",
"JSON",
"::",
"ParserError",
"error",
"(",
"{",
"code",
":",
"5001",
",",
"message",
":",
"\"Invalid JSON\"",
"}",
")",
"rescue",
"Exception",
"=>",
"e",
"error",
"(",
"{",
"code",
":",
"500",
",",
"message",
":",
"\"#{e.message}\\n #{e.backtrace.join \"\\n\"}\"",
"}",
")",
"end"
] |
Dispatches message handling to method with same name as
the event name
|
[
"Dispatches",
"message",
"handling",
"to",
"method",
"with",
"same",
"name",
"as",
"the",
"event",
"name"
] |
f26f80c675dc4d853bce401743779a6959981af1
|
https://github.com/stevegraham/slanger/blob/f26f80c675dc4d853bce401743779a6959981af1/lib/slanger/handler.rb#L27-L45
|
12,975
|
stevegraham/slanger
|
lib/slanger/presence_channel.rb
|
Slanger.PresenceChannel.dispatch
|
def dispatch(message, channel)
if channel =~ /\Aslanger:/
# Messages received from the Redis channel slanger:* carry info on
# subscriptions. Update our subscribers accordingly.
update_subscribers message
else
push Oj.dump(message, mode: :compat)
end
end
|
ruby
|
def dispatch(message, channel)
if channel =~ /\Aslanger:/
# Messages received from the Redis channel slanger:* carry info on
# subscriptions. Update our subscribers accordingly.
update_subscribers message
else
push Oj.dump(message, mode: :compat)
end
end
|
[
"def",
"dispatch",
"(",
"message",
",",
"channel",
")",
"if",
"channel",
"=~",
"/",
"\\A",
"/",
"# Messages received from the Redis channel slanger:* carry info on",
"# subscriptions. Update our subscribers accordingly.",
"update_subscribers",
"message",
"else",
"push",
"Oj",
".",
"dump",
"(",
"message",
",",
"mode",
":",
":compat",
")",
"end",
"end"
] |
Send an event received from Redis to the EventMachine channel
|
[
"Send",
"an",
"event",
"received",
"from",
"Redis",
"to",
"the",
"EventMachine",
"channel"
] |
f26f80c675dc4d853bce401743779a6959981af1
|
https://github.com/stevegraham/slanger/blob/f26f80c675dc4d853bce401743779a6959981af1/lib/slanger/presence_channel.rb#L18-L26
|
12,976
|
JsonApiClient/json_api_client
|
lib/json_api_client/schema.rb
|
JsonApiClient.Schema.add
|
def add(name, options)
@properties[name.to_sym] = Property.new(name.to_sym, options[:type], options[:default])
end
|
ruby
|
def add(name, options)
@properties[name.to_sym] = Property.new(name.to_sym, options[:type], options[:default])
end
|
[
"def",
"add",
"(",
"name",
",",
"options",
")",
"@properties",
"[",
"name",
".",
"to_sym",
"]",
"=",
"Property",
".",
"new",
"(",
"name",
".",
"to_sym",
",",
"options",
"[",
":type",
"]",
",",
"options",
"[",
":default",
"]",
")",
"end"
] |
Add a property to the schema
@param name [Symbol] the name of the property
@param options [Hash] property options
@option options [Symbol] :type The property type
@option options [Symbol] :default The default value for the property
@return [void]
|
[
"Add",
"a",
"property",
"to",
"the",
"schema"
] |
e4b763f5579c4fae4b03dcc935b20627f5c14eaa
|
https://github.com/JsonApiClient/json_api_client/blob/e4b763f5579c4fae4b03dcc935b20627f5c14eaa/lib/json_api_client/schema.rb#L119-L121
|
12,977
|
JsonApiClient/json_api_client
|
lib/json_api_client/connection.rb
|
JsonApiClient.Connection.use
|
def use(middleware, *args, &block)
return if faraday.builder.locked?
faraday.builder.insert_before(Middleware::ParseJson, middleware, *args, &block)
end
|
ruby
|
def use(middleware, *args, &block)
return if faraday.builder.locked?
faraday.builder.insert_before(Middleware::ParseJson, middleware, *args, &block)
end
|
[
"def",
"use",
"(",
"middleware",
",",
"*",
"args",
",",
"&",
"block",
")",
"return",
"if",
"faraday",
".",
"builder",
".",
"locked?",
"faraday",
".",
"builder",
".",
"insert_before",
"(",
"Middleware",
"::",
"ParseJson",
",",
"middleware",
",",
"args",
",",
"block",
")",
"end"
] |
insert middleware before ParseJson - middleware executed in reverse order -
inserted middleware will run after json parsed
|
[
"insert",
"middleware",
"before",
"ParseJson",
"-",
"middleware",
"executed",
"in",
"reverse",
"order",
"-",
"inserted",
"middleware",
"will",
"run",
"after",
"json",
"parsed"
] |
e4b763f5579c4fae4b03dcc935b20627f5c14eaa
|
https://github.com/JsonApiClient/json_api_client/blob/e4b763f5579c4fae4b03dcc935b20627f5c14eaa/lib/json_api_client/connection.rb#L24-L27
|
12,978
|
JsonApiClient/json_api_client
|
lib/json_api_client/resource.rb
|
JsonApiClient.Resource.destroy
|
def destroy
self.last_result_set = self.class.requestor.destroy(self)
if last_result_set.has_errors?
fill_errors
false
else
mark_as_destroyed!
self.relationships.last_result_set = nil
_clear_cached_relationships
_clear_belongs_to_params
true
end
end
|
ruby
|
def destroy
self.last_result_set = self.class.requestor.destroy(self)
if last_result_set.has_errors?
fill_errors
false
else
mark_as_destroyed!
self.relationships.last_result_set = nil
_clear_cached_relationships
_clear_belongs_to_params
true
end
end
|
[
"def",
"destroy",
"self",
".",
"last_result_set",
"=",
"self",
".",
"class",
".",
"requestor",
".",
"destroy",
"(",
"self",
")",
"if",
"last_result_set",
".",
"has_errors?",
"fill_errors",
"false",
"else",
"mark_as_destroyed!",
"self",
".",
"relationships",
".",
"last_result_set",
"=",
"nil",
"_clear_cached_relationships",
"_clear_belongs_to_params",
"true",
"end",
"end"
] |
Try to destroy this resource
@return [Boolean] Whether or not the destroy succeeded
|
[
"Try",
"to",
"destroy",
"this",
"resource"
] |
e4b763f5579c4fae4b03dcc935b20627f5c14eaa
|
https://github.com/JsonApiClient/json_api_client/blob/e4b763f5579c4fae4b03dcc935b20627f5c14eaa/lib/json_api_client/resource.rb#L471-L483
|
12,979
|
gjtorikian/html-proofer
|
lib/html-proofer/url_validator.rb
|
HTMLProofer.UrlValidator.new_url_query_values?
|
def new_url_query_values?(uri, paths_with_queries)
queries = uri.query_values.keys.join('-')
domain_path = extract_domain_path(uri)
if paths_with_queries[domain_path].nil?
paths_with_queries[domain_path] = [queries]
true
elsif !paths_with_queries[domain_path].include?(queries)
paths_with_queries[domain_path] << queries
true
else
false
end
end
|
ruby
|
def new_url_query_values?(uri, paths_with_queries)
queries = uri.query_values.keys.join('-')
domain_path = extract_domain_path(uri)
if paths_with_queries[domain_path].nil?
paths_with_queries[domain_path] = [queries]
true
elsif !paths_with_queries[domain_path].include?(queries)
paths_with_queries[domain_path] << queries
true
else
false
end
end
|
[
"def",
"new_url_query_values?",
"(",
"uri",
",",
"paths_with_queries",
")",
"queries",
"=",
"uri",
".",
"query_values",
".",
"keys",
".",
"join",
"(",
"'-'",
")",
"domain_path",
"=",
"extract_domain_path",
"(",
"uri",
")",
"if",
"paths_with_queries",
"[",
"domain_path",
"]",
".",
"nil?",
"paths_with_queries",
"[",
"domain_path",
"]",
"=",
"[",
"queries",
"]",
"true",
"elsif",
"!",
"paths_with_queries",
"[",
"domain_path",
"]",
".",
"include?",
"(",
"queries",
")",
"paths_with_queries",
"[",
"domain_path",
"]",
"<<",
"queries",
"true",
"else",
"false",
"end",
"end"
] |
remember queries we've seen, ignore future ones
|
[
"remember",
"queries",
"we",
"ve",
"seen",
"ignore",
"future",
"ones"
] |
d00955d3b125b9a1649d056bb347ec30e935d847
|
https://github.com/gjtorikian/html-proofer/blob/d00955d3b125b9a1649d056bb347ec30e935d847/lib/html-proofer/url_validator.rb#L53-L65
|
12,980
|
gjtorikian/html-proofer
|
lib/html-proofer/url_validator.rb
|
HTMLProofer.UrlValidator.external_link_checker
|
def external_link_checker(external_urls)
external_urls = Hash[external_urls.sort]
count = external_urls.length
check_text = pluralize(count, 'external link', 'external links')
@logger.log :info, "Checking #{check_text}..."
# Route log from Typhoeus/Ethon to our own logger
Ethon.logger = @logger
establish_queue(external_urls)
@hydra.run
end
|
ruby
|
def external_link_checker(external_urls)
external_urls = Hash[external_urls.sort]
count = external_urls.length
check_text = pluralize(count, 'external link', 'external links')
@logger.log :info, "Checking #{check_text}..."
# Route log from Typhoeus/Ethon to our own logger
Ethon.logger = @logger
establish_queue(external_urls)
@hydra.run
end
|
[
"def",
"external_link_checker",
"(",
"external_urls",
")",
"external_urls",
"=",
"Hash",
"[",
"external_urls",
".",
"sort",
"]",
"count",
"=",
"external_urls",
".",
"length",
"check_text",
"=",
"pluralize",
"(",
"count",
",",
"'external link'",
",",
"'external links'",
")",
"@logger",
".",
"log",
":info",
",",
"\"Checking #{check_text}...\"",
"# Route log from Typhoeus/Ethon to our own logger",
"Ethon",
".",
"logger",
"=",
"@logger",
"establish_queue",
"(",
"external_urls",
")",
"@hydra",
".",
"run",
"end"
] |
Proofer runs faster if we pull out all the external URLs and run the checks
at the end. Otherwise, we're halting the consuming process for every file during
`process_files`.
In addition, sorting the list lets libcurl keep connections to the same hosts alive.
Finally, we'll first make a HEAD request, rather than GETing all the contents.
If the HEAD fails, we'll fall back to GET, as some servers are not configured
for HEAD. If we've decided to check for hashes, we must do a GET--HEAD is
not available as an option.
|
[
"Proofer",
"runs",
"faster",
"if",
"we",
"pull",
"out",
"all",
"the",
"external",
"URLs",
"and",
"run",
"the",
"checks",
"at",
"the",
"end",
".",
"Otherwise",
"we",
"re",
"halting",
"the",
"consuming",
"process",
"for",
"every",
"file",
"during",
"process_files",
"."
] |
d00955d3b125b9a1649d056bb347ec30e935d847
|
https://github.com/gjtorikian/html-proofer/blob/d00955d3b125b9a1649d056bb347ec30e935d847/lib/html-proofer/url_validator.rb#L90-L103
|
12,981
|
gjtorikian/html-proofer
|
lib/html-proofer/url_validator.rb
|
HTMLProofer.UrlValidator.check_hash_in_2xx_response
|
def check_hash_in_2xx_response(href, effective_url, response, filenames)
return false if @options[:only_4xx]
return false unless @options[:check_external_hash]
return false unless (hash = hash?(href))
body_doc = create_nokogiri(response.body)
unencoded_hash = Addressable::URI.unescape(hash)
xpath = %(//*[@name="#{hash}"]|/*[@name="#{unencoded_hash}"]|//*[@id="#{hash}"]|//*[@id="#{unencoded_hash}"])
# user-content is a special addition by GitHub.
if URI.parse(href).host =~ /github\.com/i
xpath << %(|//*[@name="user-content-#{hash}"]|//*[@id="user-content-#{hash}"])
# when linking to a file on GitHub, like #L12-L34, only the first "L" portion
# will be identified as a linkable portion
if hash =~ /\A(L\d)+/
xpath << %(|//td[@id="#{Regexp.last_match[1]}"])
end
end
return unless body_doc.xpath(xpath).empty?
msg = "External link #{href} failed: #{effective_url} exists, but the hash '#{hash}' does not"
add_external_issue(filenames, msg, response.code)
@cache.add(href, filenames, response.code, msg)
true
end
|
ruby
|
def check_hash_in_2xx_response(href, effective_url, response, filenames)
return false if @options[:only_4xx]
return false unless @options[:check_external_hash]
return false unless (hash = hash?(href))
body_doc = create_nokogiri(response.body)
unencoded_hash = Addressable::URI.unescape(hash)
xpath = %(//*[@name="#{hash}"]|/*[@name="#{unencoded_hash}"]|//*[@id="#{hash}"]|//*[@id="#{unencoded_hash}"])
# user-content is a special addition by GitHub.
if URI.parse(href).host =~ /github\.com/i
xpath << %(|//*[@name="user-content-#{hash}"]|//*[@id="user-content-#{hash}"])
# when linking to a file on GitHub, like #L12-L34, only the first "L" portion
# will be identified as a linkable portion
if hash =~ /\A(L\d)+/
xpath << %(|//td[@id="#{Regexp.last_match[1]}"])
end
end
return unless body_doc.xpath(xpath).empty?
msg = "External link #{href} failed: #{effective_url} exists, but the hash '#{hash}' does not"
add_external_issue(filenames, msg, response.code)
@cache.add(href, filenames, response.code, msg)
true
end
|
[
"def",
"check_hash_in_2xx_response",
"(",
"href",
",",
"effective_url",
",",
"response",
",",
"filenames",
")",
"return",
"false",
"if",
"@options",
"[",
":only_4xx",
"]",
"return",
"false",
"unless",
"@options",
"[",
":check_external_hash",
"]",
"return",
"false",
"unless",
"(",
"hash",
"=",
"hash?",
"(",
"href",
")",
")",
"body_doc",
"=",
"create_nokogiri",
"(",
"response",
".",
"body",
")",
"unencoded_hash",
"=",
"Addressable",
"::",
"URI",
".",
"unescape",
"(",
"hash",
")",
"xpath",
"=",
"%(//*[@name=\"#{hash}\"]|/*[@name=\"#{unencoded_hash}\"]|//*[@id=\"#{hash}\"]|//*[@id=\"#{unencoded_hash}\"])",
"# user-content is a special addition by GitHub.",
"if",
"URI",
".",
"parse",
"(",
"href",
")",
".",
"host",
"=~",
"/",
"\\.",
"/i",
"xpath",
"<<",
"%(|//*[@name=\"user-content-#{hash}\"]|//*[@id=\"user-content-#{hash}\"])",
"# when linking to a file on GitHub, like #L12-L34, only the first \"L\" portion",
"# will be identified as a linkable portion",
"if",
"hash",
"=~",
"/",
"\\A",
"\\d",
"/",
"xpath",
"<<",
"%(|//td[@id=\"#{Regexp.last_match[1]}\"])",
"end",
"end",
"return",
"unless",
"body_doc",
".",
"xpath",
"(",
"xpath",
")",
".",
"empty?",
"msg",
"=",
"\"External link #{href} failed: #{effective_url} exists, but the hash '#{hash}' does not\"",
"add_external_issue",
"(",
"filenames",
",",
"msg",
",",
"response",
".",
"code",
")",
"@cache",
".",
"add",
"(",
"href",
",",
"filenames",
",",
"response",
".",
"code",
",",
"msg",
")",
"true",
"end"
] |
Even though the response was a success, we may have been asked to check
if the hash on the URL exists on the page
|
[
"Even",
"though",
"the",
"response",
"was",
"a",
"success",
"we",
"may",
"have",
"been",
"asked",
"to",
"check",
"if",
"the",
"hash",
"on",
"the",
"URL",
"exists",
"on",
"the",
"page"
] |
d00955d3b125b9a1649d056bb347ec30e935d847
|
https://github.com/gjtorikian/html-proofer/blob/d00955d3b125b9a1649d056bb347ec30e935d847/lib/html-proofer/url_validator.rb#L174-L199
|
12,982
|
gjtorikian/html-proofer
|
lib/html-proofer/runner.rb
|
HTMLProofer.Runner.check_files
|
def check_files
@external_urls = {}
process_files.each do |item|
@external_urls.merge!(item[:external_urls])
@failures.concat(item[:failures])
end
# TODO: lazy. if we're checking only external links,
# we'll just trash all the failed tests. really, we should
# just not run those other checks at all.
if @options[:external_only]
@failures = []
validate_urls
elsif !@options[:disable_external]
validate_urls
end
end
|
ruby
|
def check_files
@external_urls = {}
process_files.each do |item|
@external_urls.merge!(item[:external_urls])
@failures.concat(item[:failures])
end
# TODO: lazy. if we're checking only external links,
# we'll just trash all the failed tests. really, we should
# just not run those other checks at all.
if @options[:external_only]
@failures = []
validate_urls
elsif !@options[:disable_external]
validate_urls
end
end
|
[
"def",
"check_files",
"@external_urls",
"=",
"{",
"}",
"process_files",
".",
"each",
"do",
"|",
"item",
"|",
"@external_urls",
".",
"merge!",
"(",
"item",
"[",
":external_urls",
"]",
")",
"@failures",
".",
"concat",
"(",
"item",
"[",
":failures",
"]",
")",
"end",
"# TODO: lazy. if we're checking only external links,",
"# we'll just trash all the failed tests. really, we should",
"# just not run those other checks at all.",
"if",
"@options",
"[",
":external_only",
"]",
"@failures",
"=",
"[",
"]",
"validate_urls",
"elsif",
"!",
"@options",
"[",
":disable_external",
"]",
"validate_urls",
"end",
"end"
] |
Collects any external URLs found in a directory of files. Also collectes
every failed test from process_files.
Sends the external URLs to Typhoeus for batch processing.
|
[
"Collects",
"any",
"external",
"URLs",
"found",
"in",
"a",
"directory",
"of",
"files",
".",
"Also",
"collectes",
"every",
"failed",
"test",
"from",
"process_files",
".",
"Sends",
"the",
"external",
"URLs",
"to",
"Typhoeus",
"for",
"batch",
"processing",
"."
] |
d00955d3b125b9a1649d056bb347ec30e935d847
|
https://github.com/gjtorikian/html-proofer/blob/d00955d3b125b9a1649d056bb347ec30e935d847/lib/html-proofer/runner.rb#L65-L82
|
12,983
|
gjtorikian/html-proofer
|
lib/html-proofer/runner.rb
|
HTMLProofer.Runner.process_files
|
def process_files
if @options[:parallel].empty?
files.map { |path| check_path(path) }
else
Parallel.map(files, @options[:parallel]) { |path| check_path(path) }
end
end
|
ruby
|
def process_files
if @options[:parallel].empty?
files.map { |path| check_path(path) }
else
Parallel.map(files, @options[:parallel]) { |path| check_path(path) }
end
end
|
[
"def",
"process_files",
"if",
"@options",
"[",
":parallel",
"]",
".",
"empty?",
"files",
".",
"map",
"{",
"|",
"path",
"|",
"check_path",
"(",
"path",
")",
"}",
"else",
"Parallel",
".",
"map",
"(",
"files",
",",
"@options",
"[",
":parallel",
"]",
")",
"{",
"|",
"path",
"|",
"check_path",
"(",
"path",
")",
"}",
"end",
"end"
] |
Walks over each implemented check and runs them on the files, in parallel.
|
[
"Walks",
"over",
"each",
"implemented",
"check",
"and",
"runs",
"them",
"on",
"the",
"files",
"in",
"parallel",
"."
] |
d00955d3b125b9a1649d056bb347ec30e935d847
|
https://github.com/gjtorikian/html-proofer/blob/d00955d3b125b9a1649d056bb347ec30e935d847/lib/html-proofer/runner.rb#L85-L91
|
12,984
|
Fullscreen/yt
|
lib/yt/request.rb
|
Yt.Request.set_request_body!
|
def set_request_body!(request)
case @request_format
when :json then request.body = (camelize_keys! @body).to_json
when :form then request.set_form_data @body
when :file then request.body_stream = @body
end if @body
end
|
ruby
|
def set_request_body!(request)
case @request_format
when :json then request.body = (camelize_keys! @body).to_json
when :form then request.set_form_data @body
when :file then request.body_stream = @body
end if @body
end
|
[
"def",
"set_request_body!",
"(",
"request",
")",
"case",
"@request_format",
"when",
":json",
"then",
"request",
".",
"body",
"=",
"(",
"camelize_keys!",
"@body",
")",
".",
"to_json",
"when",
":form",
"then",
"request",
".",
"set_form_data",
"@body",
"when",
":file",
"then",
"request",
".",
"body_stream",
"=",
"@body",
"end",
"if",
"@body",
"end"
] |
Adds the request body to the request in the appropriate format.
if the request body is a JSON Object, transform its keys into camel-case,
since this is the common format for JSON APIs.
|
[
"Adds",
"the",
"request",
"body",
"to",
"the",
"request",
"in",
"the",
"appropriate",
"format",
".",
"if",
"the",
"request",
"body",
"is",
"a",
"JSON",
"Object",
"transform",
"its",
"keys",
"into",
"camel",
"-",
"case",
"since",
"this",
"is",
"the",
"common",
"format",
"for",
"JSON",
"APIs",
"."
] |
bf5c33b977cb162bb7735ad5b80d1abdb5a38215
|
https://github.com/Fullscreen/yt/blob/bf5c33b977cb162bb7735ad5b80d1abdb5a38215/lib/yt/request.rb#L120-L126
|
12,985
|
Fullscreen/yt
|
lib/yt/request.rb
|
Yt.Request.parse_response!
|
def parse_response!
response.body = case @response_format
when :xml then Hash.from_xml response.body
when :json then JSON response.body
end if response.body
end
|
ruby
|
def parse_response!
response.body = case @response_format
when :xml then Hash.from_xml response.body
when :json then JSON response.body
end if response.body
end
|
[
"def",
"parse_response!",
"response",
".",
"body",
"=",
"case",
"@response_format",
"when",
":xml",
"then",
"Hash",
".",
"from_xml",
"response",
".",
"body",
"when",
":json",
"then",
"JSON",
"response",
".",
"body",
"end",
"if",
"response",
".",
"body",
"end"
] |
Replaces the body of the response with the parsed version of the body,
according to the format specified in the Request.
|
[
"Replaces",
"the",
"body",
"of",
"the",
"response",
"with",
"the",
"parsed",
"version",
"of",
"the",
"body",
"according",
"to",
"the",
"format",
"specified",
"in",
"the",
"Request",
"."
] |
bf5c33b977cb162bb7735ad5b80d1abdb5a38215
|
https://github.com/Fullscreen/yt/blob/bf5c33b977cb162bb7735ad5b80d1abdb5a38215/lib/yt/request.rb#L183-L188
|
12,986
|
Fullscreen/yt
|
lib/yt/request.rb
|
Yt.Request.server_errors
|
def server_errors
[
OpenSSL::SSL::SSLError,
Errno::ETIMEDOUT,
Errno::EHOSTUNREACH,
Errno::ENETUNREACH,
Errno::ECONNRESET,
Net::OpenTimeout,
SocketError,
Net::HTTPServerError
] + extra_server_errors
end
|
ruby
|
def server_errors
[
OpenSSL::SSL::SSLError,
Errno::ETIMEDOUT,
Errno::EHOSTUNREACH,
Errno::ENETUNREACH,
Errno::ECONNRESET,
Net::OpenTimeout,
SocketError,
Net::HTTPServerError
] + extra_server_errors
end
|
[
"def",
"server_errors",
"[",
"OpenSSL",
"::",
"SSL",
"::",
"SSLError",
",",
"Errno",
"::",
"ETIMEDOUT",
",",
"Errno",
"::",
"EHOSTUNREACH",
",",
"Errno",
"::",
"ENETUNREACH",
",",
"Errno",
"::",
"ECONNRESET",
",",
"Net",
"::",
"OpenTimeout",
",",
"SocketError",
",",
"Net",
"::",
"HTTPServerError",
"]",
"+",
"extra_server_errors",
"end"
] |
Returns the list of server errors worth retrying the request once.
|
[
"Returns",
"the",
"list",
"of",
"server",
"errors",
"worth",
"retrying",
"the",
"request",
"once",
"."
] |
bf5c33b977cb162bb7735ad5b80d1abdb5a38215
|
https://github.com/Fullscreen/yt/blob/bf5c33b977cb162bb7735ad5b80d1abdb5a38215/lib/yt/request.rb#L205-L216
|
12,987
|
deivid-rodriguez/pry-byebug
|
lib/byebug/processors/pry_processor.rb
|
Byebug.PryProcessor.perform
|
def perform(action, options = {})
return unless %i[
backtrace
down
finish
frame
next
step
up
].include?(action)
send("perform_#{action}", options)
end
|
ruby
|
def perform(action, options = {})
return unless %i[
backtrace
down
finish
frame
next
step
up
].include?(action)
send("perform_#{action}", options)
end
|
[
"def",
"perform",
"(",
"action",
",",
"options",
"=",
"{",
"}",
")",
"return",
"unless",
"%i[",
"backtrace",
"down",
"finish",
"frame",
"next",
"step",
"up",
"]",
".",
"include?",
"(",
"action",
")",
"send",
"(",
"\"perform_#{action}\"",
",",
"options",
")",
"end"
] |
Set up a number of navigational commands to be performed by Byebug.
|
[
"Set",
"up",
"a",
"number",
"of",
"navigational",
"commands",
"to",
"be",
"performed",
"by",
"Byebug",
"."
] |
d2923e7a1629c2b860a4ea66a71dec09a4a15763
|
https://github.com/deivid-rodriguez/pry-byebug/blob/d2923e7a1629c2b860a4ea66a71dec09a4a15763/lib/byebug/processors/pry_processor.rb#L45-L57
|
12,988
|
deivid-rodriguez/pry-byebug
|
lib/byebug/processors/pry_processor.rb
|
Byebug.PryProcessor.resume_pry
|
def resume_pry
new_binding = frame._binding
run do
if defined?(@pry) && @pry
@pry.repl(new_binding)
else
@pry = Pry.start_without_pry_byebug(new_binding)
end
end
end
|
ruby
|
def resume_pry
new_binding = frame._binding
run do
if defined?(@pry) && @pry
@pry.repl(new_binding)
else
@pry = Pry.start_without_pry_byebug(new_binding)
end
end
end
|
[
"def",
"resume_pry",
"new_binding",
"=",
"frame",
".",
"_binding",
"run",
"do",
"if",
"defined?",
"(",
"@pry",
")",
"&&",
"@pry",
"@pry",
".",
"repl",
"(",
"new_binding",
")",
"else",
"@pry",
"=",
"Pry",
".",
"start_without_pry_byebug",
"(",
"new_binding",
")",
"end",
"end",
"end"
] |
Resume an existing Pry REPL at the paused point.
|
[
"Resume",
"an",
"existing",
"Pry",
"REPL",
"at",
"the",
"paused",
"point",
"."
] |
d2923e7a1629c2b860a4ea66a71dec09a4a15763
|
https://github.com/deivid-rodriguez/pry-byebug/blob/d2923e7a1629c2b860a4ea66a71dec09a4a15763/lib/byebug/processors/pry_processor.rb#L110-L120
|
12,989
|
haml/haml
|
lib/haml/engine.rb
|
Haml.Engine.render
|
def render(scope = Object.new, locals = {}, &block)
parent = scope.instance_variable_defined?(:@haml_buffer) ? scope.instance_variable_get(:@haml_buffer) : nil
buffer = Haml::Buffer.new(parent, @options.for_buffer)
if scope.is_a?(Binding)
scope_object = eval("self", scope)
scope = scope_object.instance_eval{binding} if block_given?
else
scope_object = scope
scope = scope_object.instance_eval{binding}
end
set_locals(locals.merge(:_hamlout => buffer, :_erbout => buffer.buffer), scope, scope_object)
scope_object.extend(Haml::Helpers)
scope_object.instance_variable_set(:@haml_buffer, buffer)
begin
eval(@temple_engine.precompiled_with_return_value, scope, @options.filename, @options.line)
rescue ::SyntaxError => e
raise SyntaxError, e.message
end
ensure
# Get rid of the current buffer
scope_object.instance_variable_set(:@haml_buffer, buffer.upper) if buffer
end
|
ruby
|
def render(scope = Object.new, locals = {}, &block)
parent = scope.instance_variable_defined?(:@haml_buffer) ? scope.instance_variable_get(:@haml_buffer) : nil
buffer = Haml::Buffer.new(parent, @options.for_buffer)
if scope.is_a?(Binding)
scope_object = eval("self", scope)
scope = scope_object.instance_eval{binding} if block_given?
else
scope_object = scope
scope = scope_object.instance_eval{binding}
end
set_locals(locals.merge(:_hamlout => buffer, :_erbout => buffer.buffer), scope, scope_object)
scope_object.extend(Haml::Helpers)
scope_object.instance_variable_set(:@haml_buffer, buffer)
begin
eval(@temple_engine.precompiled_with_return_value, scope, @options.filename, @options.line)
rescue ::SyntaxError => e
raise SyntaxError, e.message
end
ensure
# Get rid of the current buffer
scope_object.instance_variable_set(:@haml_buffer, buffer.upper) if buffer
end
|
[
"def",
"render",
"(",
"scope",
"=",
"Object",
".",
"new",
",",
"locals",
"=",
"{",
"}",
",",
"&",
"block",
")",
"parent",
"=",
"scope",
".",
"instance_variable_defined?",
"(",
":@haml_buffer",
")",
"?",
"scope",
".",
"instance_variable_get",
"(",
":@haml_buffer",
")",
":",
"nil",
"buffer",
"=",
"Haml",
"::",
"Buffer",
".",
"new",
"(",
"parent",
",",
"@options",
".",
"for_buffer",
")",
"if",
"scope",
".",
"is_a?",
"(",
"Binding",
")",
"scope_object",
"=",
"eval",
"(",
"\"self\"",
",",
"scope",
")",
"scope",
"=",
"scope_object",
".",
"instance_eval",
"{",
"binding",
"}",
"if",
"block_given?",
"else",
"scope_object",
"=",
"scope",
"scope",
"=",
"scope_object",
".",
"instance_eval",
"{",
"binding",
"}",
"end",
"set_locals",
"(",
"locals",
".",
"merge",
"(",
":_hamlout",
"=>",
"buffer",
",",
":_erbout",
"=>",
"buffer",
".",
"buffer",
")",
",",
"scope",
",",
"scope_object",
")",
"scope_object",
".",
"extend",
"(",
"Haml",
"::",
"Helpers",
")",
"scope_object",
".",
"instance_variable_set",
"(",
":@haml_buffer",
",",
"buffer",
")",
"begin",
"eval",
"(",
"@temple_engine",
".",
"precompiled_with_return_value",
",",
"scope",
",",
"@options",
".",
"filename",
",",
"@options",
".",
"line",
")",
"rescue",
"::",
"SyntaxError",
"=>",
"e",
"raise",
"SyntaxError",
",",
"e",
".",
"message",
"end",
"ensure",
"# Get rid of the current buffer",
"scope_object",
".",
"instance_variable_set",
"(",
":@haml_buffer",
",",
"buffer",
".",
"upper",
")",
"if",
"buffer",
"end"
] |
Processes the template and returns the result as a string.
`scope` is the context in which the template is evaluated.
If it's a `Binding`, Haml uses it as the second argument to `Kernel#eval`;
otherwise, Haml just uses its `#instance_eval` context.
Note that Haml modifies the evaluation context
(either the scope object or the `self` object of the scope binding).
It extends {Haml::Helpers}, and various instance variables are set
(all prefixed with `haml_`).
For example:
s = "foobar"
Haml::Engine.new("%p= upcase").render(s) #=> "<p>FOOBAR</p>"
# s now extends Haml::Helpers
s.respond_to?(:html_attrs) #=> true
`locals` is a hash of local variables to make available to the template.
For example:
Haml::Engine.new("%p= foo").render(Object.new, :foo => "Hello, world!") #=> "<p>Hello, world!</p>"
If a block is passed to render,
that block is run when `yield` is called
within the template.
Due to some Ruby quirks,
if `scope` is a `Binding` object and a block is given,
the evaluation context may not be quite what the user expects.
In particular, it's equivalent to passing `eval("self", scope)` as `scope`.
This won't have an effect in most cases,
but if you're relying on local variables defined in the context of `scope`,
they won't work.
@param scope [Binding, Object] The context in which the template is evaluated
@param locals [{Symbol => Object}] Local variables that will be made available
to the template
@param block [#to_proc] A block that can be yielded to within the template
@return [String] The rendered template
|
[
"Processes",
"the",
"template",
"and",
"returns",
"the",
"result",
"as",
"a",
"string",
"."
] |
9aa0fbe4a91b999978927be569d2ad0cd39076f1
|
https://github.com/haml/haml/blob/9aa0fbe4a91b999978927be569d2ad0cd39076f1/lib/haml/engine.rb#L112-L136
|
12,990
|
haml/haml
|
lib/haml/engine.rb
|
Haml.Engine.render_proc
|
def render_proc(scope = Object.new, *local_names)
if scope.is_a?(Binding)
scope_object = eval("self", scope)
else
scope_object = scope
scope = scope_object.instance_eval{binding}
end
begin
str = @temple_engine.precompiled_with_ambles(local_names)
eval(
"Proc.new { |*_haml_locals| _haml_locals = _haml_locals[0] || {}; #{str}}\n",
scope,
@options.filename,
@options.line
)
rescue ::SyntaxError => e
raise SyntaxError, e.message
end
end
|
ruby
|
def render_proc(scope = Object.new, *local_names)
if scope.is_a?(Binding)
scope_object = eval("self", scope)
else
scope_object = scope
scope = scope_object.instance_eval{binding}
end
begin
str = @temple_engine.precompiled_with_ambles(local_names)
eval(
"Proc.new { |*_haml_locals| _haml_locals = _haml_locals[0] || {}; #{str}}\n",
scope,
@options.filename,
@options.line
)
rescue ::SyntaxError => e
raise SyntaxError, e.message
end
end
|
[
"def",
"render_proc",
"(",
"scope",
"=",
"Object",
".",
"new",
",",
"*",
"local_names",
")",
"if",
"scope",
".",
"is_a?",
"(",
"Binding",
")",
"scope_object",
"=",
"eval",
"(",
"\"self\"",
",",
"scope",
")",
"else",
"scope_object",
"=",
"scope",
"scope",
"=",
"scope_object",
".",
"instance_eval",
"{",
"binding",
"}",
"end",
"begin",
"str",
"=",
"@temple_engine",
".",
"precompiled_with_ambles",
"(",
"local_names",
")",
"eval",
"(",
"\"Proc.new { |*_haml_locals| _haml_locals = _haml_locals[0] || {}; #{str}}\\n\"",
",",
"scope",
",",
"@options",
".",
"filename",
",",
"@options",
".",
"line",
")",
"rescue",
"::",
"SyntaxError",
"=>",
"e",
"raise",
"SyntaxError",
",",
"e",
".",
"message",
"end",
"end"
] |
Returns a proc that, when called,
renders the template and returns the result as a string.
`scope` works the same as it does for render.
The first argument of the returned proc is a hash of local variable names to values.
However, due to an unfortunate Ruby quirk,
the local variables which can be assigned must be pre-declared.
This is done with the `local_names` argument.
For example:
# This works
Haml::Engine.new("%p= foo").render_proc(Object.new, :foo).call :foo => "Hello!"
#=> "<p>Hello!</p>"
# This doesn't
Haml::Engine.new("%p= foo").render_proc.call :foo => "Hello!"
#=> NameError: undefined local variable or method `foo'
The proc doesn't take a block; any yields in the template will fail.
@param scope [Binding, Object] The context in which the template is evaluated
@param local_names [Array<Symbol>] The names of the locals that can be passed to the proc
@return [Proc] The proc that will run the template
|
[
"Returns",
"a",
"proc",
"that",
"when",
"called",
"renders",
"the",
"template",
"and",
"returns",
"the",
"result",
"as",
"a",
"string",
"."
] |
9aa0fbe4a91b999978927be569d2ad0cd39076f1
|
https://github.com/haml/haml/blob/9aa0fbe4a91b999978927be569d2ad0cd39076f1/lib/haml/engine.rb#L163-L182
|
12,991
|
haml/haml
|
lib/haml/engine.rb
|
Haml.Engine.def_method
|
def def_method(object, name, *local_names)
method = object.is_a?(Module) ? :module_eval : :instance_eval
object.send(method, "def #{name}(_haml_locals = {}); #{@temple_engine.precompiled_with_ambles(local_names)}; end",
@options.filename, @options.line)
end
|
ruby
|
def def_method(object, name, *local_names)
method = object.is_a?(Module) ? :module_eval : :instance_eval
object.send(method, "def #{name}(_haml_locals = {}); #{@temple_engine.precompiled_with_ambles(local_names)}; end",
@options.filename, @options.line)
end
|
[
"def",
"def_method",
"(",
"object",
",",
"name",
",",
"*",
"local_names",
")",
"method",
"=",
"object",
".",
"is_a?",
"(",
"Module",
")",
"?",
":module_eval",
":",
":instance_eval",
"object",
".",
"send",
"(",
"method",
",",
"\"def #{name}(_haml_locals = {}); #{@temple_engine.precompiled_with_ambles(local_names)}; end\"",
",",
"@options",
".",
"filename",
",",
"@options",
".",
"line",
")",
"end"
] |
Defines a method on `object` with the given name
that renders the template and returns the result as a string.
If `object` is a class or module,
the method will instead be defined as an instance method.
For example:
t = Time.now
Haml::Engine.new("%p\n Today's date is\n .date= self.to_s").def_method(t, :render)
t.render #=> "<p>\n Today's date is\n <div class='date'>Fri Nov 23 18:28:29 -0800 2007</div>\n</p>\n"
Haml::Engine.new(".upcased= upcase").def_method(String, :upcased_div)
"foobar".upcased_div #=> "<div class='upcased'>FOOBAR</div>\n"
The first argument of the defined method is a hash of local variable names to values.
However, due to an unfortunate Ruby quirk,
the local variables which can be assigned must be pre-declared.
This is done with the `local_names` argument.
For example:
# This works
obj = Object.new
Haml::Engine.new("%p= foo").def_method(obj, :render, :foo)
obj.render(:foo => "Hello!") #=> "<p>Hello!</p>"
# This doesn't
obj = Object.new
Haml::Engine.new("%p= foo").def_method(obj, :render)
obj.render(:foo => "Hello!") #=> NameError: undefined local variable or method `foo'
Note that Haml modifies the evaluation context
(either the scope object or the `self` object of the scope binding).
It extends {Haml::Helpers}, and various instance variables are set
(all prefixed with `haml_`).
@param object [Object, Module] The object on which to define the method
@param name [String, Symbol] The name of the method to define
@param local_names [Array<Symbol>] The names of the locals that can be passed to the proc
|
[
"Defines",
"a",
"method",
"on",
"object",
"with",
"the",
"given",
"name",
"that",
"renders",
"the",
"template",
"and",
"returns",
"the",
"result",
"as",
"a",
"string",
"."
] |
9aa0fbe4a91b999978927be569d2ad0cd39076f1
|
https://github.com/haml/haml/blob/9aa0fbe4a91b999978927be569d2ad0cd39076f1/lib/haml/engine.rb#L222-L227
|
12,992
|
haml/haml
|
lib/haml/attribute_compiler.rb
|
Haml.AttributeCompiler.compile_attribute_values
|
def compile_attribute_values(values)
if values.map(&:key).uniq.size == 1
compile_attribute(values.first.key, values)
else
runtime_build(values)
end
end
|
ruby
|
def compile_attribute_values(values)
if values.map(&:key).uniq.size == 1
compile_attribute(values.first.key, values)
else
runtime_build(values)
end
end
|
[
"def",
"compile_attribute_values",
"(",
"values",
")",
"if",
"values",
".",
"map",
"(",
":key",
")",
".",
"uniq",
".",
"size",
"==",
"1",
"compile_attribute",
"(",
"values",
".",
"first",
".",
"key",
",",
"values",
")",
"else",
"runtime_build",
"(",
"values",
")",
"end",
"end"
] |
Compiles attribute values with the similar key to Temple expression.
@param values [Array<AttributeValue>] whose `key`s are partially or fully the same from left.
@return [Array] Temple expression
|
[
"Compiles",
"attribute",
"values",
"with",
"the",
"similar",
"key",
"to",
"Temple",
"expression",
"."
] |
9aa0fbe4a91b999978927be569d2ad0cd39076f1
|
https://github.com/haml/haml/blob/9aa0fbe4a91b999978927be569d2ad0cd39076f1/lib/haml/attribute_compiler.rb#L104-L110
|
12,993
|
haml/haml
|
lib/haml/attribute_compiler.rb
|
Haml.AttributeCompiler.static_build
|
def static_build(values)
hash_content = values.group_by(&:key).map do |key, values_for_key|
"#{frozen_string(key)} => #{merged_value(key, values_for_key)}"
end.join(', ')
arguments = [@is_html, @attr_wrapper, @escape_attrs, @hyphenate_data_attrs]
code = "::Haml::AttributeBuilder.build_attributes"\
"(#{arguments.map { |a| Haml::Util.inspect_obj(a) }.join(', ')}, { #{hash_content} })"
[:static, eval(code).to_s]
end
|
ruby
|
def static_build(values)
hash_content = values.group_by(&:key).map do |key, values_for_key|
"#{frozen_string(key)} => #{merged_value(key, values_for_key)}"
end.join(', ')
arguments = [@is_html, @attr_wrapper, @escape_attrs, @hyphenate_data_attrs]
code = "::Haml::AttributeBuilder.build_attributes"\
"(#{arguments.map { |a| Haml::Util.inspect_obj(a) }.join(', ')}, { #{hash_content} })"
[:static, eval(code).to_s]
end
|
[
"def",
"static_build",
"(",
"values",
")",
"hash_content",
"=",
"values",
".",
"group_by",
"(",
":key",
")",
".",
"map",
"do",
"|",
"key",
",",
"values_for_key",
"|",
"\"#{frozen_string(key)} => #{merged_value(key, values_for_key)}\"",
"end",
".",
"join",
"(",
"', '",
")",
"arguments",
"=",
"[",
"@is_html",
",",
"@attr_wrapper",
",",
"@escape_attrs",
",",
"@hyphenate_data_attrs",
"]",
"code",
"=",
"\"::Haml::AttributeBuilder.build_attributes\"",
"\"(#{arguments.map { |a| Haml::Util.inspect_obj(a) }.join(', ')}, { #{hash_content} })\"",
"[",
":static",
",",
"eval",
"(",
"code",
")",
".",
"to_s",
"]",
"end"
] |
Renders attribute values statically.
@param values [Array<AttributeValue>]
@return [Array] Temple expression
|
[
"Renders",
"attribute",
"values",
"statically",
"."
] |
9aa0fbe4a91b999978927be569d2ad0cd39076f1
|
https://github.com/haml/haml/blob/9aa0fbe4a91b999978927be569d2ad0cd39076f1/lib/haml/attribute_compiler.rb#L125-L134
|
12,994
|
haml/haml
|
lib/haml/attribute_compiler.rb
|
Haml.AttributeCompiler.compile_attribute
|
def compile_attribute(key, values)
if values.all? { |v| Temple::StaticAnalyzer.static?(v.to_literal) }
return static_build(values)
end
case key
when 'id', 'class'
compile_id_or_class_attribute(key, values)
else
compile_common_attribute(key, values)
end
end
|
ruby
|
def compile_attribute(key, values)
if values.all? { |v| Temple::StaticAnalyzer.static?(v.to_literal) }
return static_build(values)
end
case key
when 'id', 'class'
compile_id_or_class_attribute(key, values)
else
compile_common_attribute(key, values)
end
end
|
[
"def",
"compile_attribute",
"(",
"key",
",",
"values",
")",
"if",
"values",
".",
"all?",
"{",
"|",
"v",
"|",
"Temple",
"::",
"StaticAnalyzer",
".",
"static?",
"(",
"v",
".",
"to_literal",
")",
"}",
"return",
"static_build",
"(",
"values",
")",
"end",
"case",
"key",
"when",
"'id'",
",",
"'class'",
"compile_id_or_class_attribute",
"(",
"key",
",",
"values",
")",
"else",
"compile_common_attribute",
"(",
"key",
",",
"values",
")",
"end",
"end"
] |
Compiles attribute values for one key to Temple expression that generates ` key='value'`.
@param key [String]
@param values [Array<AttributeValue>]
@return [Array] Temple expression
|
[
"Compiles",
"attribute",
"values",
"for",
"one",
"key",
"to",
"Temple",
"expression",
"that",
"generates",
"key",
"=",
"value",
"."
] |
9aa0fbe4a91b999978927be569d2ad0cd39076f1
|
https://github.com/haml/haml/blob/9aa0fbe4a91b999978927be569d2ad0cd39076f1/lib/haml/attribute_compiler.rb#L158-L169
|
12,995
|
haml/haml
|
lib/haml/util.rb
|
Haml.Util.parse_haml_magic_comment
|
def parse_haml_magic_comment(str)
scanner = StringScanner.new(str.dup.force_encoding(Encoding::ASCII_8BIT))
bom = scanner.scan(/\xEF\xBB\xBF/n)
return bom unless scanner.scan(/-\s*#\s*/n)
if coding = try_parse_haml_emacs_magic_comment(scanner)
return bom, coding
end
return bom unless scanner.scan(/.*?coding[=:]\s*([\w-]+)/in)
return bom, scanner[1]
end
|
ruby
|
def parse_haml_magic_comment(str)
scanner = StringScanner.new(str.dup.force_encoding(Encoding::ASCII_8BIT))
bom = scanner.scan(/\xEF\xBB\xBF/n)
return bom unless scanner.scan(/-\s*#\s*/n)
if coding = try_parse_haml_emacs_magic_comment(scanner)
return bom, coding
end
return bom unless scanner.scan(/.*?coding[=:]\s*([\w-]+)/in)
return bom, scanner[1]
end
|
[
"def",
"parse_haml_magic_comment",
"(",
"str",
")",
"scanner",
"=",
"StringScanner",
".",
"new",
"(",
"str",
".",
"dup",
".",
"force_encoding",
"(",
"Encoding",
"::",
"ASCII_8BIT",
")",
")",
"bom",
"=",
"scanner",
".",
"scan",
"(",
"/",
"\\xEF",
"\\xBB",
"\\xBF",
"/n",
")",
"return",
"bom",
"unless",
"scanner",
".",
"scan",
"(",
"/",
"\\s",
"\\s",
"/n",
")",
"if",
"coding",
"=",
"try_parse_haml_emacs_magic_comment",
"(",
"scanner",
")",
"return",
"bom",
",",
"coding",
"end",
"return",
"bom",
"unless",
"scanner",
".",
"scan",
"(",
"/",
"\\s",
"\\w",
"/in",
")",
"return",
"bom",
",",
"scanner",
"[",
"1",
"]",
"end"
] |
Parses a magic comment at the beginning of a Haml file.
The parsing rules are basically the same as Ruby's.
@return [(Boolean, String or nil)]
Whether the document begins with a UTF-8 BOM,
and the declared encoding of the document (or nil if none is declared)
|
[
"Parses",
"a",
"magic",
"comment",
"at",
"the",
"beginning",
"of",
"a",
"Haml",
"file",
".",
"The",
"parsing",
"rules",
"are",
"basically",
"the",
"same",
"as",
"Ruby",
"s",
"."
] |
9aa0fbe4a91b999978927be569d2ad0cd39076f1
|
https://github.com/haml/haml/blob/9aa0fbe4a91b999978927be569d2ad0cd39076f1/lib/haml/util.rb#L233-L243
|
12,996
|
haml/haml
|
lib/haml/buffer.rb
|
Haml.Buffer.rstrip!
|
def rstrip!
if capture_position.nil?
buffer.rstrip!
return
end
buffer << buffer.slice!(capture_position..-1).rstrip
end
|
ruby
|
def rstrip!
if capture_position.nil?
buffer.rstrip!
return
end
buffer << buffer.slice!(capture_position..-1).rstrip
end
|
[
"def",
"rstrip!",
"if",
"capture_position",
".",
"nil?",
"buffer",
".",
"rstrip!",
"return",
"end",
"buffer",
"<<",
"buffer",
".",
"slice!",
"(",
"capture_position",
"..",
"-",
"1",
")",
".",
"rstrip",
"end"
] |
Remove the whitespace from the right side of the buffer string.
Doesn't do anything if we're at the beginning of a capture_haml block.
|
[
"Remove",
"the",
"whitespace",
"from",
"the",
"right",
"side",
"of",
"the",
"buffer",
"string",
".",
"Doesn",
"t",
"do",
"anything",
"if",
"we",
"re",
"at",
"the",
"beginning",
"of",
"a",
"capture_haml",
"block",
"."
] |
9aa0fbe4a91b999978927be569d2ad0cd39076f1
|
https://github.com/haml/haml/blob/9aa0fbe4a91b999978927be569d2ad0cd39076f1/lib/haml/buffer.rb#L146-L153
|
12,997
|
haml/haml
|
lib/haml/helpers.rb
|
Haml.Helpers.preserve
|
def preserve(input = nil, &block)
return preserve(capture_haml(&block)) if block
s = input.to_s.chomp("\n")
s.gsub!(/\n/, '
')
s.delete!("\r")
s
end
|
ruby
|
def preserve(input = nil, &block)
return preserve(capture_haml(&block)) if block
s = input.to_s.chomp("\n")
s.gsub!(/\n/, '
')
s.delete!("\r")
s
end
|
[
"def",
"preserve",
"(",
"input",
"=",
"nil",
",",
"&",
"block",
")",
"return",
"preserve",
"(",
"capture_haml",
"(",
"block",
")",
")",
"if",
"block",
"s",
"=",
"input",
".",
"to_s",
".",
"chomp",
"(",
"\"\\n\"",
")",
"s",
".",
"gsub!",
"(",
"/",
"\\n",
"/",
",",
"'
'",
")",
"s",
".",
"delete!",
"(",
"\"\\r\"",
")",
"s",
"end"
] |
Takes any string, finds all the newlines, and converts them to
HTML entities so they'll render correctly in
whitespace-sensitive tags without screwing up the indentation.
@overload preserve(input)
Escapes newlines within a string.
@param input [String] The string within which to escape all newlines
@overload preserve
Escapes newlines within a block of Haml code.
@yield The block within which to escape newlines
|
[
"Takes",
"any",
"string",
"finds",
"all",
"the",
"newlines",
"and",
"converts",
"them",
"to",
"HTML",
"entities",
"so",
"they",
"ll",
"render",
"correctly",
"in",
"whitespace",
"-",
"sensitive",
"tags",
"without",
"screwing",
"up",
"the",
"indentation",
"."
] |
9aa0fbe4a91b999978927be569d2ad0cd39076f1
|
https://github.com/haml/haml/blob/9aa0fbe4a91b999978927be569d2ad0cd39076f1/lib/haml/helpers.rb#L132-L138
|
12,998
|
haml/haml
|
lib/haml/helpers.rb
|
Haml.Helpers.capture_haml
|
def capture_haml(*args, &block)
buffer = eval('if defined? _hamlout then _hamlout else nil end', block.binding) || haml_buffer
with_haml_buffer(buffer) do
position = haml_buffer.buffer.length
haml_buffer.capture_position = position
value = block.call(*args)
captured = haml_buffer.buffer.slice!(position..-1)
if captured == '' and value != haml_buffer.buffer
captured = (value.is_a?(String) ? value : nil)
end
captured
end
ensure
haml_buffer.capture_position = nil
end
|
ruby
|
def capture_haml(*args, &block)
buffer = eval('if defined? _hamlout then _hamlout else nil end', block.binding) || haml_buffer
with_haml_buffer(buffer) do
position = haml_buffer.buffer.length
haml_buffer.capture_position = position
value = block.call(*args)
captured = haml_buffer.buffer.slice!(position..-1)
if captured == '' and value != haml_buffer.buffer
captured = (value.is_a?(String) ? value : nil)
end
captured
end
ensure
haml_buffer.capture_position = nil
end
|
[
"def",
"capture_haml",
"(",
"*",
"args",
",",
"&",
"block",
")",
"buffer",
"=",
"eval",
"(",
"'if defined? _hamlout then _hamlout else nil end'",
",",
"block",
".",
"binding",
")",
"||",
"haml_buffer",
"with_haml_buffer",
"(",
"buffer",
")",
"do",
"position",
"=",
"haml_buffer",
".",
"buffer",
".",
"length",
"haml_buffer",
".",
"capture_position",
"=",
"position",
"value",
"=",
"block",
".",
"call",
"(",
"args",
")",
"captured",
"=",
"haml_buffer",
".",
"buffer",
".",
"slice!",
"(",
"position",
"..",
"-",
"1",
")",
"if",
"captured",
"==",
"''",
"and",
"value",
"!=",
"haml_buffer",
".",
"buffer",
"captured",
"=",
"(",
"value",
".",
"is_a?",
"(",
"String",
")",
"?",
"value",
":",
"nil",
")",
"end",
"captured",
"end",
"ensure",
"haml_buffer",
".",
"capture_position",
"=",
"nil",
"end"
] |
Captures the result of a block of Haml code,
gets rid of the excess indentation,
and returns it as a string.
For example, after the following,
.foo
- foo = capture_haml(13) do |a|
%p= a
the local variable `foo` would be assigned to `"<p>13</p>\n"`.
@param args [Array] Arguments to pass into the block
@yield [args] A block of Haml code that will be converted to a string
@yieldparam args [Array] `args`
|
[
"Captures",
"the",
"result",
"of",
"a",
"block",
"of",
"Haml",
"code",
"gets",
"rid",
"of",
"the",
"excess",
"indentation",
"and",
"returns",
"it",
"as",
"a",
"string",
".",
"For",
"example",
"after",
"the",
"following"
] |
9aa0fbe4a91b999978927be569d2ad0cd39076f1
|
https://github.com/haml/haml/blob/9aa0fbe4a91b999978927be569d2ad0cd39076f1/lib/haml/helpers.rb#L372-L390
|
12,999
|
haml/haml
|
lib/haml/helpers.rb
|
Haml.Helpers.haml_internal_concat
|
def haml_internal_concat(text = "", newline = true, indent = true)
if haml_buffer.tabulation == 0
haml_buffer.buffer << "#{text}#{"\n" if newline}"
else
haml_buffer.buffer << %[#{haml_indent if indent}#{text.to_s.gsub("\n", "\n#{haml_indent}")}#{"\n" if newline}]
end
end
|
ruby
|
def haml_internal_concat(text = "", newline = true, indent = true)
if haml_buffer.tabulation == 0
haml_buffer.buffer << "#{text}#{"\n" if newline}"
else
haml_buffer.buffer << %[#{haml_indent if indent}#{text.to_s.gsub("\n", "\n#{haml_indent}")}#{"\n" if newline}]
end
end
|
[
"def",
"haml_internal_concat",
"(",
"text",
"=",
"\"\"",
",",
"newline",
"=",
"true",
",",
"indent",
"=",
"true",
")",
"if",
"haml_buffer",
".",
"tabulation",
"==",
"0",
"haml_buffer",
".",
"buffer",
"<<",
"\"#{text}#{\"\\n\" if newline}\"",
"else",
"haml_buffer",
".",
"buffer",
"<<",
"%[#{haml_indent if indent}#{text.to_s.gsub(\"\\n\", \"\\n#{haml_indent}\")}#{\"\\n\" if newline}]",
"end",
"end"
] |
Internal method to write directly to the buffer with control of
whether the first line should be indented, and if there should be a
final newline.
Lines added will have the proper indentation. This can be controlled
for the first line.
Used by #haml_concat and #haml_tag.
@param text [#to_s] The text to output
@param newline [Boolean] Whether to add a newline after the text
@param indent [Boolean] Whether to add indentation to the first line
|
[
"Internal",
"method",
"to",
"write",
"directly",
"to",
"the",
"buffer",
"with",
"control",
"of",
"whether",
"the",
"first",
"line",
"should",
"be",
"indented",
"and",
"if",
"there",
"should",
"be",
"a",
"final",
"newline",
"."
] |
9aa0fbe4a91b999978927be569d2ad0cd39076f1
|
https://github.com/haml/haml/blob/9aa0fbe4a91b999978927be569d2ad0cd39076f1/lib/haml/helpers.rb#L412-L418
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.