Class: Linked::Item

Inherits:
Object
  • Object
show all
Includes:
Listable
Defined in:
lib/linked/item.rb

Overview

This is the default implementation of a listable object

This class implements a listable value object that wraps an arbitrary value an can be with other listable items.

Instance Attribute Summary collapse

Instance Method Summary collapse

Methods included from Listable

#after, #before, #in_chain?, #initialize_copy, #item, #next, #prev, #take

Methods included from Mutable

#append, #delete, #delete_after, #delete_before, #prepend

Constructor Details

#initialize(value = nil) ⇒ Item

Creates a new item. If a list is given the item will be considered a part of that list and appended to the end of it.



21
22
23
24
# File 'lib/linked/item.rb', line 21

def initialize(value = nil)
  @value = value
  super()
end

Instance Attribute Details

#valueObject

The Item can hold an arbitrary object as its value and it will stay with the item.



15
16
17
# File 'lib/linked/item.rb', line 15

def value
  @value
end

Instance Method Details

#==(other) ⇒ true, false Also known as: eql?

Item equality is solely determined by tha value. If the other object responds to #value, and its value is equal (#==) to this value, the objects are considered equal.



47
48
49
50
# File 'lib/linked/item.rb', line 47

def ==(other)
  return false unless other.respond_to? :value
  value == other.value
end

#freezeself

Freezes the value, as well as making the item itself immutable.



64
65
66
67
# File 'lib/linked/item.rb', line 64

def freeze
  value.freeze
  super
end

#hashInteger

Uses the hash value of the item value.



57
58
59
# File 'lib/linked/item.rb', line 57

def hash
  value.hash
end

#initialize_dup(source) ⇒ item

Calling #dup on an item returns a copy that is no longer connected to the original item chain. The value will also be copied.



31
32
33
34
35
36
37
38
# File 'lib/linked/item.rb', line 31

def initialize_dup(source)
  @value = begin
             source.value.dup
           rescue TypeError
             source.value
           end
  super
end

#inspectString

The default #inspect method becomes very cluttered the moment you start linking objects together. This implementation fixes that and only shows the class name, object id and value (if set).



74
75
76
77
# File 'lib/linked/item.rb', line 74

def inspect
  return yield(self).to_s if block_given?
  value ? object_identifier + " value=#{value.inspect}" : object_identifier
end