Skip to content

Instantly share code, notes, and snippets.

@robmiller
Created June 19, 2014 18:27
Show Gist options
  • Save robmiller/d9186f3f9bef71b38311 to your computer and use it in GitHub Desktop.
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
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