Sha256: 3791e9a655351e9fa8186ac90e863b52fdd9d1dc69a62d64e571a0925b1f369c

Contents?: true

Size: 1.17 KB

Versions: 5

Compression:

Stored size: 1.17 KB

Contents

class Object
  # Get or set state of object.
  #
  # TODO: Would #instance_state be a more appropriate name?
  def object_state(data=nil)
    if data
      instance_variables.each do |iv|
        name = iv.to_s.sub(/^[@]/, '').to_sym
        instance_variable_set(iv, snap[name])
      end
    else
      data = {}
      instance_variables.each do |iv|
        name = iv.to_s.sub(/^[@]/, '').to_sym
        data[name] = instance_variable_get(iv)
      end
      data
    end
  end

  # Replace state of object.
  def replace(data)
    instance_variables.each do |iv|
      name = iv.to_s.sub(/^[@]/, '').to_sym
      instance_variable_set(iv, data[name])
    end
  end
end

class Array
  def object_state(data=nil)
    data ? replace(data) : dup
  end
end

class String
  def object_state(data=nil)
    data ? replace(data) : dup
  end
end

class Hash
  def object_state(data=nil)
    data ? replace(data) : dup
  end
end

class Struct
  def object_state(data=nil)
    if data
      data.each_pair {|k,v| send(k.to_s + "=", v)}
    else
      data = {}
      each_pair{|k,v| data[k] = v}
      data
    end
  end

  def replace(snap)
    snap.each_pair {|k,v| send(k.to_s + "=", v)}
  end
end

Version data entries

5 entries across 5 versions & 1 rubygems

Version Path
facets-2.8.4 lib/core/facets/kernel/object_state.rb
facets-2.8.3 lib/core/facets/kernel/object_state.rb
facets-2.8.2 lib/core/facets/kernel/object_state.rb
facets-2.8.1 lib/core/facets/kernel/object_state.rb
facets-2.8.0 lib/core/facets/kernel/object_state.rb