Created
March 18, 2011 04:23
-
-
Save charissa/875615 to your computer and use it in GitHub Desktop.
This makes a class_attr_accessor Class method a la email from Snuggs.
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
| #!/opt/local/bin/ruby1.9 | |
| class Class | |
| def self.class_attr_accessor *accessors | |
| accessors.each do |accessor| | |
| define_method(accessor) do | |
| class_variable_get("@@#{accessor}") | |
| end | |
| define_method("#{accessor}=") do |val| | |
| class_variable_set("@@#{accessor}", val) | |
| end | |
| end | |
| end | |
| end | |
| class Customer | |
| Class.class_attr_accessor "no_of_customers" | |
| @@no_of_customers=0 | |
| def initialize | |
| @@no_of_customers+=1 | |
| end | |
| # def Customer.no_of_customers | |
| # @@no_of_customers | |
| # end | |
| end | |
| puts Class.methods(false).sort | |
| #puts Customer.methods.sort | |
| a=Customer.new | |
| #puts Customer.methods.sort | |
| puts Customer.no_of_customers | |
| Customer.new | |
| puts Customer.no_of_customers |
Author
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
If self inspection is useful, maybe the added comments will add some light to what is going on. Otherwise maybe some self -introspection would help....
In retrospect this seems obvious, but the define_method(accessor) seems only to be run when the accessor is is used on a Class, e.g., when I say Customer.no_of_customers. Does this mean that the syntax, etc. is only checked at that point? I think so, which means it is very important to have tests that test ALL the conditions/edge-conditions of your code, lest certain code remains un-exercised until someone goes there in production...
and the result: