Giter Site home page Giter Site logo

uploadcare / uploadcare-rails Goto Github PK

View Code? Open in Web Editor NEW
58.0 16.0 67.0 2.08 MB

Rails API client that handles uploads and further operations with files by wrapping Uploadcare Upload and REST APIs.

Home Page: https://uploadcare.com

License: MIT License

Ruby 91.49% HTML 8.36% Shell 0.15%
ruby ruby-on-rails uploadcare widget cdn upload-images upload upload-pictures upload-videos uploading

uploadcare-rails's Introduction

Uploadcare Rails

license Build Status

A Ruby on Rails plugin for Uploadcare service. Based on uploadcare-ruby gem (general purpose wrapper for Uploadcare API)

Note: the gem uploadcare-rails 2.x is not backward compatible with 1.x.

Table of Contents

Requirements

  • ruby 2.7+
  • Ruby on Rails 6.0+

Installation

Using Gemfile

Add this line to your application's Gemfile:

gem "uploadcare-rails"

And then execute:

$ bundle install

If you use api_struct gem in your project, replace it with uploadcare-api_struct:

gem 'uploadcare-api_struct'

and run bundle install

Using command line

$ gem install uploadcare-rails

Usage

Configuration

To start using Uploadcare API you just need to set your API keys (public key and secret key). These keys can be set as ENV variables using the export directive:

$ export UPLOADCARE_PUBLIC_KEY=your_public_key
$ export UPLOADCARE_SECRET_KEY=your_private_key

Or you can use popular gems like dotenv-rails for setting ENV variables. You must set the gem before uploadcare-rails like this :

gem "dotenv-rails", require: "dotenv/rails-now", groups: [:development, :test]
gem "uploadcare-rails"

⚠️ require: "dotenv/rails-now" is very important!

Run the config generator command to generate a configuration file:

$ rails g uploadcare_config

The generator will create a new file in config/initializers/uploadcare.rb.

The public key must be specified in config/initializers/uploadcare.rb to use Uploadcare file upload. This step is done automatically in the initializer if you set the ENV variable UPLOADCARE_PUBLIC_KEY earlier.

...
Uploadcare::Rails.configure do |config|
  # Sets your Uploadcare public key.
  config.public_key = ENV.fetch("UPLOADCARE_PUBLIC_KEY", "your_public_key")
  ...
end

There are also some options set by default:

...
# Deletes files from Uploadcare servers after object destroy.
config.delete_files_after_destroy = true

# Sets caching for Uploadcare files
config.cache_files = true

# Available locales currently are:
# ar az ca cs da de el en es et fr he it ja ko lv nb nl pl pt ro ru sk sr sv tr uk vi zhTW zh
config.locale = "en"

# If true, inputs on your page are initialized automatically, see the article for details -
# https://uploadcare.com/docs/file-uploader-api/widget-initialization/
config.live = true

# If true, input initialization is invoked manually.
# See https://uploadcare.com/docs/file-uploader-api/widget-initialization/).
config.manual_start = false

Then you can configure all global variables such as files storing/caching, deleting files, etc. Full list of available options is listed in the file itself. Just uncomment an option and set the value.

Uploadcare File Uploader

Widget

Using CDN

The fastest way to start using file uploading is to add the Uploadcare widget to the html-page. There is a view helper that can do it with two strings of code:

Add this string to your <head> html-tag

<!DOCTYPE html>
<html>
<head>
  <title>RailsApp</title>
  <%= uploadcare_include_tag %>
  <!--
    results in:
    <script src="https://ucarecdn.com/libs/widget/3.x/uploadcare.full.min.js"></script>
    <script>
      //<![CDATA[
      UPLOADCARE_PUBLIC_KEY = "your_public_key";
      UPLOADCARE_LOCALE = "en";
      UPLOADCARE_LIVE = true;
      UPLOADCARE_MANUAL_START = false;
      //]]>
    </script>
  -->
</head>
...

This helper uses a CDN-url for the widget bundle and supports three options:

  • version — version of the Uploadcare widget. Default is "3.x".
  • bundle — bundle name. Available names are "full", "default", "api", "ie8" and "lang.en". Default bundle is "full" — a full bundle with built-in jQuery. More info about bundles here.
  • min — bool value detecting if the bundle must be minified.

The <head> tag then also includes the <script> with widget global settings set in config/initializers/uploadcare.rb. You can override them later in an individual widget.

Using asset pipeline.

