Featured image

If you code in Ruby, you can discover new features practically every day. For instance, one of the coolest features I stumbled upon in the documentation just a few days ago (despite writing Ruby for over 10 years!) is that you can embed text data directly inside your source file. All you need to do is place an __END__ marker at the bottom of the file. Anything you write after that line can be read right out of the DATA object inside the same source file. Under the hood, the DATA constant is simply an open file stream of your current file in read-only mode, with its pointer positioned immediately after the __END__ line.

Have you ever used __END__ and DATA in your projects, or is this new to you too?

#!/bin/env ruby

# Save as ./data.rb
# $ chmod +x data.rb
# $ ./data.rb

puts 'DATA constant:'
puts "Class: #{DATA.class.inspect}"
puts "Path: #{File.expand_path(DATA.path).inspect}"
puts "Total size: #{DATA.size.inspect}"
puts "Position: #{DATA.pos.inspect}"
puts "DATA: #{DATA.read.chomp.inspect}"

# A quick trick for reading the current file from the beginning
# puts DATA.tap { it.seek(0) }.read

# And here is how you can try to implement this functionality yourself
# File.open(__FILE__, 'r').tap do |file|
#   until file.eof?
#     if file.readline.start_with?('__END__')
#       MY_DATA = file
#       break
#     end
#   end
# end
# puts MY_DATA.read

__END__
Some text
Other data