Created
September 13, 2011 14:16
-
-
Save juanje/1213900 to your computer and use it in GitHub Desktop.
Ruby class template based on attribs and a passed hash using mixins
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
| module Base | |
| def initialize args | |
| update args | |
| end | |
| def update args | |
| args.each do |k,v| | |
| instance_variable_set "@#{k}", v if respond_to? k | |
| end | |
| end | |
| end | |
| class Person | |
| attr_accessor :firstname, :lastname, :age | |
| include Base | |
| end | |
| class Dog | |
| attr_accessor :name, :age | |
| include Base | |
| end |
Author
Well, I was creating a general class to make more specialized ones. I didn't see a good idea to have a mothod initialize in a mixin either, I do think is better a class...
I still don't see the advantage of using mixins here...
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Define the
initializemethod in a mixin is not a good practice. At least, the arguments should be optionals.For something like this I prefer a mixin instead of a derived class. A derived class should be used only when the new class is a specialization of the parent. In this case, the mixin is just extending the functionality.