Alder Green
2006-Jul-21 10:37 UTC
[Rails] File.open behavior for ActiveRecord, to ensure save after manipulation?
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. -- -Alder
Ezra Zygmuntowicz
2006-Jul-21 17:43 UTC
[Rails] File.open behavior for ActiveRecord, to ensure save after manipulation?
On Jul 21, 2006, at 3:37 AM, Alder Green wrote:> 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. > > -- > -Alderclass 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
Alder Green
2006-Jul-21 18:34 UTC
[Rails] File.open behavior for ActiveRecord, to ensure save after manipulation?
On 7/21/06, Ezra Zygmuntowicz <ezmobius@gmail.com> wrote:> > On Jul 21, 2006, at 3:37 AM, Alder Green wrote: > > > 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. > > > > -- > > -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 >Awesome, thanks! -- -Alder