Add nanoc/ruledsl/filter.rb

This commit is contained in:
0x1eef 2024-05-02 09:58:30 -03:00
parent 8dd8373116
commit c4593eac90
5 changed files with 39 additions and 23 deletions

3
Rules
View file

@ -7,6 +7,7 @@ require "nanoc-gzip"
require "nanoc-webpack"
require "nanoc-tidy"
require_relative "nanoc/lib/require_rules"
Nanoc::RuleDSL::CompilationRuleContext.prepend(Nanoc::RuleDSL::Filter)
##
# Common vars
@ -37,7 +38,7 @@ end
# /sitemap.xml
compile "/sitemap.xml.erb" do
filter(:erb, locals: {locales:, name_by_id:})
filter(:strip)
filter Proc.new { _1.each_line.reject { |s| s.strip.empty? }.join }
write("/sitemap.xml")
end

View file

@ -11,7 +11,7 @@ text_extensions: [
prune:
auto_prune: true
lib_dirs: ['nanoc/lib']
lib_dirs: ['nanoc/lib', 'nanoc/ruledsl']
output_dir: build/al-quran/
data_sources:

View file

@ -1,11 +0,0 @@
# frozen_string_literal: true
class Nanoc::Filters::MinifyJSON < Nanoc::Filter
require "json"
identifier :minify_json
type text: :text
def run(content, options = {})
JSON.dump(JSON.parse(content))
end
end

View file

@ -1,10 +0,0 @@
# frozen_string_literal: true
class Nanoc::Filters::Strip < Nanoc::Filter
identifier :strip
type text: :text
def run(content, options = {})
content.each_line.reject { _1.strip.empty? }.join
end
end

36
nanoc/ruledsl/filter.rb Normal file
View file

@ -0,0 +1,36 @@
module Nanoc::RuleDSL
module Filter
##
# @example
# compile "/sitemap.xml.erb" do
# filter(:erb)
# filter Proc.new { _1.each_line.reject { |s| s.strip,empty? } }
# write("/sitemap.xml")
# end
#
# @param [Proc, Symbol] fn
# The name of a Symbol, or Proc for an anonymous filter
#
# @param [Hash] options
# Filter options
#
# @return [void]
def filter(fn, options = {})
if Proc === fn
id = random_id
Nanoc::Filter.define(id) { fn.call(_1, _2) }
super(id, options)
else
super(fn, options)
end
end
private
def random_id
name = item.identifier.to_s.gsub(%r|[./\\]|, "_")[/[A-Za-z0-9_]+/]
random = SecureRandom.alphanumeric
"__nanoc_#{name}_#{random}".to_sym
end
end
end