Created
April 17, 2015 18:24
-
-
Save pricees/ce96c751828b08ec9a15 to your computer and use it in GitHub Desktop.
Macro fun with define method
This file contains hidden or 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
| # | |
| # 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