Sha256: cf1cdfc71f2ba8c3ae27ae710d46da26e3dfea7ec04edc626b806ad57f8fe1c3

Contents?: true

Size: 828 Bytes

Versions: 1

Compression:

Stored size: 828 Bytes

Contents

require "active_support/hash_with_indifferent_access"
require "dirty_hashy/version"

class DirtyHashy < HashWithIndifferentAccess

  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.0 lib/dirty_hashy.rb