Class: SugarBee::SRB::Compiler

Inherits:
Parslet::Transform
  • Object
show all
Defined in:
lib/sugar_bee/srb/compiler.rb

Overview

Compiles an SRB::Grammar parse tree into an ERB string. tokens: is ALWAYS emitted (even empty → %i[]); tag pairs emit do |c| (the block param is the slot receiver Story 4.4 will use). Self-closing tags emit no block.

Defined Under Namespace

Classes: KvPair

Class Method Summary collapse

Class Method Details

.render_call(name, args) ⇒ Object



49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
# File 'lib/sugar_bee/srb/compiler.rb', line 49

def self.render_call(name, args)
  const = "#{name}Component"
  unless Object.const_defined?(const)
    raise SugarBee::UnknownComponentError, "Unknown component <#{name}>: no #{const} class is defined"
  end

  token_strings, kv_pairs = [], []
  Array(args).each do |item|
    case item
    when KvPair
      unless item.key.match?(/\A[a-z_][a-zA-Z0-9_]*\z/)
        raise SugarBee::ParseError, "Invalid attribute key '#{item.key}': not a valid Ruby keyword argument"
      end
      kv_pairs << "#{item.key}: #{item.code}"
    when Array then token_strings.concat(item)
    else token_strings << item
    end
  end
  kwargs = kv_pairs.empty? ? "" : ", #{kv_pairs.join(", ")}"
  "#{const}.new(tokens: %i[#{token_strings.join(" ")}]#{kwargs})"
end