Class: Rbdux::Store

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

Defined Under Namespace

Classes: Reducer

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.instanceObject



9
10
11
# File 'lib/rbdux/store.rb', line 9

def instance
  @instance ||= Store.new
end

.method_missing(method, *args, &block) ⇒ Object



17
18
19
20
21
# File 'lib/rbdux/store.rb', line 17

def method_missing(method, *args, &block)
  return unless instance.respond_to?(method)

  @instance.send(method, *args, &block)
end

.resetObject



13
14
15
# File 'lib/rbdux/store.rb', line 13

def reset
  @instance = nil
end

Instance Method Details

#add_middleware(middleware) ⇒ Object



32
33
34
35
36
37
# File 'lib/rbdux/store.rb', line 32

def add_middleware(middleware)
  @before_middleware << middleware if middleware.respond_to? :before
  @after_middleware << middleware if middleware.respond_to? :after

  self
end

#dispatch(action) ⇒ Object



60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
# File 'lib/rbdux/store.rb', line 60

def dispatch(action)
  validate_store_container

  previous_state = @store_container.all

  dispatched_action = apply_before_middleware!(action)

  reducers.fetch(action.class.name, []).each do |reducer|
    apply_reducer!(reducer, dispatched_action)
  end

  apply_after_middleware!(previous_state, dispatched_action)

  observers.values.each(&:call)
end

#fetch(state_key = nil, default_value = nil, &block) ⇒ Object



39
40
41
42
43
44
45
46
47
# File 'lib/rbdux/store.rb', line 39

def fetch(state_key = nil, default_value = nil, &block)
  validate_store_container

  if state_key
    @store_container.fetch(state_key, default_value, &block)
  else
    @store_container.all
  end
end

#reduce(action, state_key = nil, &block) ⇒ Object



49
50
51
52
53
54
55
56
57
58
# File 'lib/rbdux/store.rb', line 49

def reduce(action, state_key = nil, &block)
  validate_functional_inputs(block)

  key = action.name

  reducers[key] = [] unless reducers.key?(key)
  reducers[key] << Reducer.new(state_key, block)

  self
end

#subscribe(&block) ⇒ Object



76
77
78
79
80
81
82
83
84
# File 'lib/rbdux/store.rb', line 76

def subscribe(&block)
  validate_functional_inputs(block)

  subscriber_id = SecureRandom.uuid

  observers[subscriber_id] = block

  subscriber_id
end

#unsubscribe(subscriber_id) ⇒ Object



86
87
88
# File 'lib/rbdux/store.rb', line 86

def unsubscribe(subscriber_id)
  observers.delete(subscriber_id)
end

#with_store(store) ⇒ Object

Raises:

  • (ArgumentError)


24
25
26
27
28
29
30
# File 'lib/rbdux/store.rb', line 24

def with_store(store)
  raise ArgumentError, 'You must provide a store.' unless store

  @store_container = store

  self
end