class Rack::HanoiApp

Public Class Methods

new(root, height, from=:A, to=:C, via=:B) click to toggle source
# File lib/rack/hanoi.rb, line 20
def initialize(root, height, from=:A, to=:C, via=:B)
  @root, @height, @from, @to, @via = root, height, from, to, via
end

Public Instance Methods

call(env) click to toggle source
# File lib/rack/hanoi.rb, line 24
def call(env)
  env["rack.hanoi"] ||= ""
  logger = env["rack.logger"] || ::Logger.new(STDERR)
  if @height < 1
    return Rack::Response.new do |res|
      res["Content-Type"] = "text/plain"
      res.body << with_lines(env["rack.hanoi"])
    end.finish
  else
    HanoiApp.new(false, @height - 1, @from, @via, @to).call(env)
    logger.info "Disc Moved #{@from} to #{@to}"
    env["rack.hanoi"] << "Disc Moved #{@from} to #{@to}\n"
    HanoiApp.new(false, @height - 1, @via, @to, @from).call(env)
  end
end

Private Instance Methods

with_lines(body) click to toggle source
# File lib/rack/hanoi.rb, line 41
def with_lines(body)
  lines = body.strip.lines
  digits = (Math.log(lines.to_a.size - 1) / Math.log(10)).floor + 1 rescue 1
  lines.map.with_index{|ln, i| "%0#{digits}d: %s" % [i, ln]}.join
end