Class: Uniword::Template::VariableResolver
- Inherits:
-
Object
- Object
- Uniword::Template::VariableResolver
- Defined in:
- lib/uniword/template/variable_resolver.rb
Overview
Resolves variable expressions to values from data context.
Handles nested property access (e.g., “chapter.number”) and conditional evaluation. Works with both Hash and object data sources.
Responsibility: Variable resolution only Single Responsibility Principle: Does NOT parse, render, or validate
Instance Method Summary collapse
-
#evaluate(condition) ⇒ Boolean
Evaluate conditional expression.
-
#initialize(data, context = {}) ⇒ VariableResolver
constructor
Initialize resolver with data context.
-
#resolve(expression) ⇒ Object
Resolve variable expression to value.
Constructor Details
#initialize(data, context = {}) ⇒ VariableResolver
Initialize resolver with data context
36 37 38 39 |
# File 'lib/uniword/template/variable_resolver.rb', line 36 def initialize(data, context = {}) @data = data @context = context end |
Instance Method Details
#evaluate(condition) ⇒ Boolean
Evaluate conditional expression
Supports:
-
Simple truthiness: “has_annexes”
-
Comparisons: “count > 5”, “status == ‘active’”
75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 |
# File 'lib/uniword/template/variable_resolver.rb', line 75 def evaluate(condition) return false if condition.nil? || condition.empty? # Simple variable existence/truthiness check if condition.match?(/^\w+(\.\w+)*$/) value = resolve(condition) return !!value end # Comparison operators - order matters, check >= and <= before > and < match = condition.match(/(.+?)\s*(>=|<=|==|!=|>|<)\s*(.+)/) if match left_expr = match[1].strip operator = match[2] right_expr = match[3].strip left = resolve(left_expr) right = parse_literal(right_expr) evaluate_comparison(left, operator, right) else false end end |
#resolve(expression) ⇒ Object
49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 |
# File 'lib/uniword/template/variable_resolver.rb', line 49 def resolve(expression) return nil if expression.nil? || expression.empty? parts = expression.to_s.split(".") # Start with root data value = @data # Navigate through each part parts.each do |part| break if value.nil? value = navigate_property(value, part) end value end |