Class: VenusMediaLibrary::ImagesController

Inherits:
ApplicationController show all
Includes:
ImagesHelper
Defined in:
app/controllers/venus_media_library/images_controller.rb

Overview

Lists and uploads images backed by Active Storage. Storage-agnostic: it uses whatever service the host app configures (Disk in dev, S3 in prod, ...).

Constant Summary collapse

MAX_PER_PAGE =
100

Instance Method Summary collapse

Methods included from ImagesHelper

#ml_blob_url, #ml_image_payload, #ml_thumb_url

Instance Method Details

#createObject

POST /images Accepts an uploaded file and stores it via Active Storage.



33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
# File 'app/controllers/venus_media_library/images_controller.rb', line 33

def create
  uploaded = params[:file] || params.dig(:image, :file)

  if uploaded.blank?
    return respond_error("No file was uploaded.", :unprocessable_entity)
  end

  unless allowed_content_type?(uploaded.content_type)
    return respond_error("Content type #{uploaded.content_type} is not allowed.", :unprocessable_entity)
  end

  blob = ActiveStorage::Blob.create_and_upload!(
    io:           uploaded.tempfile,
    filename:     uploaded.original_filename,
    content_type: uploaded.content_type,
    service_name: VenusMediaLibrary.configuration.storage_service
  )
  asset = VenusMediaLibrary::Asset.create!(
    blob: blob, owner: venus_media_library_user,
    community_shared: ActiveModel::Type::Boolean.new.cast(params[:community_shared]) || false
  )

  respond_to do |format|
    format.json { render json: ml_image_payload(asset), status: :created }
    format.html { redirect_to images_path }
  end
rescue ActiveRecord::RecordInvalid
  blob&.purge
  raise
end

#indexObject

GET /images Lists image blobs, newest first, with simple offset pagination. Responds with an HTML grid or a JSON payload for the picker.



12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
# File 'app/controllers/venus_media_library/images_controller.rb', line 12

def index
  @page     = [ params.fetch(:page, 1).to_i, 1 ].max
  @per_page = per_page
  offset    = (@page - 1) * @per_page

  scope        = visible_media_assets
  @total_count = scope.count
  @blobs       = scope.order(created_at: :desc).offset(offset).limit(@per_page).to_a
  @has_more    = offset + @blobs.size < @total_count
  @images      = @blobs.map { |asset| ml_image_payload(asset) }

  respond_to do |format|
    format.html # index.html.erb
    format.json do
      render json: { images: @images, page: @page, has_more: @has_more, total: @total_count }
    end
  end
end