Permalink
Browse files

Keep relative imports at the end when sorting (#126)

  • Loading branch information...
Spone authored and florentferry committed Feb 4, 2019
1 parent 6057772 commit 2418e2a4e56f0227e62b7ca41e7c70bfc277ec44
Showing with 43 additions and 3 deletions.
  1. +28 −0 features/component_generator.feature
  2. +15 −3 lib/generators/component/component_generator.rb
@@ -115,6 +115,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"
@@ -173,14 +173,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)

0 comments on commit 2418e2a

Please sign in to comment.