Skip to content

Commit

Permalink
Merge pull request #310 from ankane/lazy_load_key
Browse files Browse the repository at this point in the history
Only load key if needed
  • Loading branch information
saghaulor authored Nov 13, 2018
2 parents 7b823b2 + c268863 commit cc05f95
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 3 deletions.
12 changes: 9 additions & 3 deletions lib/attr_encrypted.rb
Original file line number Diff line number Diff line change
Expand Up @@ -368,15 +368,21 @@ def encrypted_attributes
# Returns attr_encrypted options evaluated in the current object's scope for the attribute specified
def evaluated_attr_encrypted_options_for(attribute)
evaluated_options = Hash.new
attribute_option_value = encrypted_attributes[attribute.to_sym][:attribute]
encrypted_attributes[attribute.to_sym].map do |option, value|
evaluated_options[option] = evaluate_attr_encrypted_option(value)
attributes = encrypted_attributes[attribute.to_sym]
attribute_option_value = attributes[:attribute]

[:if, :unless, :value_present, :allow_empty_value].each do |option|
evaluated_options[option] = evaluate_attr_encrypted_option(attributes[option])
end

evaluated_options[:attribute] = attribute_option_value

evaluated_options.tap do |options|
if options[:if] && !options[:unless] && options[:value_present] || options[:allow_empty_value]
(attributes.keys - evaluated_options.keys).each do |option|
options[option] = evaluate_attr_encrypted_option(attributes[option])
end

unless options[:mode] == :single_iv_and_salt
load_iv_for_attribute(attribute, options)
end
Expand Down
9 changes: 9 additions & 0 deletions test/attr_encrypted_test.rb
Original file line number Diff line number Diff line change
Expand Up @@ -478,4 +478,13 @@ def test_encrypted_attributes_state_is_not_shared
assert_equal :encrypting, user.encrypted_attributes[:ssn][:operation]
assert_nil another_user.encrypted_attributes[:ssn][:operation]
end

def test_should_not_by_default_generate_key_when_attribute_is_empty
user = User.new
calls = 0
user.stub(:secret_key, lambda { calls += 1; SECRET_KEY }) do
user.ssn
end
assert_equal 0, calls
end
end

0 comments on commit cc05f95

Please sign in to comment.