My Ruby on Rails application needs to generate reports based on database records I have been storing the SQL and ERB code required to generate these reports in the database. Each reports is composed of three parts:
- A header, which is an ERB snippet, rendered using
<%= render inline: @report.header %> - A footer, which is another ERB snippet, rendered using
<%= render inline: @report.footer %>
The body is then, of which the content are evaluated using @rows = eval("#{@report.model}.find_by_sql('#{@report.query}')"), rendered using:
<% @rows.each do |row| %>
<tr>
<% row.attributes.each_value do |value| %>
<td><%= value %></td>
<% end %>
</tr>
<% end %>
The model in @report.model is the name of a Ruby class stored in a column.
While this gets the job done perfectly fine, I have started to feel uneasy about storing actual source code in the database. An alternative that has been proposed is instead of storing code in the database would be to store the code in files and from the database refer to those files. To me this does not sound much better (in fact it’s more of a hassle since instead of simply rendering the text in the database column, I have to go open and read the file as well).
What is the general consensus on storing source code like this in the database, and what are some (better) alternatives: Some considerations include:
- New data is rarely added (we’re talking reports based on federal regulations that have not changed since 1999)
- If it does need to be changed, it will never be modified by anyone other than me (while I obviously cannot predict the future, let’s for argument sake assume that this holds true).
- The number of records is limited. We are talking about eight different reports here at most.
I don’t have an issue storing code in the DB, but I do wonder, if it’s rarely added, and you’re the only person changing it, what you really gain by doing so (keeping it in the DB). I’m a little skeptical it’d be worth it unless it’s something that needs to change often. OTOH, IMO, no harm in doing so as long as it’s subject to the same testing the rest of your app gets.
Templates in the DB–no problem with that either, although the same caveats apply. Note that particularly in Rails 3+, you can extend Rails to automatically retrieve templates from the DB, potentially saving yourself some manual work.
I don’t know as there are any great other alternatives, although I’d probably consider uploaded files rather than DB blobs, if your concern is redeployment.