Singleton Class, acts_as_rated and twitterify in Rails

Today, I went to San Jose Ruby Hackfest meetup, and met a bunch of cool guys. One of them was Noah Gibbs, who helped me tremendously with one of the most pesky problems I had.

Before you go on, you might want to read up on really good tutorials on Singleton Class and Self variable.

At any rate, I use both acts_as_rated for rating playgrounds and twitterify for automatically generating a tweet when a new playground is added. They both are for my playground model, and I found out that they conflicts with each other. Ordinarily they both would be “declared” in the model like the following.

class Playground < ActiveRecord::Base
  acts_as_rated
  twitterify :name, :url, :if => Proc.new { |record| record.new_record? }
end

However, for some reason, when rate method from acts_as_rated is called, it would give me wrong number of argument error. Since it worked well before I installed twitterify, it was clear that there must have been conflict of methods, where two plug-ins may have been creating a method(s) with the same name. The simplest solution would be to put twitterify in a function and call it after a new record is created.

class Playground < ActiveRecord::Base
  after_create :tweet
  acts_as_rated
  def tweet
    twitterify :name, :url, :if => Proc.new { |record| record.new_record? }
  end
end

However, this generated “missing method” error.

undefined method `twitterify' for #<Playground:0xb73a7930>

Twitterify is a method that should be called on an object. When it was on the class level, it would have been called on Playground object indirectly because self here would be Playground object. However, when it was pushed down to another method called tweet, the search for the twitterify returned nothing, and thus the error.

By specifying a Class, everything is dandy.

class Playground < ActiveRecord::Base
  after_create :tweet
  acts_as_rated
  def tweet
    Playground.twitterify :name, :url, :if => Proc.new { |record| record.new_record? }
  end
end

However, I am still a bit fuzzy about Singleton Class and self variables. If you have a better explanation, please be my guest and do leave a comment.

3 thoughts on “Singleton Class, acts_as_rated and twitterify in Rails

Leave a Reply

Your email address will not be published. Required fields are marked *