2010-07-23 20:09:54 +00:00
|
|
|
module Locomotive
|
|
|
|
module Liquid
|
2010-06-01 00:06:46 +00:00
|
|
|
module LiquifyTemplate
|
2010-07-23 20:09:54 +00:00
|
|
|
|
2010-06-01 00:06:46 +00:00
|
|
|
def self.included(base)
|
|
|
|
base.extend(ClassMethods)
|
|
|
|
end
|
|
|
|
|
|
|
|
# Store the parsed version of a liquid template into a column in order to increase performance
|
2010-07-23 20:09:54 +00:00
|
|
|
# See http://cjohansen.no/en/rails/liquid_email_templates_in_rails
|
2010-06-01 00:06:46 +00:00
|
|
|
#
|
|
|
|
# class Page
|
|
|
|
# liquify_template :body
|
|
|
|
# end
|
|
|
|
#
|
|
|
|
# page = Page.new :body => '...some liquid tags'
|
|
|
|
# page.template # Liquid::Template
|
2010-07-23 20:09:54 +00:00
|
|
|
#
|
2010-06-01 00:06:46 +00:00
|
|
|
#
|
|
|
|
module ClassMethods
|
|
|
|
|
|
|
|
def liquify_template(source = :value)
|
|
|
|
field :serialized_template, :type => Binary
|
2010-07-20 10:15:53 +00:00
|
|
|
before_validation :store_template
|
2010-07-23 20:09:54 +00:00
|
|
|
|
2010-06-01 00:06:46 +00:00
|
|
|
class_eval <<-EOV
|
|
|
|
def liquify_template_source
|
|
|
|
self.send(:#{source.to_s})
|
|
|
|
end
|
|
|
|
EOV
|
2010-07-23 20:09:54 +00:00
|
|
|
|
2010-06-01 00:06:46 +00:00
|
|
|
include InstanceMethods
|
|
|
|
end
|
|
|
|
|
|
|
|
end
|
2010-07-23 20:09:54 +00:00
|
|
|
|
2010-06-01 00:06:46 +00:00
|
|
|
module InstanceMethods
|
2010-07-23 20:09:54 +00:00
|
|
|
|
2010-06-01 00:06:46 +00:00
|
|
|
def template
|
|
|
|
Marshal.load(read_attribute(:serialized_template).to_s) rescue nil
|
|
|
|
end
|
2010-07-23 20:09:54 +00:00
|
|
|
|
2010-06-01 00:06:46 +00:00
|
|
|
protected
|
2010-07-23 20:09:54 +00:00
|
|
|
|
2010-06-01 00:06:46 +00:00
|
|
|
def store_template
|
|
|
|
begin
|
|
|
|
template = ::Liquid::Template.parse(self.liquify_template_source)
|
|
|
|
self.serialized_template = BSON::Binary.new(Marshal.dump(template))
|
|
|
|
rescue ::Liquid::SyntaxError => error
|
|
|
|
self.errors.add :template, :liquid_syntax_error
|
|
|
|
end
|
|
|
|
end
|
2010-07-23 20:09:54 +00:00
|
|
|
|
|
|
|
end
|
|
|
|
end
|
|
|
|
end
|
|
|
|
end
|