Skip to content
This repository

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
tree: 92aaa68e3e
Fetching contributors…

Octocat-spinner-32-eaf2f5

Cannot retrieve contributors at this time

file 73 lines (61 sloc) 1.906 kb
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72
$: << File.dirname(__FILE__)
$: << File.join(File.dirname(__FILE__), 'app')
require 'bundler'
Bundler.require(:default, :app)

require 'goliath/rack/templates'
require 'store'
require 'book'

class ISBN < Goliath::API
  include Goliath::Rack::Templates
  use Goliath::Rack::Params
  use Goliath::Rack::Validation::RequiredParam, {key: :isbn}

  def response(env)
    if isbn = Book.is_isbn?(params[:isbn])
      if isbn == params[:isbn]
        Book.new(params[:isbn], config['redis']).fetch_prices
        [200, {}, slim(:isbn, views: Goliath::Application.root_path('views'),
                       locals: {isbn: params[:isbn], num_stores: Store.num_stores })]
      else
        [301, {'Location' => "#{config['host']}/isbn/#{isbn}/price"}, '']
      end
    else
        [400, {}, slim(:error, views: Goliath::Application.root_path('views'),
                       locals: {message: 'ISBN provided is invalid'})]
    end
  end
end

class Poll < Goliath::API
  use Goliath::Rack::DefaultMimeType
  use Goliath::Rack::Render, 'json'
  use Goliath::Rack::Params

  def process_request
    i = 0
    # not idiomatic but much simpler to handle in js
    # than streaming
    while i < 50
      prices = Book.new(params[:isbn], config['redis']).prices(params[:stores].to_i)
      break if prices[:status] != 'fetching'
      i += 1
      EM::Synchrony.sleep(1)
    end
    prices
  end

  def response(env)
    [200, {}, process_request]
  end
end

class Home < Goliath::API
  include Goliath::Rack::Templates

  def response(env)
    [200, {}, slim(:home, :views => Goliath::Application.root_path('views'))]
  end
end

class App < Goliath::API
  include Goliath::Rack::Templates

  use(Rack::Static,
      :root => Goliath::Application.app_path("public"),
      :urls => ["/favicon.ico", '/stylesheets', '/javascripts', '/images'])

  get '/', Home
  map '/isbn/:isbn/price/', ISBN
  map '/poll', Poll
end
Something went wrong with that request. Please try again.