Module: Nano::Unit
Overview
The Unit module provides utilities to allow conversion for the different unit types referenced in the Nano protocol.
Constant Summary collapse
- UNIT_SET =
A set of unit symbols found in the Nano protocol.
[ :hex, :raw, :nano, :knano, :Nano, :NANO, :KNano, :MNano ].to_set.freeze
- UNIT_ZEROS =
A hash of the unit types and number of zeros the unit is offset by.
{ :hex => 0, :raw => 0, :nano => 20, :knano => 24, :Nano => 30, :NANO => 30, :KNano => 33, :MNano => 36 }.freeze
Instance Method Summary collapse
-
#convert(value, from, to) ⇒ String
Converts the value in a unit type into another representation.
-
#unit_zeros ⇒ Hash
The unit zeros constant.
-
#valid_unit?(unit) ⇒ Boolean
True if the unit is contained within the unit set.
-
#zeros_for_unit(unit) ⇒ Integer
The number of zeros for a unit type.
Instance Method Details
#convert(value, from, to) ⇒ String
Converts the value in a unit type into another representation
43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 |
# File 'lib/nano/conversion.rb', line 43 def convert(value, from, to) raise ArgumentError, "Invalid from unit type" unless Unit.valid_unit?(from) raise ArgumentError, "Invalid to unit type" unless Unit.valid_unit?(to) from_zeros = zeros_for_unit(from) to_zeros = zeros_for_unit(to) raise ArgumentError, "Value must be a string" unless value.is_a? String if from == :hex is_hex = Nano::Check.is_valid_hex? value raise ArgumentError, "Invalid hex value string" unless is_hex else is_number = Nano::Check.is_numerical? value raise ArgumentError, "Invalid number value string" unless is_number end zero_difference = from_zeros - to_zeros big_number = 0 if from == :hex big_number = BigDecimal(value.to_i(16)) else big_number = BigDecimal(value) end is_increase = zero_difference > 0 zero_difference.abs.times do |i| if is_increase big_number = big_number * 10 else big_number = big_number / 10 end end if to == :hex big_number.to_i.to_s(16).rjust(32, "0") else if big_number.to_i == big_number big_number.to_i.to_s else big_number.to_s("F") end end end |
#unit_zeros ⇒ Hash
Returns The unit zeros constant.
91 92 93 |
# File 'lib/nano/conversion.rb', line 91 def unit_zeros UNIT_ZEROS end |
#valid_unit?(unit) ⇒ Boolean
Returns True if the unit is contained within the unit set.
32 33 34 |
# File 'lib/nano/conversion.rb', line 32 def valid_unit?(unit) UNIT_SET === unit end |
#zeros_for_unit(unit) ⇒ Integer
Returns The number of zeros for a unit type.
97 98 99 100 |
# File 'lib/nano/conversion.rb', line 97 def zeros_for_unit(unit) raise ArgumentError, "Invalid unit" unless valid_unit? unit UNIT_ZEROS[unit] end |