set_default_values rocket science - continuing after_initialize/after_find misfeature

Just starting a new thread so that it's easy to follow.

I just submitted a patch at trac to add a new class method called "set_default_values" ( not a great name I think ), which lets you do all kinds of crazy stuff with setting default values.

This ticket is at http://dev.rubyonrails.org/ticket/9093 and example pastie is at Parked at Loopia

It also lets you make use of other attributes ( set by supplying attributes to Model.new call or even those set by set_default_values call ) in setter method/proc.

If people like this approach, I'll add tests to patch, else will just close the ticket :slight_smile:

i didn't see the switch, sorry!

- why not instance_eval the so it's 'inside' initialize? seems a pain if you need a private method...

- can't you avoid the 'skipped' business with

     self.class.default_values.keys - attributes.keys.map(&:to_s)

looks awesome though. it will be very nice feature to have!

i posted my fix here

http://drawohara.tumblr.com/post/6677354

which i'm double posting (sorry) because the the thread switch.

kind regards.

a @ http://drawohara.com/

What kind of use cases are you expecting where this sort of behavior is desirable? I think I'm coming up short on experience to imagine one.

James H.

Typical cases that hit my head on first thought :

- When you want to set an attr_protected value based on value of other fields. With my current patch, it won't work if you supply protected value in mass assignment. Will patch it later.

- When you are using STI and have some fields whose default value depends on type

- On a longer run, I'd love to make this useful for has_many :through << - but that's very far. In an idea world, I'd like to do something like :

has_many :friendships do   set_default_values :relation => "Family" end has_many :friends, :through => :friendships

And @model.friends << Something.create

Just a rough example. Achieving wouldn't really be simple. But if it's done, it could be just awesome. This patch *might* be a first step towards it.

Thanks, Pratik

i've got about ten right now, a few of them spelled out here

   http://drawohara.tumblr.com/post/6677354

in my current project i need

  - default values set via database functions   - default values set via manual sequence manpulation   - default values overridden in STI (STI being totally useless without this ability)

so i think it's a really good development.

cheers.

a @ http://drawohara.com/

I'm jumping on this boat. I actually just noticed I had written a sticky note to myself about something like this earlier. Oh, memory... why hast thou forsaken me?

James