Class: Upcastable::UpcastedObject

Inherits:
Object
  • Object
show all
Defined in:
lib/upcastable/upcasted_object.rb

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(object, ancestor, base = object.class) ⇒ UpcastedObject

Returns a new instance of UpcastedObject.



9
10
11
12
13
14
15
# File 'lib/upcastable/upcasted_object.rb', line 9

def initialize(object, ancestor, base = object.class)
  unless base <= ancestor
    raise ArgumentError, "#{ancestor} is not an ancestor of #{base}"
  end
  @object   = object
  @ancestor = ancestor
end

Dynamic Method Handling

This class handles dynamic methods through the method_missing method

#method_missing(m, *args, &block) ⇒ Object



57
58
59
60
61
62
# File 'lib/upcastable/upcasted_object.rb', line 57

def method_missing(m, *args, &block)
  unless @ancestor.method_defined?(m)
    raise NoMethodError, "`#{m}' is not defined in #{@ancestor}"
  end
  @object.send(m, *args, &block)
end

Class Method Details

.define_delegate_method(m) ⇒ Object



3
4
5
6
7
# File 'lib/upcastable/upcasted_object.rb', line 3

def self.define_delegate_method(m)
  define_method(m) do |*args, &block|
    @object.send(m, *args, &block)
  end
end

Instance Method Details

#downcastObject



53
54
55
# File 'lib/upcastable/upcasted_object.rb', line 53

def downcast
  @object
end

#initialize_clone(other) ⇒ Object



21
22
23
# File 'lib/upcastable/upcasted_object.rb', line 21

def initialize_clone(other)
  @object = @object.clone
end

#respond_to?(m, private = false) ⇒ Boolean

Returns:

  • (Boolean)


32
33
34
35
36
37
38
# File 'lib/upcastable/upcasted_object.rb', line 32

def respond_to?(m, private = false)
  if private
    @ancestor.private_method_defined?(m) || @ancestor.method_defined?(m)
  else
    @ancestor.method_defined?(m)
  end
end

#send(m, *args, &block) ⇒ Object



25
26
27
28
29
30
# File 'lib/upcastable/upcasted_object.rb', line 25

def send(m, *args, &block)
  unless @ancestor.method_defined?(m) && @ancestor.private_method_defined?(m)
    raise NoMethodError, "`#{m}' is not defined in #{@ancestor}"
  end
  @object.send(m, *args, &block)
end

#upcast_to(ancestor) ⇒ Object



40
41
42
43
# File 'lib/upcastable/upcasted_object.rb', line 40

def upcast_to(ancestor)
  return self if ancestor == @ancestor
  UpcastedObject.new(@object, ancestor, @ancestor)
end

#upcasted?Boolean

Returns:

  • (Boolean)


49
50
51
# File 'lib/upcastable/upcasted_object.rb', line 49

def upcasted?
  true
end

#upcastingObject



45
46
47
# File 'lib/upcastable/upcasted_object.rb', line 45

def upcasting
  @ancestor
end