Sha256: 91d2244022960b420a87facc3546243060f45475e2fed45b8c50b0eb5363bf79

Contents?: true

Size: 1.46 KB

Versions: 1

Compression:

Stored size: 1.46 KB

Contents

require 'delegate'

module Husky

  class Entity < SimpleDelegator

    class << self

      def wrap(items)
        items.map { |item| new(item) }
      end

      def new_from_hash(hash)
        raise hash_error(hash) unless hash.is_a? Hash
        instance = allocate
        instance.initialize_from_hash(hash)
        instance
      end

      def new_basic
        instance = allocate
        instance.initialize_basic
        instance
      end

      private

      def hash_error(hash)
        "Entity#initialize_from_hash expects a hash as an argument, and you provided a #{hash.class.name} (#=> #{hash})."
      end

    end

    attr_reader :object

    def initialize(object)
      @object = object
      super
    end

    def initialize_basic
    end

    def initialize_from_hash(post_data)
      post_data.each_pair do |key, value|
        instance_variable_set("@#{key}", value)
      end

      post_data.each_pair do |key, value|
        self.class.send(:define_method, key) do
          instance_variable_get("@#{key}")
        end
      end
    end

    def set_basic_attributes_from_hash(hash)
      hash.each_pair do |key, value|
        unless value.respond_to? :each
          instance_variable_set("@#{key}", value)
        end
      end

      hash.each_pair do |key, value|
        unless value.respond_to? :each
          self.class.send(:define_method, key) do
            instance_variable_get("@#{key}")
          end
        end
      end
    end

  end

end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
husky-0.4.5 lib/husky/entity.rb