태그 보관물: 변환

카멜케이스를 언더바로 변환하는 스크립트

소스파일내의 카멜케이스를 언더바로 변환하여 다른 파일로 저장해주는 ruby 스크립트 입니다.

에) helloWorld => hello_world

### camel2under.rb ###

if ARGV.empty?
    puts '사용법:'
    puts "#{$0} 소스파일경로 [변환된파일경로]";
    exit
end

source_file = ARGV[0];
target_file = ARGV[1] ? ARGV[1] : "#{source_file}.convert";

ftarget = File.open(target_file, "w")

File.open(source_file).each { |line|
    convert_line = line

    line.scan(/[A-Z]?[a-z](?:[a-z0-9])*(?:[A-Z][a-z0-9]+)+/) { |match_str|
        # 대문자로 시작하면
        break if match_str.match(/^[A-Z]/)

        replace_str = match_str.gsub(/([a-z0-9])([A-Z])/, '\1_\2').downcase

        convert_line = convert_line.gsub(match_str, replace_str)
    }

    if ( line != convert_line )
        puts '┏' + line.gsub(/^ +/, '')
        puts '┗' + convert_line.gsub(/^ +/, '')
    end

    ftarget.puts convert_line
}

ftarget.close