Skip to content

Instantly share code, notes, and snippets.

@tonycoco
Last active August 29, 2015 14:08
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tonycoco/aa67c398953ebb920100 to your computer and use it in GitHub Desktop.
Save tonycoco/aa67c398953ebb920100 to your computer and use it in GitHub Desktop.
Carrierwave Uploader (with Cloudinary support) Input for ActiveAdmin's Formtastic Inputs
class UploaderInput < Formtastic::Inputs::FileInput
MAX_WIDTH_PIXELS = 300
MAX_HEIGHT_PIXELS = 200
def to_html
input_wrapping do
html_array = []
html_array << label_html
html_array << cache_html if method_changed?
html_array << file_html
html_array << existing_html if method_present?
html_array << remove_html if method_was_present?
html_array.join("").html_safe
end
end
private
def method_present?
if object.respond_to?("#{method}?")
object.send("#{method}?")
else
object.send(method).present?
end
end
def method_changed?
if object.respond_to?("#{method}_changed?")
object.send("#{method}_changed?")
else
false
end
end
def method_was_present?
if !method_changed?
method_present?
else
object.send("#{method}_was").present?
end
end
def cache_html
builder.hidden_field("#{method}_cache")
end
def file_html
builder.file_field(method, input_html_options)
end
def cloudinary?
object.send(method).is_a?(Cloudinary::CarrierWave) rescue false
end
def image_html
if cloudinary?
template.cl_image_tag(object.send(method).file.public_id, width: MAX_WIDTH_PIXELS, height: MAX_HEIGHT_PIXELS, crop: :limit)
else
template.image_tag(object.send(method).url, style: "max-width: #{MAX_WIDTH_PIXELS}px; max-height: #{MAX_HEIGHT_PIXELS}px;")
end
end
def inner_existing_html
if %w(jpg jpeg png gif).include?(object.send(method).file.format)
image_html
else
object.send(method).file.filename
end
end
def existing_html
template.content_tag(:div, style: "margin-left: 20%; padding-top: 5px;") do
template.link_to(inner_existing_html, object.send(method).url, target: :_blank)
end
end
def remove_html
template.content_tag(:div, style: "margin-left: 20%; padding-top: 5px;") do
template.content_tag(:label, style: "float: none; width: auto;") do
html_array = []
html_array << template.check_box_tag("#{object_name}[remove_#{method}]", 1, false, id: "#{sanitized_object_name}_remove_#{sanitized_method_name}")
html_array << "Remove"
html_array.join(" ").html_safe
end
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment