Category Archives: debugging

Frustrations abound: RVM vs. MacPorts and the [BUG] Segmentation fault

Do you use RVM? Do you use MacPorts? Have you installed openssh via MacPorts? And have you torn your hair out when trying to compile Ruby 1.9.x and gotten errors like this:

% bundle install
Fetching gem metadata from https://rubygems.org/......
Fetching gem metadata from https://rubygems.org/..
/Users/amy/.rvm/rubies/ruby-1.9.3-p194/lib/ruby/1.9.1/net/http.rb:799: [BUG] Segmentation fault
ruby 1.9.3p194 (2012-04-20 revision 35410) [x86_64-darwin11.3.0]

-- Control frame information -----------------------------------------------
c:0033 p:---- s:0199 b:0199 l:000198 d:000198 CFUNC  :connect
c:0032 p:0011 s:0196 b:0196 l:002460 d:000195 BLOCK  /Users/amy/.rvm/rubies/ruby-1.9.3-p194/lib/ruby/1.9.1/net/http.rb:799
c:0031 p:0031 s:0194 b:0194 l:000193 d:000193 METHOD /Users/amy/.rvm/rubies/ruby-1.9.3-p194/lib/ruby/1.9.1/timeout.rb:54
c:0030 p:0026 s:0182 b:0182 l:000181 d:000181 METHOD /Users/amy/.rvm/rubies/ruby-1.9.3-p194/lib/ruby/1.9.1/timeout.rb:99
c:0029 p:0485 s:0176 b:0176 l:002460 d:002460 METHOD /Users/amy/.rvm/rubies/ruby-1.9.3-p194/lib/ruby/1.9.1/net/http.rb:799
c:0028 p:0011 s:0168 b:0168 l:000167 d:000167 METHOD /Users/amy/.rvm/rubies/ruby-1.9.3-p194/lib/ruby/1.9.1/net/http.rb:755
c:0027 p:0089 s:0165 b:0165 l:000164 d:000164 METHOD /Users/amy/.rvm/rubies/ruby-1.9.3-p194/lib/ruby/1.9.1/net/http.rb:750

You are most likely to have been in my position for the past day or so where unfruitful searches for “rvm” and “http.rb:799: [BUG] Segmentation fault” turned up not much conclusive. There are a number of posts on StackOverflow which seem to be talking about this and even a very detailed post, but I found the solutions to be incomplete. Then I chanced across the Using MacPorts with RVM page. It turns out that using MacPorts will install openssl but in a different place than what RVM is expecting, hence because your Gemfile most likely has:

source 'https://rubygems.org'

gem 'rails', '3.2.1'

Rails/bundler is going to try to use openssl, but of course http.rb is going to fail with a:

-- C level backtrace information -------------------------------------------

   See Crash Report log file under ~/Library/Logs/CrashReporter or
   /Library/Logs/CrashReporter, for the more detail of.

...

You may have encountered a bug in the Ruby interpreter or extension libraries.
Bug reports are welcome.
For details: http://www.ruby-lang.org/bugreport.html

Abort trap: 6

Not happy. Worse yet, many of the solutions just say to use “with-openssl-dir”, but that didn’t completely solve it for me.

Fortunately the official RVM page has an incantation if you want the MacPorts’ installation of openssl: add this to your master $HOME/.rvmrc:

export CFLAGS="-O2 -arch x86_64"
export LDFLAGS="-L/opt/local/lib"
export CPPFLAGS="-I/opt/local/include"

Follow that up with a basic install of 1.8.7:

rvm install 1.8.7 --with-openssl-dir=/opt/local

And finish that with the actual Ruby version of your choice:

rvm install ruby-1.9.3-p194 --with-opt-dir=/opt/local

(You can also do an rvm reinstall.)

The happy result?

rvm reinstall ruby-1.9.3-p194 --with-opt-dir=/opt/local
Removing /Users/amy/.rvm/src/ruby-1.9.3-p194...
Removing /Users/amy/.rvm/rubies/ruby-1.9.3-p194...
Removing ruby-1.9.3-p194 aliases...
Removing ruby-1.9.3-p194 wrappers...
Removing ruby-1.9.3-p194 environments...
Removing ruby-1.9.3-p194 binaries...
Please note that you are using your own '--with-opt-dir=', make sure 'libyaml' is installed and available for ruby compilation.
Installing Ruby from source to: /Users/amy/.rvm/rubies/ruby-1.9.3-p194, this may take a while depending on your cpu(s)...

