Skip to content

Commit

Permalink
Adding support for swapping out the parse function.
Browse files Browse the repository at this point in the history
This can be used to cache parsed liquid templates, closing chamnap#18
  • Loading branch information
gja committed May 29, 2016
1 parent 9dbd005 commit a8bf77b
Show file tree
Hide file tree
Showing 3 changed files with 19 additions and 2 deletions.
12 changes: 12 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -113,6 +113,18 @@ Check out more [examples](https://github.com/yoolk/liquid-rails/blob/master/spec

It works for any ORMs. The PORO should include `Liquid::Rails::Droppable`. That's all you need to do to have your POROs supported.

### Caching Compiled Templates

In order to cache compiled templates, you may do something like the following in your application.rb (using the excellent `concurrent-ruby` gem):
```
cached_templates = Concurrent::Map.new do |m, template|
Rails.logger.info "Compiling Template"
m[template] = ::Liquid::Template.parse(template)
end
app.config.liquid_rails.render_method = :render!
app.config.liquid_rails.parse_template = lambda { |template| Rails.logger.info("compiling new template"); cached_templates[template] }
```

### RSpec

In spec_helper.rb, you'll need to require the matchers:
Expand Down
2 changes: 1 addition & 1 deletion lib/liquid-rails.rb
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ module Rails
autoload :Drop, 'liquid-rails/drops/drop'
autoload :CollectionDrop, 'liquid-rails/drops/collection_drop'

Configuration = Struct.new(:render_method).new
Configuration = Struct.new(:render_method, :parse_template).new

def self.setup_drop(base)
base.class_eval do
Expand Down
7 changes: 6 additions & 1 deletion lib/liquid-rails/template_handler.rb
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,11 @@ def render_method
(::Rails.env.development? || ::Rails.env.test?) ? :render! : :render
end

def parse(template)
return Configuration.parse_template.call(template) if Configuration.parse_template
Liquid::Template.parse(template)
end

def render(template, local_assigns={})
@view.controller.headers['Content-Type'] ||= 'text/html; charset=utf-8'

Expand All @@ -28,7 +33,7 @@ def render(template, local_assigns={})
assigns['content_for_layout'] = @view.content_for(:layout) if @view.content_for?(:layout)
assigns.merge!(local_assigns.stringify_keys)

liquid = Liquid::Template.parse(template)
liquid = parse(template)
liquid.send(render_method, assigns, filters: filters, registers: { view: @view, controller: @controller, helper: @helper }).html_safe
end

Expand Down

0 comments on commit a8bf77b

Please sign in to comment.