When you use the ERB api from Ruby, you provide a string to ERB.new
, so there isn’t really any way for ERB to know where that file came from. You can however tell the object which file it came from using the filename
attribute:
t = ERB.new(File.read('my_template.erb')
t.filename = 'my_template.erb'
Now you can use __FILE__
in my_template.erb
and it will refer to the name of the file. (This is what the erb
executable does, which is why __FILE__
works in ERB files that you run from the command line).
To make this a bit a bit more useful, you could monkey patch ERB with a new method to read from a file and set the filename
:
require 'erb'
class ERB
# these args are the args for ERB.new, which we pass through
# after reading the file into a string
def self.from_file(file, safe_level=nil, trim_mode=nil, eoutvar='_erbout')
t = new(File.read(file), safe_level, trim_mode, eoutvar)
t.filename = file
t
end
end
You can now use this method to read ERB files, and __FILE__
should work in them, and refer to the actual file and not just (erb)
:
t = ERB.from_file 'my_template.erb'
puts t.result