Sha256: a8a8e602112a206f4c911260f79779e8b9969ecbbcd0e5225fe9908deae3dd2e

Contents?: true

Size: 1.68 KB

Versions: 1

Compression:

Stored size: 1.68 KB

Contents

# frozen_string_literal: true

require_relative "action"
require_relative "compiler"

module Core
  module Operation
    class Callable
      def initialize(object)
        @object = object
        @actions = []
        @compiled = false
        @compiler = Compiler
      end

      def initialize_copy(...)
        @actions = @actions.clone
        super
      end

      attr_reader :actions

      # [public] Relocates to another object context.
      #
      def relocate(object)
        @object = object
      end

      # [public] Defines an action.
      #
      def action(...)
        @actions << Action.build(...)
        recompile if compiled?
      end

      # [public]
      #
      def action?(name)
        @actions.any? { |action| action.name == name.to_sym }
      end

      # [public] Calls the default operation action with the given arguments.
      #
      def call(object, ...)
        finalize.call(object, ...)
      end

      # [public]
      #
      def invoke(object, name, ...)
        finalize.invoke(object, name, ...)
      end

      # [public] Finalizes the operation.
      #
      def finalize
        compile

        self
      end

      private def compile
        return if compiled?

        instance_eval(@compiler.compile(self, @object), __FILE__, __LINE__ - 1)
        @compiled = true
      end

      private def recompile
        remove_compiled_methods
        compile
      end

      private def compiled?
        @compiled == true
      end

      private def remove_compiled_methods
        return unless compiled?

        singleton_class.remove_method(:call)
        singleton_class.remove_method(:invoke)
        @compiled = false
      end
    end
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
core-operation-0.2.0 lib/core/operation/callable.rb