Skip to content

Instantly share code, notes, and snippets.

@quatermain
Created May 7, 2015 10:25
Show Gist options
  • Save quatermain/3d91b8a0f6b95f9e1343 to your computer and use it in GitHub Desktop.
Save quatermain/3d91b8a0f6b95f9e1343 to your computer and use it in GitHub Desktop.
Service layer
# app/services/pages/base.rb
module Pages
class Base
include Service
def self.call(account: nil, user: nil, page: nil, param: nil)
new(account: account, user: user, page: page).call( param: param)
end
def initialize(account: nil, user: nil, page: nil)
@account = account
@user = user
@page = page || Page.new(account: @account)
end
# some methods
end
end
# app/services/pages/create.rb
module Pages
class Create < Base
def call(param)
#some logic
@page
end
end
end
# app/controllers/pages_controller.rb
class PagesController < ApplicationController
# some methods
def create
@page = Pages::Create.call(account: current_account, user: current_user, params: page_params)
respond_to do |format|
if @page.persisted? && @page.errors.empty?
format.json {}
else
format.json{ render json: @page.errors, status: :unprocessable_entity}
end
end
end
#....
end
# app/services/service.rb
module Service
extend ActiveSupport::Concern
included do
def round_to_i(num)
num.round.to_i
end
def allow_state_update?(object)
if object.respond_to?('workflow_state_changed?') && object.workflow_state_changed?
if Pundit.policy(@user, object).allow_state_update?
true
else
object.errors.add(:state, "You don't have permissions to update this attribute to #{object.workflow_state.try(:humanize)}")
false
end
else
true
end
end
# ....
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment