Sha256: e65542f764025dc0dc781938aae4caaadea1ce80f503c984c683e09d86476d4e

Contents?: true

Size: 1.6 KB

Versions: 22

Compression:

Stored size: 1.6 KB

Contents

module TypeStation
  class Entity
    include ::Mongoid::Document
    include ::Mongoid::Tree
    include ::Mongoid::Tree::Ordering

    # RELATIONS
    embeds_many :contents, class_name: 'TypeStation::Content', cascade_callbacks: true

    # FIELDS
    field :name, type: Symbol, default: :unnamed

    # CLASS METHODS

    def self.find_by_name(name)
      self.where(name: name).first
    end

    # INSTANT METHODS

    def update_contents(params)
      params.each do |data|
        field, value, type = data[:field].to_sym, data[:value], data[:type].to_sym
        set(field, value, type)
      end

      save
    end

    def content_attributes
      @content_attributes ||= Hash[self.contents.map {|c| [c.name, c]}]
    end

    def get(key)
      if entity_fields?(key)
        self[key]
      elsif content?(key)
        content_attributes[key].get
      else
        nil
      end
    end

    def set(key, value, type = 'text')
      if entity_fields?(key) && !changed.include?(key) #and not changed already
        self[key] = value
      else
        if content?(key)
          content_attributes[key].set value
        else
          contents.build(name: key, type: type).set(value)
        end
      end
    end

    def content?(key)
      content_attributes[key].present?
    end

    def entity_fields?(key)
      entity_fields.include?(key)
    end

    def move_entity(direction)
      case direction.to_sym
      when :move_up
        move_up
      when :move_down
        move_down
      end
    end

    private

    def entity_fields
      @entity_fields ||= self.class.fields.keys.map(&:to_sym)
    end

  end
end

Version data entries

22 entries across 22 versions & 1 rubygems

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