public
Last active

  • Download Gist
module_inclusion.rb
Ruby
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54
module Wrapped
# This is the wrapper class
class Wrapper
attr_accessor :content
 
def initialize(content)
@content = content
end
 
def content_value
@content.value
end
end
 
# So that module can be inluded as well as extended
def self.included(base)
base.extend self
end
 
def new(*args)
Wrapper.new(super)
end
end
 
 
class Content
 
include Wrapped
 
attr_accessor :value
 
def initialize(default)
@value = default
end
 
end
 
class ComplicatedContent < Content
alias_method :simple_value, :value
def value
simple_value.reverse
end
end
 
c = Content.new("a_to_z")
puts "Content.new(\"a_to_z\"):"
puts "- class = #{c.class}"
puts "- value = #{c.content_value}"
 
c = ComplicatedContent.new("a_to_z")
puts "ComplicatedContent.new(\"a_to_z\"):"
puts "- class = #{c.class}"
puts "- value = #{c.content_value}"
singleton_super_version.rb
Ruby
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43
class Wrapper
attr_accessor :content
 
def initialize(content)
@content = content
end
 
def content_value
@content.value
end
end
 
class Content
attr_accessor :value
 
class << self
def new(*args)
Wrapper.new(super)
end
end
 
def initialize(default)
@value = default
end
 
end
 
class ComplicatedContent < Content
alias_method :simple_value, :value
def value
simple_value.reverse
end
end
 
c = Content.new("a_to_z")
puts "Content.new(\"a_to_z\"):"
puts "- class = #{c.class}"
puts "- value = #{c.content_value}"
 
c = ComplicatedContent.new("a_to_z")
puts "ComplicatedContent.new(\"a_to_z\"):"
puts "- class = #{c.class}"
puts "- value = #{c.content_value}"

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.