Topic: How to cache contents of a text file
Hi. I'm new to Rails. I'm writing a program to look up words. It should read a text file (the
You are not logged in. Please login or register.
Rails Forum - Ruby on Rails Help and Discussion Forum » Other Rails Programming » How to cache contents of a text file
Hi. I'm new to Rails. I'm writing a program to look up words. It should read a text file (the
My post got cut off. Here's the whole thing...
Hi. I'm new to Rails. I'm writing a program to look up words. It should read a text file (the "dictionary"), and output the words that contain a string entered by the user. Some of the code for a simplified version is as follows...
Here's app/controllers/home_controller.rb:
class HomeController < ApplicationController
def index
end
end
And here's app/views/home/index.html.erb
<%= form_tag do %>
<%= text_field_tag(:target) %>
<%= submit_tag "Save" %>
<% end %>
<br />
----------------<br />
<% if !params[:target].nil? && !params[:target].empty? %>
<% File.open("dictionary.txt", "r") do |f| %>
<% a = f.readlines %>
<% for line in a %>
<% if line.include?(params[:target]) %>
<%= "#{line}<br />".html_safe %>
<% end %>
<% end %>
<% end %>
<% end %>
There is no model, because this functionality doesn't read or write anything in a database.
This works, but suppose that dictionary.txt is large. I don't want to read it every time a user requests the page. I'd like to read dictionary.txt once and cache the contents in memory. I've seen advice against using class variables or instance variables in Ruby. And I've seen suggestions to store such data in a database, but that seems like overkill, since it would incur a round trip to the database, for a large amount of data, every time the page is viewed.
So what's the best way to persist the contents of the dictionary across requests?
Thanks for your help!
Hosting provided by aTech Media