File.open behavior for ActiveRecord, to ensure save after ma

File.open in core Ruby is nifty, in that it automagically closes the
file when you’re done using/manipulating it. I’m wondering whether
there’s something like that for ActiveRecord?

So you can do:

AR.find(23).open {|ar|
ar.foo = ‘bar’

}

And ar.save would be called when the block closes.

On Jul 21, 2006, at 3:37 AM, Alder G. wrote:

And ar.save would be called when the block closes.


-Alder

class ActiveRecord::Base

def self.build_with_block(attributes = nil, &block)
item = self.new(attributes || {})
yield item if block_given?
item.save!
item
end

def modify_with_block(attributes = nil, &block)
self.attributes = attributes
yield self if block_given?
save!
self
end

end

Model.build_with_block do |m|
m.foo = ‘bar’
m.bar = ‘foo’
end

Model.find(23).modify_with_block do |m|
m.foo = ‘bizz’
m.bar = ‘fuzz!’
end

Cheers-
-Ezra

On 7/21/06, Ezra Z. [email protected] wrote:

ar.foo = ‘bar’
def self.build_with_block(attributes = nil, &block)
self
Model.find(23).modify_with_block do |m|
m.foo = ‘bizz’
m.bar = ‘fuzz!’
end

Cheers-
-Ezra

Awesome, thanks!

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs