Last active
December 31, 2015 14:19
-
-
Save gschorkopf/7999488 to your computer and use it in GitHub Desktop.
Nifty ways to have custom sanitation for columns in Rails
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
# 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 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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.