Skip to content

Commit

Permalink
Keep relative imports at the end when sorting (#126)
Browse files Browse the repository at this point in the history
  • Loading branch information
Spone committed Feb 26, 2019
1 parent 212c836 commit ddcd37a
Show file tree
Hide file tree
Showing 2 changed files with 43 additions and 3 deletions.
28 changes: 28 additions & 0 deletions features/component_generator.feature
Original file line number Diff line number Diff line change
Expand Up @@ -113,6 +113,34 @@ Feature: Component generator
import "components/world/world";
"""

Scenario: relative `imports` in JavaScript files kept at the end when generating a component
When I cd to "frontend/components"
And a file named "index.js" with:
"""
import "../a_relative_file.js";
import "../other_relative_file.js";
"""
Then the file named "index.js" should contain:
"""
import "../a_relative_file.js";
import "../other_relative_file.js";
"""
When I run `rails generate component button`
Then the file named "index.js" should contain:
"""
import "components/button/button";
import "../a_relative_file.js";
import "../other_relative_file.js";
"""
When I run `rails generate component awesome_button`
Then the file named "index.js" should contain:
"""
import "components/awesome_button/awesome_button";
import "components/button/button";
import "../a_relative_file.js";
import "../other_relative_file.js";
"""

Scenario: Generate component with `erb` template engine
When I run `rails generate component AwesomeButton`
And I cd to "frontend/components/awesome_button"
Expand Down
18 changes: 15 additions & 3 deletions lib/generators/component/component_generator.rb
Original file line number Diff line number Diff line change
Expand Up @@ -169,14 +169,26 @@ def app_generators
end

def sort_lines_alphabetically!(path)
relative_imports, imports = read_imports_from_path(path)

return if imports.empty?

imports = imports.uniq.sort + relative_imports

write_imports_to_path(imports, path)
end

def read_imports_from_path(path)
lines = File.readlines(path).map do |line|
line if line =~ /^import ["'](.*)["'];$/
end.compact

return if lines.empty?

lines = lines.uniq.sort
lines.partition do |l|
l =~ /^import ["']\.(.*)["'];$/
end
end

def write_imports_to_path(lines, path)
File.open(path, "w") do |f|
lines.each do |line|
f.write(line)
Expand Down

0 comments on commit ddcd37a

Please sign in to comment.