File: index.html.md

package info (click to toggle)
ruby-dry-equalizer 0.3.0-2
  • links: PTS, VCS
  • area: main
  • in suites: bookworm, bullseye, forky, trixie
  • size: 172 kB
  • sloc: ruby: 400; makefile: 4
file content (86 lines) | stat: -rw-r--r-- 1,814 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
---
title: Introduction & Usage
description: Simple mixin providing equality, equivalence and inspection methods
layout: gem-single
order: 5
type: gem
name: dry-equalizer
---

`dry-equalizer` is a simple mixin that can be used to add instance variable based equality, equivalence and inspection methods to your objects.

### Usage

```ruby
require 'dry-equalizer'

class GeoLocation
  include Dry::Equalizer(:latitude, :longitude)

  attr_reader :latitude, :longitude

  def initialize(latitude, longitude)
    @latitude, @longitude = latitude, longitude
  end
end

point_a = GeoLocation.new(1, 2)
point_b = GeoLocation.new(1, 2)
point_c = GeoLocation.new(2, 2)

point_a.inspect    # => "#<GeoLocation latitude=1 longitude=2>"

point_a == point_b           # => true
point_a.hash == point_b.hash # => true
point_a.eql?(point_b)        # => true
point_a.equal?(point_b)      # => false

point_a == point_c           # => false
point_a.hash == point_c.hash # => false
point_a.eql?(point_c)        # => false
point_a.equal?(point_c)      # => false
```

### Configuration options

#### `inspect`

Use `inspect` option to skip `#inspect` method overloading:

```ruby
class Foo
  include Dry::Equalizer(:a, inspect: false)

  attr_reader :a, :b

  def initialize(a, b)
    @a, @b = a, b
  end
end

Foo.new(1, 2).inspect
# => "#<Foo:0x00007fbc9c0487f0 @a=1, @b=2>"
```

#### `immutable`

For objects that are immutable it doesn't make sense to calculate `#hash` every time it's called. To memoize hash use `immutable` option:

```ruby
class ImmutableHash
  include Dry::Equalizer(:foo, :bar, immutable: true)

  attr_accessor :foo, :bar

  def initialize(foo, bar)
    @foo, @bar = foo, bar
  end
end

obj = ImmutableHash.new('foo', 'bar')
old_hash = obj.hash
obj.foo = 'changed'
old_hash == obj.hash
# => true
```