Sha256: ac0aaf0ed47d13cf2556c227fc7bf36bd4233e50ebb346ce35cd3fee7ea213ec

Contents?: true

Size: 1.69 KB

Versions: 1

Compression:

Stored size: 1.69 KB

Contents

class Trailblazer::V2_1::Operation
  def self.Model(model_class, action=nil, find_by_key=nil)
    task = Trailblazer::V2_1::Activity::TaskBuilder::Binary(Model.new)

    extension = Trailblazer::V2_1::Activity::TaskWrap::Merge.new(
      Wrap::Inject::Defaults(
        "model.class"          => model_class,
        "model.action"         => action,
        "model.find_by_key"    => find_by_key
      )
    )

    { task: task, id: "model.build", Trailblazer::V2_1::Activity::DSL::Extension.new(extension) => true }
  end

  class Model
    def call(options, params:,  **)
      builder                 = Model::Builder.new
      options[:model]         = model = builder.call(options, params)
      options["result.model"] = result = Result.new(!model.nil?, {})

      result.success?
    end

    class Builder
      def call(options, params)
        action        = options["model.action"] || :new
        model_class   = options["model.class"]
        find_by_key   = options["model.find_by_key"] || :id
        action        = :pass_through unless %i[new find_by].include?(action)

        send("#{action}!", model_class, params, options["model.action"], find_by_key)
      end

      def new!(model_class, params, *)
        model_class.new
      end

      # Doesn't throw an exception and will return false to divert to Left.
      def find_by!(model_class, params, action, find_by_key, *)
        model_class.find_by(find_by_key.to_sym => params[find_by_key])
      end

      # Call any method on the model class and pass find_by_key, for example find(params[:id]).
      def pass_through!(model_class, params, action, find_by_key, *)
        model_class.send(action, params[find_by_key])
      end
    end
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
trailblazer-future-2.1.0.rc1 lib/trailblazer/v2_1/operation/model.rb