Skip to content

Instantly share code, notes, and snippets.

@arenoir
Last active December 29, 2015 18:18
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save arenoir/7709521 to your computer and use it in GitHub Desktop.
Save arenoir/7709521 to your computer and use it in GitHub Desktop.
class AccessControl < Struct.new(:user, :params)
def authorized_params!
authorized_params
end
def serialization_keys!(_keys, _resource)
_authorized_keys = authorize_serialization_keys(_keys, _resource)
_params_keys = serialization_keys_from_params
if _params_keys.any?
_authorized_keys & _params_keys
else
_authorized_keys
end
end
private
#safe defaluts.
def authorized_params
return []
end
def authorize_serialization_keys(_keys, _resource)
_keys
end
def _serialization_keys_from_params
_params = params[serialization_keys_param_name]
if _params && _params.is_a?(Array)
return _params.map!(&:to_sym)
else
[]
end
end
end
PostSerializer < ActiveModel::Serializer
attributes :title, :body
has_many :comments
def filter(_keys)
if scope
scope.serialization_keys!(_keys, object)
else
_keys
end
end
end
PostsAccessControl < AccessControl
def authorize_serialization_keys(_keys, _resource)
@_keys ||= _autorized_keys(_keys)
end
def authorized_params
params.require(:post).permit(*_autorized_params)
end
private
def _authorized_keys(_keys)
if user.manager?
_keys
else
_keys - [:comments]
end
end
def _autorized_params
_params = [:body]
if user.manager?
_params.push(:title)
end
return _params
end
end
class PostController < ActionController::Base
#https://gist.github.com/arenoir/7709928
include JsonApiConcern
#relevent part
serialization_scope :access_control
def access_control
@access_control ||= PostsAccessControl.new(current_user, params)
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment