Created
February 17, 2018 22:31
-
-
Save SergeyMell/2216a9c282c8311fc5e1c071961c83ec to your computer and use it in GitHub Desktop.
Formtastic extension of file inputs to make them as inputs with image preview
This file contains hidden or 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
class ImageWithPreviewInput < Formtastic::Inputs::FileInput | |
def to_html | |
options.merge!(hint: preview_html.html_safe) | |
super + "<script>#{preview_script}</script>".html_safe | |
end | |
private | |
def preview_html | |
<<-HTML | |
<span style="display: inline-block; margin-right: 20px; vertical-align: top;"> | |
Current #{method}<br> | |
<image src="#{object.send(method).url}" height="100"> | |
</span> | |
<span style="display: inline-block; vertical-align: top;"> | |
Selected #{method}<br> | |
<img height="100" id="#{input_html_options[:id]}_upload"> | |
</span> | |
HTML | |
end | |
def preview_script | |
<<-JavaScript | |
$("##{input_html_options[:id]}").change(function() { | |
readURL(this); | |
}); | |
function readURL(input) { | |
if (input.files && input.files[0]) { | |
var reader = new FileReader(); | |
reader.onload = function(e) { | |
$('##{input_html_options[:id]}_upload').attr('src', e.target.result); | |
} | |
reader.readAsDataURL(input.files[0]); | |
} | |
} | |
JavaScript | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment