Skip to content

Commit

Permalink
Refactor Rails module inclusion
Browse files Browse the repository at this point in the history
  • Loading branch information
jaredcwhite committed Nov 14, 2020
1 parent 79af7fc commit 7702e9b
Show file tree
Hide file tree
Showing 3 changed files with 29 additions and 25 deletions.
4 changes: 1 addition & 3 deletions lib/serbea.rb
Original file line number Diff line number Diff line change
Expand Up @@ -32,9 +32,7 @@ class Railtie < ::Rails::Railtie
ActiveSupport.on_load(:action_view) do
require "serbea/rails_support"

app.config.after_initialize do
Serbea::Plugin.initialize_frontmatter
end
ActionController::Base.include Serbea::Rails::FrontmatterControllerActions
end
end
end
Expand Down
48 changes: 27 additions & 21 deletions lib/serbea/rails_support.rb
Original file line number Diff line number Diff line change
@@ -1,34 +1,40 @@
# frozen_string_literal: true

# inspired by https://github.com/haml/haml/blob/main/lib/haml/plugin.rb
module Serbea
# This module makes Serbea work with Rails using the template handler API.
class Plugin
def handles_encoding?; true; end

def compile(template, source)
"self.class.include(Serbea::Helpers);" + Tilt::SerbeaTemplate.new { source }.precompiled_template([])
module Rails
module FrontmatterHelpers
def set_page_frontmatter=(data)
@frontmatter ||= HashWithDotAccess::Hash.new
@frontmatter.update(data)
end
end

def self.call(template, source = nil)
source ||= template.source
module FrontmatterControllerActions
extend ActiveSupport::Concern

new.compile(template, source)
included do
Serbea::TemplateEngine.front_matter_preamble = "self.set_page_frontmatter = local_frontmatter = YAML.load"

before_action { @frontmatter ||= HashWithDotAccess::Hash.new }

helper Serbea::Rails::FrontmatterHelpers
end
end

def self.initialize_frontmatter
if defined?(ApplicationHelper)
Serbea::TemplateEngine.front_matter_preamble = "self.set_page_frontmatter = local_frontmatter = YAML.load"

ApplicationHelper.define_method(:set_page_frontmatter=) do |data|
@frontmatter ||= HashWithDotAccess::Hash.new
@frontmatter.update(data)
end

ApplicationController.before_action { @frontmatter ||= HashWithDotAccess::Hash.new }
class TemplateHandler
def handles_encoding?; true; end

def compile(template, source)
"self.class.include(Serbea::Helpers);" + Tilt::SerbeaTemplate.new { source }.precompiled_template([])
end

def self.call(template, source = nil)
source ||= template.source

new.compile(template, source)
end
end
end
end

ActionView::Template.register_template_handler(:serb, Serbea::Plugin)
ActionView::Template.register_template_handler(:serb, Serbea::Rails::TemplateHandler)
2 changes: 1 addition & 1 deletion lib/version.rb
Original file line number Diff line number Diff line change
@@ -1,3 +1,3 @@
module Serbea
VERSION = "0.8.0"
VERSION = "0.8.1"
end

0 comments on commit 7702e9b

Please sign in to comment.