Skip to content

Instantly share code, notes, and snippets.

@sensq
Last active October 10, 2016 11:09
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 sensq/dc302c9185cb260104a581cc39c656bd to your computer and use it in GitHub Desktop.
Save sensq/dc302c9185cb260104a581cc39c656bd to your computer and use it in GitHub Desktop.
class Indent
attr_accessor :indent
def initialize (ary)
@indent = 2 # インデントの空白数
@counter = 0 # 現在のインデントの深さ
@ret_ary = ary
# 予約語を定義
create_reserved_word
end
public
# フォーマットを実行するメソッド
def format
# 最初に全部のインデントを消去
@ret_ary.each do |line|
line.gsub!(/^\s*/, "")
end
# フォーマット実行
@ret_ary.each do |line|
chk_minus_word(line)
add_indent(line)
chk_plus_word(line)
end
return @ret_ary
end
# ファイルに保存するメソッド
def output_file (path)
File.open(path, "w") do |file|
file.puts @ret_ary
end
end
private
def create_reserved_word
indent_pm_word
indent_plus_word
indent_minus_word
end
def indent_pm_word
@pm_words = []
@pm_words.push(/^\s*when(\(|\s)/)
@pm_words.push(/^\s*else\s/)
@pm_words.push(/^\s*elsif(\(|\s)/)
@pm_words.push(/^\s*rescue\s/)
@pm_words.push(/^\s*ensure\s/)
end
def indent_plus_word
@p_words = []
@p_words.concat(@pm_words)
@p_words.push(/^\s*module\s/)
@p_words.push(/^\s*class\s/)
@p_words.push(/^\s*def\s/)
@p_words.push(/^\s*unless(\(|\s)/)
@p_words.push(/^\s*if(\(|\s)/)
@p_words.push(/^\s*case\s/)
@p_words.push(/^\s*begin\s/)
@p_words.push(/^\s*while\s/)
@p_words.push(/^\s*until(\(|\s)/)
@p_words.push(/\sdo\s/)
@p_words.push(/.*\{/)
end
def indent_minus_word
@m_words = []
@m_words.concat(@pm_words)
@m_words.push(/^\s*end(\s|$)/)
@m_words.push(/.*\}/)
end
def chk_comment_word (line)
if /^\s*#/ =~ line
return true
end
return false
end
def chk_inline_line (line)
if /.*\{.*\}.*/ =~ line
return true
end
return false
end
def chk_plus_word (line)
if chk_comment_word(line)
return
end
if chk_inline_line(line)
return
end
@p_words.each do |item|
if item =~ line
@counter += 1
break
end
end
end
def chk_minus_word (line)
if chk_comment_word(line)
return
end
if chk_inline_line(line)
return
end
@m_words.each do |item|
if item =~ line
@counter -= 1
break
end
end
end
def add_indent (line)
spaces = " " * @indent * @counter
line.gsub!(/^/, spaces)
end
end
# 読み込み
format_file = File.open(ARGV[0]).readlines
indent = Indent.new(format_file)
# バックアップ作成
bk_name = ARGV[0].split(".rb")[0] + "_fmt_backup.rb"
indent.output_file(bk_name)
# フォーマットして上書き保存
if ARGV[1]
indent.indent = ARGV[1].to_i
end
indent.format
indent.output_file(ARGV[0])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment