Class: SpecForge::Attribute::Template

Inherits:
Attribute
  • Object
show all
Defined in:
lib/spec_forge/attribute/template.rb

Overview

Handles string interpolation with } template syntax

Parses strings containing variable } placeholders and resolves them at runtime by looking up variables, faker calls, or other attribute types.

Examples:

Template interpolation

Template.new("Hello {{ user_name }}!")
# When resolved with user_name = "Alice": "Hello Alice!"

Multiple templates

Template.new("/users/{{ user_id }}/posts/{{ post_id }}")

Constant Summary collapse

REGEX =

Regex pattern for matching variable } placeholders

Returns:

  • (Regexp)
/\{\{\s*[\w.]+\s*\}\}/

Instance Method Summary collapse

Constructor Details

#initializeTemplate

Creates a new template attribute by parsing placeholders



29
30
31
32
33
# File 'lib/spec_forge/attribute/template.rb', line 29

def initialize(...)
  super

  @parsed, @templates = parse_templates
end

Instance Method Details

#valueObject

Returns the interpolated string value

Replaces all } placeholders with their resolved values. If the entire string is a single placeholder, returns the value in its original type (not stringified).

Returns:

  • (Object)

    The interpolated value



44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
# File 'lib/spec_forge/attribute/template.rb', line 44

def value
  value =
    @templates.each_with_object(@parsed.dup) do |(placeholder, attribute), string|
      value = attribute.value

      replacement_value =
        case value
        when Hash, Array
          value.to_json
        else
          value.to_s
        end

      string.gsub!(placeholder, replacement_value)
    end

  if @templates.size == 1
    placeholder, template_value = @templates.first
    value = cast_to_type(value, template_value.value) if @parsed == placeholder
  end

  value
end