Created
September 12, 2011 03:49
-
-
Save juanje/1210545 to your computer and use it in GitHub Desktop.
Ruby class template based on attribs and a passed hash
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 Base | |
def initialize args | |
update args | |
end | |
def update args | |
args.each do |k,v| | |
send "#{k}=", v if respond_to? k | |
end | |
end | |
end | |
class Person < Base | |
attr_accessor :firstname, :lastname, :age | |
end | |
class Dog < Base | |
attr_accessor :name, :age | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
The good thing of those classes is that you can initialize them passing a Hash with the attribs:
And the created objects will just take the declared attribs:
The method update is not really necessary but I found it useful for update the object values after it is created. For example: