Created
June 3, 2009 15:05
-
-
Save troelskn/123027 to your computer and use it in GitHub Desktop.
attr_initializer
This file contains 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
class Class | |
# Adds a initialize method, which takes attributes as a hash | |
# Optionally call with symbol-names, to additionally create attribute accessors with `attr_accessor` | |
def attr_initializer(*args) | |
attr_accessor *args unless args.empty? | |
module_eval <<-END | |
def initialize(attributes = {}) | |
initialize_attributes(attributes) | |
end | |
def initialize_attributes(attributes = {}) | |
attributes.each do |k,v| | |
sym = "#\{k}=".to_sym | |
raise "Initialization of undefined attribute #\{k}" unless self.respond_to? sym | |
self.__send__ sym, v | |
end | |
end | |
END | |
end #m:attr_initializer | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment