Sha256: 50c47d781af918ed6762fa1caaec0019924583d0c63bf2f7c0c0ee20e0936c48

Contents?: true

Size: 942 Bytes

Versions: 6

Compression:

Stored size: 942 Bytes

Contents

module Zinc
  class Model
    def initialize(hash, exclude: {})
      hash.each do |key, value|
        if exclude.include?(key)
          next
        end

        if respond_to?("#{key}=")
          send("#{key}=", value)
        else
          Zinc.logger.warn "Invalid attribute #{key} specified for #{self.class.name}"
        end
      end
    end

    def to_hash
      instance_variables.map do |instance_variable|
        key   = instance_variable_name(instance_variable)
        value = instance_variable_get(instance_variable)

        if value.is_a?(Array) && value.all? { |element| element.respond_to?(:to_hash) }
          value = value.map(&:to_hash)
        elsif value.respond_to?(:to_hash)
          value = value.to_hash
        end

        value ? [key, value] : nil
      end.compact.to_h
    end

    private

    def instance_variable_name(instance_variable)
      instance_variable.to_s.delete('@')
    end
  end
end

Version data entries

6 entries across 6 versions & 1 rubygems

Version Path
zinc-api-0.0.6 lib/zinc/model.rb
zinc-api-0.0.5 lib/zinc/model.rb
zinc-api-0.0.4 lib/zinc/model.rb
zinc-api-0.0.3 lib/zinc/model.rb
zinc-api-0.0.2 lib/zinc/model.rb
zinc-api-0.0.1 lib/zinc/model.rb