Loading Text Files2:43 with Jay McGavren
I've added a plain Ruby method called "page_content" to the app. It loads the contents of a text file and returns them as a string. You pass the title of a page to it as an argument, and it uses the "read" method on the core Ruby "File" class to open a ".txt" file from a "pages/" subdirectory within your app's main directory.
We've added a
page_content method to the app to read contents of a wiki page from a file:
Here's a quick explanation of
Ruby has a core class named
File that's used for working with files.
File is a subclass of the
IO class, so
File inherits a class method named
File.read lets you read the entire contents of a file into a string, using only the file name. You can read more about it here in the
If the requested file isn't found, the call to
File.read may raise an
Errno::ENOENT exception. Normally, this would just cause processing of the HTTP request to stop in its tracks. But if we add
end keywords before the call that might raise an exception (or, in this case, we can skip
end because the code is inside a method), and add a
rescue keyword, we can "rescue" our program from being halted by the exception. You can learn more about rescuing exceptions here.
You need to sign up for Treehouse in order to download course files.Sign up