Mr. Black
Mr. Black

Reputation: 12122

rails skip after_find callback for particular method

I am using after_find callback to denormalize the phone after executing/selecting users table.

after_find :denormalize_phone

def denormalize_phone
  self.phone = "....."
end

I have a problem when I tried to create a dynamic method like below. I want to skip the after_find callback for this particular block. Can anyone help me?

User.order(:state).map(&:state).uniq.each do |state|
  define_singleton_method("is_#{state}_for") do |r|
    ....
  end
end

tx

Upvotes: 0

Views: 532

Answers (1)

Andrius Chamentauskas
Andrius Chamentauskas

Reputation: 756

Don't use after_find for this. Seriously I can't find any reason to ever use after_find. Here are your options (ordered from best to worst IMO):

  1. Use a decorator object for your User object. Decorators are used to group presentation logic of models. You could implement it yourself (not that hard) or here's a gem to get you started.
  2. Use a helper method. Something like format_phone(@user.phone). The downside is of course that you will have to call helper everywhere.
  3. Overwrite phone method in your User model. To get database value of it you can use self[:phone]. This is a bit messy though since you're putting presentation logic in data layer.

Upvotes: 1

Related Questions