Sha256: 17f411d16bd9e2718bb1e549c48c200dd00d023dc739248d29fe574ac0be08fb

Contents?: true

Size: 1.25 KB

Versions: 2

Compression:

Stored size: 1.25 KB

Contents

# TODO: Write a Entity::attr_collection method that returns an empty array if not set

module Materialize
  class Entity
    include Utils

    class << self

      def wrap(entities_data)
        entities_data.map { |entity_data| new(entity_data) }
      end

      alias :build :new

    end

    def initialize(attributes)
      raise "Attributes must be a hash" unless attributes.is_a?(Hash)

      attributes.each_pair do |key, value|
        value = attempt_entity_conversion(key, value) if collection?(value)
        instance_variable_set("@#{key}", value)
        (class << self; self; end).class_eval do
          attr_reader key.to_sym
        end
      end
    end

    private

    def attempt_entity_conversion(key, value)
      if class_exists?(covert_to_entity_class_name(key))
        klass = Module.const_get(covert_to_entity_class_name(key))
        if value.is_a?(Array)
          klass.wrap(value)
        else
          klass.new(value)
        end
      else
        value
      end
    end

    def collection?(value)
      value.is_a? Enumerable
    end

    def covert_to_entity_class_name(key)
      "Entities::#{base_name_for(key)}"
    end

    def base_name_for(key)
      key.to_s.singularize.split('_').collect(&:capitalize).join
    end

  end
end

Version data entries

2 entries across 2 versions & 1 rubygems

Version Path
materialize-0.4.4 lib/materialize/entity.rb
materialize-0.4.3 lib/materialize/entity.rb