Search code examples
ruby-on-railsrubyobserver-pattern

Rails How to add observer to only one custom method


I would like to create an observer which will observe only one custom method.

I got Baner model. For each call for image method I would like to increase pageview field.

class Baner < ActiveRecord::Base

has_attached_file :image

def pageview_inc
  pageview += 1
  save
end

alias old_image image

def image
  old_image
end
end

Is it possibly to set observer for only one custom method? That after image method call pageview_inc method will be executed.

EDIT

If i change that method for

  def image                                                            
    old_image
    self.pageview   += 1
    self.save!
  end

And I get stack level too deep.

The same effect for

  def image    
    self.pageview   += 1
    self.save!                                                        
    old_image
  end

Solution

  • class Baner < ActiveRecord::Base
    
      has_attached_file :image
    
      alias_method :old_image, :image
    
      def image
        increment!(:pageview)
        old_image
      end
    end
    

    Two things here:

    1) see this question: Should I use alias or alias_method?

    2) increment! will update the counter without saving the entire model, avoiding possible calls to image in the process of saving it (thus causing a recursion loop).