module Casting
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
Constants
- VERSION
Public Class Methods
cast_object(object, mod)
click to toggle source
# 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) { || ... }
click to toggle source
# 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)
click to toggle source
# File lib/casting.rb, line 28 def self.uncast_object(object) return unless object.respond_to?(:uncast) object.uncast end