Last active
June 22, 2020 09:48
-
-
Save majedbojan/216471179a27768741c99aaef05b000c to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
module Attachable | |
extend ActiveSupport::Concern | |
included do | |
## -------------------- Associations -------------------- ## | |
if const_defined?('STORAGE_TYPES') | |
self::STORAGE_TYPES.each do |k, v| | |
v == :one ? has_one_attached(k.to_sym) : has_many_attached(k.to_sym) | |
end | |
end | |
## ---------------------- Methods ----------------------- ## | |
if const_defined?('STORAGE_TYPES') | |
self::STORAGE_TYPES.each do |name, v| | |
define_method("#{name}_url") do | |
if v == :one | |
send(name).attached? ? send(name).service_url : default_attach | |
else | |
send(name).map(&:service_url) | |
end | |
end | |
end | |
end | |
end | |
# Override it if the model has no default attach | |
def default_attach? | |
true | |
end | |
def config | |
Rails.application.secrets.slice(:host, :http_type) | |
end | |
def default_attach | |
"#{config[:http_type]}://#{config[:host]}/images/missing.png" if default_attach? | |
end | |
end | |
# Usage: | |
# Include the concern and setup the constant as defined below | |
# STORAGE_TYPES = {img: :one, files: :many, file: :one} | |
class User < ApplicationRecord | |
STORAGE_TYPES = {img: :one, files: :many, file: :one} | |
include Attachable | |
end | |
user = User.first | |
user.files.attach(io: File.open("/Users/majed/Majeddocs/majed.jpeg"), filename: "majed.jpeg", content_type: "image/jpg") | |
user.files_url # Array of attach URLS | |
user.img.attach(io: File.open("/Users/majed/Majeddocs/majed.jpeg"), filename: "majed.jpeg", content_type: "image/jpg") | |
user.img_url # URL as String |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment