Sha256: 35ed785ecb1894b4d43a26648e888c1c154ce6e32d3536cf4e427e7f949a548f

Contents?: true

Size: 1.01 KB

Versions: 23

Compression:

Stored size: 1.01 KB

Contents

class Timespan
	class DurationParseError < StandardError; end

	module Span
		attr_reader :duration

		def duration= duration
			@duration = if duration.kind_of? Numeric
				 Duration.new duration
			else
				case duration
				when Timespan
					duration.duration
				when Duration
					duration
				when Hash
					Duration.new duration
				when String
					Duration.new parse_duration(duration)
				else
					raise ArgumentError, "Unsupported duration type: #{duration.inspect} of class #{duration.class}"
				end	
			end
			unless is_new?
				add_dirty :duration
				refresh!
				calculate!
			end
		end

		protected

		def parse_duration text
			spanner_parse text
		rescue Spanner::ParseError => e
			chronic_parse text
		rescue ChronicDuration::DurationParseError => e
			raise Timespan::DurationParseError, "Internal error: neither Spanner or ChronicDuration could parse '#{duration}'"
		end

		def spanner_parse text
			Spanner.parse(text.gsub /and/, '')
		end

		def chronic_parse text
			ChronicDuration.parse text
		end
	end
end

Version data entries

23 entries across 23 versions & 1 rubygems

Version Path
timespan-0.2.8 lib/timespan/span.rb
timespan-0.2.7 lib/timespan/span.rb
timespan-0.2.6 lib/timespan/span.rb