Created
January 19, 2011 18:18
-
-
Save chad/786579 to your computer and use it in GitHub Desktop.
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
#https://gist.github.com/786350 | |
module Names | |
def self.included(klass) | |
klass.extend ClassLevelMethods | |
klass.send(:attr_reader, :displayed_attribute_info) | |
end | |
def to_s | |
"<#{self.class.name} " + | |
self.class.displayed_attribute_info.map do |attr_name, label| | |
"#{label}: #{send(attr_name)}" | |
end.join(", ") + | |
">" | |
end | |
module ClassLevelMethods | |
def displayed_attribute(attribute_name, options = {}) | |
@displayed_attribute_info ||= {} | |
attr_accessor attribute_name | |
@displayed_attribute_info[attribute_name] = options[:label] || attribute_name | |
end | |
end | |
end | |
Object.send(:include, Names) | |
class Person | |
displayed_attribute :name | |
displayed_attribute :age | |
displayed_attribute :ssn, :label => "Social Security Number" | |
attr_accessor :foo | |
end | |
chad = Person.new | |
chad.age = 40 | |
chad.name = "Chad Fowler" | |
chad.ssn = "444-222-1111" | |
puts chad.to_s | |
#"<Person age: 40, name: Chad Fowler, Social Security Number: 444-222-1111>" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment