magic_encoding gem源码解析

本来想写一个devise的源码分析的blog的,奈何devise源码太多,一时也不好讲,先奉上一个简单但是很实用的吧。解决中文ruby代码中无法正常运行的问题的gem。

此gem非常简单。就两个文件。 gem 源码在:https://github.com/m-ryan/magic_encoding


bin文件夹下面调用lib文件夹下的magic_encoding 文件。

# -*- encoding : utf-8 -*-

# A simple library to prepend magic comments for encoding to multiple ".rb" files

module AddMagicComment

  # Options :
  # 1 : Encoding
  # 2 : Path
  # TODO : check that the encoding specified is a valid encoding
	# TODO : allow use of only one option, so the encoding would be guessed (maybe using `file --mime`?)
  def self.process(options)

    # defaults
    encoding  = options[0] || "utf-8"
    directory = options[1] || Dir.pwd

    prefix = "-*- encoding : #{encoding} -*-\n"

    # TODO : add options for recursivity (and application of the script to a single file)

		extensions = {
			'rb' => '# {text}',
			'rake' => '# {text}',
			'haml' => '-# {text}',
		}

		count = 0
		extensions.each do |ext, comment_style|
			rbfiles = File.join(directory ,'**', '*.'+ext)
			Dir.glob(rbfiles).each do |filename|
				file = File.new(filename, "r+")

				lines = file.readlines

				# remove current encoding comment(s)
        while lines[0].match(/^-?# ?(-\*-)? ?(en)?coding/)
          lines.shift
        end

				# set current encoding
				lines.insert(0,comment_style.sub('{text}', prefix))
				count += 1

				file.pos = 0
				file.puts(lines.join)
				file.close
			end
		end

    puts "Magic comments set for #{count} source files"
  end

end

class String

  def starts_with?(s)
    self[0..s.length-1] == s
  end

end


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值