Skip to content

Commit

Permalink
Make the Humanizer self contained
Browse files Browse the repository at this point in the history
Addresses feedback here square#49 (comment)
  • Loading branch information
craigmcnamara committed Dec 17, 2022
1 parent e0c15e8 commit 8c1a319
Show file tree
Hide file tree
Showing 2 changed files with 31 additions and 39 deletions.
34 changes: 31 additions & 3 deletions lib/rrule/humanizer.rb
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,16 @@ class Humanizer

OPTION_ATTRIBUTE_RE = /_option/.freeze

DAY_NAMES = %w[
Sunday
Monday
Tuesday
Wednesday
Thursday
Friday
Saturday
].freeze

def initialize(rrule, options)
@rrule = rrule
@options = options
Expand Down Expand Up @@ -145,21 +155,21 @@ def monthly
end

def weekdaytext(day)
[day.ordinal && day.nth, day.full_name].compact.join(' ')
[day.ordinal && nth(day.ordinal), DAY_NAMES[day.index]].compact.join(' ')
end

def all_weeks?
bynweekday_option.all? { |option| option.ordinal.nil? }
end

def every_day?
byweekday_option.sort_by(&:index).map(&:short_name) == RRule::WEEKDAYS
byweekday_option.sort_by(&:index).map { |day| WEEKDAYS[day.index]} == RRule::WEEKDAYS
end

def weekdays?
return false if byweekday_option.none?

byweekday_option.sort_by(&:index).map(&:short_name) == RRule::WEEKDAYS - %w[SA SU]
byweekday_option.sort_by(&:index).map { |day| WEEKDAYS[day.index]} == RRule::WEEKDAYS - %w[SA SU]
end

def _bymonth
Expand All @@ -183,5 +193,23 @@ def _byhour
add 'at'
add list byhour_option, :to_s, 'and'
end

def nth(ordinal)
return 'last' if ordinal == -1

nth =
case npos = ordinal.abs
when 1, 21, 31
"#{npos}st"
when 2, 22
"#{npos}nd"
when 3, 23
"#{npos}rd"
else
"#{npos}th"
end

ordinal < 0 ? "#{nth} last" : nth
end
end
end
36 changes: 0 additions & 36 deletions lib/rrule/weekday.rb
Original file line number Diff line number Diff line change
Expand Up @@ -4,16 +4,6 @@ module RRule
class Weekday
attr_reader :index, :ordinal

DAY_NAMES = %w[
Sunday
Monday
Tuesday
Wednesday
Thursday
Friday
Saturday
].freeze

def initialize(index, ordinal = nil)
@index = index
@ordinal = ordinal
Expand All @@ -25,31 +15,5 @@ def self.parse(weekday)
ordinal = match[1]&.to_i
new(index, ordinal)
end

def full_name
DAY_NAMES[index]
end

def short_name
WEEKDAYS[index]
end

def nth
return 'last' if ordinal == -1

nth =
case npos = ordinal.abs
when 1, 21, 31
"#{npos}st"
when 2, 22
"#{npos}nd"
when 3, 23
"#{npos}rd"
else
"#{npos}th"
end

ordinal < 0 ? "#{nth} last" : nth
end
end
end

0 comments on commit 8c1a319

Please sign in to comment.