Skip to content

Instantly share code, notes, and snippets.

@thatrubylove
Created April 17, 2014 20:33
Show Gist options
  • Save thatrubylove/11009895 to your computer and use it in GitHub Desktop.
Save thatrubylove/11009895 to your computer and use it in GitHub Desktop.
an-exercise-in-refactoring-large-methods-in-ruby-2-example-10
module UserPasswordHashCleaner
extend self
def call(params)
return {} if params.nil?
return params if hash_has_password_info?(params)
strip_password_keys_from_hash(params)
end
protected
def strip_password_keys_from_hash(params)
user_params = params[:user].reject {|k,_| key_has_password_info?(k) }
params[:user] = user_params
params
end
def key_has_password_info?(key)
%w(password password_confirmation).include? key.to_s
end
def hash_has_password_info?(params)
return false if params.nil? || params[:user].to_s == ""
user_params = params[:user]
user_params[:password].to_s != "" &&
user_params[:password_confirmation].to_s != ""
end
end
require 'minitest/autorun'
describe UserPasswordHashCleaner do
subject { UserPasswordHashCleaner }
describe "call(params)" do
it "will return an empty hash when sent nil" do
subject.call(nil).must_equal({})
end
it "will return a hash without the password key if it it's value is blank" do
params = { user: { password: "", admin: true } }
subject.call(params).must_equal({ user: { admin: true } })
end
it "will return a hash without the password_confirmation key if it it's value is blank" do
params = { user: { password_confirmation: "", admin: true } }
subject.call(params).must_equal({ user: { admin: true } })
end
it "will return the hash as is if it has a password && password_confirmation" do
params = { user: { password: "ok",
password_confirmation: "ok",
admin: true } }
subject.call(params).must_equal({ user: {
password: "ok",
password_confirmation: "ok",
admin: true } })
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment