In Rails you ought to look at before_save as your slightly bad ass friend, who you won't give control of your assets to.

You might think that's a bad analogy. When in fact it's not. Bear with me.

Truth/Sane part of analogy:

Don't modify your objects in an before_save hook. In any way, small string manipulation, prepend a dollar sign. Any of that, in any way. Of course, this argument is only valid if you're going to add validations on that object on those fields.

Example:


class Thing
before_save :underscore_most_special

private

def underscore_most_special
name.gsub!(/[-_/]/, '_')
end

end


This is all cool right, well let's say now you throw in a validation.


class Thing

before_save :underscore_most_special
validates_uniqueness_of :name

private

def underscore_most_special
name.gsub!(/[-_/]/, '_')
end

end



class ThingTest

def test_name_should_be_unique
Thing.create!(:name=>"rambo")
assert_equal false, Thing.new(:name=>"rambo").valid?
end

end



Of course this test will pass, what test won't pass on the other hand which I didn't write on the first go is.


def test_name_should_be_unique
Thing.create!(:name=>"rambo-the-dude")
assert_equal false, Thing.new(:name=>"rambo-the-dude").valid?
end


Any guesses why?

The thing that's saved is saved with underscores, and the thing that's wants to get saved is being compared with hyphens. Later on get's saved with underscores. And you end up with duplicates.

So what's the solution. Don't use those AR hooks? Hell no, hooks are awesome! Use before_validates.