Module: Casting

Defined in:
lib/casting/context.rb,
lib/casting.rb,
lib/casting/enum.rb,
lib/casting/null.rb,
lib/casting/client.rb,
lib/casting/version.rb,
lib/casting/delegation.rb,
lib/casting/super_delegate.rb,
lib/casting/method_consolidator.rb,
lib/casting/missing_method_client.rb,
lib/casting/missing_method_client_class.rb

Overview

This is an experimental implementation of allowing contextual use of behaviors.

This relies on versions of Ruby supporting refinements.

You must include the following module and use it for refinements, and you must set the current context for the thread:

class SomeContext
  using Casting::Context
  extend Casting::Context

  initialize(:some, :thing)
  # doing that defines your constructor but would cause it too look for
  # modules named Some and Thing
  module Some; end
  module Thing; end

  # if you want different module names (why would you?) then you'd need
  # to do all this:
  def initialize(some, thing)
    assign [some, SomeRole], [thing, OtherRole]
    Thread.current[:context] = self
  end
  attr_reader :some, :thing, :assignments

  module SomeRole; end
  module OtherRole; end
end

Defined Under Namespace

Modules: Blank, Client, Context, Empty, Enum, MethodConsolidator, MissingMethodClient, MissingMethodClientClass, Null, SuperDelegate Classes: Delegation, InvalidAttendant, InvalidClientError, MissingAttendant

Constant Summary collapse

VERSION =
"1.0.2"

Class Method Summary collapse

Class Method Details

.cast_object(object, mod) ⇒ Object

Raises:



22
23
24
25
26
# File 'lib/casting.rb', line 22

def self.cast_object(object, mod)
  raise InvalidClientError.new unless object.respond_to?(:cast_as)

  object.cast_as(mod)
end

.delegating(assignments) ⇒ Object



11
12
13
14
15
16
17
18
19
20
# File 'lib/casting.rb', line 11

def self.delegating(assignments)
  assignments.each do |object, mod|
    cast_object(object, mod)
  end
  yield
ensure
  assignments.each do |object, mod|
    uncast_object(object)
  end
end

.uncast_object(object) ⇒ Object



28
29
30
31
32
# File 'lib/casting.rb', line 28

def self.uncast_object(object)
  return unless object.respond_to?(:uncast)

  object.uncast
end