Sha256: fe55f3ee8dd873ff962c8a6696dc46f813c7d84578b6b47f64afb6b9f600689d

Contents?: true

Size: 1.3 KB

Versions: 3

Compression:

Stored size: 1.3 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, *args)
      @app      = app
      @active   = Spontaneous::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

3 entries across 3 versions & 1 rubygems

Version Path
spontaneous-0.2.0.beta4 lib/spontaneous/rack/middleware/reloader.rb
spontaneous-0.2.0.beta3 lib/spontaneous/rack/middleware/reloader.rb
spontaneous-0.2.0.beta2 lib/spontaneous/rack/middleware/reloader.rb