Created
February 8, 2010 12:15
-
-
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
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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> | |
# ... |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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