how do sizing image with paperclip gem - ruby-on-rails

i want to use avatar through paperclip. in tutorial use gravatar
messages_helper.rb
def recipients_options(chosen_recipient = nil)
s = ''
User.all.each do |user|
s << "<option value='#{user.id}'
data-img-src='#{gravatar_image_url(user.email, size: 50)}'
#{'selected' if user == chosen_recipient}>
#{user.name}</option>"
end
s.html_safe
end
i change on this code and it working.
module MessagesHelper
def recipients_options(chosen_recipient = nil)
s = ''
User.all.each do |user|
s << "<option value='#{user.id}' data-img-src='#{user.avatar.url(:thumb)}'
#{'selected' if user == chosen_recipient}>#{user.username}</option>"
end
s.html_safe
end
end
new.html.erb
<div class="form-group">
<%= label_tag 'recipients', 'Choose recipients' %>
<%= select_tag 'recipients', recipients_options(#chosen_recipient), multiple: true, class: 'form-control chosen-it ' %>
</div>
user.rb
has_attached_file :avatar, :styles => { :medium => "150x150>", :thumb => "30x30#" }, default_url: "https://s3.amazonaws.com/myinstick/logo/instagram-icon.png"
validates_attachment_content_type :avatar, :content_type => /\Aimage\/.*\Z/
But! if user dont have avatar, that use image paperclip default. and it does not scaling and It looks big. how to set the style or size.
it looks like this

in your model:
has_attached_file :avatar,
:styles => { thumb: "100x100#", medium: "300x300#", large: "900x500#"}
or whatever size you want it to be. The # is for cropping. It will select the center of the image and crop the specified height and width from there. You can also just use the default > if you don't want the cropping... and in your view:
<%= image_tag #user.avatar.url(:medium) %>

I solved the problem. Drop-down list uses
jquery.image-select.js
(function($) {
// Image template, this can be overridden from the constructor (options.template),
// must contains {src} placeholder. Ther eare two class names 'chose-image' or 'chose-image-small', modifiy in CSS
var fn_template = '<img class="{class_name} " src="{url}" />';
// Store the original 'chosen' method
var fn_chosen = $.fn.chosen;........
I can set class for all images, like this
var fn_template = '<img class="{class_name} image-circle-minisize" src="{url}" />';
and everything works

Related

ActionView::Template::Error (undefined method `image_url' for #<ActionView::Helpers::FormBuilder:0x00007f921c2ac9b0>)

I'm using the shrine gem in form object,
I want to clip images, so, I followed https://github.com/shrinerb/shrine/wiki/Image-Cropping,
but, happed above error,
I think that it seems to be don't recognize photos models
views
<%= form_with model: #blog_form , url: user_blogs_path ,local: true do |f| %>
<div class="field">
<% f.label :title %>
<%= f.text_field :title %>
</div>
<div class="field">
<% f.label :content %>
<%= f.text_area :content %>
</div>
<div class="field">
<% f.label :user_id %>
<%= f.hidden_field :user_id, value: current_user.id %>
</div>
<div class ="field">
<%= f.fields_for :photos, #blog_form do |photos_fileds| %>
<%= photos_fileds.label :image %>
<%= photos_fileds.hidden_field :image, value: photos_fileds.cached_image_data if defined?
(photos_filed.cached_image_data) %>
%= photos_fileds.file_field :image %><br/>
<div>
<img id="image" src="<%= photos_fileds.image_url %>"
</div>
<% end %>
</div>
image_uploader
require "vips"
require "image_processing/vips"
class ImageUploader < Shrine
plugin :derivatives
THUMBNAILS = {
large: [800, 800],
medium: [600, 600],
small: [300, 300],
}
Attacher.derivatives do |original|
vips = ImageProcessing::Vips.source(original)
vips = vips.crop(*file.crop_points) # apply cropping
THUMBNAILS.transform_values do |(width, height)|
vips.resize_to_limit!(width, height)
end
end
plugin :derivation_endpoint, prefix: "derivations/image"
# Default URLs of missing derivatives to on-the-fly processing.
Attacher.default_url do |derivative: nil, **|
next unless derivative && file
file.derivation_url :transform, shrine_class.urlsafe_serialize(
crop: file.crop_points,
resize_to_limit: THUMBNAILS.fetch(derivative),
)
end
# Generic derivation that applies a given sequence of transformations.
derivation :transform do |file, transformations|
transformations = shrine_class.urlsafe_deserialize(transformations)
vips = ImageProcessing::Vips.source(file)
vips.apply!(transformations)
end
end
class UploadedFile
# convenience method for fetching crop points from metadata
def crop_points
metadata.fetch("crop").fetch_values("x", "y", "width", "height")
end
end
shrine.rb
require "shrine"
require "shrine/storage/file_system"
Shrine.storages = {
cache: Shrine::Storage::FileSystem.new("app/assets/images", prefix: "uploads/cache"), # temporary
store: Shrine::Storage::FileSystem.new("app/assets/images", prefix: "uploads"), # permanent
}
Shrine.plugin :activerecord # loads Active Record integration
Shrine.plugin :cached_attachment_data # enables retaining cached file across form redisplays
Shrine.plugin :restore_cached_data # extracts metadata for assigned cached files
Shrine.plugin :determine_mime_type
Shrine.plugin :derivatives
Shrine.plugin :backgrounding
Shrine::Attacher.promote_block { PromoteJob.perform_later(record, name, file_data) }
Shrine::Attacher.destroy_block { DestroyJob.perform_later(data) }
Shrine.plugin :derivation_endpoint, secret_key: Rails.application.secret_key_base
Shrine.plugin :default_url
cropbox.js
import 'cropperjs/dist/cropper.css'
import Cropper from 'cropperjs'
function cropbox(image, url, { onCrop }) {
image.src = url
new Cropper(image, {
aspectRatio: 1,
viewMode: 1,
guides: false,
autoCropArea: 1.0,
background: false,
zoomable: false,
crop: event => onCrop(event.detail)
})
}
export default cropbox
fileUpload.js
import cropbox from 'cropbox'
// ...
uppy.on('upload-success', (file, response) => {
// retrieve uploaded file data
const uploadedFileData = response.body['data']
// set hidden field value to the uploaded file data so that it's submitted
// with the form as the attachment
hiddenInput.value = JSON.stringify(uploadedFileData)
cropbox(imagePreview, response.uploadURL, {
onCrop(detail) {
let fileData = JSON.parse(hiddenInput.value)
fileData['metadata']['crop'] = detail
hiddenInput.value = JSON.stringify(fileData)
}
})
})
promote_job.rb
class PromoteJob < ApplicationJob
def perform(record, name, file_data)
attacher = Shrine::Attacher.retrieve(model: record, name: name, file: file_data)
attacher.create_derivatives
attacher.atomic_promote
end
end
destroy_job.rb
class DestroyJob < ApplicationJob
def perform(data)
attacher = Shrine::Attacher.from_data(data)
attacher.destroy
end
end
route.rb
Rails.application.routes.draw do
mount ImageUploader.derivation_endpoint => "/derivations/image"
get 'sessions/new'
devise_for :users
resources :users do
resources :blogs
end
# For details on the DSL available within this file, see
https://guides.rubyonrails.org/routing.html
end
blog_form.rb
class BlogForm
include ActiveModel::Model
attr_accessor :title, :content, :user_id , :photos, :tag_list
def blog_builder
#user = User.find(user_id)
#blogs = #user.blogs.create(title: title , content: content )
end
concerning :PhotosBuilder do
attr_reader :photos_attributes
def photos
#photos ||= Photo.new
end
def photos_attributes=(attributes)
debugger
#photos ||= Photo.new(attributes)
end
end
def build_association
#blogs.photos << #photos if photos?
#user.photos << #photos if photos
end
def save
return false if invalid?
blog_builder
#blogs.save
#photos.save if #photos != nil
build_association
end
def photos?
return true if #photos != nil
end
end
controller
def new
#user = params[:user_id]
#blog_form = BlogForm.new
end
def create
debugger
#blog_form = BlogForm.new(add_params) if has_a_tags? == true
#blog_form = BlogForm.new(blog_form_params)
if #blog_form.save
redirect_to user_blogs_path
else
#False action
end
end
I appreciate you, janko-m, arieljuod
I rewrite views, then happened new error
before
ActionView::Template::Error (undefined method `image_url' for #
<ActionView::Helpers::FormBuilder:0x00007f9228150380>):
<%= photos_fileds.hidden_field :image, value: photos.cached_image_data if
defined?(photos.cached_image_data) %>
<%= photos_fileds.file_field :image %><br/>
<div>
<img id="image" src="<%= photos_fileds.image_url %>"
</div>
<% end %>
after
ActionView::Template::Error (undefined method `image_url' for #
<BlogForm:0x00007f9228090a58>):
<%= photos_fileds.hidden_field :image, value:
photos_fileds.cached_image_data if defined?
(photos_filed.cached_image_data) %>
<%= photos_fileds.file_field :image %><br/>
<div>
<img id="image" src="<%= photos_fileds.object.image_url %>" />
</div>
<% end %>
environment
rails 6.0.2 ruby 2.5.3
This line is trying to call #image_url on the form object:
<img id="image" src="<%= photos_fileds.image_url %>" />
Instead it needs to be calling #image_url on the ActiveRecord model:
<img id="image" src="<%= photos_fileds.object.image_url %>" />

Rails Paperclip interpolates and before_save with custom id

In my app (Rails 5.2), my model uses an id with UUID type .
I have created one more field: id_server which will be the id I want to use with paperclip for :id_partition to create multiple folders (default id_partition works with id field, not with another field).
I have done that:
before_save do
id_server = Photo.maximum(:id_server) + 1
end
to create the next id_server.
And for Paperclip:
# paperclip
has_attached_file :file, path: "/upload/:class/:attachment/:id_server_partition/:style/:basename.:extension",
styles: { :tiny => "140x140>", :small => "160x240", :high => "640x960" }
validates_attachment :file, content_type: { content_type: ['image/jpg', 'image/jpeg', 'image/pjpeg', 'image/png', 'image/x-png'] }
validates_attachment :file, size: { in: 0..5.megabytes }
# create multiple folders path with id_server
Paperclip.interpolates :id_server_partition do |attachment, style|
attachment.instance.id_server_partition
end
def id_server_partition
("%09d".freeze % id_server).scan(/\d{3}/).join("/".freeze)
end
The fact is before_save() seems to never be called before Paperclip.interpolates.
id_server is nil in:
("%09d".freeze % id_server).scan(/\d{3}/).join("/".freeze)
can't convert nil into Integer
What did I miss ?
Strangely, it was because self was missing in:
before_save do
end
so this works, and the id_server is created here:
self.id_server = Photo.maximum(:id_server) + 1
but not this:
id_server = Photo.maximum(:id_server) + 1
But here, no need of the self before id_server:
("%09d".freeze % id_server).scan(/\d{3}/).join("/".freeze)

Integration with ckeditor, isnt showing the images-wicked-pdf

So, I load the images from a ckeditor, and when I render the html, it does not show, no error appears, just a blank square, instead of the image, I tried raw, html_safe, but it does not solve, the text I put is showing normally, does anyone have any idea why this happens?
a image is in
https://user-images.githubusercontent.com/26804018/31889194-ae1084e8-b7dd-11e7-85c7-1ba09d946269.png
in my view:
<h6><b>1. Objetivo:</b></h6>
<p><%= raw #pop.objective %></p>
my controller:
def show
# redirect_to :index_pdf
# #pop = Pop.friendly.find(params[:id])
#pop = Pop.find(params[:id])
pdf = render pdf: #pop.title,
:layout => false,
template: "pops/index_pdf.html.erb",
locals: {:pop => #pop},
header: {
right: 'Pág. [page] de [topage].'
}
# send_file(pdf, :filename => #pop.title+'.pdf')
# baixar automaticamente
# precisa fazer
end
my model:
has_attached_file :image, styles: { medium: "300x300>" }, default_url: "/images/default.png"
I solved by putting a helper method:
def with_abs_path(htmlstring)
htmlstring.to_s.gsub(/(href|src)=(['"])\/([^\"']*|[^"']*)['"]/, '\1=\2' + 'address_of_server' + '\3\2')
end
and calling in a view of my pdf:
<%= raw with_abs_path(#pop.objective) %>
the view was the same show:
<%= raw #pop.objective %>

How to Re-size Images that are Too Large on-the-fly with Paperclip and Rails 3

I am trying to implement the steps to check and resize images with paperclip based on this blog post: http://www.techdarkside.com/how-to-re-size-images-that-are-too-large-on-the-fly-with-paperclip-and-rails
Here is what I have in place...
class Question < ActiveRecord::Base
# subclasses
class Question::Image < Asset
has_attached_file :attachment,
:url => "/uploads/:class/:attachment/:id_partition/:basename_:style.:extension",
:styles => Proc.new { |attachment| attachment.instance.styles },
:styles => Proc.new { |attachment| attachment.instance.resize }
attr_accessible :attachment
# http://www.ryanalynporter.com/2012/06/07/resizing-thumbnails-on-demand-with-paperclip-and-rails/
def dynamic_style_format_symbol
URI.escape(#dynamic_style_format).to_sym
end
def styles
unless #dynamic_style_format.blank?
{ dynamic_style_format_symbol => #dynamic_style_format }
else
{ :medium => "300x300>", :thumb => "100x100>" }
end
end
def dynamic_attachment_url(format)
#dynamic_style_format = format
attachment.reprocess!(dynamic_style_format_symbol) unless attachment.exists?(dynamic_style_format_symbol)
attachment.url(dynamic_style_format_symbol)
end
def resize
if self.attachment_file_size > 2000000
"300x300>"
else
" "
end
end
end
I'm thinking the issue is with the reuse of the :styles symbol, however I'm not sure how to work both the styles method AND the resize method into a single Proc statement.
Here is what I ended up with thanks to #janfoeh suggestion. I did need to add :originalto the options in style to get this to work. I also bumped the max file size up to 5mb.
class Question < ActiveRecord::Base
# subclasses
class Question::Image < Asset
has_attached_file :attachment,
:url => "/uploads/:class/:attachment/:id_partition/:basename_:style.:extension",
:styles => Proc.new { |attachment| attachment.instance.styles }
attr_accessible :attachment
# http://www.ryanalynporter.com/2012/06/07/resizing-thumbnails-on-demand-with-paperclip-and-rails/
def dynamic_style_format_symbol
URI.escape(#dynamic_style_format).to_sym
end
def styles
unless #dynamic_style_format.blank?
{ dynamic_style_format_symbol => #dynamic_style_format }
else
{ :original => resize, :medium => "300x300>", :thumb => "100x100>" }
end
end
def dynamic_attachment_url(format)
#dynamic_style_format = format
attachment.reprocess!(dynamic_style_format_symbol) unless attachment.exists?(dynamic_style_format_symbol)
attachment.url(dynamic_style_format_symbol)
end
def resize
if self.attachment_file_size > 5000000
"1000x1000>"
else
" "
end
end
end

Latitude/Longitude not woking in EXIFR gem for Ruby

Am trying to use the exifr gem to read lat/long for an image upload.
In the model:
attr_accessible :image, :post_process_photo, :width, :height, :model, :datetime, :latitude, :longitude
belongs_to :user
has_attached_file :image, styles: { medium: "300x300#", thumb: "50x50#", large:"500x500#" }
after_post_process :post_process_photo
def post_process_photo
imgfile = EXIFR::JPEG.new(image.queued_for_write[:original].path)
return unless imgfile
self.width = imgfile.width
self.height = imgfile.height
self.model = imgfile.model
self.datetime = imgfile.date_time
self.latitude = imgfile.gps.latitude
self.longitude = imgfile.gps.longitude
end
In the view... the width/height stuff is working, but lat/long isn't:
<%= #pic.width %> #this works!
<%= #pic.height %> #this works!
<%= #pic.latitude %> #this doesn't!
<%= #pic.longitude %> #this doesn't!
...which is odd, because it's marked up exactly as instructed in the gem docs.
Have also added the appropriate migrations to the DB, which appear as should on the schema.
The view renders undefined methodlatitude'`
Any help much appreciated!
I think you want imgfile.gps_latitude and imgfile.gps_longitude - underscored instead of dots

Resources