Class: HyperStore::MutatorWrapper

Inherits:
BaseStoreClass show all
Defined in:
lib/hyper-store/mutator_wrapper.rb

Overview

< BasicObject

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Dynamic Method Handling

This class handles dynamic methods through the method_missing method

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

Any method_missing call will create a state and accessor with that name



66
67
68
69
# File 'lib/hyper-store/mutator_wrapper.rb', line 66

def method_missing(name, *args, &block) # rubocop:disable Style/MethodMissing
  (class << self; self end).add_method(nil, name)
  __send__(name, *args, &block)
end

Instance Attribute Details

#__from__Object

Returns the value of attribute __from__.



57
58
59
# File 'lib/hyper-store/mutator_wrapper.rb', line 57

def __from__
  @__from__
end

Class Method Details

.add_method(klass, method_name, opts = {}) ⇒ Object



5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
# File 'lib/hyper-store/mutator_wrapper.rb', line 5

def add_method(klass, method_name, opts = {})
  define_method(:"#{method_name}") do |*args|
    from = opts[:scope] == :shared ? klass.state.__from__ : __from__
    current_value = React::State.get_state(from, method_name.to_s)

    if args.count > 0
      React::State.set_state(from, method_name.to_s, args[0])
      current_value
    else
      React::State.set_state(from, method_name.to_s, current_value)
      React::Observable.new(current_value) do |update|
        React::State.set_state(from, method_name.to_s, update)
      end
    end
  end

  initialize_values(klass, method_name, opts) if initialize_values?(opts)
end

.initialize_values(klass, name, opts) ⇒ Object



28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
# File 'lib/hyper-store/mutator_wrapper.rb', line 28

def initialize_values(klass, name, opts)
  initializer = initializer_proc(opts[:initializer], klass, name) if opts[:initializer]

  if initializer && opts[:block]
    klass.receives(Hyperloop::Application::Boot, initializer) do
      klass.mutate.__send__(:"#{name}", opts[:block].call)
    end
  elsif initializer
    klass.receives(Hyperloop::Application::Boot, initializer)
  elsif opts[:block]
    klass.receives(Hyperloop::Application::Boot) do
      klass.mutate.__send__(:"#{name}", opts[:block].call)
    end
  end
end

.initialize_values?(opts) ⇒ Boolean

Returns:

  • (Boolean)


24
25
26
# File 'lib/hyper-store/mutator_wrapper.rb', line 24

def initialize_values?(opts)
  [:class, :shared].include?(opts[:scope]) && (opts[:initializer] || opts[:block])
end

.new(from) ⇒ Object



59
60
61
62
63
# File 'lib/hyper-store/mutator_wrapper.rb', line 59

def self.new(from)
  instance = allocate
  instance.__from__ = from
  instance
end