ruby-1.9.3-p194 - #fetching
ruby-1.9.3-p194 - #extracting ruby-1.9.3-p194 to /Users/amy/.rvm/src/ruby-1.9.3-p194
ruby-1.9.3-p194 - #extracted to /Users/amy/.rvm/src/ruby-1.9.3-p194
ruby-1.9.3-p194 - #configuring
ruby-1.9.3-p194 - #compiling
ruby-1.9.3-p194 - #installing
Removing old Rubygems files...
Installing rubygems-1.8.24 for ruby-1.9.3-p194 ...
Installation of rubygems completed successfully.
ruby-1.9.3-p194 - adjusting #shebangs for (gem irb erb ri rdoc testrb rake).
ruby-1.9.3-p194 - #importing default gemsets (/Users/amy/.rvm/gemsets/)
Install of ruby-1.9.3-p194 - #complete

Note the fact I also had done a sudo port install libyaml. Also note that should that fail, you may have to do the manual installation of libyaml per instructions on http://pyyaml.org/wiki/LibYAML:

% ./configure
% make
% make install (or "sudo make install")

Configure Rails 3’s I18N load path for subdirectories

If you’re like me you want to use nested directories to organize all of your files, especially when it comes to internationalization (I18N). I just found out about the nifty views trick that uses your current controller and action as the first part of your translation key. For example, let’s say you are looking at a list of all uploads you might be viewing the action:

http://www.yoursite.com/uploads/

Inside the template you probably have:

<h1><%= t('.title') %></h1>

Because of the leading dot Rails will be looking for the key defined as (assuming :en locale):

en:
  uploads:
    index:
      title: Your title

Since you’re going to have a lot of locale files, you might think of placing the English locale file in:

config/locales/views/uploads/index/en.yml

Which is all well and good until you realize the I18N load path doesn’t include subdirectories. A quick fix to application.rb is all it takes though. Add:

config.i18n.load_path += Dir[Rails.root.join('config', 'locales', '**/*.{rb,yml}').to_s]

The ** is the magic there.

join() is slower than the

Turns out the Internet was right on this one: if you’re trying to create a big string from little ones it’s faster to << (less-than-less-than operator) on a String than to make an array of Strings and join its elements. Without diving into the Ruby code itself my guess is that strings are linked lists in memory and its end pointer is just moved, whereas making a bunch of array elements means new String objects for each and then having to walk all of the objects to form a new String in the end. (Granted, I’m using Ruby 1.8.7 still!)

Here’s the code:

require 'benchmark'
Benchmark.bm(20) do |x|
  x.report('join') do
    1_000.times do
      a = []
      1_000.times do
        a << 'This is some string stuff'
      end
      a.join
    end
  end
  x.report('<<') do
    1_000.times do
      a = ''
      1_000.times do
        a << 'This is some string stuff'
      end
      a
    end
  end
end

And the result:

          user     system      total      real
join  1.180000   0.390000   1.570000 (1.571057)
<<    1.090000   0.390000   1.480000 (1.491420)

Double-checking for nil and the Maybe Pattern

While listening to The Ruby Show episode #176 I heard about the ThoughtBot post about the Maybe Pattern as discussed in their “If you gaze into nil, nil gazes also into you” post.

It took me a minute to figure out what was going on. (Maybe I’m just getting slower in my old age.) Plagiarizing from their post, they included the code required to set up the Maybe Pattern and I’ll try to add my own comments in red so I feel like I’m adding something to this conversation:

This is modifying the base Object of which every Ruby object is
a child. Yes, that means even Nil gets an automatic maybe()
method stuck in it.

The idea is that if you think a method *might* return a value
then you ought to return your value with a .maybe() on it.
That accomplishes the "wrapping". You'll see that it takes
itself and returns an instance of Some with itself stuffed
into it. Thus at this point you really get a Some() object
back, not your original return value.
class Object
  def maybe
    Some.new(self)
  end
