option for before(:init)
-
hkstar
- Assigned user set to J. Chris A.
After further examination, it seems that what I wanted is possible with existing code. I had wanted to be able to generate random codes on init (not for _id) - this is possible without further work by developer.
For those interested, there are two ways to do this - you can set static init values by feeding in a hash via set_defaults, which sets a class attribute with those values, or you can just override the reader method to that class attribute by defining self.default and having it output whatever you want. Not sure if this is encouraged though :)
Thanks. If I could mark this closed or withdraw it, I would.
-
J. Chris A.
- State changed from new to resolved
thanks for the ticket.
I'd be happy to see a patch that allows lambda on the defaults hash, and evaluates them either at init (or perhaps at save, but maybe that's asking for trouble.)
-
hkstar
Well, it can be as simple as http://friendpaste.com/nLYwTGq9, though you'll need to pass the hash directly (ie, not in an array like it is in the specs) for it to work.
Needs to be called like this: set_default :random1 => lambda { return rand(99999999) }, :random2 => lambda { return rand(99999999) }
-
hkstar
The current defaults system has a pretty nasty flaw. See demonstration here: http://friendpaste.com/a72JqDEY .. yup, the old referencing problem.
The Class.defaults hash needs to be deep copied in apply_defaults. I have updated my above Proc-compatible implementation with a Marshal load/dump which effectively deep-copies anything in the hash that's not a Proc.
Here's my fix: http://friendpaste.com/nLYwTGq9
Please Sign in or create a free account to add a new ticket.
With your very own profile, you can contribute to projects, track your activity, watch tickets, receive and update tickets through your email and much more.