class Rails::UseCase
UseCase
. See README.
Attributes
Public Class Methods
DSL to define a process step of the UseCase
. You can use if/unless with a lambda in the options to conditionally skip the step. @param name [Symbol] @param options [Hash]
# File lib/rails/use_case.rb, line 39 def self.step(name, options = {}) @steps ||= [] @steps << { name: name.to_sym, options: options } end
DSL to include a behavior. @param mod [Module]
# File lib/rails/use_case.rb, line 47 def self.with(mod) include mod end
Public Instance Methods
@raises [UseCase::Error] When validations failed.
# File lib/rails/use_case.rb, line 93 def break_when_invalid! return true if valid? raise UseCase::Error, errors.full_messages.join(', ') end
Will be called by Callable.call
. @param params [Hash] The arguments for the UseCase
as Hash
so we can auto assign instance variables.
# File lib/rails/use_case.rb, line 24 def call(params) prepare params process successful_outcome rescue UseCase::Error => e failure_outcome e end
Prepare step. Runs automatically before the UseCase
process starts. Sets all params as instance variables and then runs the validations. @param params [Hash]
# File lib/rails/use_case.rb, line 83 def prepare(params) params.each do |key, value| instance_variable_set "@#{key}", value end break_when_invalid! end
Will run the steps of the use case.
# File lib/rails/use_case.rb, line 53 def process self.class.steps.each do |step| next if skip_step?(step) next if send(step[:name]) raise UseCase::Error, "Step #{step[:name]} returned false" end end
Checks whether to skip a step. @param step [Hash]
# File lib/rails/use_case.rb, line 65 def skip_step?(step) if step[:options][:if] proc = step[:options][:if] result = instance_exec(&proc) return true unless result end return false unless step[:options][:unless] proc = step[:options][:unless] result = instance_exec(&proc) return true if result end
Private Instance Methods
@param error [StandardError] @return [UseCase::Outcome] Failure outcome with exception set.
# File lib/rails/use_case.rb, line 138 def failure_outcome(error) Outcome.new( success: false, record: @record, errors: errors, exception: error ) end
Saves the a ActiveRecord object. When the object can't be saved, the validation errors are pushed into the UseCase
errors array and then a UseCase::Error
is raised. @param record [ApplicationModel] Record to save. @raises [UseCase::Error] When record can't be saved.
# File lib/rails/use_case.rb, line 105 def save!(record = nil) if record.nil? record = @record name = :record else name = record.model_name.singular end return false unless record return true if record.save errors.add( name, :invalid, message: record.errors.full_messages.join(', ') ) raise UseCase::Error, "#{record.class.name} is not valid" end
@return [UseCase::Outcome] Successful outcome.
# File lib/rails/use_case.rb, line 127 def successful_outcome Outcome.new( success: true, record: @record, errors: errors ) end