Archive for December, 2008

Ruby 1.8.7 String#chars compatibility problem with rails

Recently, I started getting weird "LoadError" with my Rails app on Dreamhost. I had an "Article" model which contained many "Photo" models. When the "Article" controller tried to refer to the photos in its object, I got the following error:
LoadError: Expected {full server path}/photo.rb to define Photo.

I had a photo.rb file which had class Photo defined. I was using attachment_fu plugin to implement photos. After some head scratching, I found that the error was in photo.rb file. Hence photo.rb was not loading correctly, and therefore a load error.

The actual error happened coz the Dreamhost guys had updated Ruby to 1.8.7 which has some incompatibility with Rails 2.0.2 that I was using. When I tried to create a Photo object on the command line, I got this error:
NoMethodError: undefined method '[]' for #<Enumerable:enumerator></code>

Ruby 1.8.7 has String#chars. This returns an Enumerator object but Rails 2.0.2 expects an ActiveSupport::MultiBye::Chars object.

We can avoid this conflict, by putting the following code in the config/initializers/ directory.

  1.  
  2. unless '1.9'.respond_to?(:force_encoding)
  3. String.class_eval do
  4. begin
  5. remove_method :chars
  6. rescue NameError
  7. # OK
  8. end
  9. end
  10. end
  11.  

Comments (3)

Insert comments in an erb file

How does one insert comments in an erb file. The normal http tag to insert comments do not work well when there are embedded ruby statements in the html.

<!-- <b>Hello</b><%= @article.author %> -->

The above statement will not stop the evaluation of article.author. Instead, @article.author will still be evaluated and placed as a comment in the generated html file. Say the author was Balpreet, then we have a html comment:

<!-- <b>Hello</b>Balpreet -->

So, what if we want to just comment stuff out, so that the embedded ruby statements are not evaluated at all. There are basically two ways that I think we can achieve this:

1. Insert block level comments using embedded ruby.
<%
=begin %>
<b>Hello</b><%= @article.author %><%
=end %>

2. Insert conditional
<% if false %>
<b>Hello</b><%= @article.author %>
<% end %>

Leave a Comment