Module: APIResourceIncludable::HelperMethods

Defined in:
app/api/concerns/api_resource_includable.rb

Instance Method Summary collapse

Instance Method Details

#inclusion(resource = nil, field = nil) ⇒ Object

Getter for the inclusion data.


183
184
185
186
187
188
189
190
191
192
# File 'app/api/concerns/api_resource_includable.rb', line 183

def inclusion(resource = nil, field = nil)
  if resource.blank?
    @inclusion ||= {}
  elsif field.blank?
    (@inclusion ||= {})[resource] ||= []
  else
    return false if (try(:fieldset, resource).present? && !fieldset(resource, field))
    inclusion(resource).include?(field)
  end
end

#inclusion_for(resource, root: false, default_includes: []) ⇒ Object

Gets the include parameters, organize them into a @inclusion hash for model to use inner-join queries and/or templates to render relation attributes included. Following the URL rules of JSON API: jsonapi.org/format/#fetching-includes

Params:

resource

Symbol name of resource to receive the inclusion


144
145
146
147
148
149
150
151
152
153
154
155
156
157
# File 'app/api/concerns/api_resource_includable.rb', line 144

def inclusion_for(resource, root: false, default_includes: [])
  @inclusion ||= Hashie::Mash.new
  @meta ||= Hashie::Mash.new

  # put the includes in place
  if params[:include].is_a? Hash
    @inclusion[resource] = params[:include][resource] || params[:include][resource]
  elsif root
    @inclusion[resource] = params[:include]
  end

  # splits the string into array of symbles
  @inclusion[resource] = @inclusion[resource] ? @inclusion[resource].split(',').map(&:to_sym) : default_includes
end

#set_inclusion(resource, default_includes: []) ⇒ Object

View Helper to set the inclusion and default_inclusion.


160
161
162
163
164
# File 'app/api/concerns/api_resource_includable.rb', line 160

def set_inclusion(resource, default_includes: [])
  @inclusion ||= {}
  @inclusion_field ||= {}
  @inclusion[resource] = default_includes if @inclusion[resource].blank?
end

#set_inclusion_field(self_resource, field, id_field, class_name: nil, url: nil) ⇒ Object

View Helper to set the inclusion details.


167
168
169
170
171
172
173
174
175
176
177
178
179
180
# File 'app/api/concerns/api_resource_includable.rb', line 167

def set_inclusion_field(self_resource, field, id_field, class_name: nil, url: nil)
  return if (@fieldset.present? && @fieldset[self_resource].present? && !@fieldset[self_resource].include?(field))

  @inclusion_field ||= {}
  @inclusion_field[self_resource] ||= []
  field_data = {
    field: field,
    id_field: id_field,
    class_name: class_name,
    url: url
  }
  @inclusion_field[self_resource] << field_data
  @fieldset[self_resource].delete(field) if @fieldset[self_resource].present?
end