Is this your first visit? You may want to subscribe to the feed.

Articles tagged with code

Fix for acts_as_audited and attr_accessible

The biggest complaint I get about acts_as_audited is finally fixed: if you want to use acts_as_audited on a model that uses attr_accessible, you can set the :protect option to false:

class User < ActiveRecord::Base
  acts_as_audited :protect => false
  attr_accessible :name
end

This will prevent acts_as_audited from using attr_protected, which would cause Active Record to raise an error in combination with attr_accessible.

Get the latest code from GitHub

Update: Timothy N. Jones had a good suggestion to automatically disable attr_protected if attr_accessible has already been called. I updated acts_as_audited, so now you only have to set :protect to false if you are declaring attr_accessible after you call acts_as_audited.

Code: code Aug 02, 2008 ● updated Oct 14, 2008 0 comments

Daily WTF: NilClass#method_missing

With great power comes great responsibility.

I’ve been leading Ruby and Rails training over the last couple weeks for a company in Brisbane, Australia, Xerox in El Segundo, CA, and yellowpages.com in Glendale, CA. Visiting companies is always so interesting because you get to see how different people work together and how they go about solving problems. You also get to see some really interesting code.

I was helping one of the companies walk through some code they inherited from an acquisition and came across something similar to this wonderful snippet of code:

class NilClass
    def method_missing(method, *args)
      raise(NoMethodError, "undefined method '#{method}' for nil")
    rescue => e
      CustomLogger.error(e)
      nil
    end
  end

WTF? They’re overriding #method_missing on nil to raise an exception, they then proceed to rescue it, log the error, and return nil!

I’m guessing they had some buggy code that was calling a method on nil, causing a NoMethodError to be raised. And instead of fixing the code, they just decided to change it so that you could call methods on nil and it would just silently fail.

>> nil.foo.bar.baz
=> nil

It took me a while to figure out why they were raising an error and then rescuing it, but I’m guessing it’s so they have access to a stack trace in the logger.

I’ll give them credit for being creative, but whoever wrote that piece of code doesn’t deserve to be using Ruby. Yes, Ruby’s open classes are powerful, but that’s just ridiculous.

Code: code Apr 18, 2008 ● updated Oct 14, 2008 8 comments

Subscribe

Browse by Tag