Sha256: 47304e584a772bc26af32efdae7457431476186c35003a911d07df386d100338

Contents?: true

Size: 1.25 KB

Versions: 20

Compression:

Stored size: 1.25 KB

Contents

require 'erb'
require 'ostruct'

class Sfp::Template < OpenStruct
	# Render given template string, and then return the result
	# @template   template string to be rendered
	#
	def render(template)
		ERB.new(template).result(binding)
	end

	# Render given file, and then save the result back to the file
	# @file   target file that will be rendered
	#
	def render_file(file)
		File.open(file, File::RDWR|File::CREAT) do |f|
			f.flock(File::LOCK_EX)
			result = render(f.read)
			f.rewind
			f.write(result)
			f.flush
			f.truncate(f.pos)
		end
	end

	# Render given template string, and then return the result
	# @template   template string to be rendered
	# @map        a Hash of accessible variables in the template
	#
	def self.render(template, map)
		if map.is_a?(Hash)
			renderer = ::Sfp::Template.new(map)
			renderer.render(template)
		elsif map.is_a?(OpenStruct)
			ERB.new(template).result(map.instance_eval { binding })
		else
			raise Exception, 'A Hash or OpenStruct is required!'
		end
	end

	# Render given file, and then save the result back to the file
	# @file   target file to be rendered
	# @map    a Hash of accessible variables in the template
	#
	def self.render_file(file, map)
		renderer = ::Sfp::Template.new(map)
		renderer.render_file(file)
	end
end

Version data entries

20 entries across 20 versions & 1 rubygems

Version Path
sfpagent-0.4.15 lib/sfpagent/template.rb
sfpagent-0.4.14 lib/sfpagent/template.rb
sfpagent-0.4.13 lib/sfpagent/template.rb
sfpagent-0.4.12 lib/sfpagent/template.rb
sfpagent-0.4.11 lib/sfpagent/template.rb
sfpagent-0.4.10 lib/sfpagent/template.rb
sfpagent-0.4.9 lib/sfpagent/template.rb
sfpagent-0.4.8 lib/sfpagent/template.rb
sfpagent-0.4.7 lib/sfpagent/template.rb
sfpagent-0.4.6 lib/sfpagent/template.rb
sfpagent-0.4.5 lib/sfpagent/template.rb
sfpagent-0.4.4 lib/sfpagent/template.rb
sfpagent-0.4.3 lib/sfpagent/template.rb
sfpagent-0.4.2 lib/sfpagent/template.rb
sfpagent-0.4.1 lib/sfpagent/template.rb
sfpagent-0.4.0 lib/sfpagent/template.rb
sfpagent-0.3.10 lib/sfpagent/template.rb
sfpagent-0.3.9 lib/sfpagent/template.rb
sfpagent-0.3.8 lib/sfpagent/template.rb
sfpagent-0.3.7 lib/sfpagent/template.rb