1
0
Fork 0
mirror of https://github.com/ruby/ruby.git synced 2022-11-09 12:17:21 -05:00
ruby--ruby/lib/irb/magic-file.rb
a_matsuda 88de87c295 Don't pollute toplevel by an IRB internal method
There actually are some libraries that requires 'irb' such as byebug, and when
'irb' is required, it requires irb/src_encoding.rb, then it defines the toplevel
default_src_encoding method that is visible from anywhere in the end users' apps.

Here's a quick oneliner that shows what's happening.

  % ruby -rpry-byebug -e 'p private_methods(false)'
  [:include, :using, :define_method, :public, :private, :DelegateClass, :default_src_encoding]

git-svn-id: svn+ssh://ci.ruby-lang.org/ruby/trunk@59090 b2dd03c8-39d4-4d8f-98ff-823fe69b080e
2017-06-15 10:43:17 +00:00

38 lines
928 B
Ruby

# frozen_string_literal: false
module IRB
class << (MagicFile = Object.new)
# see parser_magic_comment in parse.y
ENCODING_SPEC_RE = %r"coding\s*[=:]\s*([[:alnum:]\-_]+)"
def open(path)
io = File.open(path, 'rb')
line = io.gets
line = io.gets if line[0,2] == "#!"
encoding = detect_encoding(line)
internal_encoding = encoding
encoding ||= IRB.default_src_encoding
io.rewind
io.set_encoding(encoding, internal_encoding)
if block_given?
begin
return (yield io)
ensure
io.close
end
else
return io
end
end
private
def detect_encoding(line)
return unless line[0] == ?#
line = line[1..-1]
line = $1 if line[/-\*-\s*(.*?)\s*-*-$/]
return nil unless ENCODING_SPEC_RE =~ line
encoding = $1
return encoding.sub(/-(?:mac|dos|unix)/i, '')
end
end
end