Subclass module + use module_eval to define methods
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class AttributeAccessor < Module | |
def initialize(name) | |
@name = name | |
module_eval { define_accessors } | |
end | |
private | |
def define_accessors | |
ivar = "@#{@name}" | |
define_writer(ivar) | |
define_reader(ivar) | |
end | |
def define_writer(ivar) | |
define_method("#{@name}=") do |value| | |
instance_variable_set("#{ivar}", value) | |
end | |
end | |
def define_reader(ivar) | |
define_method(@name) do | |
instance_variable_get("#{ivar}") | |
end | |
end | |
end | |
module SingletonBook | |
extend AttributeAccessor.new(:title) | |
def self.title | |
"#{super} + super works on singletons!" | |
end | |
end | |
SingletonBook.title = "Module Subclassing Guide" | |
puts SingletonBook.title |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment