Skip to content

Commit

Permalink
Merge pull request #379 from rails/schneems/error-when-asset-not-found
Browse files Browse the repository at this point in the history
Explicit API to error when an asset is not found
  • Loading branch information
schneems committed Sep 9, 2016
2 parents 9ac1b80 + 1352b09 commit d590c1c
Show file tree
Hide file tree
Showing 3 changed files with 36 additions and 0 deletions.
20 changes: 20 additions & 0 deletions lib/sprockets/base.rb
Expand Up @@ -93,6 +93,18 @@ def [](*args)
find_asset(*args)
end

# Find asset by logical path or expanded path.
#
# If the asset is not found an error will be raised.
def find_asset!(*args)
asset = find_asset(*args)
if asset
return asset
else
raise_on_unknown_asset(*args)
end
end

# Pretty inspect
def inspect
"#<#{self.class}:0x#{object_id.to_s(16)} " +
Expand All @@ -107,5 +119,13 @@ def compress_from_root(uri)
def expand_from_root(uri)
URITar.new(uri, self).expand
end

private
def raise_on_unknown_asset(*args)
asset_name = args.shift
msg = String.new("Could not load asset #{ asset_name.inspect }")
msg << "with options #{ args.inspect }" unless args.empty?
raise Sprockets::NotFound, msg
end
end
end
4 changes: 4 additions & 0 deletions lib/sprockets/environment.rb
Expand Up @@ -31,6 +31,10 @@ def find_asset(*args)
cached.find_asset(*args)
end

def find_asset!(*args)
cached.find_asset!(*args)
end

def find_all_linked_assets(*args, &block)
cached.find_all_linked_assets(*args, &block)
end
Expand Down
12 changes: 12 additions & 0 deletions test/test_environment.rb
Expand Up @@ -47,6 +47,18 @@ def self.test(name, &block)
assert_equal "hello: world\n", context.call("JST['hello']", name: "world")
end

test "find_asset! does not raise an exception when asset is found" do
@env.find_asset!("hello.js") # assert no raise
end

test "find_asset! raises an error when asset is not found" do
does_not_exist_file_name = "doesnotexist.blerg"
error = assert_raises(Sprockets::NotFound) do
@env.find_asset!(does_not_exist_file_name)
end
assert_match %r{#{does_not_exist_file_name}}, error.message
end

test "asset_data_uri helper" do
assert asset = @env["with_data_uri.css"]
assert_equal "body {\n background-image: url(data:image/gif;base64,R0lGODlhAQABAIAAAP%2F%2F%2FwAAACH5BAAAAAAALAAAAAABAAEAAAICRAEAOw%3D%3D) no-repeat;\n}\n", asset.to_s
Expand Down

0 comments on commit d590c1c

Please sign in to comment.