Ruby: add custom properties to built-in classes

Posted by dreftymac on Stack Overflow See other posts from Stack Overflow or by dreftymac
Published on 2010-03-08T02:13:49Z Indexed on 2010/03/08 3:51 UTC
Read the original article Hit count: 381

Question: Using Ruby it is simple to add custom methods to existing classes, but how do you add custom properties? Here is an example of what I am trying to do:

myarray = Array.new();
myarray.concat([1,2,3]);
myarray._meta_ = Hash.new();      # obviously, this wont work
myarray._meta_['createdby'] = 'dreftymac';
myarray._meta_['lastupdate'] = '1993-12-12';

## desired result
puts myarray._meta_['createdby']; #=> 'dreftymac'
puts myarray.inspect()            #=> [1,2,3]

The goal is to construct the class definition in such a way that the stuff that does not work in the example above will work as expected.

Update: (clarify question) One aspect that was left out of the original question: it is also a goal to add "default values" that would ordinarily be set-up in the initialize method of the class.

Update: (why do this) Normally, it is very simple to just create a custom class that inherits from Array (or whatever built-in class you want to emulate). This question derives from some "testing-only" code and is not an attempt to ignore this generally acceptable approach.

© Stack Overflow or respective owner

Ruby: add custom properties to built-in classes

Posted by dreftymac on Stack Overflow See other posts from Stack Overflow or by dreftymac
Published on 2010-03-08T02:13:49Z Indexed on 2010/03/08 3:02 UTC
Read the original article Hit count: 381

Question: Using Ruby it is simple to add custom methods to existing classes, but how do you add custom properties? Here is an example of what I am trying to do:

myarray = Array.new();
myarray.concat([1,2,3]);
myarray._meta_ = Hash.new();      # obviously, this wont work
myarray._meta_['createdby'] = 'dreftymac';
myarray._meta_['lastupdate'] = '1993-12-12';

## desired result
puts myarray._meta_['createdby']; #=> 'dreftymac'
puts myarray.inspect()            #=> [1,2,3]

The goal is to construct the class definition in such a way that the stuff that does not work in the example above will work as expected.

Update: (clarify question) One aspect that was left out of the original question: it is also a goal to add "default values" that would ordinarily be set-up in the initialize method of the class.

Update: (why do this) Normally, it is very simple to just create a custom class that inherits from Array (or whatever built-in class you want to emulate). This question derives from some "testing-only" code and is not an attempt to ignore this generally acceptable approach.

© Stack Overflow or respective owner

Related posts about monkeypatching

Related posts about ruby