Module: Casting

Defined in:
lib/casting/context.rb,
lib/casting.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/prepared_delegation.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
  include 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)
    @assignments = []
    assign [some, SomeRole], [thing, OtherRole]
    Thread.current[:context] = self
  end
  attr_reader :some, :thing, :assignments

  module SomeRole; end
  module OtherRole; end
end

In order to use this the objects sent into the context contstructor must ‘include Casting::Client` so that the `cast` method is available to them

Defined Under Namespace

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

Constant Summary collapse

VERSION =
'0.7.2'

Class Method Summary collapse

Class Method Details

.cast_object(object, mod) ⇒ Object

Raises:



20
21
22
23
24
# File 'lib/casting.rb', line 20

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

  object.cast_as(mod)
end

.delegating(assignments) ⇒ Object



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

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



26
27
28
29
30
# File 'lib/casting.rb', line 26

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

  object.uncast
end