Class: Tailmix::Runtime::Action

Inherits:
Object
  • Object
show all
Defined in:
lib/tailmix/runtime/action.rb

Overview

Represents a callable action at runtime that can apply a set of predefined mutations to its context.

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(context, action_name) ⇒ Action

Returns a new instance of Action.

Raises:



10
11
12
13
14
15
# File 'lib/tailmix/runtime/action.rb', line 10

def initialize(context, action_name)
  @context = context
  @action_name = action_name.to_sym
  @definition = context.definition.actions[@action_name]
  raise Error, "Action `#{@action_name}` not found." unless @definition
end

Instance Attribute Details

#contextObject (readonly)

Returns the value of attribute context.



8
9
10
# File 'lib/tailmix/runtime/action.rb', line 8

def context
  @context
end

#definitionObject (readonly)

Returns the value of attribute definition.



8
9
10
# File 'lib/tailmix/runtime/action.rb', line 8

def definition
  @definition
end

Instance Method Details

#applyContext

Applies the mutations to the context immutably, returning a new context.

Returns:

  • (Context)

    A new, modified context instance.



19
20
21
22
23
24
25
# File 'lib/tailmix/runtime/action.rb', line 19

def apply
  new_context = context.dup

  action_on_clone = self.class.new(new_context, @action_name)

  action_on_clone.apply!
end

#apply!Object



27
28
29
30
31
32
33
34
35
36
37
38
39
# File 'lib/tailmix/runtime/action.rb', line 27

def apply!
  # `definition.mutations`  { element_name => [commands] }
  definition.mutations.each do |element_name, commands|
    attributes_object = context.live_attributes_for(element_name)
    next unless attributes_object

    commands.each do |command|
      target_field = attributes_object.public_send(command[:field])
      target_field.public_send(command[:method], command[:payload])
    end
  end
  context
end

#to_hHash

Serializes the action’s definition into a hash for the JS bridge.

Returns:

  • (Hash)


43
44
45
46
47
48
# File 'lib/tailmix/runtime/action.rb', line 43

def to_h
  {
    method: definition.action,
    mutations: definition.mutations
  }
end