0
0
Fork 1
Spiegel von https://github.com/paviliondev/discourse-custom-wizard.git synchronisiert 2024-11-26 02:50:28 +01:00
discourse-custom-wizard/lib/custom_wizard/custom_field.rb

92 Zeilen
2 KiB
Ruby

2020-10-20 07:40:23 +02:00
class ::CustomWizard::CustomField
2020-10-17 03:31:07 +02:00
include HasErrors
include ActiveModel::Serialization
2020-10-20 07:40:23 +02:00
CLASSES ||= ["topic", "group", "category", "post"]
SERIALIZERS ||= ["topic_view", "topic_list_item", "post", "basic_category"]
TYPES ||= ["string", "boolean", "integer", "json"]
2020-10-20 07:40:23 +02:00
ATTRS ||= ["name", "klass", "type", "serializers"]
2020-10-17 03:31:07 +02:00
KEY ||= "custom_wizard_custom_fields"
def initialize(data)
data = data.with_indifferent_access
ATTRS.each do |attr|
self.class.class_eval { attr_accessor attr }
send("#{attr}=", data[attr]) if data[attr].present?
end
end
def save
validate
if valid?
data = {}
name = nil
ATTRS.each do |attr|
value = send(attr)
if attr == 'name'
2020-10-20 07:40:23 +02:00
name = value.parameterize(separator: '_')
2020-10-17 03:31:07 +02:00
else
data[attr] = value
end
end
PluginStore.set(KEY, name, data)
else
false
end
end
def validate
ATTRS.each do |attr|
value = send(attr)
2020-10-20 07:40:23 +02:00
if value.blank?
add_error("Attribute required: #{attr}")
next
end
if attr == 'klass' && CLASSES.exclude?(value)
add_error("Unsupported class: #{value}")
end
if attr == 'serializers' && value.present? && (SERIALIZERS & value).empty?
2020-10-20 07:40:23 +02:00
add_error("Unsupported serializer: #{value}")
end
if attr == 'type' && TYPES.exclude?(value)
add_error("Unsupported type: #{value}")
end
if attr == 'name' && value.length < 3
add_error("Field name is too short")
end
2020-10-17 03:31:07 +02:00
end
end
def valid?
errors.blank?
end
def self.list
PluginStoreRow.where(plugin_name: KEY)
.map do |record|
data = JSON.parse(record.value)
data[:name] = record.key
self.new(data)
end
end
def self.list_by(attr, value)
self.list.select do |cf|
if attr == 'serializers'
cf.send(attr).include?(value)
else
cf.send(attr) == value
end
end
end
2020-10-17 03:31:07 +02:00
end