Class: Kdeploy::Template
- Inherits:
-
Object
- Object
- Kdeploy::Template
- Defined in:
- lib/kdeploy/template/template.rb
Overview
ERB template rendering and upload handler
Class Method Summary collapse
- .create_template_context(variables) ⇒ Object
- .extract_template_identifiers(template_content) ⇒ Object
- .render(template_path, variables = {}) ⇒ Object
- .render_and_upload(executor, template_path, destination, variables = {}) ⇒ Object
- .ruby_keywords ⇒ Object
- .validate_template_variables(template_content, variables) ⇒ Object
Class Method Details
.create_template_context(variables) ⇒ Object
17 18 19 20 21 22 23 24 |
# File 'lib/kdeploy/template/template.rb', line 17 def self.create_template_context(variables) # Use a simple class instead of OpenStruct for better performance context_class = Class.new variables.each do |key, value| context_class.define_method(key) { value } end context_class.new end |
.extract_template_identifiers(template_content) ⇒ Object
53 54 55 56 |
# File 'lib/kdeploy/template/template.rb', line 53 def self.extract_template_identifiers(template_content) identifiers = template_content.scan(/<%=\s*([a-zA-Z_]\w*)/).flatten identifiers.uniq - ruby_keywords end |
.render(template_path, variables = {}) ⇒ Object
10 11 12 13 14 15 |
# File 'lib/kdeploy/template/template.rb', line 10 def self.render(template_path, variables = {}) template_content = File.read(template_path) validate_template_variables(template_content, variables) context = create_template_context(variables) ERB.new(template_content).result(context.instance_eval { binding }) end |
.render_and_upload(executor, template_path, destination, variables = {}) ⇒ Object
26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 |
# File 'lib/kdeploy/template/template.rb', line 26 def self.render_and_upload(executor, template_path, destination, variables = {}) rendered_content = render(template_path, variables) # Create temporary file temp_file = Tempfile.new('kdeploy') begin temp_file.write(rendered_content) temp_file.close # Upload rendered file executor.upload(temp_file.path, destination) ensure temp_file.unlink end end |
.ruby_keywords ⇒ Object
58 59 60 61 |
# File 'lib/kdeploy/template/template.rb', line 58 def self.ruby_keywords %w[alias and begin break case class def defined? do else elsif end ensure false for if in module next nil not or redo rescue retry return self super then true undef unless until when while yield] end |
.validate_template_variables(template_content, variables) ⇒ Object
42 43 44 45 46 47 48 49 50 51 |
# File 'lib/kdeploy/template/template.rb', line 42 def self.validate_template_variables(template_content, variables) required = extract_template_identifiers(template_content) return if required.empty? provided = variables.keys.to_set(&:to_s) missing = required.reject { |name| provided.include?(name) } return if missing.empty? raise ArgumentError, "Missing template variables: #{missing.sort.join(', ')}" end |