Skip to content

Commit cc05f95

Browse files
authored
Merge pull request #310 from ankane/lazy_load_key
Only load key if needed
2 parents 7b823b2 + c268863 commit cc05f95

File tree

2 files changed

+18
-3
lines changed

2 files changed

+18
-3
lines changed

lib/attr_encrypted.rb

+9-3
Original file line numberDiff line numberDiff line change
@@ -368,15 +368,21 @@ def encrypted_attributes
368368
# Returns attr_encrypted options evaluated in the current object's scope for the attribute specified
369369
def evaluated_attr_encrypted_options_for(attribute)
370370
evaluated_options = Hash.new
371-
attribute_option_value = encrypted_attributes[attribute.to_sym][:attribute]
372-
encrypted_attributes[attribute.to_sym].map do |option, value|
373-
evaluated_options[option] = evaluate_attr_encrypted_option(value)
371+
attributes = encrypted_attributes[attribute.to_sym]
372+
attribute_option_value = attributes[:attribute]
373+
374+
[:if, :unless, :value_present, :allow_empty_value].each do |option|
375+
evaluated_options[option] = evaluate_attr_encrypted_option(attributes[option])
374376
end
375377

376378
evaluated_options[:attribute] = attribute_option_value
377379

378380
evaluated_options.tap do |options|
379381
if options[:if] && !options[:unless] && options[:value_present] || options[:allow_empty_value]
382+
(attributes.keys - evaluated_options.keys).each do |option|
383+
options[option] = evaluate_attr_encrypted_option(attributes[option])
384+
end
385+
380386
unless options[:mode] == :single_iv_and_salt
381387
load_iv_for_attribute(attribute, options)
382388
end

test/attr_encrypted_test.rb

+9
Original file line numberDiff line numberDiff line change
@@ -478,4 +478,13 @@ def test_encrypted_attributes_state_is_not_shared
478478
assert_equal :encrypting, user.encrypted_attributes[:ssn][:operation]
479479
assert_nil another_user.encrypted_attributes[:ssn][:operation]
480480
end
481+
482+
def test_should_not_by_default_generate_key_when_attribute_is_empty
483+
user = User.new
484+
calls = 0
485+
user.stub(:secret_key, lambda { calls += 1; SECRET_KEY }) do
486+
user.ssn
487+
end
488+
assert_equal 0, calls
489+
end
481490
end

0 commit comments

Comments
 (0)