Class: ForestLiana::SmartActionFormParser

Inherits:
Object
  • Object
show all
Defined in:
app/services/forest_liana/smart_action_form_parser.rb

Class Method Summary collapse

Class Method Details

.extract_fields_and_layout(form) ⇒ Object



3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
# File 'app/services/forest_liana/smart_action_form_parser.rb', line 3

def self.extract_fields_and_layout(form)
  fields = []
  layout = []
  form&.each do |element|
    if element[:type] == 'Layout'
      validate_layout_element(element)
      element[:component] = element[:component].camelize(:lower)
      if %w[page row].include?(element[:component])
        extract = extract_fields_and_layout_for_component(element)
        layout << element
        fields.concat(extract[:fields])
      else
        layout << element
      end
    else
      fields << element
      # frontend rule
      layout << { component: 'input', fieldId: element[:field] }
    end
  end

  { fields: fields, layout: layout }
end

.extract_fields_and_layout_for_component(element) ⇒ Object



27
28
29
30
31
32
33
34
# File 'app/services/forest_liana/smart_action_form_parser.rb', line 27

def self.extract_fields_and_layout_for_component(element)
  # 'page' is in camel case because at this step the 'component' attribute is already convert for the response
  key = element[:component] == 'page' ? :elements : :fields
  extract = extract_fields_and_layout(element[key])
  element[key] = extract[:layout]

  extract
end

.validate_layout_element(element) ⇒ Object



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
# File 'app/services/forest_liana/smart_action_form_parser.rb', line 36

def self.validate_layout_element(element)
  valid_components = %w[Page Row Separator HtmlBlock]
  unless valid_components.include?(element[:component])
    raise ForestLiana::Errors::HTTP422Error.new(
      "#{element[:component]} is not a valid component. Valid components are #{valid_components.join(' or ')}"
    )
  end

  if element[:component] == 'Page'
    unless element[:elements].is_a? Array
      raise ForestLiana::Errors::HTTP422Error.new(
        "Page components must contain an array of fields or layout elements in property 'elements'"
      )
    end

    if element[:elements].any? { |element| element[:component] === 'Page' }
      raise ForestLiana::Errors::HTTP422Error.new('Pages cannot contain other pages')
    end
  end

  if element[:component] == 'Row'
    unless element[:fields].is_a? Array
      raise ForestLiana::Errors::HTTP422Error.new(
        "Row components must contain an array of fields in property 'fields'"
      )
    end

    if element[:fields].any? { |element| element[:type] === 'Layout' }
      raise ForestLiana::Errors::HTTP422Error.new('Row components can only contain fields')
    end
  end
end