Skip to content

Instantly share code, notes, and snippets.

@juanje
Created September 13, 2011 14:16
Show Gist options
  • Save juanje/1213900 to your computer and use it in GitHub Desktop.
Save juanje/1213900 to your computer and use it in GitHub Desktop.
Ruby class template based on attribs and a passed hash using mixins
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
@ayosec
Copy link

ayosec commented Sep 13, 2011

Define the initialize method in a mixin is not a good practice. At least, the arguments should be optionals.

def initialize(args = nil)
  update args if args
end

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.

@juanje
Copy link
Author

juanje commented Sep 13, 2011

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