Class: Alchemist::NumericConversion
- Inherits:
-
Object
- Object
- Alchemist::NumericConversion
show all
- Includes:
- Comparable
- Defined in:
- lib/alchemist.rb
Instance Method Summary
collapse
Dynamic Method Handling
This class handles dynamic methods through the method_missing method
#method_missing(unit_name, *args, &block) ⇒ Object
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
|
# File 'lib/alchemist.rb', line 469
def method_missing unit_name, *args, &block
exponent, unit_name = Alchemist.parse_prefix(unit_name)
if Conversions[ unit_name ]
types = Conversions[ @unit_name] & Conversions[ unit_name]
if types[0] if(Alchemist.conversion_table[types[0]][unit_name].is_a?(Array))
Alchemist.conversion_table[types[0]][unit_name][1].call(base(types[0]))
else
NumericConversion.new(base(types[0]) / (exponent * Alchemist.conversion_table[types[0]][unit_name]), unit_name)
end
else
raise Exception, "Incompatible Types"
end
else
if args[0] && args[0].is_a?(NumericConversion) && Alchemist.operator_actions[unit_name]
t1 = Conversions[ @unit_name ][0]
t2 = Conversions[ args[0].unit_name ][0]
Alchemist.operator_actions[unit_name].each do |s1, s2, new_type|
if t1 == s1 && t2 == s2
return (@value * args[0].to_f).send(new_type)
end
end
end
if unit_name == :*
if args[0].is_a?(Numeric)
@value *= args[0]
return self
else
raise Exception, "Incompatible Types"
end
end
if unit_name == :/ && args[0].is_a?(NumericConversion)
raise Exception, "Incompatible Types" unless (Conversions[@unit_name] & Conversions[args[0].unit_name]).length > 0
end
args.map!{|a| a.is_a?(NumericConversion) ? a.send(@unit_name).to_f / @exponent : a }
@value = @value.send( unit_name, *args, &block )
unit_name == :/ ? @value : self
end
end
|
Instance Method Details
#<=>(other) ⇒ Object
458
459
460
|
# File 'lib/alchemist.rb', line 458
def <=>(other)
(self.to_f * @exponent).to_f <=> other.to(@unit_name).to_f
end
|
#==(other) ⇒ Object
454
455
456
|
# File 'lib/alchemist.rb', line 454
def ==(other)
(self <=> other) == 0
end
|
#base(unit_type) ⇒ Object
#p ⇒ Object
417
418
419
|
# File 'lib/alchemist.rb', line 417
def p
per
end
|
#to(type = nil) ⇒ Object
Also known as:
as
421
422
423
424
425
426
427
|
# File 'lib/alchemist.rb', line 421
def to(type = nil)
unless type
self
else
send(type)
end
end
|
#to_f ⇒ Object
450
451
452
|
# File 'lib/alchemist.rb', line 450
def to_f
@value
end
|
#to_s ⇒ Object
442
443
444
|
# File 'lib/alchemist.rb', line 442
def to_s
@value.to_s
end
|
#unit_name ⇒ Object
438
439
440
|
# File 'lib/alchemist.rb', line 438
def unit_name
@unit_name
end
|
#value ⇒ Object
446
447
448
|
# File 'lib/alchemist.rb', line 446
def value
@value
end
|