-
Notifications
You must be signed in to change notification settings - Fork 617
Expand file tree
/
Copy pathcurrent_site_metafields_helper.rb
More file actions
125 lines (97 loc) · 2.72 KB
/
current_site_metafields_helper.rb
File metadata and controls
125 lines (97 loc) · 2.72 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
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
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
module Locomotive
module CurrentSiteMetafieldsHelper
def current_site_metafields_schema
@site_metafields_schema ||= @site.metafields_schema.map do |g|
SchemaGroup.new(@site, g)
end.sort_by(&:_position)
end
class SchemaGroup
def initialize(site, attributes)
@site, @attributes = site, attributes
end
def _name
@attributes['name'].downcase.underscore.gsub(' ', '_')
end
alias :dom_id :_name
def model_name
ActiveModel::Name.new(self, nil, _name)
end
def _label
_t(@attributes['label'] || @attributes['name'].humanize)
end
def _position
@attributes['position']
end
def _fields
@fields ||= @attributes['fields'].map do |f|
SchemaField.new(@site, _name, f)
end.sort_by(&:position)
end
def method_missing(name, *args, &block)
if field = _fields.find { |f| f.name == name.to_s }
field.value
else
super
end
end
protected
def _t(value)
value.is_a?(Hash) ? value[I18n.locale.to_s] || value['default'] : value
end
end
class SchemaField
def initialize(site, namespace, attributes)
@site, @namespace, @attributes = site, namespace, attributes
end
def name
t(@attributes['name']).downcase.underscore.gsub(' ', '_')
end
def label
t(@attributes['label'] || @attributes['name'].humanize)
end
def hint
t(@attributes['hint'])
end
def type
@type ||= case (type = @attributes['type'].try(:to_sym))
when :boolean then :toggle
when :text
@attributes['format'] == 'raw' ? :text : :rte
else
type || :string
end
end
def input_options
case type
when :select then { collection: select_collection }
else
{}
end.merge(default_input_options)
end
def select_collection
@attributes['select_options'].map do |name, label|
label = { 'default' => name.humanize } if label.blank?
[(t(label) || name).html_safe, name]
end
end
def position
@attributes['position']
end
def value
t((@site.metafields[@namespace] || {})[name], ::Mongoid::Fields::I18n.locale.to_s)
end
def default_input_options
{
label: self.label,
hint: self.hint.try(:html_safe),
as: self.type,
required: false
}
end
protected
def t(value, locale = I18n.locale.to_s)
value.is_a?(Hash) ? value[locale] || value['default'] : value
end
end
end
end