Module: AlphaApi::Concerns::Actionable

Extended by:
ActiveSupport::Concern
Defined in:
lib/alpha_api/concerns/actionable.rb

Instance Method Summary collapse

Instance Method Details

#createObject



10
11
12
13
14
15
16
17
18
19
20
21
# File 'lib/alpha_api/concerns/actionable.rb', line 10

def create
  authorize! :create, resource_class
  new_resource = build_resource(permitted_create_params)
  if new_resource.valid?
    authorize! :create, new_resource
    new_resource.save
    render status: :created, json: resource_serializer.new(new_resource).serializable_hash
  else
    errors = reformat_validation_error(new_resource)
    raise AlphaApi::Exceptions::ValidationErrors.new(errors), 'Validation Errors'
  end
end

#destroyObject



59
60
61
62
63
64
65
66
67
68
69
70
71
# File 'lib/alpha_api/concerns/actionable.rb', line 59

def destroy
  if destroyable
    resource = resource_class.find(params[:id])
    authorize! :destroy, resource
    if resource.destroy
      head :no_content
    else
      raise AlphaApi::Exceptions::ValidationErrors.new(resource.errors), 'Validation Errors'
    end
  else
    raise AlphaApi::Exceptions::MethodNotAllowed, 'Method Not Allowed'
  end
end

#indexObject



23
24
25
26
27
28
29
30
31
32
33
34
35
36
# File 'lib/alpha_api/concerns/actionable.rb', line 23

def index
  authorize! :read, resource_class
  query = apply_filter_and_sort(collection)
  apply_pagination
  if params[:page].present?
    records = paginate(query)
    records = records.padding(params[:page][:offset]) if params[:page][:offset]
  else
    records = query
  end

  options = options(nested_resources, params[:page], query.count)
  render json: resource_serializer.new(records, options).serializable_hash
end

#showObject



38
39
40
41
42
43
# File 'lib/alpha_api/concerns/actionable.rb', line 38

def show
  resource = resource_class.find(params[:id])
  authorize! :read, resource
  options = options(nested_resources)
  render json: resource_serializer.new(resource, options).serializable_hash
end

#updateObject



45
46
47
48
49
50
51
52
53
54
55
56
57
# File 'lib/alpha_api/concerns/actionable.rb', line 45

def update
  cached_resource_class = resource_class
  resource = cached_resource_class.find(params[:id])
  authorize! :update, resource
  options = options(nested_resources)
  if resource.update(permitted_update_params(resource))
    updated_resource = cached_resource_class.find(params[:id])
    render json: resource_serializer.new(updated_resource, options).serializable_hash
  else
    errors = reformat_validation_error(resource)
    raise AlphaApi::Exceptions::ValidationErrors.new(errors), 'Validation Errors'
  end
end