Sha256: e22125d05b96b7e415f5591340ed00835cf8d0fc8583e7d1aeddd222c4b82e0f

Contents?: true

Size: 1.04 KB

Versions: 3

Compression:

Stored size: 1.04 KB

Contents

module Amazon
  module Associates
    class Measurement < ApiResult
      include Comparable

      xml_reader :value, :from => :content, :as => Float
      xml_reader :units, :from => :attr

      def initialize(value = nil, units = 'pixels')
        @value = value && Float(value)
        @units = units.to_s
        normalize_hundredths
      end

      def to_s
        value = @value.whole? ? @value.to_i : @value
        #singularize here to avoid comparison problems
        units = @value == 1 ? @units.singularize : @units
        [value, units].join(' ')
      end
      alias :inspect :to_s

      def to_i
        @value.round
      end

      def <=>(other)
        return nil unless @units == other.units

        @value <=> other.value
      end

    private
      def after_parse
        @units ||= 'pixels'
        normalize_hundredths
      end

      def normalize_hundredths
        if @units.try(:starts_with?, 'hundredths-')
          @value /= 100.0
          @units = @units.split('hundredths-')[1]
        end
      end
    end
  end
end

Version data entries

3 entries across 3 versions & 1 rubygems

Version Path
amazon-associates-0.7.2 lib/amazon-associates/types/measurement.rb
amazon-associates-0.7.1 lib/amazon-associates/types/measurement.rb
amazon-associates-0.7.0 lib/amazon-associates/types/measurement.rb