This course will be retired on June 1, 2025.
Heads up! To view this whole video, sign in with your Courses account or enroll in your free 7-day trial. Sign In Enroll
Start a free Courses trial
to watch this video
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:
def page_content(title)
File.read("pages/#{title}.txt")
rescue Errno::ENOENT
return nil
end
Here's a quick explanation of page_content
's code...
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 read
. 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 IO.read
documentation.
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 begin
and end
keywords before the call that might raise an exception (or, in this case, we can skip begin
and 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.
Related Discussions
Have questions about this video? Start a discussion with the community and Treehouse staff.
Sign upRelated Discussions
Have questions about this video? Start a discussion with the community and Treehouse staff.
Sign up
You need to sign up for Treehouse in order to download course files.
Sign upYou need to sign up for Treehouse in order to set up Workspace
Sign up