Skip to content

Commit

Permalink
Refactor install generator
Browse files Browse the repository at this point in the history
  • Loading branch information
mcelicalderon committed May 22, 2020
1 parent 5d5baf5 commit a85404d
Showing 1 changed file with 8 additions and 37 deletions.
45 changes: 8 additions & 37 deletions lib/generators/graphql_devise/install_generator.rb
Original file line number Diff line number Diff line change
Expand Up @@ -15,52 +15,23 @@ def execute_dta_installer

def mount_resource_route
routes_file = 'config/routes.rb'
routes_path = File.join(destination_root, routes_file)
gem_helper = 'mount_graphql_devise_for'
gem_route = "#{gem_helper} '#{user_class}', at: '#{mount_path}'"
gem_route = "mount_graphql_devise_for '#{user_class}', at: '#{mount_path}'"
dta_route = "mount_devise_token_auth_for '#{user_class}', at: '#{mount_path}'"
file_start = 'Rails.application.routes.draw do'

if File.exist?(routes_path)
current_route = parse_file_for_line(routes_path, gem_route)

if current_route.present?
say_status('skipped', "Routes already exist for #{user_class} at #{mount_path}")
else
current_dta_route = parse_file_for_line(routes_path, dta_route)

if current_dta_route.present?
replace_line(routes_path, dta_route, gem_route)
else
insert_text_after_line(routes_path, file_start, gem_route)
end
end
if file_contains_str?(routes_file, gem_route)
gsub_file(routes_file, /^\s+#{Regexp.escape(dta_route + "\n")}/i, '') if file_contains_str?(routes_file, dta_route)
say_status('skipped', "Routes already exist for #{user_class} at #{mount_path}")
else
say_status('skipped', "#{routes_file} not found. Add \"#{gem_route}\" to your routes file.")
gsub_file(routes_file, /#{Regexp.escape(dta_route)}/i, gem_route)
end
end

private

def insert_text_after_line(filename, line, str)
gsub_file(filename, /(#{Regexp.escape(line)})/mi) do |match|
"#{match}\n #{str}"
end
end

def replace_line(filename, old_line, new_line)
gsub_file(filename, /(#{Regexp.escape(old_line)})/mi, " #{new_line}")
end

def parse_file_for_line(filename, str)
match = false
def file_contains_str?(filename, regex_str)
path = File.join(destination_root, filename)

File.open(filename) do |f|
f.each_line do |line|
match = line if line =~ /(#{Regexp.escape(str)})/mi
end
end
match
File.read(path) =~ /(#{Regexp.escape(regex_str)})/i
end
end
end

0 comments on commit a85404d

Please sign in to comment.