Skip to content

Instantly share code, notes, and snippets.

@joahking
Last active November 1, 2016 14:08
Show Gist options
  • Save joahking/88ee87091e7dde0a3e8ecc1cd038eae1 to your computer and use it in GitHub Desktop.
Save joahking/88ee87091e7dde0a3e8ecc1cd038eae1 to your computer and use it in GitHub Desktop.
example of usage of a service in a controller
# app/services/store_tracking.rb
# service that tracks user visits to a store, and keeps counters in the models
class StoreTracking
def initialize(store, user, request)
@store = store
@user = user
@request = request
end
def track
RestClient.post "trackings/store/#{@store.id}", { user_id: @user.id, ip: @request.ip }
@store.increment! :visits_count
@user.increment! :visits_count
end
end
# app/controllers/stores_controller.rb
StoresController < ApplicationController
before_action :find_store
def show
StoreTracking.new(@store, current_user, request).track
end
private
def find_store
@store = Store.find params[:id]
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment