Class: Fronde::Templater
- Inherits:
-
Object
- Object
- Fronde::Templater
- Defined in:
- lib/fronde/templater.rb
Overview
Insert custom part inside generated HTML files.
Class Method Summary collapse
Instance Method Summary collapse
- #applied? ⇒ Boolean
- #apply ⇒ Object
-
#initialize(source, dom, config = {}) ⇒ Templater
constructor
A new instance of Templater.
- #valid? ⇒ Boolean
Constructor Details
#initialize(source, dom, config = {}) ⇒ Templater
Returns a new instance of Templater.
10 11 12 13 14 15 16 |
# File 'lib/fronde/templater.rb', line 10 def initialize(source, dom, config = {}) @dom = dom @org_file = source @config = { 'type' => 'after' }.merge(config) digest = Digest::MD5.hexdigest(config.to_s) @config['check_line'] = " Fronde Template: #{digest} " end |
Class Method Details
.apply_templates(source) ⇒ Object
59 60 61 62 63 64 65 66 67 68 69 |
# File 'lib/fronde/templater.rb', line 59 def apply_templates(source) public_file = source.pub_file absolute: true dom = File.open(public_file, 'r') { Nokogiri::HTML _1 } changes = Fronde::CONFIG.get('templates', []).map do |config| template = Fronde::Templater.new(source, dom, config) next if !template.valid? || template.applied? template.apply end File.open(public_file, 'w') { dom.write_to _1 } if changes.any? end |
Instance Method Details
#applied? ⇒ Boolean
32 33 34 35 36 37 38 |
# File 'lib/fronde/templater.rb', line 32 def applied? @dom.xpath('//html').children.any? do |child| next false unless child.comment? child.text == @config['check_line'] end end |
#apply ⇒ Object
18 19 20 21 22 23 24 25 26 27 28 29 30 |
# File 'lib/fronde/templater.rb', line 18 def apply # Flag the file for this template html = @dom.xpath('//html').first html.add_child("<!--#{@config['check_line']}-->\n") content = @org_file.format extract_content # Remove source element if necessary to avoid doubling it during # the insert action @config['source'].unlink if @config.has_key? 'source' # Insert new content @dom.css(@config['selector']).map do |element| insert_new_node_at element, content end end |
#valid? ⇒ Boolean
40 41 42 43 44 45 46 47 48 |
# File 'lib/fronde/templater.rb', line 40 def valid? return false unless @config.has_key?('selector') unless @config.has_key?('content') || @config.has_key?('source') return false end check_path end |