Class: LatoCms::PageField

Inherits:
ApplicationRecord
  • Object
show all
Defined in:
app/models/lato_cms/page_field.rb

Instance Method Summary collapse

Instance Method Details

#as_json(_options = {}) ⇒ Object



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
# File 'app/models/lato_cms/page_field.rb', line 58

def as_json(_options = {})
  result = {
    id: id,
    field_id: field_id,
    field_type: field_type,
    field_name: field_name,
    required: field_required?,
    value: nil,
    attachments: []
  }

  case field_type
  when 'file', 'image'
    attached = files.first
    result[:attachments] = attached ? [attachment_as_json(attached)] : []
  when 'gallery'
    order = value ? (JSON.parse(value) rescue []) : []
    all_files = files.to_a
    ordered = order.any? ? all_files.sort_by { |f| order.index(f.id.to_s) || Float::INFINITY } : all_files
    result[:attachments] = ordered.map { |f| attachment_as_json(f) }
  else
    result[:value] = parsed_value
  end

  result
end

#field_configObject



36
37
38
39
40
# File 'app/models/lato_cms/page_field.rb', line 36

def field_config
  component = LatoCms::TemplateManager.find_component(component_id)
  return nil unless component
  component.dig('fields', field_id)
end

#field_nameObject



46
47
48
# File 'app/models/lato_cms/page_field.rb', line 46

def field_name
  field_config&.dig('name') || field_id.to_s.humanize
end

#field_required?Boolean

Returns:

  • (Boolean)


50
51
52
# File 'app/models/lato_cms/page_field.rb', line 50

def field_required?
  field_config&.dig('required') == true
end

#field_settingsObject



54
55
56
# File 'app/models/lato_cms/page_field.rb', line 54

def field_settings
  field_config&.dig('settings') || {}
end

#field_typeObject



42
43
44
# File 'app/models/lato_cms/page_field.rb', line 42

def field_type
  field_config&.dig('type') || 'string'
end

#parsed_valueObject



15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
# File 'app/models/lato_cms/page_field.rb', line 15

def parsed_value
  return nil if value.blank?

  case field_type
  when 'number'
    value.include?('.') ? value.to_f : value.to_i
  when 'boolean'
    value == 'true'
  when 'json'
    JSON.parse(value) rescue value
  when 'date'
    Date.parse(value) rescue value
  when 'datetime'
    DateTime.parse(value) rescue value
  when 'multiselect'
    JSON.parse(value) rescue [value]
  else
    value
  end
end