lib/ruby-version.rb in ruby-version-0.1.1 vs lib/ruby-version.rb in ruby-version-0.2.0

- old
+ new

@@ -1,9 +1,11 @@ # encoding: utf-8 # (c) 2011 Martin Kozák (martinkozak@martinkozak.net) -require "hash-utils/numeric" +require "hash-utils/numeric" # >= 0.16.0 +require "hash-utils/object" # >= 0.17.0 +require "lookup-hash" ## # Outer wrapper for the {Ruby::Version} module. # @@ -22,73 +24,91 @@ # VERSION = RUBY_VERSION.freeze ## + # Holds comparign cache. + # + + @cache + + ## # Higher or equal operator. # # @param [String, Symbol, Array] value version identifier # @return [Boolean] +true+ if yes, +false otherwise # def self.>=(value) - __compare(value, false, true, true) + __cache(:">=", value) do + __compare(value, false, true, true) + end end ## # Lower or equal operator. # # @param [String, Symbol, Array] value version identifier # @return [Boolean] +true+ if yes, +false otherwise # def self.<=(value) - __compare(value, true, false, true) + __cache(:"<=", value) do + __compare(value, true, false, true) + end end ## # Lower operator. # # @param [String, Symbol, Array] value version identifier # @return [Boolean] +true+ if yes, +false otherwise # def self.<(value) - __compare(value, true, false, false) + __cache(:<, value) do + __compare(value, true, false, false) + end end ## # Higher operator. # # @param [String, Symbol, Array] value version identifier # @return [Boolean] +true+ if yes, +false otherwise # def self.>(value) - __compare(value, false, true, false) + __cache(:>, value) do + __compare(value, false, true, false) + end end ## # Equality operator. # # @param [String, Symbol, Array] value version identifier # @return [Boolean] +true+ if yes, +false otherwise # def self.==(value) - __compare(value, false, false, true) + __cache(:"==", value) do + __compare(value, false, false, true) + end end ## # Compares version strings. # # @param [String, Symbol, Array] value version identifier # @return [Boolean] +1+ if this one is higher, +-1+ if lower and +0+ otherwise # def self.compare(value) - __compare(value, -1, 1, 0) + __cache(:compare, value) do + __compare(value, -1, 1, 0) + end end ## # Brokes string identifier to numeric tokens in array. # @@ -112,11 +132,11 @@ # Universal comparing routine for all type of (in)equalities. # private def self.__compare(value, lower, higher, equal) - if not value.kind_of? Array + if not value.array? value = self.broke(value.to_s) end self::TOKENS.each_index do |i| case self::TOKENS[i].to_i.compare(value[i].to_i) @@ -126,9 +146,28 @@ return higher end end return equal + end + + ## + # Universal cache routine. + # + + private + def self.__cache(operation, value, &block) + value = value.to_sym if value.string? + + if @cache.nil? + @cache = Hash::new { |dict, key| dict[key] = { } } + end + + if not @cache[operation].has_key? value + @cache[operation][value] = block.call() + end + + @cache[operation][value] end end end