Module: Casting::Context::InstanceMethods
- Defined in:
- lib/casting/context.rb
Instance Method Summary collapse
-
#assign(object, role_name) ⇒ Object
Keep track of objects and their behaviors.
-
#assigned_roles(object) ⇒ Object
Get the roles for the given object.
- #assignments ⇒ Object
- #contains?(obj) ⇒ Boolean
- #context ⇒ Object
-
#dispatch(object, method_name) ⇒ Object
Execute the behavior from the role on the specifed object.
-
#role_for(name) ⇒ Object
Get the behavior module for the named role.
-
#role_implementing(object, method_name) ⇒ Object
Find the first assigned role which implements a response for the given method name.
Instance Method Details
#assign(object, role_name) ⇒ Object
Keep track of objects and their behaviors
68 69 70 71 |
# 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) ⇒ Object
Get the roles for the given object
92 93 94 95 96 |
# File 'lib/casting/context.rb', line 92 def assigned_roles(object) assignments.select { |pair| pair.first == object }.map(&:last) end |
#assignments ⇒ Object
63 64 65 |
# File 'lib/casting/context.rb', line 63 def assignments @assignments ||= [] end |
#contains?(obj) ⇒ Boolean
73 74 75 |
# File 'lib/casting/context.rb', line 73 def contains?(obj) assignments.map(&:first).include?(obj) end |
#context ⇒ Object
59 60 61 |
# File 'lib/casting/context.rb', line 59 def context self end |
#dispatch(object, method_name) ⇒ Object
Execute the behavior from the role on the specifed object
78 79 80 81 82 83 84 |
# 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) ⇒ Object
Get the behavior module for the named role. This role constant for special_person is SpecialPerson.
100 101 102 103 104 105 |
# 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) ⇒ Object
Find the first assigned role which implements a response for the given method name
87 88 89 |
# 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 |