I’m learning how to use class_eval in modules (I’m somewhat familiar with class_eval) and came across this helpful class in resource_controller. In there they have things like this:
class_eval <<-"end_eval", __FILE__, __LINE__
def #{block_accessor}(*args, &block)
unless args.empty? && block.nil?
args.push block if block_given?
@#{block_accessor} = [args].flatten
end
@#{block_accessor}
end
end_eval
What does __FILE__ and __LINE__ do in that context? I know __FILE__ references the current file, but what does that whole thing do exactly? Don’t really know how to search for that :).
__FILE__and__LINE__are sort of dynamic constants that hold the file and line that are currently executing. Passing them in here allow errors to properly report their location.When you run this
Note it says the file and line #5 even though that was just text in an eval. Without those the file/line trick the output would look like this:
The stack trace simply shows
(eval)which isn’t as helpful.