Skip to content

Instantly share code, notes, and snippets.

@pricees
Created April 17, 2015 18:24
Show Gist options
  • Select an option

  • Save pricees/ce96c751828b08ec9a15 to your computer and use it in GitHub Desktop.

Select an option

Save pricees/ce96c751828b08ec9a15 to your computer and use it in GitHub Desktop.
Macro fun with define method
#
# Ted Price
# Fun demo using define_method
#
class Base
def self.has_a(*attrs)
attrs.each do |attr|
define_method(attr) do
instance_variable_get("@#{attr}")
end
define_method("#{attr}=") do |val|
instance_variable_set("@#{attr}", val)
end
end
end
end
class Person < Base
has_a :name
end
p = Person.new
p.name = "Ted"
p1 = Person.new
p1.name = "Greg"
# Anon
anon = Class.new(Base) { has_a :name, :age }.new
anon.name = "Jeah!"
anon.age = 35
puts p.name
puts p1.name
puts anon.name
puts anon.age
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment