From ce705d32dac9b4cd27b66c54e22045010d1874ac Mon Sep 17 00:00:00 2001 From: Faizaan Gagan Date: Sun, 23 May 2021 23:11:46 +0530 Subject: [PATCH] simple framework to compute field attributes at runtime --- lib/custom_wizard/field.rb | 90 +++++++++++++++++--------------------- 1 file changed, 41 insertions(+), 49 deletions(-) diff --git a/lib/custom_wizard/field.rb b/lib/custom_wizard/field.rb index 7912251f..2d987d9c 100644 --- a/lib/custom_wizard/field.rb +++ b/lib/custom_wizard/field.rb @@ -3,67 +3,59 @@ class CustomWizard::Field include ActiveModel::SerializerSupport - def self.attributes - %i{ - raw - id - index - type - step - required - value - description - image - key - validations - min_length - max_length - char_counter - file_types - format - limit - property - content + def self.attribute_map + { + raw: [], + id: [:serializable], + index: [:accessible, :serializable], + type: [:serializable], + step: [:accessible], + required: [:serializable], + value: [:serializable], + description: [:serializable], + image: [:serializable], + key: [], + validations: [:serializable], + min_length: [], + max_length: [:serializable], + char_counter: [:serializable], + file_types: [:serializable], + format: [:serializable], + limit: [:serializable], + property: [:serializable], + content: [:serializable], + # label is excluded so that it isn't initialized and the value + # returned by `label` method is used for serialization + label: [:excluded, :serializable] } end + def self.all_attributes + attribute_map.keys + end + + def self.included_attributes + all_attributes - excluded_attributes + end + + def self.type_attributes(type) + attribute_map.map { |attribute, props| props.include?(type.to_sym) ? attribute : nil }.compact + end + def self.accessible_attributes - %i{ - index - step - } + type_attributes(:accessible) end def self.excluded_attributes - %i{ - label - } + type_attributes(:excluded) end def self.readonly_attributes - attributes - accessible_attributes - excluded_attributes + included_attributes - accessible_attributes end def self.serializable_attributes - %i{ - id - index - type - required - value - label - placeholder - description - image - file_types - format - limit - property - content - validations - max_length - char_counter - } + type_attributes(:serializable) end attr_reader *readonly_attributes @@ -71,7 +63,7 @@ class CustomWizard::Field def initialize(attrs) attrs.each do |k, v| - if self.singleton_class.attributes.include?(k.to_sym) + if self.singleton_class.included_attributes.include?(k.to_sym) instance_variable_set("@#{k}", v) end end