Skip to content

Instantly share code, notes, and snippets.

@cvengros
Created October 10, 2014 23:52
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save cvengros/335571d28ba47cf5150d to your computer and use it in GitHub Desktop.
Save cvengros/335571d28ba47cf5150d to your computer and use it in GitHub Desktop.
Change references from gems to local libraries
require 'fileutils'
require 'json'
# change require 'library' to require_relative 'path'
# path will be dynamic depending on the current file path
# I don't deal with libraries I don't know
LIBS_DIR = 'libs'
def generate_require_relative(file_path, require_path)
# for each dir in file path add ..
dir_up = File.join(File.dirname(file_path).split(File::SEPARATOR).map{|_| '..'})
return "require_relative '#{File.join(dir_up, LIBS_DIR, require_path)}'\n"
end
FileUtils.mkdir_p(LIBS_DIR)
apps_dir = ARGV[0]
config_file = ARGV[1]
# check args
if config_file.nil?
fail "Args not provided. Usage: #{__FILE__} <app directory> <config>"
end
# parse config
config = JSON.parse(IO.read(config_file))
# generate a list of regexps for each lib
require_regexps = config.keys.map do |k|
{
regexp: /\s*require\s+['"]#{k}['"]\s*/,
key: k
}
end
# go recursively through all the ruby files in apps
apps_files = Dir.glob(File.join(apps_dir, "**/*.rb"))
# and also in libs - interdependencies
lib_files = Dir.glob(File.join(LIBS_DIR, "**/*.rb"))
(apps_files + lib_files).each do |f|
# line by line
lines = IO.readlines(f).map do |line|
new_line = line
require_regexps.each do |r|
# if it matches one of the regexps, replace it
if line =~ r[:regexp]
# not nice
new_line = generate_require_relative(f, config[r[:key]])
puts "Changing #{line} to #{new_line} in #{f}"
break
end
end
new_line
end
File.open(f, 'w') {|file| file.puts lines}
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment