Sha256: 5e58e474488e3aa20fb431fe88e6a9d241b0d881f5acc7191aa8d2ac749e662c

Contents?: true

Size: 1.23 KB

Versions: 9

Compression:

Stored size: 1.23 KB

Contents

# frozen_string_literal: true

require_relative 'hash_binding'

module Epuber
  class RubyTemplater
    # @return [String]
    #
    attr_accessor :source_text

    # @return [String]
    #
    attr_accessor :file_path

    # @return [Hash]
    #
    attr_accessor :locals

    # @param [String] source
    #
    # @return [self]
    #
    def self.from_source(source, file_path = nil)
      inst = new
      inst.source_text = source
      inst.file_path = file_path
      inst
    end

    # @param [String, File] file
    #
    # @return [self]
    #
    def self.from_file(file)
      file_obj = if file.is_a?(String)
                   File.new(file, 'r')
                 else
                   file
                 end

      from_source(file_obj.read, file_obj.path)
    end


    # ----------------------------------------------------------------------------- #
    # DSL methods


    # @param [Hash] locals
    #
    # @return [self]
    #
    def with_locals(locals = {})
      self.locals = locals
      self
    end

    # @return [String]
    #
    def render
      hash_binding = HashBinding.new(locals)
      eval_string = %(%(#{source_text}))
      eval(eval_string, hash_binding.get_binding) # rubocop:disable Security/Eval
    end
  end
end

Version data entries

9 entries across 9 versions & 1 rubygems

Version Path
epuber-0.11.1 lib/epuber/vendor/ruby_templater.rb
epuber-0.11.0 lib/epuber/vendor/ruby_templater.rb
epuber-0.10.3 lib/epuber/vendor/ruby_templater.rb
epuber-0.10.2 lib/epuber/vendor/ruby_templater.rb
epuber-0.10.1 lib/epuber/vendor/ruby_templater.rb
epuber-0.9.3 lib/epuber/vendor/ruby_templater.rb
epuber-0.9.2 lib/epuber/vendor/ruby_templater.rb
epuber-0.9.1 lib/epuber/vendor/ruby_templater.rb
epuber-0.9.0 lib/epuber/vendor/ruby_templater.rb