Class: EacRubyUtils::Immutable::ArrayAccessor

Inherits:
BaseAccessor show all
Defined in:
lib/eac_ruby_utils/immutable/array_accessor.rb

Instance Method Summary collapse

Methods inherited from BaseAccessor

#duplicate_object

Instance Method Details

#apply(klass) ⇒ Object



10
11
12
13
# File 'lib/eac_ruby_utils/immutable/array_accessor.rb', line 10

def apply(klass)
  apply_singular(klass)
  apply_plural(klass)
end

#apply_plural(klass) ⇒ Object



15
16
17
18
19
20
21
22
23
24
25
# File 'lib/eac_ruby_utils/immutable/array_accessor.rb', line 15

def apply_plural(klass)
  accessor = self
  klass.send(:define_method, ::ActiveSupport::Inflector.pluralize(name)) do |*args|
    case args.count
    when 0 then next accessor.immutable_value_get(self)
    when 1 then next accessor.immutable_value_set(self, args.first)
    else
      raise ::ArgumentError, "wrong number of arguments (given #{args.count}, expected 0..1)"
    end
  end
end

#apply_singular(klass) ⇒ Object



27
28
29
30
31
32
# File 'lib/eac_ruby_utils/immutable/array_accessor.rb', line 27

def apply_singular(klass)
  accessor = self
  klass.send(:define_method, name) do |value|
    accessor.immutable_value_push(self, value)
  end
end

#immutable_value_get(object) ⇒ Object



34
35
36
# File 'lib/eac_ruby_utils/immutable/array_accessor.rb', line 34

def immutable_value_get(object)
  super || []
end

#immutable_value_push(object, value) ⇒ Object



38
39
40
41
42
# File 'lib/eac_ruby_utils/immutable/array_accessor.rb', line 38

def immutable_value_push(object, value)
  duplicate_object(object) do |old_value|
    (old_value || []) + [value]
  end
end

#immutable_value_set(object, value) ⇒ Object



44
45
46
# File 'lib/eac_ruby_utils/immutable/array_accessor.rb', line 44

def immutable_value_set(object, value)
  duplicate_object(object) { |_old_value| value }
end