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.
- #contains?(obj) ⇒ Boolean
- #context ⇒ Object
-
#dispatch(object, method_name, *args, &block) ⇒ 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
67 68 69 70 |
# File 'lib/casting/context.rb', line 67 def assign(object, role_name) instance_variable_set("@#{role_name}", object) self.assignments << [object, self.role_for(role_name)] end |
#assigned_roles(object) ⇒ Object
Get the roles for the given object
87 88 89 90 91 |
# File 'lib/casting/context.rb', line 87 def assigned_roles(object) assignments.select{|pair| pair.first == object }.map(&:last) end |
#contains?(obj) ⇒ Boolean
72 73 74 |
# File 'lib/casting/context.rb', line 72 def contains?(obj) assignments.map(&:first).include?(obj) end |
#context ⇒ Object
62 63 64 |
# File 'lib/casting/context.rb', line 62 def context self end |
#dispatch(object, method_name, *args, &block) ⇒ Object
Execute the behavior from the role on the specifed object
77 78 79 |
# File 'lib/casting/context.rb', line 77 def dispatch(object, method_name, *args, &block) object.cast(method_name, context.role_implementing(object, method_name), *args, &block) end |
#role_for(name) ⇒ Object
Get the behavior module for the named role. This role constant for special_person is SpecialPerson.
95 96 97 98 99 100 |
# File 'lib/casting/context.rb', line 95 def role_for(name) role_name = name.to_s.gsub(/(?:^|_)([a-z])/) { $1.upcase } self.class.const_get(role_name) rescue NameError Module end |
#role_implementing(object, method_name) ⇒ Object
Find the first assigned role which implements a response for the given method name
82 83 84 |
# File 'lib/casting/context.rb', line 82 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 |