Download and append widget manually to your asset pipeline. You may download (e.g. https://ucarecdn.com/libs/widget/3.x/uploadcare.full.min.js) and serve the widget yourself along with your other assets.

Using NPM

Installing via NPM instructions can be found here.

Input

When the widget is on a html-page, you want to add an input to your view that will be used by the File Uploader:

...
<%= uploadcare_uploader_field :object, :attribute %>
<!--
  results in:
  <input role="uploadcare-uploader" type="hidden" name="object[attribute]" id="object_attribute">
-->
...
  • object — object name;
  • attribute — object attribute name.

Using the File Uploader with Rails models

View helpers are good to be used for Rails models. First, you need to mount uploadcare file or group to the model attribute. For example you have a database table like this and model Post:

# DB table "posts"
---------------------
title       | String
---------------------
picture     | String
---------------------
attachments | String
---------------------

Form data

Uploadcare File

# app/models/post.rb
class Post < ApplicationRecord
  mount_uploadcare_file :picture
end
<!-- app/views/posts/new.html.erb -->
<h1> NEW POST </h1>

<%= form_tag("/posts", method: :post) do %>
  <%= uploadcare_uploader_field :post, :picture %>
  <!--
    results in:
    <input role="uploadcare-uploader" multiple="false" type="hidden" name="post[picture]" id="post_picture">
  -->
  <div>
    <%= submit_tag "Save" %>
  </div>
<% end %>

Uploadcare File Group

# app/models/post.rb
class Post < ApplicationRecord
  mount_uploadcare_file_group :attachments
end
<!-- app/views/posts/new.html.erb -->
<h1> NEW POST </h1>

<%= form_tag("/posts", method: :post) do %>
  <%= uploadcare_uploader_field :post, :attachments %>
  <!--
    results in:
    <input role="uploadcare-uploader" multiple="true" type="hidden" name="post[attachments]" id="post_attachments">
  -->
  <div>
    <%= submit_tag "Save" %>
  </div>
<% end %>

The input will have a value property set to CDN-urls when you will select files to upload in the widget.

<input role="uploadcare-uploader" type="hidden" name="post[picture]" id="post_picture" value="https://ucarecdn.com/8355c2c5-f108-4d74-963d-703d48020f83/">

So, you get CDN-urls as a value of the attribute in the controller on form submit. The value will be available in the controller by params[:post][:picture].

The helper is detecting the value of the multiple property based on the mount type in your model.

Caching issues with Turbolinks/Hotwire

If you are facing issue, with multiple input elements being rendered due to turbolinks caching you can append this fix in the app/javascript/application.js to overcome this:

document.addEventListener('turbolinks:before-cache', function() {
    const dialogClose = document.querySelector('.uploadcare--dialog__close');
    if (dialogClose) {
        dialogClose.dispatchEvent(new Event('click'));
    }

    const dialog = document.querySelector('.uploadcare--dialog');
    if (dialog) {
        dialog.remove();
    }

    const widgets = document.querySelectorAll('.uploadcare--widget');
    widgets.forEach(widget => {
        widget.remove();
    });
});

Similarly if you are using Hotwire then use can you use below code:

document.addEventListener('turbo:before-cache', function() {
    const dialogClose = document.querySelector('.uploadcare--dialog__close');
    if (dialogClose) {
        dialogClose.dispatchEvent(new Event('click'));
    }

    const dialog = document.querySelector('.uploadcare--dialog');
    if (dialog) {
        dialog.remove();
    }

    const widgets = document.querySelectorAll('.uploadcare--widget');
    widgets.forEach(widget => {
        widget.remove();
    });
});

File and Group wrappers

When you mount either Uploadcare File or Group to an attribute, this attribute is getting wrapped with a Uploadcare object. This feature adds some useful methods to the attribute.

Uploadcare File

Say, you have such model in your Rails app:

# app/models/post.rb
class Post < ApplicationRecord
  mount_uploadcare_file :picture
end

And then you create a new Post object specifying a CDN-url for your previously uploaded Uploadcare file:

post = Post.create(picture: "https://ucarecdn.com/2d33999d-c74a-4ff9-99ea-abc23496b052/")

Now the post.picture is an Uploadcare::Rails::File. Following methods are supported:

# Store the file on an Uploadcare server permanently:
post.picture.store
#   => {
#         "cdn_url"=>"https://ucarecdn.com/2d33999d-c74a-4ff9-99ea-abc23496b052/",
#          ...other group data...
#      }

#
# Delete the file from an Uploadcare server permanently:
post.picture.delete
#   => {
#         "datetime_removed"=>"2021-07-30T09:19:30.797174Z",
#          ...other group data...
#      }

# Get CDN-url of an object attribute:
post.picture.to_s
#   => "https://ucarecdn.com/2d33999d-c74a-4ff9-99ea-abc23496b052/"

# Load object (send a GET request to the server to get all the file's data)
# This data will be cached if the cache_files option is set to true
# Default data (without asking an Uploadcare server) for each file contains cdn_url and uuid only:
post.picture.load
#   => {
#         "cdn_url"=>"https://ucarecdn.com/2d33999d-c74a-4ff9-99ea-abc23496b052/",
#          ...other file data...
#      }

# Check if an attribute loaded from the server.
# Will return false unless the :load or the :store methods are called:
post.picture.loaded?
#   => true

# More about image transformations below.
# Transform a CDN-url to get a new transformed image's source. Works for images only:
post.picture.transform_url(quality: "better")
#   => "https://ucarecdn.com/2d33999d-c74a-4ff9-99ea-abc23496b052/-/quality/better/"

Uploadcare File Group

Groups work similar to the File but have some differences though.

# app/models/post.rb
class Post < ApplicationRecord
  mount_uploadcare_file_group :attachments
end

Creating a new post with the Group mounted:

post = Post.create(attachments: "https://ucarecdn.com/dbc4e868-b7a6-43ff-a35f-2ebef935dc1b~1/")

Now the post.attachments is an Uploadcare::Rails::Group. Following methods are supported:

# Store the file group on an Uploadcare server permanently:
post.attachments.store
#   => {
#         "cdn_url"=>"https://ucarecdn.com/dbc4e868-b7a6-43ff-a35f-2ebef935dc1b~1/",
#          ...other group data...
#         "files"=> [{
#            "datetime_stored"=>"2021-07-29T08:31:45.668354Z",
#            ...other file data...
#         }]
#      }

#
# Delete the file group from an Uploadcare server permanently:
post.attachments.delete
#   => {
#         "datetime_removed"=>"2021-07-30T09:19:30.797174Z",
#          ...other group data...
#      }

# Get CDN-url of an object attribute:
post.attachments.to_s
#   => "https://ucarecdn.com/dbc4e868-b7a6-43ff-a35f-2ebef935dc1b~1/"

# Load object — works the same way as for the File:
post.attachments.load
#   => {
#         "cdn_url"=>"https://ucarecdn.com/dbc4e868-b7a6-43ff-a35f-2ebef935dc1b~1/",
#          ...other group data...
#         "files"=> [{
#            "datetime_stored"=>"2021-07-29T08:31:45.668354Z",
#            ...other file data...
#         }]
#      }

# Check if an attribute loaded from the server:
post.attachments.loaded?
#   => true

# As we don't want to show (on the html-page) a file group itself,
# we can get CDN-urls for file that the group contains. No loading group or files needed.
# This works for images only:
post.attachments.transform_file_urls(quality: "better")
#   => ["https://ucarecdn.com/dbc4e868-b7a6-43ff-a35f-2ebef935dc1b~1/nth/0/-/quality/better/"]

# If you want to get non-transformed file urls, use:
post.attachments.file_urls
#   => ["https://ucarecdn.com/dbc4e868-b7a6-43ff-a35f-2ebef935dc1b~1/nth/0/"]

Image Transformation

Uploadcare provides a way to transform images stored on Uploadcare services specifying a list of operations. If an operation has just one option, you can specify it like key-value:

post.picture.transform_url(quality: "better")
#   => "https://ucarecdn.com/ebbb9929-eb92-4f52-a212-eecfdb19d27d/-/quality/better/"

and if an operation supports several options — just set them as a Hash:

post.picture.transform_url(crop: { dimensions: "300x500", coords: "50, 50", alignment: "center" })
#   => "https://ucarecdn.com/ebbb9929-eb92-4f52-a212-eecfdb19d27d/-/crop/300x500/50,50/center/"

Full list of operations and valid values can be found here.

Uploadcare API interfaces

Uploadcare provides APIs to manage files, group, projects, webhooks, video and documents conversion and file uploads. The gem has unified interfaces to use Uploadcare APIs in RailsApp.

Upload API

Upload Api provides methods to upload files in many ways.

Upload a single file

# Load a file
file = File.open("kitten.png")
#   => #<File:kitten.png>

# Upload file to Uploadcare
uploadcare_file = Uploadcare::UploadApi.upload_file(file)
#   => {
#         "uuid"=>"2d33999d-c74a-4ff9-99ea-abc23496b053",
#          ...other file data...
#      }

This method supports single file uploading and uploading files from an URL (depending on the type of first argument - can be either String (i.e. URL) or File).

# Upload file from URL
url = "https://ucarecdn.com/80b807be-faad-4f01-bbbe-0bbde172b9de/1secVIDEO.mp4"
uploadcare_file = Uploadcare::UploadApi.upload_file(url)
#   => [
#        {
#          "size"=>22108,
#          "uuid"=>"b5ed5e1d-a939-4fe4-bfb2-31d3867bb6s6",
#          "original_filename"=>"1 sec VIDEO.mp4",
#          "is_image"=>false,
#          "image_info"=>nil,
#          "is_ready"=>true,
#          "mime_type"=>"video/mp4"
#        }
#      ]

Upload several files

# Load a file
file = File.open("kitten.png")
#   => #<File:kitten.png>
# Upload several files to Uploadcare
uploadcare_file = Uploadcare::UploadApi.upload_files([file])
#   => [
#        {
#          "uuid"=>"2dfc94e6-e74e-4014-9ff5-a71b8928f4fa",
#          "original_filename"=>:"kitten.png"
#        }
#      ]

File API

FileApi provides an interface to manage single files, stored on Uploadcare Servers.

Get files

# Valid options:
# removed: [true|false]
# stored: [true|false]
# limit: (1..1000)
# ordering: ["datetime_uploaded"|"-datetime_uploaded"]
# from: A starting point for filtering files. The value depends on your ordering parameter value.
Uploadcare::FileApi.get_files(ordering: "datetime_uploaded", limit: 10)
#   => {
#        "next"=>nil,
#        "previous"=>nil,
#        "total"=>2,
#        "per_page"=>10,
#        "results"=> [
#          {
#            "datetime_removed"=>nil,
#            ... file data ...
#          }
#        ]
#      }

Get a file by UUID

$ Uploadcare::FileApi.get_file("7b2b35b4-125b-4c1e-9305-12e8da8916eb")
#   => {
#         "cdn_url"=>"https://ucarecdn.com/7b2b35b4-125b-4c1e-9305-12e8da8916eb/",
#          ...other file data...
#      }

Copy a file to default storage. Source can be UID or full CDN link

# Valid options:
# stored: [true|false]
Uploadcare::FileApi.local_copy_file("2d33999d-c74a-4ff9-99ea-abc23496b052", store: false)
#   => {
#         "uuid"=>"f486132c-2fa5-454e-9e70-93c5e01a7e04",
#          ...other file data...
#      }

Copy a file to custom storage. Source can be UID or full CDN link

# Valid options:
# make_public: [true|false]
Uploadcare::FileApi.remote_copy_file("2d33999d-c74a-4ff9-99ea-abc23496b052", "mytarget", make_public: false)
#   => {
#         "uuid"=>"f486132c-2fa5-454e-9e70-93c5e01a7e04",
#          ...other file data...
#      }

Store a file by UUID

Uploadcare::FileApi.store_file("2d33999d-c74a-4ff9-99ea-abc23496b052")
#   => {
#         "uuid"=>"2d33999d-c74a-4ff9-99ea-abc23496b052",
#          ...other file data...
#      }

Store several files by UUIDs

Uploadcare::FileApi.store_files(["f486132c-2fa5-454e-9e70-93c5e01a7e04"])
#   => {
#        "result" => [
#          {
#            "uuid"=>"f486132c-2fa5-454e-9e70-93c5e01a7e04",
#            ...other file data...
#          }
#        ]
#      }

Delete a file by UUID

Uploadcare::FileApi.delete_file("2d33999d-c74a-4ff9-99ea-abc23496b052")
#   => {
#         "uuid"=>"2d33999d-c74a-4ff9-99ea-abc23496b052",
#          ...other file data...
#      }

Delete several files by UUIDs

Uploadcare::FileApi.delete_files(["f486132c-2fa5-454e-9e70-93c5e01a7e04"])
#   => {
#        "result" => [
#          {
#            "uuid"=>"f486132c-2fa5-454e-9e70-93c5e01a7e04",
#            ...other file data...
#          }
#        ]
#      }

Group API

GroupApi provides an interface to manage file groups stored on Uploadcare Servers.

Get file groups

# Valid options:
# limit: (1..1000)
# ordering: ["datetime_created"|"-datetime_created"]
# from: A starting point for filtering group lists. MUST be a datetime value with T used as a separator.
#   example: "2015-01-02T10:00:00"
Uploadcare::GroupApi.get_groups(ordering: "datetime_uploaded", limit: 10)
#   => {
#        "next"=>"next"=>"https://api.uploadcare.com/groups/?ordering=datetime_uploaded&limit=10&from=2021-07-16T11%3A12%3A12.236280%2B00%3A00&offset=0",
#        "previous"=>nil,
#        "total"=>82,
#        "per_page"=>10,
#        "results"=> [
#          {
#            "id"=>"d476f4c9-44a9-4670-88a5-c3cf5a26b6c2~20",
#            "datetime_created"=>"2021-07-16T11:03:01.182239Z",
#            "datetime_stored"=>nil,
#            "files_count"=>20,
#            "cdn_url"=>"https://ucarecdn.com/d476f4c9-44a9-4670-88a5-c3cf5d16b6c2~20/",
#            "url"=>"https://api.uploadcare.com/groups/d476f4c9-44a9-4670-83a5-c3cf5d26b6c2~20/"
#          },
#          ... other groups data ...
#        ]
#      }

Get a single file group by a group ID

Uploadcare::GroupApi.get_group("d476f4c9-44a9-4670-88a5-c3cf5d26a6c2~20")
#   => {
#         "cdn_url"=>"https://ucarecdn.com/d476f4c9-44a9-4670-88a5-c3cf5d26a6c2~20/",
#          ...other group data...
#         "files"=> [{
#            "datetime_stored"=>"2021-07-29T08:31:45.668354Z",
#            ...other file data...
#         }]
#      }

Store files of a group by a group ID

Uploadcare::GroupApi.store_group("d476f4c9-44a9-4670-88a5-c3cf5d26a6c2~20")
#   => "200 OK"

Create a new group by file's uuids.

It is possible to specify transformed URLs with UUIDs of files OR just UUIDs.

  NOTE: Be sure to add a trailing slash "/" to the URL in case of specifying transformed URLs.
Uploadcare::GroupApi.create_group(["e08dec9e-7e25-49c5-810e-4c360d86bbae/-/resize/300x500/"])
#   => {
#         "cdn_url"=>"https://ucarecdn.com/d476f4c9-44a9-4670-88a5-c3cf5d26a6c2~1/",
#          ...other group data...
#         "files"=> [{
#            "datetime_stored"=>"2021-07-29T08:31:45.668354Z",
#            ...other file data...
#         }]
#      }

Delete a file group by its ID

Uploadcare::GroupApi.delete_group("90c93e96-965b-4dd2-b323-39d9bd5f492c~1")
#   => "200 OK"

Project API

ProjectApi interface provides just one method - to get a configuration of your Uploadcare project.

Uploadcare::ProjectApi.get_project
#   => {
#        "collaborators"=>[],
#        "name"=>"New project",
#        "pub_key"=>"your_public_key",
#        "autostore_enabled"=>true
#      }

Webhook API

WebhookApi allows to manage Uploadcare webhooks.

Get all webhooks

This method returns a non-paginated list of webhooks set in your project

Uploadcare::WebhookApi.get_webhooks
#   => [{
#        "id"=>815677,
#        "created"=>"2021-08-02T05:02:14.588794Z",
#        "updated"=>"2021-08-02T05:02:14.588814Z",
#        "event"=>"file.uploaded",
#        "target_url"=>"https://example.com",
#        "project"=>123682,
#        "is_active"=>true
#      }]

Create a new webhook

This method requires an URL that is triggered by an event, for example, a file upload. A target URL MUST be unique for each project — event type combination.

Each webhook payload can be signed with a secret (the signing_secret option) to ensure that the request comes from the expected sender. More info about secure webhooks here.

# Valid options:
# event: ["file.uploaded"]
# is_active: [true|false]
Uploadcare::WebhookApi.create_webhook("https://example.com", event: "file.uploaded", is_active: true, signing_secret: "some-secret")
#   => {
#        "id"=>815671,
#        "created"=>"2021-08-02T05:02:14.588794Z",
#        "updated"=>"2021-08-02T05:02:14.588814Z",
#        "event"=>"file.uploaded",
#        "target_url"=>"https://example.com",
#        "project"=>123682,
#        "is_active"=>true
#      }

Update an existing webhook by ID

Updating a webhook is available if webhook ID is known. The ID is returned in a response on creating or listing webhooks. Setting a signing secret is supported when updating a webhook as well.

# Valid options:
# event: Presently, we only support the "file.uploaded" event
# is_active: [true|false]
Uploadcare::WebhookApi.update_webhook("webhook_id", target_url: "https://example1.com", event: "file.uploaded", is_active: false, signing_secret: "some-secret")
#   => {
#        "id"=>815671,
#        "created"=>"2021-08-02T05:02:14.588794Z",
#        "updated"=>"2021-08-02T05:02:14.588814Z",
#        "event"=>"file.uploaded",
#        "target_url"=>"https://example1.com",
#        "project"=>123682,
#        "is_active"=>false
#      }

Delete an existing webhook by a target_url

Uploadcare::WebhookApi.delete_webhook("https://example1.com")
#   => Success(nil)

Conversion API

ConversionApi provides methods to manage video and documents conversion.

Convert a document

This method requires an UUID of a previously uploaded to Uploadcare file and target format. If using an image format, you can also specify a page number that must be converted for a document containing pages. More info about document conversion can be found here.

Uploadcare::ConversionApi.convert_document(
  { uuid: "466740dd-cfad-4de4-9218-1ddc0edf7aa6", format: "png", page: 1 },
  store: false
)
#   => Success({
#        :result=>[{
#          :original_source=>"466740dd-cfad-4de4-9218-1ddc0edf7aa6/document/-/format/png/-/page/1/",
#          :token=>21316034,
#          :uuid=>"db6e52b8-cc03-4174-a07a-012be43b144e"
#        }],
#        :problems=>{}
#     })

Get a document conversion job status

This method requires a token obtained in a response to the convert_document method.

Uploadcare::ConversionApi.get_document_conversion_status(21316034)
#   => Success({
#        :result=>{
#          :uuid=>"db6e52b8-cc03-4174-a07a-012be43b144e"
#        },
#        :error=>nil,
#        :status=>"finished"
#     })

Convert a video

Such as the document conversion method, this method requires an UUID of a previously uploaded to Uploadcare file. Also you have several options to control the way a video will be converted. All of them are optional. Description of valid options and other info about video conversion can be found here.

Uploadcare::ConversionApi.convert_video(
  {
    uuid: "466740dd-cfad-4de4-9218-1ddc0edf7aa6",
    format: "ogg",
    quality: "best",
    cut: { start_time: "0:0:0.0", length: "0:0:1.0" },
    thumbs: { N: 2, number: 1 }
  },
  store: false
)
#   => Success({
#        :result=>[{
#          :original_source=>"80b807be-faad-4f01-bbbe-0bbde172b9de/video/-/size/600x400/change_ratio/-/quality/best/-/format/ogg/-/cut/0:0:0.0/0:0:1.0/-/thumbs~2/1/",
#          :token=>916090555,
#          :uuid=>"df597ef4-59e7-47ef-af5d-365d8409934c~2",
#          :thumbnails_group_uuid=>"df597ef4-59e7-47ef-af5d-365d8409934c~2"
#        }],
#        :problems=>{}
#     })

Get a video conversion job status

This method requires a token obtained in a response to the convert_video method.

Uploadcare::ConversionApi.get_video_conversion_status(916090555)
#   => Success({
#        :result=>{
#          :uuid=>"f0a3e66e-cd22-4397-ba0a-8a8becc925f9",
#          :thumbnails_group_uuid=>"df597ef4-59e7-47ef-af5d-365d8409934c~2"
#        },
#        :error=>nil,
#        :status=>"finished"
#     })

File Metadata Api

File metadata is additional, arbitrary data, associated with uploaded file. As an example, you could store unique file identifier from your system. Metadata is key-value data.

Get file's metadata keys and values

Uploadcare::FileMetadataApi.file_metadata('f757ea10-8b1a-4361-9a7c-56bfa5d45176')
#   => {:"sample-key"=>"sample-value"}

Get the value of a single metadata key

Uploadcare::FileMetadataApi.file_metadata_value('f757ea10-8b1a-4361-9a7c-56bfa5d45176', 'sample-key')
#   => "sample-value"

Update the value of a single metadata key

If the key does not exist, it will be created.

Uploadcare::FileMetadataApi.update_file_metadata('f757ea10-8b1a-4361-9a7c-56bfa5d45176', 'sample-key', 'new-value')
#   => "new-value"

Delete a file's metadata key

Uploadcare::FileMetadataApi.delete_file_metadata('f757ea10-8b1a-4361-9a7c-56bfa5d45176', 'sample-key')
#   => "200 OK"

Add-Ons Api

An Add-On is an application implemented by Uploadcare that accepts uploaded files as an input and can produce other files and/or appdata as an output.

Execute AWS Rekognition Add-On for a given target to detect labels in an image

  Note: Detected labels are stored in the file's appdata.
Uploadcare::AddonsApi.rekognition_detect_labels('f757ea10-8b1a-4361-9a7c-56bfa5d45176')
#   => {"request_id"=>"dfeaf81c-5c0d-49d5-8ed4-ac09bac7998e"}

Check the status of an Add-On execution request that had been started using the Execute Add-On operation

Uploadcare::AddonsApi.rekognition_detect_labels_status('dfeaf81c-5c0d-49d5-8ed4-ac09bac7998e')
#   => {"status"=>"done"}

Execute AWS Rekognition Moderation Add-On for a given target to detect moderation labels in an image.

  Note: Detected labels are stored in the file's appdata.
Uploadcare::AddonsApi.rekognition_detect_moderation_labels('f757ea10-8b1a-4361-9a7c-56bfa5d45176')
#   => {"request_id"=>"dfeaf81c-5c0d-49d5-8ed4-ac09bac7998e"}

Check the status of an AWS Rekognition Moderation Add-On execution request that had been started using the Execute Add-On operation.

Uploadcare::AddonsApi.rekognition_detect_moderation_labels_status('dfeaf81c-5c0d-49d5-8ed4-ac09bac7998e')
#   => {"status"=>"done"}

Execute ClamAV virus checking Add-On for a given target

Uploadcare::AddonsApi.virus_scan('dfeaf81c-5c0d-49d5-8ed4-ac09bac7998e')
#   => {"request_id"=>"1b0126de-ace6-455b-82e2-25f4aa33fc6f"}

Check the status of an Add-On execution request that had been started using the Execute Add-On operation

Uploadcare::AddonsApi.virus_scan_status('1b0126de-ace6-455b-82e2-25f4aa33fc6f')
#   => {"status"=>"done"}

Execute remove.bg background image removal Add-On for a given target

Uploadcare::AddonsApi.remove_bg('f757ea10-8b1a-4361-9a7c-56bfa5d45176')
#   => {"request_id"=>"6d26a7d5-0955-4aeb-a9b1-c9776c83aa4c"}

Check the status of an Add-On execution request that had been started using the Execute Add-On operation

Uploadcare::AddonsApi.remove_bg_status('6d26a7d5-0955-4aeb-a9b1-c9776c83aa4c')
#   => {"status"=>"done", "result"=>{"file_id"=>"8f0a2a28-3ed7-481e-b415-ee3cce982aaa"}}

Useful links

uploadcare-rails's People

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

uploadcare-rails's Issues

Submit form after clicked on "add" button

rails (7.0.2.3) uploadcare-rails (2.1.0) importmap-rails (1.0.1)

Is there a way to submit the form after clicked on "add" button ?
Screenshot 2022-04-26 at 00 36 42

Right now I have to click on "add" and then click on my :submit button

# app/models/uploadcare_document.rb
class UploadcareDocument < ApplicationRecord
  mount_uploadcare_file_group :attachments
end

# app/views/uploadcare_documents/_form.html.erb
<%= simple_form_for uploadcare_document do |f| %>
  <%= uploadcare_uploader_field :uploadcare_document, :attachments %>
  <%= f.button  :submit %>
<% end %>
uploadcare.mp4

`initialize`: config is empty or not given at all (ArgumentError) when generating the config file

MacOS Sierra 10.12.2
Ruby 2.4.0
Rails 5.1.0.rc1
Project: Brand new rails project

rails g uploadcare_config
  Warning: no uploadcare.yml config file found.
  while we will use default settings please run
    rails g uploadcare_config
  to set up config file.

/Users/brandoncordell/.rbenv/versions/2.4.0/lib/ruby/gems/2.4.0/gems/uploadcare-rails-1.1.0/lib/uploadcare/rails/settings.rb:39:in `initialize': config is empty or not given at all (ArgumentError)
from /Users/brandoncordell/.rbenv/versions/2.4.0/lib/ruby/gems/2.4.0/gems/uploadcare-rails-1.1.0/config/initializers/uploadcare.rb:24:in `new'
from /Users/brandoncordell/.rbenv/versions/2.4.0/lib/ruby/gems/2.4.0/gems/uploadcare-rails-1.1.0/config/initializers/uploadcare.rb:24:in `<top (required)>'
from /Users/brandoncordell/.rbenv/versions/2.4.0/lib/ruby/gems/2.4.0/gems/activesupport-5.1.0.rc1/lib/active_support/dependencies.rb:286:in `load'
from /Users/brandoncordell/.rbenv/versions/2.4.0/lib/ruby/gems/2.4.0/gems/activesupport-5.1.0.rc1/lib/active_support/dependencies.rb:286:in `block in load'
from /Users/brandoncordell/.rbenv/versions/2.4.0/lib/ruby/gems/2.4.0/gems/activesupport-5.1.0.rc1/lib/active_support/dependencies.rb:258:in `load_dependency'
from /Users/brandoncordell/.rbenv/versions/2.4.0/lib/ruby/gems/2.4.0/gems/activesupport-5.1.0.rc1/lib/active_support/dependencies.rb:286:in `load'
from /Users/brandoncordell/.rbenv/versions/2.4.0/lib/ruby/gems/2.4.0/gems/railties-5.1.0.rc1/lib/rails/engine.rb:655:in `block in load_config_initializer'
from /Users/brandoncordell/.rbenv/versions/2.4.0/lib/ruby/gems/2.4.0/gems/activesupport-5.1.0.rc1/lib/active_support/notifications.rb:166:in `instrument'
from /Users/brandoncordell/.rbenv/versions/2.4.0/lib/ruby/gems/2.4.0/gems/railties-5.1.0.rc1/lib/rails/engine.rb:654:in `load_config_initializer'
from /Users/brandoncordell/.rbenv/versions/2.4.0/lib/ruby/gems/2.4.0/gems/railties-5.1.0.rc1/lib/rails/engine.rb:612:in `block (2 levels) in <class:Engine>'
from /Users/brandoncordell/.rbenv/versions/2.4.0/lib/ruby/gems/2.4.0/gems/railties-5.1.0.rc1/lib/rails/engine.rb:611:in `each'
from /Users/brandoncordell/.rbenv/versions/2.4.0/lib/ruby/gems/2.4.0/gems/railties-5.1.0.rc1/lib/rails/engine.rb:611:in `block in <class:Engine>'
from /Users/brandoncordell/.rbenv/versions/2.4.0/lib/ruby/gems/2.4.0/gems/railties-5.1.0.rc1/lib/rails/initializable.rb:30:in `instance_exec'
from /Users/brandoncordell/.rbenv/versions/2.4.0/lib/ruby/gems/2.4.0/gems/railties-5.1.0.rc1/lib/rails/initializable.rb:30:in `run'
from /Users/brandoncordell/.rbenv/versions/2.4.0/lib/ruby/gems/2.4.0/gems/railties-5.1.0.rc1/lib/rails/initializable.rb:59:in `block in run_initializers'
from /Users/brandoncordell/.rbenv/versions/2.4.0/lib/ruby/2.4.0/tsort.rb:228:in `block in tsort_each'
from /Users/brandoncordell/.rbenv/versions/2.4.0/lib/ruby/2.4.0/tsort.rb:350:in `block (2 levels) in each_strongly_connected_component'
from /Users/brandoncordell/.rbenv/versions/2.4.0/lib/ruby/2.4.0/tsort.rb:422:in `block (2 levels) in each_strongly_connected_component_from'
from /Users/brandoncordell/.rbenv/versions/2.4.0/lib/ruby/2.4.0/tsort.rb:431:in `each_strongly_connected_component_from'
from /Users/brandoncordell/.rbenv/versions/2.4.0/lib/ruby/2.4.0/tsort.rb:421:in `block in each_strongly_connected_component_from'
from /Users/brandoncordell/.rbenv/versions/2.4.0/lib/ruby/gems/2.4.0/gems/railties-5.1.0.rc1/lib/rails/initializable.rb:48:in `each'
from /Users/brandoncordell/.rbenv/versions/2.4.0/lib/ruby/gems/2.4.0/gems/railties-5.1.0.rc1/lib/rails/initializable.rb:48:in `tsort_each_child'
from /Users/brandoncordell/.rbenv/versions/2.4.0/lib/ruby/2.4.0/tsort.rb:415:in `call'
from /Users/brandoncordell/.rbenv/versions/2.4.0/lib/ruby/2.4.0/tsort.rb:415:in `each_strongly_connected_component_from'
from /Users/brandoncordell/.rbenv/versions/2.4.0/lib/ruby/2.4.0/tsort.rb:349:in `block in each_strongly_connected_component'
from /Users/brandoncordell/.rbenv/versions/2.4.0/lib/ruby/2.4.0/tsort.rb:347:in `each'
from /Users/brandoncordell/.rbenv/versions/2.4.0/lib/ruby/2.4.0/tsort.rb:347:in `call'
from /Users/brandoncordell/.rbenv/versions/2.4.0/lib/ruby/2.4.0/tsort.rb:347:in `each_strongly_connected_component'
from /Users/brandoncordell/.rbenv/versions/2.4.0/lib/ruby/2.4.0/tsort.rb:226:in `tsort_each'
from /Users/brandoncordell/.rbenv/versions/2.4.0/lib/ruby/2.4.0/tsort.rb:205:in `tsort_each'
from /Users/brandoncordell/.rbenv/versions/2.4.0/lib/ruby/gems/2.4.0/gems/railties-5.1.0.rc1/lib/rails/initializable.rb:58:in `run_initializers'
from /Users/brandoncordell/.rbenv/versions/2.4.0/lib/ruby/gems/2.4.0/gems/railties-5.1.0.rc1/lib/rails/application.rb:353:in `initialize!'
from /Users/brandoncordell/Code/uc_testing/config/environment.rb:5:in `<top (required)>'
from /Users/brandoncordell/.rbenv/versions/2.4.0/lib/ruby/gems/2.4.0/gems/spring-2.0.1/lib/spring/application.rb:92:in `require'
from /Users/brandoncordell/.rbenv/versions/2.4.0/lib/ruby/gems/2.4.0/gems/spring-2.0.1/lib/spring/application.rb:92:in `preload'
from /Users/brandoncordell/.rbenv/versions/2.4.0/lib/ruby/gems/2.4.0/gems/spring-2.0.1/lib/spring/application.rb:143:in `serve'
from /Users/brandoncordell/.rbenv/versions/2.4.0/lib/ruby/gems/2.4.0/gems/spring-2.0.1/lib/spring/application.rb:131:in `block in run'
from /Users/brandoncordell/.rbenv/versions/2.4.0/lib/ruby/gems/2.4.0/gems/spring-2.0.1/lib/spring/application.rb:125:in `loop'
from /Users/brandoncordell/.rbenv/versions/2.4.0/lib/ruby/gems/2.4.0/gems/spring-2.0.1/lib/spring/application.rb:125:in `run'
from /Users/brandoncordell/.rbenv/versions/2.4.0/lib/ruby/gems/2.4.0/gems/spring-2.0.1/lib/spring/application/boot.rb:19:in `<top (required)>'
from /Users/brandoncordell/.rbenv/versions/2.4.0/lib/ruby/2.4.0/rubygems/core_ext/kernel_require.rb:55:in `require'
from /Users/brandoncordell/.rbenv/versions/2.4.0/lib/ruby/2.4.0/rubygems/core_ext/kernel_require.rb:55:in `require'
from -e:1:in `<main>'

Uploadcare CDN Certificate is invalid

Our app can't load the JS for the widget, because the CDN certificate seems to be invalid.

Failed to load resource: The certificate for this server is invalid. You might be connecting to a server that is pretending to be “ucarecdn.com”, which could put your confidential information at risk.

image

Can you please fix this?

Skip Validation

I am getting a presence validation error when not including a file. Is there a way around this?

Cashing

Smart cashing for files and groups and their loaded models.
Autoloads for groups and files (will always be disabled by default as it requires external http request)

delete_after_destroy does not work

using widget v2.6

delete_after_destroy set to true in uploadcare.yml

files are stored, I am using groups

deleting model on console and deleting them via destroy in the controller does not delete the files in uploadcare

i.build_group.delete always returns nil (i is a model instance containing a has_uploadcare_group declaration)

any ideas?

Use non-cdn urls with the widget

Question

We have a model where the attachment receipt_url is a AWS S3 url.
We would like to use the uploadcare-widget with this url. But as far as I understand the uploadcare-widget is only working with uploadcare cdn urls.

My question is:
Could the uploadcare-widget (single-file) be mounted with a non-cdn url ? (right now it says "Incorrect Value")

Thanks !

Crop URL not working?

operation-url

In my database, the value is stored as https://ucarecdn.com/34f25e97-45cd-4d29-affd-0b0f5823d69e/-/crop/101x101/800,61/-/preview/, but when I do something like object.file.url in only pulls https://ucarecdn.com/34f25e97-45cd-4d29-affd-0b0f5823d69e

What is need is if I do something like object.file.url it will give me the cropped version, such as:
https://ucarecdn.com/34f25e97-45cd-4d29-affd-0b0f5823d69e/-/crop/101x101/800,61/-/preview/

This was working fine in other Rails app, but current project is not pulling the full url...

wrong spelling

change

calling group (or thatever attribute name you choose) in the template

to

calling group (or whatever attribute name you choose) in the template

in the readme file

Show uploader box without modal box

I would like to show embedded in the html box as shown in the following attachment.

export

Using in _from.html.erb

<%= f.uploadcare_field :file %>

Any idea how to do this?

Thankyou

Asset pipeline integration

Integrating uploadcare into the asset pipeline, I found that the following statement works instead of what's included in the readme file:

//= require uploadcare

key not found: "UPLOADCARE_SECRET_KEY" (KeyError)

I have this error when I try to run rails server

$ rails server
/Users/guillaume/.rbenv/versions/3.0.3/lib/ruby/gems/3.0.0/gems/uploadcare-ruby-3.3.1/lib/uploadcare.rb:36:in `fetch': key not found: "UPLOADCARE_SECRET_KEY" (KeyError)
Did you mean?  "UPLOADCARE_PUBLIC_KEY"

This is not a ENV problem because I wrote my credentials directly on config/initializers/uploadcare.rb and still have the same issue

Uploadcare::Rails.configure do |config|
  # Sets your Uploadcare public key.
  config.public_key = 'mypublickey' # ENV.fetch("UPLOADCARE_PUBLIC_KEY", "mypublickey")
  config.secret_key = 'mysecretkey' # ENV.fetch("UPLOADCARE_SECRET_KEY", "mysecretkey") 
...
# .env
UPLOADCARE_PUBLIC_KEY=mypublickey
UPLOADCARE_SECRET_KEY=mysecretkey

The only way to fix it right now is to run export UPLOADCARE_PUBLIC_KEY=demopublickey but it is not the solution

Environment

  • Library version: uploadcare-rails (2.1.0) uploadcare-ruby (3.3.1) dotenv-rails (2.7.6)
  • Language/framework version: rails (7.0.2.3) ruby (3.0.3)
  • OS version: OS X (12.3.1)

The autorelease github action script does not work

The script that is set for pushing the gem to RubyGems is not working with enabled 2-factor authentication. It would be nice to get it working to automate the release process. Need to edit the script so it could apply OTP-code:

Stack trace:

...
+ exec rake release
uploadcare-ruby 3.1.0 built to pkg/uploadcare-ruby-3.1.0.gem.
Tag v3.1.0 has already been created.
rake aborted!
Pushing gem to https://rubygems.org...
You have enabled multi-factor authentication. Please enter OTP code.
You have enabled multifactor authentication but no OTP code provided. Please fill it and retry.
/usr/local/bundle/gems/rake-13.0.6/exe/rake:27:in `<top (required)>'
Tasks: TOP => release => release:rubygem_push
(See full trace by running task with --trace)

Confusing ephemeral behavior with has_uploadcare_file accessor

It appears that the accessor method generated by has_uploadcare_file creates a new Uploadcare::Rails::File instance every time it is called.

This means that calling load_data doesn't appear to have any effect unless the result is manually stored.

Given:

class Company < ApplicationRecord
  ...
  has_uploadcare_file :uploadcare_logo
  ...
end

This behavior at the console is surprising:

[23] pry(main)> company.uploadcare_logo
=> #<Uploadcare::Rails::File uuid="b170e951-xxxx-xxxx-xxxxxxxxxxxx", operations=[]>
[24] pry(main)> company.uploadcare_logo.loaded?
=> false
[25] pry(main)> company.uploadcare_logo.load_data
=> #<Uploadcare::Rails::File uuid="b170e951-xxxx-xxxx-xxxxxxxxxxxx", operations=[], ... mime_type="image/jpeg", ...>
[26] pry(main)> company.uploadcare_logo.loaded?
=> false
[27] pry(main)> a = company.uploadcare_logo
=> #<Uploadcare::Rails::File uuid="b170e951-xxxx-xxxx-xxxxxxxxxxxx", operations=[]>
[28] pry(main)> a.load_data
=> #<Uploadcare::Rails::File uuid="b170e951-xxxx-xxxx-xxxxxxxxxxxx", operations=[], ... mime_type="image/jpeg", ...>
[29] pry(main)> a.loaded?
=> true
[30] pry(main)> a.mime_type
=> "image/jpeg"
[31] pry(main)> company.uploadcare_logo.mime_type
=> nil

A quick look at the source reveals that build_file tries a lookup with Rails.cache, but it doesn't look like the file ever gets saved to the cache in the normal read case. Of course, that is beside the point of whether it makes sense for the accessor to create a new object every time, even if some of it is cached.

Rails console and Migrations can't run

Not sure if I'm missing something, but the Rails console and Migrations won't run (Server works though) with this gem installed

/usr/local/rvm/gems/ruby-2.4.0/gems/uploadcare-rails-1.2.0/lib/uploadcare/rails/settings.rb:54:in `initialize': Private or public key options were not provided (ArgumentError)
rails -v:  5.2.1
ruby -v: ruby 2.4.0p0 (2016-12-24 revision 57164) [x86_64-linux]

The environment variables do return the correct values and it works fine when using the upload fields. Possible issue with the private key?

Config:

defaults: &defaults
  public_key: <%= ENV["UPLOADCARE_PUBLIC_KEY"] %> # replace it with your public key
  private_key: <%= ENV["UPLOADCARE_PRIVATE_KEY"] %> # replace it with your private key

  # instances of widget initialized for you on page load
  live: true

  # cache files json dumps to prevent calling to server if it posible
  cache_files: true

  # cache groups json dumps to prevent calling to server if it posible
  cache_groups: true

  # store file or group after model is created or updated
  store_after_save: true

  # deletes file or group after model object is deleted
  delete_after_destroy: true

  # Avaliable options are listed at https://uploadcare.com/documentation/widget/#advanced-configuration
  # please note, that for options marker as Global: N/A - there is no practical meaning
  # of putting this option here, as it will not have any effect.
  # But it also will not break anything.

  # for preview step use:
  # preview_step: false # true or false

  # for clearable option (allows user to remove uploaded file from widget) use:
  # clearable: false # true or false

  # for setting tabs use tabs option:
  # tabs: "url file facebook" # etc
  # read more here: https://uploadcare.com/documentation/widget/#tabs
  #
  #   Full list of tabs:
  # |----------------------------------------|
  # | Code       | File Source     | Default |
  # |------------|-----------------|---------|
  # | url        | Any URL         | On      |
  # | file       | Local disk      | On      |
  # | facebook   | Facebook        | On      |
  # | dropbox    | Dropbox         | Off     |
  # | gdrive     | Google Drive    | On      |
  # | box        | Box             | On      |
  # | skydrive   | SkyDrive        | On      |
  # | instagram  | Instagram       | On      |
  # | evernote   | Evernote        | On      |
  # | vk         | VK              | Off     |
  # |________________________________________|

  # for locale option use:
  # locale: "en"

  # for autostore option use:
  # autostore: true #true or false

  # for manual start (which means you will need to initialize uploaders yourself) use:
  # manual_start: false # true or false

  # for path value use:
  # path_value: true # true or false
  # (important for input values - see https://uploadcare.com/documentation/widget/#input-value)

development:
  <<: *defaults

test:
  <<: *defaults

production:
  <<: *defaults

Ruby 3.1 dry-configurable warning

There is a warning popping up when the gem is used with ruby 3.1.2.
<module:ApiStruct>' [dry-configurable] default value as positional argument to settings is deprecated and will be removed in the next major version Provide a default: keyword argument instead

Looks like an update issue to the dry configurable gem used as a dependency

mount_uploadcare_file makes network request every time model is saved

Describe the bug

Given an ActiveRecord model that has a mount_uploadcare_file attribute, a Uploadcare::FileApi.store_file is called on every save even when the mount_uploadcare_file attribute has not changed.

I would not expect a network request to be triggered when saving a model when the attribute hasn't changed.

The culprit seems to be:

after_save "uploadcare_store_#{attribute}!".to_sym unless Uploadcare::Rails.configuration.do_not_store

and

define_method "uploadcare_store_#{attribute}!" do |store_job = StoreFileJob|
file_uuid = public_send(attribute)&.uuid
return unless file_uuid
return store_job.perform_later(file_uuid) if Uploadcare::Rails.configuration.store_files_async
Uploadcare::FileApi.store_file(file_uuid)
end

I presume this could be easily fixed by checking if the attribute has changed and only then making the API call, but perhaps the current behavior is handling some edge case I am not aware of.

Remove duplicate methods

Brief description of the feature and motivation behind it

Most of Uploadcare::Rails API methods use Uploadcare::Ruby methods without any changes, for example:

def get_files(options = {})
  Uploadcare::FileList.file_list(options)
end

It may be good to remove duplicate methods and use original methods from Uploadcare::Ruby

Rails 7 credentials

Issues with rails 7

Thanks for the good job!

While the point i will raise is not creating a current problem, it might create problems in the near future.
The issue is that it would be nice if the keys would be loaded through rails credentials instead of needing to work with .env files. It would be closer to "The Rails way"

Multiple `has_uploadcare_file` calls overwrite the previous ones

If you have more than one has_uploadcare_file calls in a single model (even with different attributes), only the last one loaded works. All other attributes will return the file data for the last attribute in the 'list'. Example:

class Album < ActiveRecord::Base
  has_uploadcare_file :album_art
  has_uploadcare_file :album_art_back
end
[1] pry(main)> album = Album.first
=> #<Album:0x0055fb6d738728
 id: 1,
 album_art: "https://ucarecdn.com/22366021-02c5-42d6-a598-8e85e9c18d16/",
 album_art_back: "https://ucarecdn.com/8c38cb9b-9c1e-41ad-b8b7-b39cfebbb9af/">
[2] pry(main)> album.album_art
Cache read: https://ucarecdn.com/8c38cb9b-9c1e-41ad-b8b7-b39cfebbb9af/
D, [2018-01-26T15:11:00.354794 #15215] DEBUG -- : Cache read: https://ucarecdn.com/8c38cb9b-9c1e-41ad-b8b7-b39cfebbb9af/
Dalli::Server#connect 127.0.0.1:11211
D, [2018-01-26T15:11:00.354995 #15215] DEBUG -- : Dalli::Server#connect 127.0.0.1:11211
=> #<Uploadcare::Rails::File uuid="8c38cb9b-9c1e-41ad-b8b7-b39cfebbb9af", operations=[], datetime_removed=nil, datetime_stored="2018-01-26T19:08:53.415735Z", datetime_uploaded="2018-01-26T19:08:53.109187Z", image_info={"orientation"=>nil, "format"=>"JPEG", "height"=>500, "width"=>500, "geo_location"=>nil, "datetime_original"=>nil, "dpi"=>nil}, is_image=true, is_ready=true, mime_type="image/jpeg", original_file_url="https://ucarecdn.com/8c38cb9b-9c1e-41ad-b8b7-b39cfebbb9af/mbidcb100c18fb2948288d242fdbac6d6cff15675237690_thumb500.jpg", original_filename="mbid-cb100c18-fb29-4828-8d24-2fdbac6d6cff-15675237690_thumb500.jpg", size=70552, url="https://api.uploadcare.com/files/8c38cb9b-9c1e-41ad-b8b7-b39cfebbb9af/", source=nil>
[3] pry(main)> album.album_art.url
Cache read: https://ucarecdn.com/8c38cb9b-9c1e-41ad-b8b7-b39cfebbb9af/
D, [2018-01-26T15:11:02.806458 #15215] DEBUG -- : Cache read: https://ucarecdn.com/8c38cb9b-9c1e-41ad-b8b7-b39cfebbb9af/
=> "https://ucarecdn.com/8c38cb9b-9c1e-41ad-b8b7-b39cfebbb9af/"
[4] pry(main)> album.album_art_back
Cache read: https://ucarecdn.com/8c38cb9b-9c1e-41ad-b8b7-b39cfebbb9af/
D, [2018-01-26T15:11:08.642813 #15215] DEBUG -- : Cache read: https://ucarecdn.com/8c38cb9b-9c1e-41ad-b8b7-b39cfebbb9af/
=> #<Uploadcare::Rails::File uuid="8c38cb9b-9c1e-41ad-b8b7-b39cfebbb9af", operations=[], datetime_removed=nil, datetime_stored="2018-01-26T19:08:53.415735Z", datetime_uploaded="2018-01-26T19:08:53.109187Z", image_info={"orientation"=>nil, "format"=>"JPEG", "height"=>500, "width"=>500, "geo_location"=>nil, "datetime_original"=>nil, "dpi"=>nil}, is_image=true, is_ready=true, mime_type="image/jpeg", original_file_url="https://ucarecdn.com/8c38cb9b-9c1e-41ad-b8b7-b39cfebbb9af/mbidcb100c18fb2948288d242fdbac6d6cff15675237690_thumb500.jpg", original_filename="mbid-cb100c18-fb29-4828-8d24-2fdbac6d6cff-15675237690_thumb500.jpg", size=70552, url="https://api.uploadcare.com/files/8c38cb9b-9c1e-41ad-b8b7-b39cfebbb9af/", source=nil>
[5] pry(main)> album.album_art_back.url
Cache read: https://ucarecdn.com/8c38cb9b-9c1e-41ad-b8b7-b39cfebbb9af/
D, [2018-01-26T15:11:10.793781 #15215] DEBUG -- : Cache read: https://ucarecdn.com/8c38cb9b-9c1e-41ad-b8b7-b39cfebbb9af/
=> "https://ucarecdn.com/8c38cb9b-9c1e-41ad-b8b7-b39cfebbb9af/"

As you can see, the #album_art_back attribute returns info from the #album_art attribute, even though the attribute value is stored correctly in the database. It looks like the problem is with the dynamic #build_file method in Uploadcare::Rails::ActiveRecord#has_uploadcare_file (and probably the same issue with that dynamic method in #has_uploadcare_group).

I've changed that method definition to use the attribute like so:

define_method "build_#{attribute}_file"

which seems to fix the issue. I'll submit a PR for this shortly.

Error when running tests

Hi, i'm having some problems with uploadcare-rails gem when running my tests. Everything seems to be running smoothly on development env, but fails on test env.

Here is the trace (it happens with all kind of tests):

I've tried with different gem versions with same results.

The model

class Announcement < ApplicationRecord
  has_uploadcare_file :image

  # -- Validations
  validates :title, presence: true
  validates :description, presence: true
  validates :image, presence: true
end

Test trace

# Running:                                                                                

#### -------This Faraday error also appeared after adding UploadCare gem
WARNING: Unexpected middleware set after the adapter. This won't be supported from Faraday
WARNING: Unexpected middleware set after the adapter. This won't be supported from Faraday

Finished in 0.201850s
  1) Error:                                                                         
AnnouncementTest#test_should_have_a_title:
NoMethodError: undefined method `names' for nil:NilClass from /Users/gonzalo/.rbenv/versions/2.4.0/lib/ruby/gems/2.4.0/gems/uploadcare-ruby-1.1.0/lib/uploadcare/utils/parser.rb:45:in `parse'

    test/models/announcement_test.rb:10:in `block in <class:AnnouncementTest>'

  2) Error:
AnnouncementTest#test_should_have_a_description:
NoMethodError: undefined method `names' for nil:NilClass from /Users/gonzalo/.rbenv/versions/2.4.0/lib/ruby/gems/2.4.0/gems/uploadcare-ruby-1.1.0/lib/uploadcare/utils/parser.rb:45:in `parse'

    test/models/announcement_test.rb:16:in `block in <class:AnnouncementTest>'

Any idea?
Thanks!

Conflict when installing with activeadmin

When installing this gem with activeadmin gem, css and js files for activeadmin are no longer generated. I saw a few posts around the net so figured I would post an issue here as it seemed they were just abandoning this tool for another.

Basically if you do a Rails 4 app from scratch with just devise, activeadmin, and uploadcare-care gems the css and js are not rendered as the uploadcare-gem. It appears to be something with the js_include_tag and css_include_tag being overwritten and spitting out a /stylesheets and /javascripts path.

If you comment out the uploadcare gem, bundle install, it will then show /assets path and all works again.

Not sure if you were aware, but seems to be an issue for those using the popular admin backend in rails.

Can't install in Rails 4.1

Seems like this relies on rails 4.0.1

Is this minor version reliance necessary?

Bundler output:

Bundler could not find compatible versions for gem "rails":
  In Gemfile:
    uploadcare-rails (~> 1.0) ruby depends on
      rails (~> 4.0.1) ruby

    rails (4.1.1)

Rails 5.1 Deprecation Warning

I'm getting the following warning:

DEPRECATION WARNING: Passing string to define callback is deprecated and will be removed in Rails 5.1 without replacement.

for including:

has_uploadcare_file :file

Add "cheap" url fetching methods

Given a group's url, its cheap to construct a list of URLs for its items based on the uid in the url.

I'm suggesting a change to the Group object that exposes an api similar to this:

      def cheap_urls
        return [] unless self.cdn_url

        self.files_count.to_i.times.map do |i|
          self.cdn_url + "nth/#{i.to_s}/"
        end
      end

This way, you can display all your images without having to load a group...

Initializer failing in Rails 4 beta

Following README example:
the initializer is throwing method_missing errors

stack trace as follows:
/Users/adamrobbie/Code/Ruby/regionals/vendor/bundle/gems/railties-4.0.0.beta1/lib/rails/railtie/configuration.rb:95:in method_missing': undefined methoduploadcare' for #Rails::Engine::Configuration:0x007fe7cd886758 (NoMethodError)
from /Users/adamrobbie/Code/Ruby/regionals/config/initializers/uploadcare.rb:2:in block in <top (required)>' from /Users/adamrobbie/Code/Ruby/regionals/vendor/bundle/gems/railties-4.0.0.beta1/lib/rails/railtie/configurable.rb:24:inclass_eval'
from /Users/adamrobbie/Code/Ruby/regionals/vendor/bundle/gems/railties-4.0.0.beta1/lib/rails/railtie/configurable.rb:24:in configure' from /Users/adamrobbie/Code/Ruby/regionals/config/initializers/uploadcare.rb:1:in<top (required)>'
from /Users/adamrobbie/Code/Ruby/regionals/vendor/bundle/gems/activesupport-4.0.0.beta1/lib/active_support/dependencies.rb:222:in load' from /Users/adamrobbie/Code/Ruby/regionals/vendor/bundle/gems/activesupport-4.0.0.beta1/lib/active_support/dependencies.rb:222:inblock in load'
from /Users/adamrobbie/Code/Ruby/regionals/vendor/bundle/gems/activesupport-4.0.0.beta1/lib/active_support/dependencies.rb:213:in load_dependency' from /Users/adamrobbie/Code/Ruby/regionals/vendor/bundle/gems/activesupport-4.0.0.beta1/lib/active_support/dependencies.rb:222:inload'
from /Users/adamrobbie/Code/Ruby/regionals/vendor/bundle/gems/railties-4.0.0.beta1/lib/rails/engine.rb:608:in `block (2 levels) in class:Engine'

[dry-configurable] warnings

Question

Hi,
We added the uploadcare-ruby-3.2.0 gem and now we have several warnings each time we started our app.

"vendor/bundle/gems/uploadcare-ruby-3.2.0/lib/uploadcare.rb:29:in <top (required)>' [dry-configurable] default value as positional argument to settings is deprecated and will be removed in the next major version Provide a default:` keyword argument instead"

May be a way to fix it : https://hanamimastery.com/episodes/5-configure-anything-with-dry-configurable
(search keyword "constructor" in the page)

How to fix it ?
Thanks

Error when saving nested form without giving uploadcare a file.

I have a Branding table that has a logo column. When updating just the branding object, I have not had any issues. The issue arose when I turned it into a nested form:

Nested Form: https://gist.github.com/FsDevNinja/8f713295f8e6a42acbb7ce3474f4c57e

When saving the form without supplying an image to uploadcare I get this error message on update:

NameError (undefined local variable or method cdn_url' for #Branding:0x007ffd61d381f8)

NoMethodError - undefined method delete' for nil:NilClass: app/controllers/brandings_controller.rb:11:in block in update'
app/controllers/brandings_controller.rb:10:in update' app/controllers/application_controller.rb:61:in set_time_zone'`

GemLock:
uploadcare-rails (1.1.1) rails (>= 4, < 5.2) uploadcare-ruby (~> 1.0) uploadcare-ruby (1.1.0)

Branding View:
<%= include_uploadcare_widget_from_cdn version: '3.x', min: true %>

Let me know if there is any other information I can give.

Chrome Inspector Breaks With Widget Version 2.6

I used a 1.5 version of the widget before. Working as expected.

I transferred to 2.5:

https://ucarecdn.com/widget/2.6.0/uploadcare/uploadcare.full.min.js

and Chrome inspector breaks.

When I try to uncheck style boxes, the boxes just blink without uncheck-ing

I have another project where it does that. I investigated and "something" seems to be applying the same classes to the html DOM element over and over again. The classes are js and csstransitions

Allow use of ENV variables for public/private keys

I'd like to store these values in environment variables instead of checking them into the repository. Is this possible with an alternative configuration method?

defaults: &defaults                                                              
  public_key: <%= ENV["UPLOADCARE_PUBLIC_KEY"] %>                                
  private_key: <%= ENV["UPLOADCARE_PRIVATE_KEY"] %> 

Just blows up.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.