Skip to content

Instantly share code, notes, and snippets.

@troelskn
Created June 3, 2009 15:05
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save troelskn/123027 to your computer and use it in GitHub Desktop.
Save troelskn/123027 to your computer and use it in GitHub Desktop.
attr_initializer
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