Skip to content

Commit

Permalink
Execute block-based filters within object scope (#142)
Browse files Browse the repository at this point in the history
* Execute block-based filters within object scope

* Switch to using instance_exec
  • Loading branch information
jaredcwhite authored Sep 11, 2020
1 parent 991a0ef commit b0acbf7
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 3 deletions.
14 changes: 11 additions & 3 deletions bridgetown-builder/lib/bridgetown-builder/dsl/liquid.rb
Original file line number Diff line number Diff line change
Expand Up @@ -5,10 +5,18 @@ module Builders
module DSL
module Liquid
def liquid_filter(filter_name, method_name = nil, &block)
block = method(method_name) if method_name.is_a?(Symbol)

builder_self = self
m = Module.new
m.send(:define_method, filter_name, &block)

if block
m.define_method filter_name do |*args|
builder_self.instance_exec(*args, &block)
end
elsif method_name
block = method(method_name)
m.define_method filter_name, &block
end

::Liquid::Template.register_filter(m)

functions << { name: name, filter: m }
Expand Down
10 changes: 10 additions & 0 deletions bridgetown-builder/test/test_filters_dsl.rb
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,10 @@ def build
value = input * multiply_by
add_by ? value + add_by : value
end

liquid_filter "site_config" do |input|
input.to_s + " #{site.root_dir}"
end
end
end

Expand Down Expand Up @@ -48,5 +52,11 @@ class TestFilterDSL < BridgetownUnitTest
result = Liquid::Template.parse(content).render
assert_equal "5 times 10 plus 3 equals 53", result
end

should "allow access to local builder scope" do
content = "root_dir: {{ 'is' | site_config }}"
result = Liquid::Template.parse(content).render
assert_equal "root_dir: is #{@site.root_dir}", result
end
end
end

0 comments on commit b0acbf7

Please sign in to comment.