Sha256: 487f8bc929d02af939f9f784932e318c86b112c3a8aa9bb83c3b35c9ed2c5e4f

Contents?: true

Size: 1.91 KB

Versions: 7

Compression:

Stored size: 1.91 KB

Contents

class Blade::RackAdapter
  include Blade::RackRouter

  route "", to: :redirect_to_index
  route "/", to: :index
  route "/blade*", environment: :blade
  route "/blade/adapter*", environment: :adapter
  route "/blade/websocket*", to: :websocket
  default_route environment: :user

  delegate :environment, to: Blade::Assets

  attr_reader :request, :env

  def initialize
    Blade.initialize!
  end

  def call(env)
    @env = env
    @request = Rack::Request.new(env)

    route = find_route(request.path_info)
    base_path, action = route.values_at(:base_path, :action)

    rewrite_path!(base_path)

    case
    when action[:environment]
      environment(action[:environment]).call(env)
    when action[:to]
      send(action[:to])
    end
  end

  def index
    request.path_info = "/index.html"
    response = environment(:blade).call(env)
    response = add_session_cookie(response) if needs_session_cookie?
    response.to_a
  end

  def redirect_to_index
    Rack::Response.new.tap do |response|
      path = request.path
      path = path + "/" unless path.last == "/"
      response.redirect(path)
    end.to_a
  end

  def websocket
    faye_adapter.call(env)
  end

  private
    def needs_session_cookie?
      Blade.running? && !Blade::Session.find(request.cookies[Blade::Session::KEY])
    end

    def add_session_cookie(response)
      user_agent = UserAgent.parse(request.user_agent)
      session = Blade::Session.create(user_agent: user_agent)
      status, headers, body = response
      response = Rack::Response.new(body, status, headers)
      response.set_cookie(Blade::Session::KEY, session.id)
      response
    end

    def rewrite_path!(path = nil)
      return if path.nil?
      request.path_info = request.path_info.sub(path, "").presence || "/"
      request.script_name = request.script_name + path
    end

    def faye_adapter
      @faye_adapter ||= Faye::RackAdapter.new(mount: "/", timeout: 25)
    end
end

Version data entries

7 entries across 7 versions & 1 rubygems

Version Path
blade-0.5.6 lib/blade/rack/adapter.rb
blade-0.5.5 lib/blade/rack/adapter.rb
blade-0.5.4 lib/blade/rack/adapter.rb
blade-0.5.3 lib/blade/rack/adapter.rb
blade-0.5.2 lib/blade/rack/adapter.rb
blade-0.5.1 lib/blade/rack/adapter.rb
blade-0.5.0 lib/blade/rack/adapter.rb