Class: Farce::ModeManager::SmartRule

Inherits:
Object
  • Object
show all
Includes:
Shareable::Immutable
Defined in:
lib/farce/mode_manager/smart_rule.rb

Overview

Class for converting values based on smart rules.

Class Method Summary collapse

Methods included from Shareable

#initialize, #ractor_shareable?

Class Method Details

.define(klass, mode = nil) ⇒ Class .define(klass) {|value, mode_manager, mode| ... } ⇒ Class .define(klass) { ... } ⇒ Class

Note:

This method must be called from the main ractor.

Allows you to add rules for smart wrapping of specific classes.

Overloads:

  • .define(klass, mode = nil) ⇒ Class

    Examples:

    # Have smart modes use the :make_shareable mode for instances of MyClass
    Farce::ModeManager::SmartRule.define(MyClass, :make_shareable)

    Parameters:

    • klass (Class) —

      the class to define a smart wrapping rule for

    • mode (Symbol) (defaults to: nil) —

      the mode to use when wrapping instances of the class

  • .define(klass) {|value, mode_manager, mode| ... } ⇒ Class

    Examples:

    # Have smart modes use a custom block for instances of MyClass
    Farce::ModeManager::SmartRule.define(MyClass) do |value, mode_manager|
      raise Ractor::Error, "#{value.inspect} cannot be shared" if value.dont_share?
      mode_manager.wrap(value, mode: :make_shareable)
    end

    Parameters:

    • klass (Class) —

      the class to define a smart wrapping rule for

    Yields:

    • (value, mode_manager, mode) —

      The block will be called when wrapping an instance of klass.

    Yield Parameters:

    • value (BasicObject) —

      The value being wrapped.

    • mode_manager (Farce::ModeManager) —

      The mode manager instance.

    • mode (Symbol) —

      The mode to use when wrapping the value, like :smart or :smart_copy.

    Yield Returns:

    • (BasicObject) —

      The shareable version of the value.

  • .define(klass) { ... } ⇒ Class

    Examples:

    Farce::ModeManager::SmartRule.define(MyClass) do
      def smart_copy(value, mode_manager) = mode_manager.wrap(value, mode: :copy)
      def smart_move(value, mode_manager) = mode_manager.wrap(value, mode: :move)
    end

    Yields:

    • block used for defining different methods for different smart modes.

    Yield Receiver:

Returns:

  • (Class) —

    the defined smart rule class.



51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
# File 'lib/farce/mode_manager/smart_rule.rb', line 51

def self.define(klass, mode = nil, &block)
  SMART_RULES.define(klass) do
    if mode
      class_eval <<~RUBY, __FILE__, __LINE__ + 1
        def call(value, mode_manager, _) = mode_manager.wrap(value, mode: #{mode.inspect})
      RUBY
    end

    if block_given?
      if block.arity.zero?
        class_eval(&block)
        SMART_MODES.each { private it if method_defined?(it) }
      else
        define_method(:call, &Ractor.shareable_lambda(&block))
      end
    end
  end
end