0

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
nothing-special-here
  • 11,230
  • 13
  • 64
  • 94

2 Answers2

1
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).

Community
  • 1
  • 1
Leonid Shevtsov
  • 14,024
  • 9
  • 51
  • 82
0

This should accomplish your goal:

def image
  old_image
  write_attribute("pageview", pageview + 1)
end
Ryan
  • 2,073
  • 1
  • 19
  • 33