Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
Group Artworks into columns for a pinterest style layout (for use in emails)
module ArtworkColumns
# Return an array of artworks grouped together in sub arrays by being added to the shortest 'column'
# based on a fixed width and aspect ratios.
#
# @param {Array} artworks The array of artworks to group into columns
# @param {Number} num_columns The number of columns to group them into
# @param {Number} width The width the images will be displayed at
#
# @return {Array} An array of artworks grouped into sub arrays by being added to the shortest one.
def self.artwork_columns(artworks, num_columns, width)
artwork_cols = []
# Initialize columns
num_columns.times do
artwork_cols << []
end
artworks.each do |artwork|
add_to_shortest_column!(artwork_cols, artwork, width) if artwork.default_image
end
artwork_cols
end
private
# Adds artwork to shortest column
def self.add_to_shortest_column!(artwork_cols, artwork, width)
min_height = column_height(artwork_cols[0], width)
min_column_idx = 0
artwork_cols.each_with_index do |column, idx|
height = column_height(column, width)
if height < min_height
min_height = height
min_column_idx = idx
end
end
artwork_cols[min_column_idx] << artwork
end
# Calculate sum of heights of artworks in column
def self.column_height(artwork_col, width)
height = 0
artwork_col.each do |artwork|
if (aspect_ratio = artwork.default_image.aspect_ratio)
height += (width / aspect_ratio).floor
else
height += width
end
end
height
end
# Calculate sun of widths of artworks in row
def self.calculate_width(artwork_row, height)
width = 0
artwork_row.each do |artwork|
if (aspect_ratio = artwork.default_image.aspect_ratio)
width += (height * aspect_ratio).ceil
else
width += height
end
end
width
end
# calculate height of each artwork in collection to sum up to width
def self.calculate_max_height_for_width(artworks, width)
calculated_width = 0
height = 0
while calculated_width <= width
height += 1
calculated_width = calculate_width(artworks, height)
end
height - 1
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment