Skip to content

Commit

Permalink
added 'expose' to expose a value to the caller from within a handler …
Browse files Browse the repository at this point in the history
…block
  • Loading branch information
tomichj committed Feb 23, 2019
1 parent bb1ded8 commit 6de91b9
Show file tree
Hide file tree
Showing 2 changed files with 46 additions and 0 deletions.
26 changes: 26 additions & 0 deletions lib/operate/command.rb
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ module Operate
# `register` handlers with on().
# `broadcast` results with broadcast().
# `transaction` wraps ActiveRecord transactions.
# `expose` to set a value from the handler block to the caller
#
module Command
include Operate::Pubsub::Publisher
Expand All @@ -17,12 +18,19 @@ def self.included(target)
end

module ClassMethods
attr_reader :command_presenter

# Call will initialize the class with *args and invoke instance method `call` with no arguments
def call(*args, &block)
command = new(*args)
command.evaluate(&block) if block_given?
command.call
end

# def presenter presenter
# @command_presenter = presenter
# self
# end
end

def transaction(&block)
Expand Down Expand Up @@ -51,5 +59,23 @@ def method_missing(method_name, *args, &block)
def respond_to_missing?(method_name, include_private = false)
@caller.respond_to?(method_name, include_private)
end

#
# Expose a value within a handler block to the caller.
# Sets attribute directly if available, or as an instance variable.
#
# RegisterAccount.call(@form) do
# on(:ok) { |user| expose(:user => user) }
# end
#
def expose(presentation_data)
presentation_data.each do |attribute, value|
if @caller.respond_to?("#{attribute}=")
@caller.public_send("#{attribute}=", value)
else
@caller.instance_variable_set("@#{attribute}", value)
end
end
end
end
end
20 changes: 20 additions & 0 deletions spec/lib/operate/command_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,26 @@ module Operate
expect(received).to be_truthy
end
end

describe '#expose' do
context 'from caller without the attribute' do
it 'sets the instance variable on the caller' do
WithConstructorCommand.call('1234') do
on(:ok) { |msg| expose(test_var: msg) }
end
expect(@test_var).to be_present
end
end
context 'from controller with the attribute' do
it 'sets the attribute on the caller' do
@new_test_var = 'fail'
WithConstructorCommand.call('1234') do
on(:ok) { |msg| expose(new_test_var: msg) }
end
expect(@new_test_var).to eq '1234'
end
end
end
end
end

Expand Down

0 comments on commit 6de91b9

Please sign in to comment.