Class: Yaml::Converter::StateMachine

Inherits:
Object
  • Object
show all
Defined in:
lib/yaml/converter/state_machine.rb

Overview

Simple state machine to transform Parser::Token sequences into
Markdown lines. Produces:

  • Title lines as plain paragraphs
  • A validation status line (formatted with date)
  • Fenced YAML blocks for YAML content
  • Blockquoted notes (outside fences)

Constant Summary collapse

START_YAML =
"```yaml"
END_YAML =
"```"

Instance Method Summary collapse

Constructor Details

#initialize(options = {}) ⇒ StateMachine

Returns a new instance of StateMachine.

Parameters:

  • options (Hash) (defaults to: {})

Options Hash (options):

  • :validation_status (Symbol) — default: :ok

    Injected validation result (:ok or :fail)

  • :max_line_length (Integer) — default: 70
  • :truncate (Boolean) — default: true
  • :margin_notes (Symbol) — default: :auto
  • :current_date (Date) — default: Date.today


23
24
25
26
27
28
29
30
# File 'lib/yaml/converter/state_machine.rb', line 23

def initialize(options = {})
  @options = options
  @validate_status = options.fetch(:validation_status, :ok)
  @max_len = options.fetch(:max_line_length, 70)
  @truncate = options.fetch(:truncate, true)
  @margin_notes = options.fetch(:margin_notes, :auto)
  @current_date = options[:current_date] || Date.today
end

Instance Method Details

#apply(tokens) ⇒ Array<String>

Apply stateful transformations to tokens and emit Markdown lines.

Parameters:

Returns:

  • (Array<String>)

    Output lines (without trailing newlines)



36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
# File 'lib/yaml/converter/state_machine.rb', line 36

def apply(tokens)
  out = []
  state = :text
  tokens.each do |t|
    case t.type
    when :blank
      out << ""
    when :title
      close_yaml(out, state)
      out << t.text
      out << ""
      state = :text
    when :validation
      close_yaml(out, state)
      date = @current_date.strftime("%d/%m/%Y")
      status_str = ((@validate_status == :ok) ? "OK" : "Fail")
      out << "YAML validation:*#{status_str}* on #{date}"
      out << ""
      state = :text
    when :separator
      # ignore
    when :dash_heading
      close_yaml(out, state)
      out << "# #{t.text}".strip
      out << ""
      state = :text
    when :yaml_line
      state = open_yaml(out, state)
      line = t.text
      if @truncate && line.length > @max_len
        line = line[0...(@max_len - 2)] + ".."
      end
      out << line
    when :note
      if @margin_notes != :ignore
        was_yaml = (state == :yaml)
        close_yaml(out, state)
        out << "" if out.last && out.last != ""
        out << "> NOTE: #{t.text}"
        out << ""
        state = was_yaml ? open_yaml(out, :text) : :text
      end
    else
      # unknown token type: ignore gracefully
    end
  end
  close_yaml(out, state)
  out
end