Sha256: c71d3cc07b0fcb52390493319c8dc303a4e83087c61c212908b801a8d1be8e64
Contents?: true
Size: 1.72 KB
Versions: 4
Compression:
Stored size: 1.72 KB
Contents
module DynamicFields module ActiveRecord extend ActiveSupport::Concern included do has_many :dynamic_fields_attributes, class_name: "DynamicFields::Attribute", as: :record end class_methods do def has_dynamic_field(field_name, field_type: DynamicFields::Attribute::DEFAULT_FIELD_TYPE) raise ArgumentError, "#{field_type} is not a valid DynamicFields attribute type. Available values include #{DynamicFields::Attribute::AVAILABLE_ATTRIBUTE_TYPES}" unless DynamicFields::Attribute::AVAILABLE_ATTRIBUTE_TYPES.include?(field_type.to_sym) has_one :"#{field_name}_attribute", -> { where(name: field_name) }, class_name: DynamicFields::Attribute.attribute_class_for_attribute_type(field_type), as: :record, inverse_of: :record, dependent: :destroy define_method(field_name) do if dynamic_field_changes["#{field_name}"] dynamic_field_changes["#{field_name}"].value else dynamic_fields_attributes.find { |attribute| attribute.name == field_name.to_s }&.value end end define_method("#{field_name}=") do |value| # Not checking for `value.blank?` here to account for boolean fields, as false.blank? is true dynamic_field_changes["#{field_name}"] = if value == "" || value.nil? DynamicFields::Changes::Delete.new(field_name, self) else DynamicFields::Changes::CreateOrUpdate.new(value, field_name, field_type, self) end end after_save { dynamic_field_changes[field_name.to_s]&.save } end end def dynamic_field_changes @dynamic_field_changes ||= {} end def reload(*) super.tap { @dynamic_field_changes = nil } end end end
Version data entries
4 entries across 4 versions & 1 rubygems