Module: Casting::Context::InstanceMethods

Defined in:
lib/casting/context.rb

Instance Method Summary collapse

Instance Method Details

#assign(object, role_name) ⇒ Object

Keep track of objects and their behaviors



74
75
76
77
# File 'lib/casting/context.rb', line 74

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



98
99
100
101
102
# File 'lib/casting/context.rb', line 98

def assigned_roles(object)
  assignments.select{|pair|
    pair.first == object
  }.map(&:last)
end

#assignmentsObject



69
70
71
# File 'lib/casting/context.rb', line 69

def assignments
  @assignments ||= []
end

#contains?(obj) ⇒ Boolean

Returns:

  • (Boolean)


79
80
81
# File 'lib/casting/context.rb', line 79

def contains?(obj)
  assignments.map(&:first).include?(obj)
end

#contextObject



65
66
67
# File 'lib/casting/context.rb', line 65

def context
  self
end

#dispatch(object, method_name) ⇒ Object

Execute the behavior from the role on the specifed object



84
85
86
87
88
89
90
# File 'lib/casting/context.rb', line 84

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.



106
107
108
109
110
111
# File 'lib/casting/context.rb', line 106

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



93
94
95
# File 'lib/casting/context.rb', line 93

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