Sha256: 4f4a22df06c27b00c02c2b24d1c8defd575f1eed0a37d436ea5bdcfb442d3c30

Contents?: true

Size: 1.05 KB

Versions: 1

Compression:

Stored size: 1.05 KB

Contents

require "active_support/hash_with_indifferent_access"
require "dirty_hashy/version"
require "dirty_attributes"
require "method_map"

class DirtyHashy < HashWithIndifferentAccess

  def self.new(constructor = {}, map_methods = false)
    super(constructor).tap do |instance|
      if map_methods
        instance.extend MethodMap
        instance.dirty_map!
      end
    end
  end

  alias :_regular_writer :regular_writer
  def regular_writer(key, value)
    original_value = changes.key?(key) ? was(key) : self[key]
    if original_value == value
      changes.delete key
    else
      changes[key] = [original_value, value]
    end
    _regular_writer key, value
  end

  def delete(key)
    self[key] = nil
    super
  end

  def changes
    @changes ||= HashWithIndifferentAccess.new
  end

  def changed?(key = nil)
    key.nil? ? !changes.empty? : changes.key?(key)
  end
  alias :dirty? :changed?

  def change(key)
    changes[key] if changed?(key)
  end

  def was(key)
    change(key).first if changed?(key)
  end

  def clean_up!
    changes.clear
    nil
  end

end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
dirty_hashy-0.1.1 lib/dirty_hashy.rb