Skip to content

Commit

Permalink
Merge pull request #238 from calebowens/fix-regex-for-super-indexes
Browse files Browse the repository at this point in the history
Updated module_name regexp to not match incorrect indexes
  • Loading branch information
rafaelfranca authored Apr 19, 2024
2 parents f2779ee + eae70a3 commit 2ecde30
Show file tree
Hide file tree
Showing 4 changed files with 21 additions and 1 deletion.
12 changes: 11 additions & 1 deletion lib/importmap/map.rb
Original file line number Diff line number Diff line change
Expand Up @@ -141,7 +141,17 @@ def expand_directories_into(paths)
end

def module_name_from(filename, mapping)
[ mapping.under, filename.to_s.remove(filename.extname).remove(/\/?index$/).presence ].compact.join("/")
# Regex explanation:
# (?:\/|^) # Matches either / OR the start of the string
# index # Matches the word index
# $ # Matches the end of the string
#
# Sample matches
# index
# folder/index
index_regex = /(?:\/|^)index$/

[ mapping.under, filename.to_s.remove(filename.extname).remove(index_regex).presence ].compact.join("/")
end

def module_path_from(filename, mapping)
Expand Down
1 change: 1 addition & 0 deletions test/dummy/app/javascript/controllers/special_index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
console.log("Sorry - no imports here!")
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
console.log("Sorry, nothing helpful here")
8 changes: 8 additions & 0 deletions test/importmap_test.rb
Original file line number Diff line number Diff line change
Expand Up @@ -44,10 +44,18 @@ def setup
assert_match %r|assets/controllers/index.*\.js|, generate_importmap_json["imports"]["controllers"]
end

test "directory pin mounted under matching subdir doesn't map *_index as root" do
assert_match %r|assets/controllers/special_index.*\.js|, generate_importmap_json["imports"]["controllers/special_index"]
end

test "directory pin mounted under matching subdir maps index as root at second depth" do
assert_match %r|assets/helpers/requests/index.*\.js|, generate_importmap_json["imports"]["helpers/requests"]
end

test "directory pin mounted under matching subdir doesn't map *_index as root at second depth" do
assert_match %r|assets/helpers/requests/special_index.*\.js|, generate_importmap_json["imports"]["helpers/requests/special_index"]
end

test "directory pin under custom asset path" do
assert_match %r|assets/spina/controllers/another_controller-.*\.js|, generate_importmap_json["imports"]["controllers/spina/another_controller"]
assert_match %r|assets/spina/controllers/deeper/again_controller-.*\.js|, generate_importmap_json["imports"]["controllers/spina/deeper/again_controller"]
Expand Down

0 comments on commit 2ecde30

Please sign in to comment.