Class: ImmutableRecord::Value

Inherits:
Object
  • Object
show all
Defined in:
lib/immutable_record.rb

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(opts) ⇒ Value

Returns a new instance of Value.



16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
# File 'lib/immutable_record.rb', line 16

def initialize (opts)
  missing_keys = self.class::ATTRIBUTES - opts.keys
  if missing_keys.any?
    raise ArgumentError, "Missing attribute(s): #{missing_keys.inspect}"
  end

  extra_keys = opts.keys - self.class::ATTRIBUTES
  if extra_keys.any?
    raise ArgumentError, "Unknown attribute(s): #{extra_keys.inspect}"
  end

  self.class::ATTRIBUTES.each do |attr|
    instance_variable_set("@#{attr}", opts.fetch(attr))
  end
  freeze
end

Class Method Details

.[](opts) ⇒ Object



37
38
39
# File 'lib/immutable_record.rb', line 37

def self.[] (opts)
  new(opts)
end

.nameObject



33
34
35
# File 'lib/immutable_record.rb', line 33

def self.name
  super || to_s
end

Instance Method Details

#==(other) ⇒ Object



55
56
57
# File 'lib/immutable_record.rb', line 55

def == (other)
  other.is_a?(self.class) && __values__ == other.send(:__values__)
end

#clone(opts = {}, &block) ⇒ Object



41
42
43
44
45
# File 'lib/immutable_record.rb', line 41

def clone (opts={}, &block)
  opts = __attributes__.merge(opts)
  opts = opts.merge(block.call(opts)) if block_given?
  self.class.new(opts)
end

#eql?(other) ⇒ Boolean

Returns:

  • (Boolean)


59
60
61
# File 'lib/immutable_record.rb', line 59

def eql? (other)
  hash == other.hash
end

#hashObject



63
64
65
# File 'lib/immutable_record.rb', line 63

def hash
  self.class.hash ^ __attributes__.hash
end

#inspectObject



51
52
53
# File 'lib/immutable_record.rb', line 51

def inspect
  to_s
end

#pretty_print(q) ⇒ Object



67
68
69
70
71
# File 'lib/immutable_record.rb', line 67

def pretty_print (q)
  name = self.class.name
  size = name.length + 1
  q.group(size, "#{name}[", "]") { q.pp __attributes__ }
end

#to_sObject



47
48
49
# File 'lib/immutable_record.rb', line 47

def to_s
  "#{self.class.name}[#{__attributes__.inspect}]"
end