Skip to content

Instantly share code, notes, and snippets.

@renato-zannon
Created September 4, 2012 04:07
  • Star 4 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save renato-zannon/3616434 to your computer and use it in GitHub Desktop.
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