end

... Except for Nil. This one definitely is empty/blank/nothing
so we need to create an instance of Some that will throw
exceptions if you try to unwrap it.
class NilClass
  def maybe
    None.new
  end
end

And here is the Some object that wraps anything you give
it by storing it in its own @object attribute.
class Some
  def initialize(object)
    @object = object
  end

  This is how you "unwrap" an object. Pay close attention
that the None version of this will throw exceptions.
  def get
    @object
  end

  This is one way you can check to see if there might
be values.
  def present?
    true
  end

  And this is the other.
  def blank?
    false
  end
end

And back to some Magic Sauce. It creates a new error type,
Unwrapped, and will return it when you attempt to call get().
This is because as a consumer of the Some or None values
you ought to have checked present?() or blank?() first. That's 
right, consumers need to be sure that they're not just going
to use a nil value.
class None
  class Unwrapped < StandardError; end

  def get
    raise Unwrapped
  end

  def present?
    false
  end

  def blank?
    true
  end
end

OK, great. So how do you use this in practice?

When you return a value that is absolutely true or false, then do so. If you think your return value might be null then wrap it by tacking on a .maybe() call.

The consumer of these return values should always check for present?() or blank?(). If something is not present or is blank then you should no longer need to access the return value because, well, you got your answer.

However, if you need to use the return value for something (e.g. it might be a single object, or might be an array, or a Hash, or ...) then you need to check if it's present?() and/or not blank?(). If that's true then you can call the object's .get() method to grab that value and continue with your logic. Like:

accounts = bank(me).accounts
# accounts might be nil ... check present?()
if accounts.present?
  account_list = accounts.get
  # Now account_list definitely has something which isn't nil!
end

The main thought I had in all of this is that this will create tons of wrapper objects that could just add bloat to your application. Plus there's the extra evaluation involved. In my own code I almost always just use the Rails .blank?() method to check if things are there. That seems to handle nil, empty strings, and empty arrays just fine!

Have your custom Paperclip Processors gone missing?

I’ve been converting a Rails 2.3.8 app into a Rails 3 app and one snafu was figuring out what happened to Paperclip. I use it to actually post-process audio files after upload, in this case slowing them down. I was getting this error:

uninitialized constant Paperclip::SlowerAudioFile:

Which is weird because I checked the readme and it still says to put them in the lib/paperclip_processors. I moved things around, I tried a bunch of little changes to the processor code, but nothing.

It seems the larger problem is just that the lib directory wasn’t being automatically loaded at all. (Turns out someone blogged this.) But by the time I had read that I had already taken the advice of a StackOverflow conversation and had just moved my processor to config/initializers/paperclip/slower_audio_file.rb, the beginning of the code looking like:

module Paperclip
  class SlowerAudioFile < Processor
    def initialize file, options = {}, attachment = nil
      ...
    end
    ...
  end
end

Firebug error “invalid label” with Rails + UJS + jQuery

I’ve been playing more with Rails’ UJS via jQuery and I came across an error that took a while to track down. It turned out to be a content type problem.

Making the form was easy:

And the JavaScript hookup was also easy:

So was the Rails controller:

But Firebug kept showing the error “invalid label”. After much Googling and playing around with things I came to realize that there was one thing that was left out: the content type. Rails was returning the JSON as a string, not as a JSON data type. So a minor tweak to the controller solved everything:

JavaScript negative numbers modulus bug

I just got bit by a rather weird bug. In most programming languages you can do “a modulo b” and get back a number between 0..(b-1). This is wonderful when you have an array of n items and you want to select a number in the range of array indexes 0..(n-1) but you want to use some kind of an incremental counter. For example:

var letters = ['a', 'b', 'c', 'd'];
var idx = 0;
for (i = 0; i < 100; i++) {
  window.console.log(letters[idx % letters.length]);
  idx++;
}

This should print out to the debug console: a b c d a b c d a b c d … and so on. The “% letters.length” keeps the range of integer indexes between 0..3 in this case.

So the cool thing is that instead of incrementing idx you could reverse it:

