Sha256: 08143d929885c6aeea8ac0d9323fcd1481c2d752d5325973d10cfabfa6675338

Contents?: true

Size: 1.24 KB

Versions: 7

Compression:

Stored size: 1.24 KB

Contents

module CustomAttributes
  module ActsAsCustomValue
    extend ActiveSupport::Concern

    included do
    end

    module ClassMethods
      def acts_as_custom_value(_options = {})
        include CustomAttributes::ActsAsCustomValue::InstanceMethods

        belongs_to :custom_field
        belongs_to :customizable, polymorphic: true

        after_save :custom_field_after_save_custom_value
      end
    end

    module InstanceMethods
      def initialize(attributes = nil, *args)
        super
        if new_record? && custom_field && !attributes.key?(:value)
          self.value ||= custom_field.default
        end
      end

      def value
        return read_attribute(:value) if new_record?

        read_attribute(:value) || custom_field.try(:default)
      end

      def true?
        value == '1'
      end

      def visible?
        custom_field.visible?
      end

      def required?
        custom_field.is_required?
      end

      def to_s
        value.to_s
      end

      private

      # Calls CustomAttributes::FieldType.after_save_custom_value
      # Thus extendable by FieldType
      # Default is: do nothing
      def custom_field_after_save_custom_value
        custom_field.after_save_custom_value(self)
      end
    end
  end
end

Version data entries

7 entries across 7 versions & 1 rubygems

Version Path
create_custom_attributes-0.5.12 lib/custom_attributes/acts_as/acts_as_custom_value.rb
create_custom_attributes-0.5.11 lib/custom_attributes/acts_as/acts_as_custom_value.rb
create_custom_attributes-0.5.10 lib/custom_attributes/acts_as/acts_as_custom_value.rb
create_custom_attributes-0.5.9 lib/custom_attributes/acts_as/acts_as_custom_value.rb
create_custom_attributes-0.5.8 lib/custom_attributes/acts_as/acts_as_custom_value.rb
create_custom_attributes-0.5.7 lib/custom_attributes/acts_as/acts_as_custom_value.rb
create_custom_attributes-0.5.6 lib/custom_attributes/acts_as/acts_as_custom_value.rb