Skip to content

Commit

Permalink
Refactor If()-Macro to use Nested::Decider
Browse files Browse the repository at this point in the history
  • Loading branch information
richardboehme committed Nov 21, 2023
1 parent dcbbab0 commit 1014564
Showing 1 changed file with 34 additions and 11 deletions.
45 changes: 34 additions & 11 deletions lib/trailblazer/macro/if.rb
Original file line number Diff line number Diff line change
Expand Up @@ -5,19 +5,42 @@ def self.If(condition, name: :default, id: Macro.id_for(condition, macro: :If, h
raise ArgumentError, "If() requires a block"
end

option = Trailblazer::Option(condition)
wrap = ->((ctx, flow_options), **circuit_args, &block) {
ctx[:"result.condition.#{name}"] = result =
option.call(ctx, keyword_arguments: ctx.to_hash, **circuit_args)
block_activity, outputs = Macro.block_activity_for(nil, &block)
success_output = outputs.find { |output| output.semantic == :success }
state = Declarative::State(
block_activity: [block_activity, {copy: Trailblazer::Declarative::State.method(:subclass)}],
name: [name, {}],
success_signal: [success_output.signal, {}]
)

if result
block.call
else
[Trailblazer::Activity::Right, [ctx, flow_options]]
end
}
task = Class.new(If) do
extend Macro::Strategy::State
initialize!(state)
end

merge = [
[Nested::Decider.new(condition), id: "If.compute_condition", prepend: "task_wrap.call_task"],
]

task_wrap_extension = Activity::TaskWrap::Extension::WrapStatic.new(extension: Activity::TaskWrap::Extension(*merge))

Activity::Railway.Subprocess(task).merge(
id: id,
extensions: [task_wrap_extension],
)
end
end

Wrap(wrap, id: id, &block)
class If < Macro::Strategy
def self.call((ctx, flow_options), **circuit_options)
name = @state.get(:name)
ctx[:"result.condition.#{name}"] = flow_options[:decision]

if flow_options[:decision]
Activity::Circuit::Runner.(block_activity, [ctx, flow_options], **circuit_options)
else
[@state.get(:success_signal), [ctx, flow_options]]
end
end
end
end

0 comments on commit 1014564

Please sign in to comment.