Skip to content

Commit

Permalink
Merge pull request #1271 from bf4/fix_digest_failure
Browse files Browse the repository at this point in the history
Handle no serializer source file to digest.
  • Loading branch information
NullVoxPopuli committed Oct 16, 2015
2 parents 240387b + 8529ea4 commit b2cd7bb
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 7 deletions.
23 changes: 16 additions & 7 deletions lib/active_model/serializer.rb
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,20 @@ class Serializer
)
/x

# Hashes contents of file for +_cache_digest+
def self.digest_caller_file(caller_line)
serializer_file_path = caller_line[CALLER_FILE]
serializer_file_contents = IO.read(serializer_file_path)
Digest::MD5.hexdigest(serializer_file_contents)
rescue TypeError, Errno::ENOENT
warn <<-EOF.strip_heredoc
Cannot digest non-existent file: '#{caller_line}'.
Please set `::_cache_digest` of the serializer
if you'd like to cache it.
EOF
''.freeze
end

with_options instance_writer: false, instance_reader: false do |serializer|
class_attribute :_type, instance_reader: true
class_attribute :_attributes
Expand All @@ -43,9 +57,10 @@ class Serializer
end

def self.inherited(base)
caller_line = caller.first
base._attributes = _attributes.dup
base._attributes_keys = _attributes_keys.dup
base._cache_digest = digest_caller_file(caller.first)
base._cache_digest = digest_caller_file(caller_line)
super
end

Expand Down Expand Up @@ -105,12 +120,6 @@ def self.serializers_cache
@serializers_cache ||= ThreadSafe::Cache.new
end

def self.digest_caller_file(caller_line)
serializer_file_path = caller_line[CALLER_FILE]
serializer_file_contents = IO.read(serializer_file_path)
Digest::MD5.hexdigest(serializer_file_contents)
end

# @api private
def self.serializer_lookup_chain_for(klass)
chain = []
Expand Down
12 changes: 12 additions & 0 deletions test/serializers/cache_test.rb
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,8 @@
module ActiveModel
class Serializer
class CacheTest < Minitest::Test
include ActiveSupport::Testing::Stream

def setup
ActionController::Base.cache_store.clear
@comment = Comment.new(id: 1, body: 'ZOMG A COMMENT')
Expand Down Expand Up @@ -170,6 +172,16 @@ def test_digest_caller_file
file.unlink
end

def test_warn_on_serializer_not_defined_in_file
called = false
serializer = Class.new(ActiveModel::Serializer)
assert_match(/_cache_digest/, (capture(:stderr) do
serializer.digest_caller_file('')
called = true
end))
assert called
end

private

def render_object_with_cache(obj)
Expand Down

0 comments on commit b2cd7bb

Please sign in to comment.