I’ve made an Impressions model, which keeps track of how many “views” a certain photo or event has. It tracks this by remote_url, remote_ip and user_agent. It works the way I want it.
Photos controller:
def show
@photo.impressions.create(:request_url => request.url, :controller_name => controller_name, :action_name => action_name,
:ip_address => request.remote_ip, :user_agent => request.user_agent)
....
And my Events controller:
def show
@event.impressions.create(:request_url => request.url, :controller_name => controller_name, :action_name => action_name,
:ip_address => request.remote_ip, :user_agent => request.user_agent)
....
However, I am thinking of refactoring this (to make the code cleaner). Perhaps creating a method in the Photo and Event models called add_impression. Which does exactly the same thing as above, but encapsulates the functionality of how impressions are created. It would look something like:
Photos controller:
def show
@photo.add_impression(request.url, controller_name, action_name, request.remote_ip, request.user_agent)
....
And my Events controller:
def show
@event.add_impression(request.url, controller_name, action_name, request.remote_ip, request.user_agent)
....
With this approach, I would end up with an add_impression method in the Photo and Event model. Not exactly DRY (Don’t Repeat Yourself). I’m considering creating an Impression module to tackle this.
Is this the right approach? Or is there something else that I should be doing?
PS Am not very well tuned with modules yet. So if anyone would like to leave a code snippet or links to articles worth reading. Please do so.
Personally I would make Impression responsible for creating an impression with a class method, as such:
Then in the controller: