Skip to content

Instantly share code, notes, and snippets.

@jimeh
Created February 8, 2010 12:15
Show Gist options
  • Save jimeh/298088 to your computer and use it in GitHub Desktop.
Save jimeh/298088 to your computer and use it in GitHub Desktop.
Quick Rails hack for a Model#increment_attributes method that works like update_attributes
Item.create(
:name => "Lolcat",
:fans => 0,
:views => 0
)
item = Item.find_by_name("Lolcat") #=> <Item name:"Lolcat" fans:0 views:0>
item.increment_attributes({ :fans => 4, :views => 3 })
item #=> <Item name:"Lolcat" fans:4 views:3>
item = Item.find_by_name("Lolcat") #=> <Item name:"Lolcat" fans:4 views:3>
item.increment_attributes({ :views => 5 })
item #=> <Item name:"Lolcat" fans:4 views:8>
# ...
module IncrementAttributes
def increment_attributes(attributes = {}, save = true)
attributes.each do |key, value|
if self.respond_to?(key)
if read_attribute(key).nil? && (!value.is_a?(Fixnum) || !value.is_a?(Float))
write_attribute(key, value)
else
write_attribute(key, read_attribute(key) + value)
end
end
end
self.save if save
end
end
class Item < ActiveRecord::Base
include IncrementAttributes
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment