module Casting::Context::InstanceMethods
Public Instance Methods
assign(object, role_name)
click to toggle source
Keep track of objects and their behaviors
# File lib/casting/context.rb, line 68 def assign(object, role_name) instance_variable_set("@#{role_name}", object) assignments << [object, role_for(role_name)] end
assigned_roles(object)
click to toggle source
Get the roles for the given object
# File lib/casting/context.rb, line 92 def assigned_roles(object) assignments.select { |pair| pair.first == object }.map(&:last) end
assignments()
click to toggle source
# File lib/casting/context.rb, line 63 def assignments @assignments ||= [] end
contains?(obj)
click to toggle source
# File lib/casting/context.rb, line 73 def contains?(obj) assignments.map(&:first).include?(obj) end
context()
click to toggle source
# File lib/casting/context.rb, line 59 def context self end
dispatch(object, method_name, ...)
click to toggle source
Execute the behavior from the role on the specifed object
# File lib/casting/context.rb, line 78 def dispatch(object, method_name, ...) if object.respond_to?(:cast) object.cast(method_name, context.role_implementing(object, method_name), ...) else Casting::Delegation.prepare(method_name, object).to(role_implementing(object, method_name)).with(...).call end end
role_for(name)
click to toggle source
Get the behavior module for the named role. This role constant for special_person is SpecialPerson.
# File lib/casting/context.rb, line 100 def role_for(name) role_name = name.to_s.gsub(/(?:^|_)([a-z])/) { $1.upcase } self.class.const_get(role_name) rescue NameError Module.new end
role_implementing(object, method_name)
click to toggle source
Find the first assigned role which implements a response for the given method name
# File lib/casting/context.rb, line 87 def role_implementing(object, method_name) assigned_roles(object).find { |role| role.method_defined?(method_name) } || raise(NoMethodError, "unknown method '#{method_name}' expected for #{object}") end