Repository URL to install this package:
|
Version:
0.4.2 ▾
|
module Scrapbook
class Placement < ApplicationRecord
belongs_to :master, foreign_key: :scrapbook_master_id,
class_name: 'Scrapbook::Master'
belongs_to :parent, polymorphic: true,
required: false # Temporarily dont require parent?
default_scope { sorted }
scope :context, ->(context) { where(context_name: context) }
scope :sorted, -> { order(:position) }
delegate :target_resolution, to: :context, prefix: false
delegate :aspect_ratio, to: :target_resolution, prefix: false
delegate :title, to: :master, prefix: false, allow_nil: true
delegate :metadata, to: :master, prefix: true
delegate :all_metadata, to: :master, prefix: true
attribute :crop_origin, :scrapbook_coordinate, default: '0,0'
attribute :crop_resolution, :scrapbook_resolution
validates_presence_of :context_name
has_attached_file :file,
styles: lambda { |attachment| attachment.instance.sizes },
processors: [:cropped_resize]
do_not_validate_attachment_file_type :file
before_save :recrop_check
def initialize(attributes = {})
super context_name: attributes.delete(:context_name)
assign_attributes(attributes)
end
def context
Context.find(context_name)
end
def recrop_check
return unless crop_changed? && !new_record?
self.file.assign(self.file)
file.save
end
def sizes
sizes = { standard: target_resolution.to_s }
if crop_retina_ready?
sizes.merge!(retina: target_resolution.retinafy.to_s)
end
sizes
end
def crop_retina_ready?
usable_crop_resolution.retinable?(target_resolution)
end
def crop_metrics
{
width: usable_crop_resolution.width,
height: usable_crop_resolution.height,
x: crop_origin.x,
y: crop_origin.y
}
end
def overriding_metadata
attributes.select do |k, v|
self.class.metadata_fields.include?(k) && v.present?
end
end
def overriding_metadata=(hsh)
assign_attributes(hsh)
end
def metadata
master_metadata.merge(overriding_metadata)
end
def all_metadata
master_all_metadata.merge(overriding_metadata)
end
def usable_crop_resolution
crop_resolution || target_resolution
end
def file_urls
Hash[sizes.keys.map { |size| [size, file_url(size)] }]
end
def file_url(style = :standard)
return unless file.exists?
file.url(style)
end
def edit_path
@edit_path ||= Engine.routes.url_helpers.edit_placement_path(self)
end
def to_data
as_json(methods: [:edit_path, :file_urls, :title, :metadata], except: [:crop_origin, :crop_resolution])
end
def crop_changed?
crop_resolution_changed? || crop_origin_changed?
end
def master=(other)
super
self.file = master.file
end
def scrapbook_master_id=(other_id)
super
self.file = master.file
end
private
def self.metadata_fields
Scrapbook.config.metadata_fields.keys
end
end
end