class Tide

Constants

POST_URL
STATION_REGEX
TIDE_REGEX

Public Class Methods

new(options = {}) click to toggle source

Create new tide table.

# File lib/tide.rb, line 12
def initialize(options = {})
  options     = { :station => 610, :timezone => 'AST', :date => Time.now }.merge(options)
  @station    = options[:station]
  @timezone   = options[:timezone]
  @date       = options[:date]
end
station(sid) click to toggle source

Shortcut for station lookup

# File lib/tide.rb, line 20
def self.station(sid)
  new(:station => sid)
end

Public Instance Methods

data() click to toggle source

Download raw data

# File lib/tide.rb, line 25
def data
  @data ||= download_tide_data
end
to_csv() click to toggle source

Returns semi-colon delimited list of tide data.

# File lib/tide.rb, line 30
def to_csv
  @csv ||= format_csv
end
to_html() click to toggle source

Returns formatted html table of tide data.

# File lib/tide.rb, line 35
def to_html
  @html ||= format_html
end

Private Instance Methods

download_tide_data(type='predict', view='text', language='english') click to toggle source

Downloads new tide data

# File lib/tide.rb, line 42
def download_tide_data(type='predict', view='text', language='english')
  res = Net::HTTP.post_form(
  URI.parse(POST_URL),
    {
      'station'   => @station,
      'year'      => @date.year,
      'month'     => @date.month,
      'day'       => @date.day,
      'TZ'        => @timezone, # TODO use supplied date for timezone
      'queryType' => type,
      'view'      => view,
      'language'  => language
    }
  )
  # TODO rescue request errors
  res.body
end
format_csv() click to toggle source

Formats tide data as csv.

# File lib/tide.rb, line 61
def format_csv
  data.match(TIDE_REGEX)[1].gsub('<br>', "\n").gsub(';', ',')
end
format_html() click to toggle source

Formats tide data as html table.

# File lib/tide.rb, line 66
def format_html
  formatted = "<table summary=\"Tide tables with columns for time of day and tide height (in meters).\">\n\t<thead>\n\t\t<tr><th scope=\"col\">Time</th><th scope=\"col\">Height</th></tr>\n\t</thead>\n"
  last_date = nil
  to_csv.each_line do |row|
    row = row.chomp.split(',')
    if row[0] != last_date
      formatted += "\t</tbody>\n" unless last_date.nil?
      formatted += "\t<tbody>\n\t\t<tr><th scope=\"rowgroup\" colspan=\"2\">#{row[0]}</th></tr>\n"
      last_date = row[0]
    end
    formatted += "\t\t<tr><td>#{row[1]}</td><td>#{row[2]}m</td></tr>\n"
  end
  formatted += "\t</tbody>\n</table>\n"
  formatted
end