Created
June 19, 2014 18:27
-
-
Save robmiller/d9186f3f9bef71b38311 to your computer and use it in GitHub Desktop.
Solution to Ara T. Howard's metakoans.rb Ruby Quiz: http://rubyquiz.com/quiz67.html
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 Module | |
def attribute(attribute, &block) | |
case attribute | |
when Hash | |
name = attribute.keys.first | |
default = attribute[name] | |
when String, Symbol | |
name = attribute | |
default = nil | |
end | |
sym = name.to_sym | |
instance_variable = :"@#{name}" | |
define_method(:"#{name}?") do | |
!!send(sym) | |
end | |
define_method(:"#{name}=") do |value| | |
instance_variable_set(:"@#{name}", value) | |
end | |
define_method(sym) do | |
if instance_variable_defined?(instance_variable) | |
instance_variable_get(instance_variable) | |
else | |
block ? instance_eval(&block) : default | |
end | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment