mirror of
https://github.com/zhigang1992/RubyMotion.git
synced 2026-06-12 09:09:02 +08:00
[Version] Add a util class that can be used to compare versions.
This commit is contained in:
47
lib/motion/util/version.rb
Normal file
47
lib/motion/util/version.rb
Normal file
@@ -0,0 +1,47 @@
|
||||
module Motion; module Util
|
||||
class Version
|
||||
include Comparable
|
||||
|
||||
def initialize(version)
|
||||
@version = version.to_s
|
||||
unless @version =~ /^[.0-9]+$/
|
||||
raise ArgumentError, "A version may only contain periods and digits."
|
||||
end
|
||||
end
|
||||
|
||||
def to_s
|
||||
@version
|
||||
end
|
||||
|
||||
def segments
|
||||
@segments ||= @version.split('.').map(&:to_i)
|
||||
end
|
||||
|
||||
# This is pretty much vendored straight from RubyGems, except we don’t
|
||||
# care about string segments for our purposes.
|
||||
#
|
||||
# https://github.com/rubygems/rubygems/blob/81d806d818baeb5dcb6398ca631d772a003d078e/lib/rubygems/version.rb
|
||||
#
|
||||
def <=>(other)
|
||||
return unless Version === other
|
||||
return 0 if @version == other.to_s
|
||||
|
||||
lhsegments = segments
|
||||
rhsegments = other.segments
|
||||
|
||||
lhsize = lhsegments.size
|
||||
rhsize = rhsegments.size
|
||||
limit = (lhsize > rhsize ? lhsize : rhsize) - 1
|
||||
|
||||
i = 0
|
||||
while i <= limit
|
||||
lhs, rhs = lhsegments[i] || 0, rhsegments[i] || 0
|
||||
i += 1
|
||||
next if lhs == rhs
|
||||
return lhs <=> rhs
|
||||
end
|
||||
|
||||
return 0
|
||||
end
|
||||
end
|
||||
end; end
|
||||
Reference in New Issue
Block a user