Module: StandardAPI::Controller

Defined in:
lib/standard_api/controller.rb

Defined Under Namespace

Modules: ClassMethods

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.included(klass) ⇒ Object



6
7
8
9
10
11
12
13
14
15
# File 'lib/standard_api/controller.rb', line 6

def self.included(klass)
  klass.helper_method :includes, :orders, :model, :models, :resource_limit,
    :default_limit
  klass.before_action :set_standardapi_headers
  klass.before_action :includes, except: [:destroy, :add_resource, :remove_resource]
  klass.rescue_from StandardAPI::ParameterMissing, with: :bad_request
  klass.rescue_from StandardAPI::UnpermittedParameters, with: :bad_request
  klass.append_view_path(File.join(File.dirname(__FILE__), 'views'))
  klass.extend(ClassMethods)
end

Instance Method Details

#add_resourceObject



130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
# File 'lib/standard_api/controller.rb', line 130

def add_resource
  resource = resources.find(params[:id])
  association = resource.association(params[:relationship])
  subresource = association.klass.find(params[:resource_id])

  result = case association
  when ActiveRecord::Associations::CollectionAssociation
    association.concat(subresource)
  when ActiveRecord::Associations::SingularAssociation
    resource.update(params[:relationship] => subresource)
  end
  head result ? :created : :bad_request
rescue ActiveRecord::RecordNotUnique
  render json: {errors: [
    "Relationship between #{resource.class.name} and #{subresource.class.name} violates unique constraints"
  ]}, status: :bad_request
end

#calculateObject



38
39
40
41
42
43
44
45
46
47
48
49
# File 'lib/standard_api/controller.rb', line 38

def calculate
  @calculations = resources.reorder(nil).pluck(*calculate_selects).map do |c|
    if c.is_a?(Array)
      c.map { |v| v.is_a?(BigDecimal) ? v.to_f : v }
    else
      c.is_a?(BigDecimal) ? c.to_f : c
    end
  end
  @calculations = Hash[@calculations] if @calculations[0].is_a?(Array) && params[:group_by]

  render json: @calculations
end

#createObject



60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
# File 'lib/standard_api/controller.rb', line 60

def create
  record = model.new(model_params)
  instance_variable_set("@#{model.model_name.singular}", record)

  if record.save
    if request.format == :html
      redirect_to url_for(
        controller: record.class.base_class.model_name.collection,
        action: 'show',
        id: record.id,
        only_path: true
      )
    else
      render :show, status: :created
    end
  else
    if request.format == :html
      render :new, status: :bad_request
    else
      render :show, status: :bad_request
    end
  end
end

#create_resourceObject



148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
# File 'lib/standard_api/controller.rb', line 148

def create_resource
  resource = resources.find(params[:id])
  association = resource.association(params[:relationship])

  subresource_params = if self.respond_to?("filter_#{model_name(association.klass)}_params", true)
    self.send("filter_#{model_name(association.klass)}_params", params[model_name(association.klass)], id: params[:id])
  elsif self.respond_to?("#{association.klass.model_name.singular}_params", true)
    params.require(association.klass.model_name.singular).permit(self.send("#{association.klass.model_name.singular}_params"))
  elsif self.respond_to?("filter_model_params", true)
    filter_model_params(params[model_name(association.klass)], association.klass.base_class)
  else
    ActionController::Parameters.new
  end

  subresource = association.klass.new(subresource_params)

  result = case association
  when ActiveRecord::Associations::CollectionAssociation
    association.concat(subresource)
  when ActiveRecord::Associations::SingularAssociation
    resource.update(params[:relationship] => subresource)
  end

  partial = model_partial(subresource)
  partial_record_name = partial.split('/').last.to_sym
  if result
    render partial: partial, locals: {partial_record_name => subresource}, status: :created
  else
    render partial: partial, locals: {partial_record_name => subresource}, status: :bad_request
  end
end

#destroyObject



108
109
110
111
112
113
# File 'lib/standard_api/controller.rb', line 108

def destroy
  records = resources.find(params[:id].split(','))
  model.transaction { records.each(&:destroy!) }

  head :no_content
end

#indexObject



33
34
35
36
# File 'lib/standard_api/controller.rb', line 33

def index
  records = preloadables(resources.limit(limit).offset(params[:offset]).sort(orders), includes)
  instance_variable_set("@#{model.model_name.plural}", records)
end

#maskObject



180
181
182
183
184
# File 'lib/standard_api/controller.rb', line 180

def mask
  @mask ||= Hash.new do |hash, key|
    hash[key] = mask_for(key)
  end
end

#mask_for(table_name) ⇒ Object

Override if you want to support masking



187
188
189
190
191
# File 'lib/standard_api/controller.rb', line 187

def mask_for(table_name)
  # case table_name
  # when 'accounts'
  # end
end

#newObject



56
57
58
# File 'lib/standard_api/controller.rb', line 56

def new
  instance_variable_set("@#{model.model_name.singular}", model.new) if model
end

#remove_resourceObject



115
116
117
118
119
120
121
122
123
124
125
126
127
128
# File 'lib/standard_api/controller.rb', line 115

def remove_resource
  resource = resources.find(params[:id])
  association = resource.association(params[:relationship])

  result = case association
  when ActiveRecord::Associations::CollectionAssociation
    association.delete(association.klass.find(params[:resource_id]))
  when ActiveRecord::Associations::SingularAssociation
    if resource.send(params[:relationship])&.id&.to_s == params[:resource_id]
      resource.update(params[:relationship] => nil)
    end
  end
  head result ? :no_content : :not_found
end

#schemaObject



28
29
30
# File 'lib/standard_api/controller.rb', line 28

def schema
  Rails.application.eager_load! if !Rails.application.config.eager_load
end

#showObject



51
52
53
54
# File 'lib/standard_api/controller.rb', line 51

def show
  record = preloadables(resources, includes).find(params[:id])
  instance_variable_set("@#{model.model_name.singular}", record)
end

#tablesObject



17
18
19
20
21
22
23
24
25
# File 'lib/standard_api/controller.rb', line 17

def tables
  Rails.application.eager_load! if !Rails.application.config.eager_load

  tables = ApplicationController.descendants
  tables.select! { |c| c.ancestors.include?(self.class) && c != self.class }
  tables.map!(&:model).compact!
  tables.map!(&:table_name)
  render json: tables
end

#updateObject



84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
# File 'lib/standard_api/controller.rb', line 84

def update
  record = resources.find(params[:id])
  instance_variable_set("@#{model.model_name.singular}", record)

  if record.update(model_params)
    if request.format == :html
      redirect_to url_for(
        controller: record.class.base_class.model_name.collection,
        action: 'show',
        id: record.id,
        only_path: true
      )
    else
      render :show, status: :ok
    end
  else
    if request.format == :html
      render :edit, status: :bad_request
    else
      render :show, status: :bad_request
    end
  end
end