Skip to content

Instantly share code, notes, and snippets.

@gschorkopf
Last active December 31, 2015 14:19
Show Gist options
  • Save gschorkopf/7999488 to your computer and use it in GitHub Desktop.
Save gschorkopf/7999488 to your computer and use it in GitHub Desktop.
Nifty ways to have custom sanitation for columns in Rails
# Goal: To clean up surrounding whitespace from a user's first_name field:
# rspec test:
describe User do
describe "first_name" do
it "sanitizes surrounding whitespace from column" do
user = User.new(first_name: " Stafford ")
expect(user.first_name).to eq "Stafford"
end
end
end
# Option 1: overwrite default accessor (used in update/create)
# Source: http://api.rubyonrails.org/classes/ActiveRecord/Base.html#label-Overwriting+default+accessors
class User > ActiveRecord::Base
def first_name=(value)
value ||= ''
write_attribute(:last_name, value.strip)
end
end
# Option 2: send first_name= to ActiveRecord::Base module, which uses write_attribute
# Source: https://github.com/rails/rails/blob/e20dd73df42d63b206d221e2258cc6dc7b1e6068/activerecord/lib/active_record/attribute_methods/write.rb
class User > ActiveRecord::Base
def first_name=(value)
super((value || '').strip)
end
end
@blithe
Copy link

blithe commented May 28, 2014

Interesting. Hadn't really thought about either of these options. I'll keep these in mind when I need to do this in the future.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment