Class: Reaction::Action

Inherits:
Object
  • Object
show all
Includes:
HasErrors, HasParams
Defined in:
lib/reaction/action.rb

Instance Method Summary collapse

Methods included from HasParams

included, #param, #params, #raw_param, #set_param, #set_params, #typed_params

Methods included from HasErrors

#errors, included

Constructor Details

#initialize(params = {}, meta = {}) ⇒ Action

meta isn’t used by default, but it is supported for use cases where you need to attach metadata to parameters, such as who or what set the attribute. For example, Paid currently has a flow like:

action = Action.new(request.params, via: :request)
action.set_params(account: api_key., via: :api_key)

Which allows us to use a validator to define who can set various attributes. Specifically, we limit certain attributes from being set by the request so end users can’t set params that we don’t expect them to set.



19
20
21
# File 'lib/reaction/action.rb', line 19

def initialize(params = {}, meta = {})
  set_params(params, meta)
end

Instance Method Details

#cleanupObject



51
52
53
54
55
56
57
58
# File 'lib/reaction/action.rb', line 51

def cleanup
  self.class.types.each do |name, type|
    type.cleanup
  end
  self.class.validators.each do |name, validator|
    validator.cleanup
  end
end

#invokeObject



23
24
25
26
27
28
# File 'lib/reaction/action.rb', line 23

def invoke
  validate!
  ret = perform
ensure
  cleanup
end

#performObject



30
31
32
# File 'lib/reaction/action.rb', line 30

def perform
  # Implement this for your action
end

#validate!Object



34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
# File 'lib/reaction/action.rb', line 34

def validate!
  params.each do |name, value|
    unless self.class.class_for_type(name)
      errors.add(name, 'is not a valid parameter.')
    end
  end
  self.class.types.each do |name, type|
    type.validate_each(self, name, raw_param(name))
  end
  self.class.validators.each do |name, validator|
    validator.validate_each(self, name, raw_param(name))
  end
  if errors.any?
    raise ArgumentError.new("Validations failed: #{errors.full_messages.join(',')}")
  end
end