Skip to content

Instantly share code, notes, and snippets.

@eddieantonio
Last active August 29, 2015 14:21
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save eddieantonio/b3fa5310e52710b4808e to your computer and use it in GitHub Desktop.
Save eddieantonio/b3fa5310e52710b4808e to your computer and use it in GitHub Desktop.
My attempt at this metaprogramming balleyhoo. Did I really need to use eval?
#!/usr/bin/env ruby
require 'ripper'
class Module
# Public: Defines a behooked getter for the given attribute names.
#
# symbols - names of the @attribute to access.
#
def attr_boolean(*symbols)
symbols.each do |symbol|
# Ensure the symbol is exactly *one* identifier!
ident, *rest = Ripper.lex(symbol.to_s)
raise SyntaxError unless rest.empty?
_, type, attr = ident
# Only accept idenfiers as valid.
raise SyntaxError unless type == :on_ident
attr = attr.chomp '?'
method = eval "Proc.new { @#{attr} }"
define_method("#{attr}?", &method)
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment