Skip to content

Instantly share code, notes, and snippets.

@renato-zannon
Created September 4, 2012 04:07
Embed
What would you like to do?
Subclass module + use module_eval to define methods
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