Class: Shioconv::Unit
- Inherits:
-
Object
- Object
- Shioconv::Unit
- Defined in:
- lib/shioconv/unit.rb
Constant Summary collapse
- UNIT_TYPES =
{ volume: { cc: 1.0, ml: 1.0, tbsp: 15.0, tsp: 5.0, cup: 200.0, us_cup: 236.56, jp_cup: 200.0, }.freeze, weight: { g: 1.0, kg: 1000.0, oz: 28.349, lb: 453.592, }.freeze, }.freeze
- CONVERTABLE_UNITS =
UNIT_TYPES.map { |_, units| units.keys }.flatten.freeze
Instance Attribute Summary collapse
-
#name ⇒ Object
readonly
Returns the value of attribute name.
-
#type ⇒ Object
readonly
Returns the value of attribute type.
-
#value ⇒ Object
readonly
Returns the value of attribute value.
Class Method Summary collapse
Instance Method Summary collapse
- #convert(condiment, quantity, dst_unit) ⇒ Object
-
#initialize(type: type, name: name, value: value) ⇒ Unit
constructor
A new instance of Unit.
Constructor Details
#initialize(type: type, name: name, value: value) ⇒ Unit
Returns a new instance of Unit.
45 46 47 48 49 |
# File 'lib/shioconv/unit.rb', line 45 def initialize(type: type, name: name, value: value) @type = type @name = name @value = value end |
Instance Attribute Details
#name ⇒ Object (readonly)
Returns the value of attribute name.
2 3 4 |
# File 'lib/shioconv/unit.rb', line 2 def name @name end |
#type ⇒ Object (readonly)
Returns the value of attribute type.
2 3 4 |
# File 'lib/shioconv/unit.rb', line 2 def type @type end |
#value ⇒ Object (readonly)
Returns the value of attribute value.
2 3 4 |
# File 'lib/shioconv/unit.rb', line 2 def value @value end |
Class Method Details
.convertable?(unit) ⇒ Boolean
34 35 36 |
# File 'lib/shioconv/unit.rb', line 34 def self.convertable?(unit) CONVERTABLE_UNITS.include?(unit) end |
.find_by(unit_name) ⇒ Object
24 25 26 27 28 29 30 31 32 |
# File 'lib/shioconv/unit.rb', line 24 def self.find_by(unit_name) UNIT_TYPES.each do |unit_type, units| if units.has_key?(unit_name) return self.new(type: unit_type, name: unit_name, value: units[unit_name]) end end raise ArgumentError.new("unit [#{unit_name}] does not found.") unless @name end |
.list ⇒ Object
38 39 40 41 42 43 |
# File 'lib/shioconv/unit.rb', line 38 def self.list UNIT_TYPES.map do |type, units| (base_unit, _) = units.dup.shift "#{type}: #{base_unit}, " << units.map { |unit, value| "#{unit}(#{value}#{base_unit})" }.join(', ') end end |
Instance Method Details
#convert(condiment, quantity, dst_unit) ⇒ Object
51 52 53 54 55 56 57 58 59 60 61 62 63 |
# File 'lib/shioconv/unit.rb', line 51 def convert(condiment, quantity, dst_unit) return quantity if name == dst_unit dst_unit = self.class.find_by(dst_unit) current_vavlue = quantity * value / dst_unit.value if type == :weight && dst_unit.type == :volume current_vavlue /= condiment.specific_gravity elsif type == :volume && dst_unit.type == :weight current_vavlue *= condiment.specific_gravity end current_vavlue end |