Last active
November 15, 2017 01:14
-
-
Save max-power/0decf94a29b665bd96a096061692efea to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Gem::Specification.new do |s| | |
s.name = 'power-month' | |
s.version = '0.0.4' | |
s.platform = Gem::Platform::RUBY | |
s.author = 'Kevin Melchert' | |
s.email = '[email protected]' | |
s.summary = 'Month of Year.' | |
s.description = 'Super simple Month of Year implementation.' | |
s.files = ['month.rb'] | |
s.require_path = '.' | |
end |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
require 'date' | |
class Month | |
include Comparable | |
def self.from(obj) | |
if obj.respond_to?(:year) && obj.respond_to?(:month) | |
new(obj.year, obj.month) | |
else | |
raise ArgumentError.new("Argument doesn't respond to 'year' and/or 'month'") | |
end | |
end | |
def self.now | |
from Time.now | |
end | |
attr_reader :year, :month | |
def initialize(year, month) | |
@year = Integer(year) | |
@month = Integer(month).clamp(1, 12) | |
end | |
def first_day | |
Date.new(year, month, 1) | |
end | |
def last_day | |
Date.new(year, month, -1) | |
end | |
def length | |
last_day.day | |
end | |
def days | |
first_day..last_day | |
end | |
def each_day(&block) | |
days.each(&block) | |
end | |
def succ | |
self.class.from(last_day + 1) | |
end | |
def pred | |
self.class.from(first_day - 1) | |
end | |
alias_method :next, :succ | |
alias_method :prev, :pred | |
def hash | |
[year, month].hash | |
end | |
def <=>(other) | |
(year <=> other.year).nonzero? || month <=> other.month | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment