engine/lib/locomotive/liquid/liquify_template.rb

67 lines
1.8 KiB
Ruby

module Locomotive
module Liquid
module LiquifyTemplate
def self.included(base)
base.extend(ClassMethods)
end
# Store the parsed version of a liquid template into a column in order to increase performance
# See http://cjohansen.no/en/rails/liquid_email_templates_in_rails
#
# class Page
# liquify_template :body
# end
#
# page = Page.new :body => '...some liquid tags'
# page.template # Liquid::Template
#
#
module ClassMethods
def liquify_template(source = :value)
field :serialized_template, :type => Binary
before_validation :store_template
class_eval <<-EOV
def liquify_template_source
self.send(:#{source.to_s})
end
EOV
include InstanceMethods
end
end
module InstanceMethods
def template
@template ||= Marshal.load(read_attribute(:serialized_template).to_s) rescue nil
end
protected
def store_template
begin
# puts "self.liquify_template_source = #{self.liquify_template_source.inspect}"
@template = ::Liquid::Template.parse(self.liquify_template_source, { :site => self.site })
@template.root.context.clear
# puts "@template = #{@template.inspect}"
# @template = Locomotive::Liquid::Template.parse(self)
if self.respond_to?(:after_parse_template) # kind of callback
self.send(:after_parse_template)
end
self.serialized_template = BSON::Binary.new(Marshal.dump(@template))
rescue ::Liquid::SyntaxError => error
self.errors.add :template, :liquid_syntax_error
end
end
end
end
end
end