var letters = ['a', 'b', 'c', 'd'];
var idx = 0;
for (i = 0; i < 100; i++) {
  window.console.log(letters[idx % letters.length]);
  idx--;
}

And we should see: a d c b a d c b a d c b a … and so on.

But not in JavaScript.

Apparently there is a bug where it will constrain idx but it will allow negative numbers! So the idx values in this case will go: 0 -1 -2 -3 0 -1 -2 -3 0 -1 -2 -3 … and so on. What we expected was that it would go: 0 3 2 1 0 3 2 1.

The solution (which also ended up on About.com) is to add your modulo back to the number and do a second modulo. It’s totally inefficient, I know. So in this example:

var letters = ['a', 'b', 'c', 'd'];
var idx = 0;
for (i = 0; i < 100; i++) {
  window.console.log(letters[((idx % letters.length) + letters.length) % letters.length]);
  idx--;
}

or the formula: ((a % b) + b) % b)

Ugh.

Web pages with small fonts, 12px/0.9em at the very least please

So an interesting thing happened the other day. I was reading a popular site that deals with creating web content and I caught myself doing one of the tell-tale things that users do when the fonts on a web page are too small: they lean inward. Now, I know that I’m not exactly in my early 20s anymore and it is true that I do wear glasses almost all of the time now, but my eyesight really isn’t that bad. And I’ve read this site off and on for a while and I don’t remember having to have this lean-in problem before. Then I remembered one thing: I have a new laptop.

Yes, if you’ve read previous posts you know how I used to rave about my old 2008-edition MacBook Air. So light, so powerful, so fast, yada yada. And then I switched up to a 2010 edition at the end of last year. Bigger SSD, higher resolution, dual USB ports, yada yad—wait. Higher resolution? Yes, in fact I now have a 13″ display that has almost 128 dots per inch compared to the old 113 dots per inch. So how much of a difference does that make? Apparently a lot.

For comparison, let me put up this image:

Previously I had a 1280px-wide display that has about 11.26″ horizontal length. Now I have a 1440px display. That means those web sites with tiny fonts just got a heckuva lot tinier. I mean, you would think that 12% smaller might not be a great big deal, but I really do think it does.

I went around the web this morning looking at other examples of font sizing. It seems the smallest comfortable font size for me now is 12px high. The website which has the tiny fonts above works out to about 11px high. But if they just increased it a smidge …

We’re clearly into a time where LCD display technology has gotten so good that we now have displays *AT* (not “approaching”) print resolution. Case in point: Apple’s Retina Display technology gives us 300 ppi. A couple of years ago I had been looking at a Sony ultraportable that was at 220 ppi. We’ve reached the point where small definitely means small.

I don’t exactly know what the solution is here. We could ask browser manufacturers to set their default browser font sizes at a certain ppi. There are some web pages that depend on fonts being only a certain height. Maybe the new tablet era of computing with it’s pinch-zoom mitigates all of this because users just expand the text content until it looks comfortable.

In the meanwhile I’m recommending that anyone making web UIs not use a font smaller than 12px high or 0.90em high.

Rails forms automatically insert a hidden utf8 field? (a.k.a. what’s with the checkmark/snowman?)

Yes, apparently this is true according to a response on StackOverflow. Let’s say you have a simple form from a model:

  <%= form_for @some_model do |f| %>
   ...
  <% end %>

You might see the following output in the generated HTML:

  <div style="margin:0;padding:0;display:inline">
  <input name="utf8" type="hidden" value="&#x2713;" />
  ...other stuff...
  </div>

Apparently in order to force browsers to submit the form in UTF-8 encoding mode this UTF-8 value (✓) does the trick. If you peer into the code you can see inside the actionpack form_tag_helper.rb that this is called the “snowman_tag”. A little Googling reveals this post on http://railssnowman.info:

What’s with the _utf8/_e/_snowman tag in Rails 3?

The _utf8 input tag forces Internet Explorer to properly respect your form’s character encoding.

Rails uses the accept-charset attribute in your form element to let the server know that it should be able to deal with unicode characters (think of a user searching for café).

But it looks like old snowman value &#9731; (☃) has been since replaced with the simple check mark &#x2713; (✓). 🙂