Last active
September 1, 2015 01:46
-
-
Save JohnAmican/a408f74cdaff00854671 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
module React | |
module Server | |
module Rendering | |
extend ActiveSupport::Concern | |
include ::BeforeRender | |
included do | |
before_render :set_rendered | |
attr_reader :rendered | |
helper_method :rendered | |
end | |
def set_rendered | |
@rendered = self.class.server_js.eval( | |
"this.render(#{data.to_json})" # `this.render` is the executable name of the bundle, `data` are our props (ex. {foo: :bar}) | |
) | |
end | |
module ClassMethods | |
@@server_js = "" # cache the server js | |
@@server_js_last_modified = Time.at 0 | |
def server_js | |
if @@server_js_last_modified < mtime = File.mtime(filepath) | |
@@server_js = File.open(filepath).read | |
@@server_js = ExecJS.compile @@server_js # this will be WAY faster if you minify your js | |
@@server_js_last_modified = mtime | |
end | |
@@server_js | |
end | |
private | |
def filepath | |
Rails.configuration.react.server_js # allows me to make this configurable in a config file. You could just return a string here. | |
end | |
end | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment