Class: Liquidbook::SchemaParser

Inherits:
Object
  • Object
show all
Defined in:
lib/liquidbook/schema_parser.rb

Overview

Extracts and parses schema % blocks from section files

Constant Summary collapse

SCHEMA_REGEX =
/\{%-?\s*schema\s*-?%\}(.*?)\{%-?\s*endschema\s*-?%\}/m

Instance Method Summary collapse

Constructor Details

#initialize(template_source) ⇒ SchemaParser

Returns a new instance of SchemaParser.



10
11
12
# File 'lib/liquidbook/schema_parser.rb', line 10

def initialize(template_source)
  @source = template_source
end

Instance Method Details

#default_blocksObject

Builds default block data from schema



40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
# File 'lib/liquidbook/schema_parser.rb', line 40

def default_blocks
  schema = parse
  blocks = schema.fetch("blocks", [])

  blocks.filter_map do |block|
    next unless block["type"]

    settings = (block["settings"] || []).each_with_object({}) do |s, h|
      h[s["id"]] = s["default"] if s["id"]
    end

    {
      "type" => block["type"],
      "settings" => settings
    }
  end
end

#default_settingsObject

Builds default settings values from schema



30
31
32
33
34
35
36
37
# File 'lib/liquidbook/schema_parser.rb', line 30

def default_settings
  schema = parse
  settings = schema.fetch("settings", [])

  settings.each_with_object({}) do |setting, hash|
    hash[setting["id"]] = setting["default"] if setting["id"]
  end
end

#parseObject



14
15
16
17
18
19
20
21
22
# File 'lib/liquidbook/schema_parser.rb', line 14

def parse
  match = @source.match(SCHEMA_REGEX)
  return {} unless match

  JSON.parse(match[1].strip)
rescue JSON::ParserError => e
  warn "Warning: Failed to parse schema JSON: #{e.message}"
  {}
end

#template_without_schemaObject

Returns the template source with the schema block removed



25
26
27
# File 'lib/liquidbook/schema_parser.rb', line 25

def template_without_schema
  @source.gsub(SCHEMA_REGEX, "").strip
end