Module: FacetRenderer

Extended by:
ActiveSupport::Concern
Defined in:
lib/generators/propel_facets/templates/controllers/concerns/facet_renderer.rb

Overview

Provide means to connect a controller to a JSON facetable model.

Usage:

class MyController < ApiController
  connect_facet :short, actions: [:index]
  connect_facet :full, actions: [:show, :update, :create]
end

Instance Method Summary collapse

Instance Method Details

#resource_json(resource) ⇒ Object

To be used by controller to return params with visible and included fields



45
46
47
48
49
50
51
52
53
54
55
56
57
58
# File 'lib/generators/propel_facets/templates/controllers/concerns/facet_renderer.rb', line 45

def resource_json(resource)
  facet = self.class.action_facet(action_name.to_sym)
  result = resource.as_json(
    facet: [facet, :index, :default],
    missing: :noaction
  )

  # get attachment url in single resource
  if !resource.respond_to?('length') && resource.class.respond_to?('attachment_reflections')
    set_attachments(result, resource)
  else
    result
  end
end

#set_attachments(result, resource) ⇒ Object

set attachments to result json



61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
# File 'lib/generators/propel_facets/templates/controllers/concerns/facet_renderer.rb', line 61

def set_attachments(result, resource)
  attachment_fields = {}
  resource.class.attachment_reflections.keys.each do |name|
    begin
      attachment = resource.send(name.to_sym)
      if attachment.is_a? ActiveStorage::Attached::Many
        # Note: This is configured to return a maximum of 10 files.
        # To retrieve all files within a specific parent model, utilize the 'Attachment' class.
        attachment_fields[name.to_sym] = attachment.take(10).map {|a| url_for(a) if attachment.attached?}.compact
      else
        attachment_fields[name.to_sym] = url_for(attachment) if attachment.attached?
      end
    rescue StandardError => e
      Rails.logger.error "Failed to generate URL for attachment #{name}: #{e.message}"
      next
    end
  end

  result&.merge(attachment_fields)
end