Sha256: f633d1ac84922d3bc48dc54b8c651ad8309b0d3d4cc2bb5b8dfc9b6475f9502e

Contents?: true

Size: 1.03 KB

Versions: 1

Compression:

Stored size: 1.03 KB

Contents

module MiniCamel

  class Dto < OpenStruct

    delegate :to_json, :as_json, :to_hash, :keys, :to_ary, to: :table

    def self.empty
      new
    end

    # ensures that every hash like object is a dto
    def self.build(hash_object)
      hash_object = MultiJson.load(MultiJson.dump(self.new(hash_object)))
      deep_build(hash_object)
    end

    # @private
    def self.deep_build(hash_object)
      case hash_object
      when Hash
        hash_object.each do |k, v|
          hash_object[k] = deep_build(v)
        end
        self.new(hash_object)
      when Array
        hash_object.map{|item| deep_build(item)}
      else
        hash_object
      end
    end

    def initialize(hash = {})
      super
      @table = Hashie::Mash.new(hash)
    end

    def update(data = {})
      modifiable.update(data)
    end

    def [](key)
      fetch(key)
    end

    def fetch(key, default: nil)
      if @table.has_key?(key)
        @table.fetch(key, default)
      else
        return default unless default.nil?
      end
    end

  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
mini_camel-0.5.8 lib/mini_camel/dto.rb