Created
September 30, 2011 00:03
-
-
Save duncanbeevers/1252290 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
!!! | |
%html | |
%head | |
= csrf_meta_tags | |
= stylesheet_link_tag "application" | |
%body | |
= yield | |
= javascript_include_tag "application" | |
= render_inline_javascript_controller_action_asset |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
module InlineJsAssetHelper | |
module SprocketsActionViewContextHelper | |
def self.context= context | |
Thread.current[:SprocketsActionViewContextHelperContext] = context | |
end | |
def self.context | |
Thread.current[:SprocketsActionViewContextHelperContext] | |
end | |
def method_missing method, *args | |
SprocketsActionViewContextHelper.context.send(method, *args) | |
end | |
end | |
def render_inline_javascript_controller_action_asset | |
render_inline_javascript_asset params[:action] | |
end | |
def render_inline_javascript_asset(name) | |
app = Rails.application | |
assets = app.assets | |
helper = Sprockets::Environment.new(app.root.to_s) do |env| | |
env.js_compressor = assets.js_compressor | |
env.append_path("app/views/#{params[:controller]}") | |
end | |
# Stash a reference to the rendering context on a helper module we can mix into Sprockets renderer | |
SprocketsActionViewContextHelper.context = main_app.routes.url_helpers | |
context_assigns = assigns | |
helper.context_class.instance_eval do | |
include SprocketsActionViewContextHelper | |
end | |
# Copy the instance variables from this ActionView rendering context onto the new Sprockets rendering context | |
# by hooking into the initialization | |
helper.context_class.instance_eval do | |
define_method :initialize do |*args| | |
context_assigns.each do |k, v| | |
instance_variable_set "@#{k}", v | |
end | |
super *args | |
end | |
end | |
asset = helper.find_asset("_#{name}.js") | |
javascript_tag asset.body if asset | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment