Skip to content

Instantly share code, notes, and snippets.

@seeflanigan
Last active April 8, 2016 17:07
Show Gist options
  • Save seeflanigan/b223587eddb55de097fb20b825f194e1 to your computer and use it in GitHub Desktop.
Save seeflanigan/b223587eddb55de097fb20b825f194e1 to your computer and use it in GitHub Desktop.
Things we build when we don't read the docs in config/initializers/devise.rb
class User < ActiveRecord::Base
DO_NOT_MODIFY = ["encrypted_password", "state"]
def do_not_modify
DO_NOT_MODIFY
end
def strip_string_attributes
string_attributes.each do |k,v|
# this is a side-effect and mutates instance state
self.send("#{k}=", v.split.join(" "))
end
end
def string_attributes
attributes.reject {|k,v| do_not_modify.include?(k) }.
select {|key, val| val.is_a?(String) }
end
end
describe "#strip_string_attributes" do
it "strips whitespace from :name" do
# User.first.attributes.select {|key, val| val.is_a?(String) }
# make sure we exclude hashed pw, and state,
# because we're setting them programmatically
messy = {
email: " messy@email.com ",
name: " Whitespace Username ",
city: " White Space ",
postal_code: " 80212 " }
clean = messy.map {|k,v| [k, v.split.join(" ")]}.to_h
user = build_stubbed(:user, messy)
user.strip_string_attributes
clean.each do |k,v|
expect(user.send(k)).to eq v
end
end
end
# ... in `config/initializers/devise.rb`
# Configure which authentication keys should have whitespace stripped.
# These keys will have whitespace before and after removed upon creating or
# modifying a user and when used to authenticate or find a user. Default is :email.
config.strip_whitespace_keys = [ :email, :name, :city, :postal_code ]
# ^^^ This was literally all I needed to do. Add three keys to an config value.
# Learn from my mistakes, friends, and Read The Fine Documentation™.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment