Clear the context per request, and assign a controller reference that is used to create a new view context on demand if needed by draper outside of a template context. Fixes #287. Split out the system initialization into action_controller and action_mailer pieces for clarity. Guarded the view context lazy initialization to only attempt to create a test context if the proper test classes exist (as they won't outside of test mode).

This commit is contained in:
Chris Heald 2012-10-01 14:30:18 -07:00
parent ad9a654b34
commit 6e6217a484
4 changed files with 29 additions and 11 deletions

4
lib/draper/railtie.rb Normal file → Executable file
View File

@ -24,13 +24,13 @@ module Draper
initializer "draper.extend_action_controller_base" do |app|
ActiveSupport.on_load(:action_controller) do
Draper::System.setup(self)
Draper::System.setup_action_controller(self)
end
end
initializer "draper.extend_action_mailer_base" do |app|
ActiveSupport.on_load(:action_mailer) do
Draper::System.setup(self)
Draper::System.setup_action_mailer(self)
end
end

12
lib/draper/system.rb Normal file → Executable file
View File

@ -1,10 +1,18 @@
module Draper
class System
def self.setup(component)
def self.setup_action_controller(component)
component.class_eval do
include Draper::ViewContext
extend Draper::HelperSupport unless defined?(::ActionMailer) && self.is_a?(::ActionMailer::Base)
extend Draper::HelperSupport
before_filter lambda {|controller|
Draper::ViewContext.current = nil
Draper::ViewContext.current_controller = controller
}
end
end
def self.setup_action_mailer(component)
include Draper::ViewContext
end
end
end

22
lib/draper/view_context.rb Normal file → Executable file
View File

@ -1,11 +1,19 @@
module Draper
module ViewContext
def self.current_controller
Thread.current[:current_controller] || ApplicationController.new
end
def self.current_controller=(controller)
Thread.current[:current_controller] = controller
end
def self.current
Thread.current[:current_view_context] ||= build_view_context
end
def self.current=(input)
Thread.current[:current_view_context] = input
def self.current=(context)
Thread.current[:current_view_context] = context
end
def view_context
@ -17,10 +25,12 @@ module Draper
private
def self.build_view_context
ApplicationController.new.view_context.tap do |context|
context.controller.request ||= ActionController::TestRequest.new
context.request ||= context.controller.request
context.params ||= {}
current_controller.view_context.tap do |context|
if defined?(ActionController::TestRequest)
context.controller.request ||= ActionController::TestRequest.new
context.request ||= context.controller.request
context.params ||= {}
end
end
end
end

View File

@ -32,7 +32,7 @@ require 'action_controller/test_case'
module ActionController
class Base
Draper::System.setup(self)
Draper::System.setup_action_controller(self)
end
end