Lighthouse has a new layout. Prefer the old one? Return to the old layout, and switch back any time from the link at the top of each page.

option for before(:init)

#19

hi there,

I would really like a way to set init values for a CouchRest::Model class. Currently we have before(:create, :method) which is nice but if used to run something that sets init values will overwrite any already set in the object on save.

Is it possible to get a before(:init, :method) or something, that you can then use to feed initial values into the new object? I really don't want to start overriding initialize if a cleaner way is possible.

thanks!

Reported by hkstar · November 7th, 2008 @ 12:18 AM

State: resolved
Milestone: none
Assigned to: J. Chris A. J. Chris A.

Activity

  1. hkstar
    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.

    November 17th, 2008 @ 05:02 AM

  2. J. Chris A.
    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.)

    November 17th, 2008 @ 07:30 AM

  3. hkstar
    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) }

    November 17th, 2008 @ 11:22 AM

  4. hkstar
    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

    November 23rd, 2008 @ 11:48 PM

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.