Skip to content

Instantly share code, notes, and snippets.

@oklahomer
Last active August 29, 2015 13:57
Show Gist options
  • Save oklahomer/9680964 to your computer and use it in GitHub Desktop.
Save oklahomer/9680964 to your computer and use it in GitHub Desktop.
sub lookup_cached_image {
my ($class, $input) = @_;
# with Devel::Size, it appears that teng row object size is much bigger
# than the actual data it contains.
# so it just caches column values, here.
my $column_data = c->cache->get_or_set(
$cache_key => sub {
my $row = c->db->single(campaign_image => +{
id => $input->{id},
});
return $row->get_columns;
}, ONE_HOUR
);
# and then creates new row object
c->db->new_row_from_hash(campaign_image => $column_data);
}
my $upload = $c->req->upload('image'); # $upload is-a Plack::Request::Upload
my $fh = IO::File->new($upload->path, 'r') or die qq{Can't open image: $!};
# creates a table row object for temporary use
my $tmp_row = $c->db->new_from_hash(
campaign_image => +{
campaign_type => 'christmas',
image_filename => randome_str(32) . '.png',
}
);
# image_path() decides where to upload this file
# based on image_filename and campaign_type.
# e.g. /campaign_image/christmas/random_str_foo_bar.png
my $target_path = $tmp_row->image_path;
# upload image file to the designated path
$some_storage->put_object($target_path, $fh);
my ($width, $height) = imgsize($fh);
$fh->close;
# after image upload, insert and create actual record
my $row = $c->db->insert(campaign_image => +{
%{ $tmp_row->get_columns },
image_width => $width,
image_height => $height,
});
# image_url() adds base url to image_path(), which is equivalent to
# URI->new_abs($row->image_path, 'http://sample.com/')->as_string
# http://sample.com/campaign_image/christmas/random_str_foo_bar.png
warn $row->image_url;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment