Last active
August 18, 2020 13:11
-
-
Save breckenedge/a7ec84ab0a39721bfe94 to your computer and use it in GitHub Desktop.
Cache warmer for Jbuilder-based JSON views
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
json.cache! model.cache_key do | |
json.(model, *%i(id name description created_at super_long_running_helper_method)) | |
json.foo foo # 'bar' | |
# ... | |
end |
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
# Get about a 16-layer stack trace without this. Yes, there's probably a right way, but inheritance! | |
class WarmerView < ActionView::Base | |
def view_cache_dependencies | |
[] | |
end | |
end | |
# A little less secret sauce next time. If you've properly set up caching, the sending the `warm` method will either render your view from the cache, or warm the cache. Add any variables/objects used in your view to the :locals option. | |
class CacheWarmer | |
def warm(models) | |
models.each do |model| | |
view.render(file: path_to_partial, locals: {model: model, foo: 'bar'}) | |
end | |
end | |
private | |
def path_to_partial | |
@path_to_partial ||= 'path_to/_partial.jbuilder' | |
end | |
def view | |
return @view if @view | |
@view = WarmerView.new(view_paths, {}) | |
@view.controller = controller | |
@view | |
end | |
def view_paths | |
controller.view_paths | |
end | |
def controller | |
@controller ||= ApplicationController | |
end | |
def controller_instance | |
@controller_instance ||= controller.new | |
end | |
end |
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
DemoApp::Application.configure do | |
# ... | |
config.action_controller.perform_caching = true | |
config.cache_store = :dalli_store | |
# ... | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment