Class: M9t::Direction

Inherits:
Object
  • Object
show all
Includes:
Base
Defined in:
lib/m9t/direction.rb

Overview

Represents a geographical direction

Constant Summary collapse

DEFAULT_OPTIONS =
{units: :degrees, abbreviated: false, decimals: 5}
CONVERSIONS =
{
  degrees:  1.0,
  compass:  nil,
}
CIRCLE =

Conversions

360.0
COMPASS_SECTOR_DEGREES =
CIRCLE / 16.0

Instance Attribute Summary

Attributes included from Base

#options, #value

Class Method Summary collapse

Instance Method Summary collapse

Methods included from Base

add_options, generate_conversions, included, #initialize, #method_missing, #respond_to?

Dynamic Method Handling

This class handles dynamic methods through the method_missing method in the class M9t::Base

Class Method Details

.compass(compass_direction) ⇒ Object

Accepts a localized compass direction (e.g. “N”) and returns the equivalent M9t::Direction

M9t::Direction.compass("NE") => #<M9t::Direction:0x000000014a438618 @value=45.0>


32
33
34
35
36
# File 'lib/m9t/direction.rb', line 32

def compass(compass_direction)
  sector = I18n.t(self.measurement_name + ".sectors").find_index(compass_direction)
  raise "Compass direction '#{compass_direction}' not recognised" if sector.nil?
  new(sector.to_f * COMPASS_SECTOR_DEGREES)
end

.compass_to_degrees(compass_direction) ⇒ Object



26
27
28
# File 'lib/m9t/direction.rb', line 26

def compass_to_degrees(compass_direction)
  compass(compass_direction).to_f
end

.degrees_to_compass(degrees) ⇒ Object

Given a value in degrees, returns the nearest (localized) compass direction

M9t::Directions.to_compass(42) => "NE"


21
22
23
24
# File 'lib/m9t/direction.rb', line 21

def degrees_to_compass(degrees)
  sector = (normalize(degrees) / COMPASS_SECTOR_DEGREES).round
  I18n.t(self.measurement_name + ".sectors")[sector]
end

.normalize(degrees) ⇒ Object

Reduce directions in degrees to the range [0, 360)

M9t::Direction.normalize(1000) => 280.0


40
41
42
43
44
45
46
47
# File 'lib/m9t/direction.rb', line 40

def normalize(degrees)
  remainder = degrees.remainder(CIRCLE)
  if remainder < 0
    remainder + CIRCLE
  else
    remainder
  end
end

Instance Method Details

#to_compassObject



59
60
61
# File 'lib/m9t/direction.rb', line 59

def to_compass
  self.class.degrees_to_compass(@value)
end

#to_s(options = {}) ⇒ Object

Handles the special case where compass directions are the desired output.



51
52
53
54
55
56
57
# File 'lib/m9t/direction.rb', line 51

def to_s( options = {} )
  if options[:units] == :compass
    Direction.degrees_to_compass(@value)
  else
    super
  end
end