Sha256: 353e5cfb371f94b72448a73c305e04f704a475742b2638a4269f3d3209cad0c5

Contents?: true

Size: 965 Bytes

Versions: 1

Compression:

Stored size: 965 Bytes

Contents

module TypeStation
  class Content
    include ::Mongoid::Document
    include ::Mongoid::Attributes::Dynamic

    TYPES = [:text, :html, :image, :file, :select, :multiple_select]

    # RELATIONS

    embedded_in :page

    # FIELDS
    field :name, type: Symbol
    field :type, type: Symbol, default: TYPES.first

    # VALIDATIONS

    validates :name, presence: true, uniqueness: { scope: :type }
    validates :type, presence: true

    # INSTANT METHODS

    def get
      self[self.type]
    end

    def set(value)
      self[self.type] = convert(value)
    end

    private

    def convert(value)
      case type
      when :multiple_select
        convert_to_array(value)
      else
        value
      end
    end

    def convert_to_array(value)
      if value.is_a?(String)
        value.split(',').map(&:strip)
      elsif value.is_a?(Array)
        value
      else
        raise 'Dont know who to covert value to array'
      end
    end
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
type_station-0.1.3 app/models/type_station/content.rb