summaryrefslogtreecommitdiff
path: root/lib/xml/kit/template.rb
blob: 163b14f555e78fbcc69e4ec461be727358a5eebd (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
# frozen_string_literal: true

module Xml
  module Kit
    class Template
      TEMPLATES_DIR = Pathname.new(File.join(__dir__, 'templates/'))

      attr_reader :target

      def initialize(target)
        @target = target
      end

      # Returns the compiled template as a [String].
      #
      # @param options [Hash] The options hash to pass to the template engine.
      def to_xml(options = {})
        template.render(target, options)
      end

      private

      def template_path
        return target.template_path if target.respond_to?(:template_path)

        TEMPLATES_DIR.join(template_name)
      end

      def template_name
        "#{target.class.name.split('::').last.underscore}.builder"
      end

      def template
        @template ||= Tilt.new(template_path.to_s)
      end
    end
  end
end