Skip to content

Instantly share code, notes, and snippets.

@juanje
Created September 12, 2011 03:49
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save juanje/1210545 to your computer and use it in GitHub Desktop.
Save juanje/1210545 to your computer and use it in GitHub Desktop.
Ruby class template based on attribs and a passed hash
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
@juanje
Copy link
Author

juanje commented Sep 12, 2011

The good thing of those classes is that you can initialize them passing a Hash with the attribs:

p = Person.new :firstname => 'John', :lastname => 'Smith'
#<Person:0x8db4284 @firstname="John", @lastname="Smith">
p.firstname
# => "John"
p.lastname
# => "Smith"
p.age
# => nil

And the created objects will just take the declared attribs:

d = Dog.new :name => 'Bobby', :lastname => 'Smith', :age => 7
#<Dog:0x8d05d74 @name="Bobby", @age=7>
d.name
# => "Bobby"
d.lastname
# NoMethodError: undefined method `lastname' for #<Dog:0x8d05d74 @name="Bobby">
d.age
# => 7

The method update is not really necessary but I found it useful for update the object values after it is created. For example:

p
#<Person:0x8db4284 @firstname="John", @lastname="Smith">
p.update :firstname => "Johnny", :age => 17
 => {:firstname=>"Johnny", :age=>17}
p
#<Person:0x8db4284 @firstname="Johnny", @lastname="Smith", @age=17>

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment