Module: Kernel

Defined in:
lib/core-ext/nilclass.rb,
lib/core-ext/jopen.rb

Overview

start ego mode block, usage: catch_nil do

if @some_hash[:some_key].to_formatted_array[3]
  # do something
end

end

Instance Method Summary collapse

Instance Method Details

#catch_nil(&block) ⇒ Object



11
12
13
14
15
16
17
18
19
20
21
22
# File 'lib/core-ext/nilclass.rb', line 11

def catch_nil(&block)
	# grip methods
	ori_method_missing   = NilClass.instance_method(:method_missing)
	catch_method_missing = NilClass.instance_method(:catch_method_missing)
	# activate ego mode
	NilClass.send :define_method, :method_missing, catch_method_missing
	# run code
	yield
ensure
	# no matter what happens: restore default nil behaviour
	NilClass.send :define_method, :method_missing, ori_method_missing
end

#jopen(filename, mode, encode = "ISO-8859-1") ⇒ Object



8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
# File 'lib/core-ext/jopen.rb', line 8

def jopen(filename, mode, encode = "ISO-8859-1")
	stream = nil
	if mode == "r"
		stream = read_stream(filename, encode)
	elsif mode == "w"
		stream = write_stream(filename, encode)
	end
	if block_given?
		begin
			yield stream
		ensure
			stream.close
		end
	else
		return stream
	end
end

#read_stream(filename, encode = "ISO-8859-1") ⇒ Object



30
31
32
# File 'lib/core-ext/jopen.rb', line 30

def read_stream(filename, encode = "ISO-8859-1")
	InputStreamReader.new(FileInputStream.new(filename), encode)
end

#write_stream(filename, encode = "ISO-8859-1") ⇒ Object



26
27
28
# File 'lib/core-ext/jopen.rb', line 26

def write_stream(filename, encode = "ISO-8859-1")
	PrintStream.new(FileOutputStream.new(filename), false, encode)
end