Sha256: 878590fabf687263d57a4cf9220ebeb8440dfbe7a04e10edd2b4447fcf0add1b

Contents?: true

Size: 1.59 KB

Versions: 1

Compression:

Stored size: 1.59 KB

Contents

require 'nokogiri'
require 'htmlcompressor'

class AhcxTemplateHandler

  ESCAPED_SYMBOLS = {
    '&' => '(|escapeahx|and|)'
  }

  def self.call(template)
    erb = ActionView::Template.registered_template_handler(:erb)
    source = erb.call(template)
    source + ";AhcxTemplateHandler.render(@output_buffer.to_s)"
  end

  def self.node_content(node)
    tag = node.name
    params = {}
    node.attributes.values.each do |node_attribute|
      params[node_attribute.name] = node_attribute.value
    end
    node.children.each do |child_node|
      child_node_tag, child_node_attr = child_node.name.split(':')
      raw = child_node.attributes['raw']
      if raw || (child_node.children.length == 1 && child_node.children.first.name == 'text')
        params[child_node_attr] = child_node.children.to_html(:encoding => 'utf-8')
      else
        attr_value = ''
        child_node.children.each do  |inside_node|
          attr_value += node_content(inside_node)
        end
        params[child_node_attr] = attr_value
      end
    end
    html = Ahc.render(tag, params)
    ESCAPED_SYMBOLS.each do |sym, escaped_sym|
      html.gsub!(escaped_sym, sym)
    end
    html
  end

  def self.render(xml)
    ahcx_source = "<document>#{xml}</document>"
    ESCAPED_SYMBOLS.each do |sym, escaped_sym|
      ahcx_source.gsub!(sym, escaped_sym)
    end
    ahcx = Nokogiri.parse(ahcx_source)
    content = ''
    ahcx.children.first.children.each do |node|
      content += node_content(node)
    end
    compressor = HtmlCompressor::Compressor.new(:remove_intertag_spaces => true)
    compressor.compress(content)
  end

end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
ahc-0.2.5 lib/ahcx_template_handler.rb