Class: PhotoUtils::Length
Instance Method Summary collapse
- #-(other) ⇒ Object
- #abs ⇒ Object
- #format_imperial ⇒ Object
- #format_metric(precision = nil) ⇒ Object
-
#initialize(x) ⇒ Length
constructor
A new instance of Length.
- #to_s(format = :metric) ⇒ Object
Methods inherited from Float
Constructor Details
#initialize(x) ⇒ Length
Returns a new instance of Length.
7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 |
# File 'lib/photo_utils/length.rb', line 7 def initialize(x) case x when Length super(x) when Numeric super(x.to_f) when '∞' super(Math::Infinity) when String n = 0 s = x.dup until s.empty? if s.gsub!(/^\s*(\d+(\.\d+)?)\s*/, '') n2 = $1.to_f n2 = if s.gsub!(/^('|ft\b)/, '') n2.feet elsif s.gsub!(/^("|in\b)/, '') n2.inches elsif s.gsub!(/^\s*m\b/, '') n2.meters elsif s.gsub!(/^\s*(mm\b)?/, '') n2.mm else raise "Can't parse unit: #{s.inspect}" end n += n2 else raise "Can't parse number: #{s.inspect}" end end super(n) else raise "Can't make length from #{x.class}: #{x.inspect}" end end |
Instance Method Details
#-(other) ⇒ Object
82 83 84 |
# File 'lib/photo_utils/length.rb', line 82 def -(other) self.class.new(super(other)) end |
#abs ⇒ Object
86 87 88 |
# File 'lib/photo_utils/length.rb', line 86 def abs self.class.new(super) end |
#format_imperial ⇒ Object
43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 |
# File 'lib/photo_utils/length.rb', line 43 def format_imperial inches = self * INCHES_PER_METER / 1000 if inches.floor >= 12 feet = (inches / 12).floor inches %= 12 else feet = 0 end if inches > 0 inches = inches.ceil if inches == 12 feet += 1 inches = 0 end end (feet > 0 ? "#{feet}'" : '') + (inches > 0 ? "#{inches}\"" : '') end |
#format_metric(precision = nil) ⇒ Object
61 62 63 64 65 66 67 |
# File 'lib/photo_utils/length.rb', line 61 def format_metric(precision=nil) if self >= 1000 "#{(self / 1000).format(precision)}m" else "#{format(precision)}mm" end end |
#to_s(format = :metric) ⇒ Object
69 70 71 72 73 74 75 76 77 78 79 80 |
# File 'lib/photo_utils/length.rb', line 69 def to_s(format=:metric) if self == Math::Infinity '∞' else case format when :imperial format_imperial when :metric format_metric end end end |