Sha256: 09abb1856ec45ac26cfb3c058fd3f624d47570a1d2b8fcf956834897363b03c9

Contents?: true

Size: 1.31 KB

Versions: 6

Compression:

Stored size: 1.31 KB

Contents

# encoding: UTF-8

require 'stringio'
require 'erubis'
require 'tilt'

require 'spontaneous/rack/back/helpers'

module Spontaneous::Rack::Middleware
  class Reloader
    include Spontaneous::Rack::Back::TemplateHelpers

    def initialize(app, site, *args)
      @app      = app
      @site     = site
      @active   = @site.config.reload_classes
      config    = args.first || {}
      @cooldown = config[:cooldown] || 3
      @last     = (Time.now - @cooldown)
    end

    def call(env)
      reload if should_reload?
      @app.call(env)
    rescue Spontaneous::SchemaModificationError => error
      schema_conflict!(env, error)
    end

    def should_reload?
      @active && @cooldown && (Time.now > (@last + @cooldown))
    end

    def reload
      if Thread.list.size > 1
        Thread.exclusive{ reload! }
      else
        reload!
      end
      @last = Time.now
    end

    def reload!
      Spontaneous.reload!
    end

    def schema_conflict!(env, error)
      template_path = ::File.expand_path('../../../../../application/views/schema_modification_error.html.erb', __FILE__)
      template = Tilt::ErubisTemplate.new(template_path)
      html = template.render(self, :modification => error.modification, :env => env)
      [412, {'Content-type' => ::Rack::Mime.mime_type('.html')}, StringIO.new(html)]
    end
  end
end

Version data entries

6 entries across 6 versions & 1 rubygems

Version Path
spontaneous-0.2.0.beta10 lib/spontaneous/rack/middleware/reloader.rb
spontaneous-0.2.0.beta9 lib/spontaneous/rack/middleware/reloader.rb
spontaneous-0.2.0.beta8 lib/spontaneous/rack/middleware/reloader.rb
spontaneous-0.2.0.beta7 lib/spontaneous/rack/middleware/reloader.rb
spontaneous-0.2.0.beta6 lib/spontaneous/rack/middleware/reloader.rb
spontaneous-0.2.0.beta5 lib/spontaneous/rack/middleware/reloader.rb