Class: ReactiveArray

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

Overview

A wrapper around an array that calls #react! on any ‘send’. This enables you to react to certain events or changes to the array.

Constant Summary collapse

OPERATORS =
["&", "+", "-", "|", "<=>", "=="]

Instance Method Summary collapse

Constructor Details

#initialize(*args) {|_self| ... } ⇒ ReactiveArray

Returns a new instance of ReactiveArray.

Yields:

  • (_self)

Yield Parameters:

  • _self (ReactiveArray)

    the object that the method was called on



4
5
6
7
# File 'lib/reactive_array.rb', line 4

def initialize(*args)
  @array = Array.new(*args)
  yield self if block_given?
end

Dynamic Method Handling

This class handles dynamic methods through the method_missing method

#method_missing(m, *args, &block) ⇒ Object



29
30
31
32
33
34
# File 'lib/reactive_array.rb', line 29

def method_missing(m, *args, &block)
  x = @array.send(m, *args, &block)
  react!(m)
  # if the @array returned self, we return self too (but we will refer to our wrapper class of course)
  x.equal?(@array) ? self : x
end

Instance Method Details

#react!(m) ⇒ Object

Raises:

  • (NotImplemented)


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

def react!(m)
  raise NotImplemented, "responsibility of subclass"
  # puts "reacting on #{m.inspect}"
end

#to_aObject Also known as: to_ary



14
15
16
17
# File 'lib/reactive_array.rb', line 14

def to_a
  react!(:to_a)
  @array
end

#to_sObject



9
10
11
12
# File 'lib/reactive_array.rb', line 9

def to_s
  react!(:to_s)
  @array.to_s
end