Sha256: dc096b06b5fa3630f09a5617b547bd7291a196e7c392ae60608255fcdc3ae2d9

Contents?: true

Size: 884 Bytes

Versions: 14

Compression:

Stored size: 884 Bytes

Contents

class AttrExtras::AttrValue
  def initialize(klass, *names)
    @klass, @names = klass, names
  end

  attr_reader :klass, :names
  private :klass, :names

  def apply
    define_readers
    define_equals
    define_hash_identity
  end

  private

  def define_readers
    klass.send(:attr_reader, *names)
  end

  def define_equals
    names = @names  # Make available within block.

    klass.send(:define_method, :==) do |other|
      return false unless other.is_a?(self.class)

      names.all? { |attr| self.public_send(attr) == other.public_send(attr) }
    end
  end

  def define_hash_identity
    names = @names  # Make available within block.

    # Both #eql? and #hash are required for hash identity.

    klass.send(:alias_method, :eql?, :==)

    klass.send(:define_method, :hash) do
      [ self.class, *names.map { |attr| public_send(attr) } ].hash
    end
  end
end

Version data entries

14 entries across 14 versions & 1 rubygems

Version Path
attr_extras-6.2.5 lib/attr_extras/attr_value.rb
attr_extras-6.2.4 lib/attr_extras/attr_value.rb
attr_extras-6.2.3 lib/attr_extras/attr_value.rb
attr_extras-6.2.2 lib/attr_extras/attr_value.rb
attr_extras-6.2.1 lib/attr_extras/attr_value.rb
attr_extras-6.2.0 lib/attr_extras/attr_value.rb
attr_extras-6.1.0 lib/attr_extras/attr_value.rb
attr_extras-5.2.0 lib/attr_extras/attr_value.rb
attr_extras-5.1.0 lib/attr_extras/attr_value.rb
attr_extras-5.0.0 lib/attr_extras/attr_value.rb
attr_extras-4.6.0 lib/attr_extras/attr_value.rb
attr_extras-4.5.0 lib/attr_extras/attr_value.rb
attr_extras-4.4.0 lib/attr_extras/attr_value.rb
attr_extras-4.3.0 lib/attr_extras/attr_value.rb