How to Use Callback Classes

Posted over 2 years ago by Philip Ingram

I had a need to reuse an after_create callback over two different Models. Smelling something off, i wondered if there was a way to DRY this part of my code, as I like to reuse when i can. Although i’m not a maniac about it, to me it seems that reusing a callback is something that you’d want to keep DRY.

Off i went to the mainstay of rails knowledge the Rails Guides , and i found this bit of instruction, on which this post will elaborate.

Introducing Callback Classes

To refresh, a callback is used when you want to execute additional code after a record has been created or updated. This is some fascinating stuff, and well worth reading into. For example, these callbacks are used to update additional attributes based on a new record being created and it tidies up your code immensely.

Callback classes take this thinking a step further by allowing you to create a Class for the Callback and refer to this Class within your various different models.

Example of Callback Classes in use

I needed to generate a unique code after a certain model was created.

First, I created a file within app/models called unique_code_callbacks.rb.

Since there were two models where this code could be created, so streamlining the code this way made sense for me. I added this code to the new file i just created:


class UniqueCodeCallbacks
  def self.after_create(something)
    self.unique_unique_code(something)
  end
  #make a unique code
  def self.unique_unique_code(blah)
    if blah.class == TaxInfo
      self.make_unique_code(blah.company_info.user) if blah.company_info.user.unique_code.blank?
    else
      self.make_unique_code(blah.user) if blah.address.country != "US" && blah.user.unique_code.blank?
    end
  end
  protected
  def self.make_unique_code(user)
    user.update_attribute(:unique_code, self.make_token)
  end
  def self.secure_digest(*args)
    Digest::SHA1.hexdigest(args.flatten.join('--'))
  end
  def self.make_token
    self.secure_digest(Time.now, (1..10).map{ rand.to_s })
  end
end

I'm using the latter example from the rails guide, but i’m also extending what they have shown you by adding all my logic within this class too. A couple of gotchas to watch out for:

  • make sure you add self.method to all the methods within this class
  • you need to pass something to the after_create callback, or you’ll receive an error calling for 1 when 0 expected , as that drove me nuts. Someone may comment why that is, if you know.

Using the Callback Class in your models

To use this great callback, all you have to do is add code like this to your model:


class TaxInfo < ActiveRecord::Base
  after_create UniqueCodeCallbacks
end

I’ve only created the after_create callback in this class, but you could have an after_update too, just add it to the class and bob is your uncle… really he is, you should call him.

Enjoy.

Comments

The post is very nicely written and it contains many useful facts on using callback. I am impressed on your distinguished way of delivering an informative topic. Looking forward for more updates!
I was wondering if you ever thought of changing the page layout of your site? Its very well written; I love what youve got to say. But maybe you could a little more in the way of content so people could connect with it better. Youve got an awful lot of text for only having 1 or 2 pictures. Maybe you could space it out better?
Hey! I just wanted to ask if you ever have any issues with hackers? My last blog (wordpress) was hacked and I ended up losing months of hard work due to no backup. Do you have any methods to stop hackers?
nTvt1m comment6
FgG09X I was looking for the report in Yandex and suddenly came across this page. I found a little information on my topic of my report. I would like more, and thanks for that..!!
I was wondering if you ever considered changing the structure of your blog? Its very well written; I love what youve got to say. But maybe you could a little more in the way of content so people could connect with it better. Youve got an awful lot of text for only having one or 2 pictures. Maybe you could space it out better?
I read and feel at home. Thanks the creators for a good resource..!
Thanks for the news! Just was thinking about it! By the way Happy New Year to all of you:D
Thank you, a very interesting note!!…
Last a few years has been to Ibiza, so met a person there whose style of presentation is very similar to yours. But, unfortunately, that person is too far from the Internet!….
Yeah, now it’s clear !… And firstly I did not understand very much where there was the link with the title itself !!….
Interesting, but still I would like to know more about it. Liked the article:D
52. “The road will be overcome by that person, who goes.” I wish you never stopped and be creative – forever..!
Cool:) I would say say it exploded my brain..!