Sha256: 57527b10a720c8362125e4dd02763fe7a7bbdb498795386369eba0d0827884eb

Contents?: true

Size: 1.2 KB

Versions: 23

Compression:

Stored size: 1.2 KB

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

    after_save :clean_up

    # 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

    def clean_up
      case type
      when :image, :file
        original = changes[type.to_s][0]
        if original && original['identifier']
          Cloudinary::Uploader.destroy(original['identifier'])
        end
      end
    end

  end
end

Version data entries

23 entries across 23 versions & 1 rubygems

Version Path
type_station-0.7.0 app/models/type_station/content.rb
type_station-0.6.0 app/models/type_station/content.rb
type_station-0.5.4 app/models/type_station/content.rb
type_station-0.5.3 app/models/type_station/content.rb
type_station-0.5.2 app/models/type_station/content.rb
type_station-0.5.1 app/models/type_station/content.rb
type_station-0.4.7 app/models/type_station/content.rb
type_station-0.4.6 app/models/type_station/content.rb
type_station-0.4.5 app/models/type_station/content.rb
type_station-0.4.4 app/models/type_station/content.rb
type_station-0.4.3 app/models/type_station/content.rb
type_station-0.4.2 app/models/type_station/content.rb
type_station-0.4.1 app/models/type_station/content.rb
type_station-0.4.0 app/models/type_station/content.rb
type_station-0.3.4 app/models/type_station/content.rb
type_station-0.3.3 app/models/type_station/content.rb
type_station-0.3.2 app/models/type_station/content.rb
type_station-0.3.1 app/models/type_station/content.rb
type_station-0.3.0 app/models/type_station/content.rb
type_station-0.2.3 app/models/type_station/content.rb