Skip to content

Instantly share code, notes, and snippets.

@s1037989
Last active August 29, 2015 14:07
Show Gist options
  • Save s1037989/b02b94ef9e0a37f0f939 to your computer and use it in GitHub Desktop.
Save s1037989/b02b94ef9e0a37f0f939 to your computer and use it in GitHub Desktop.
Server-side storage for Mojolicious
package Mojo::Storage;
use Mojo::Base 'Mojo::EventEmitter';
use Carp 'croak';
use DBM::Deep;
our $VERSION = '0.01';
has _home => sub { Mojo::Home->new->detect };
has _database => sub { {} };
sub db {
my $self = shift;
my $name = shift || 'storage';
my $file = $self->_home->rel_file(join '/', 'storage', "$name.db") or return undef;
my $dirname = File::Basename::dirname($file);
mkdir $dirname unless -d $dirname;
$self->_database->{$name} ||= DBM::Deep->new($file);
}
1;
package Mojolicious::Plugin::Storage;
use Mojo::Base 'Mojolicious::Plugin';
our $VERSION = '0.01';
use Mojo::Storage;
sub register {
my ($self, $app) = @_;
$app->helper(storage => sub { return Mojo::Storage->new });
}
1;
#!/usr/bin/env perl
use Mojolicious::Lite;
use lib 'mojo-storage/lib';
use lib 'Mojolicious-Plugin-Storage/lib';
plugin 'Storage';
get '/' => sub {
my $c = shift;
my $test1 = $c->storage->db('test1');
$test1 = $test1->get("apple") .
$test1->put("apple", $c->param('a')) .
$test1->get("apple");
my $test2 = $c->storage->db('test2');
$test2 = $test2->get("apple") .
$test2->put("apple", $c->param('b')) .
$test2->get("apple");
$c->render('index', test1 => $test1, test2 => $test2);
};
app->start;
__DATA__
@@ index.html.ep
% layout 'default';
% title 'Welcome';
Welcome to the Mojolicious real-time web framework!
<%= $test1 %>
<%= $test2 %>
@@ layouts/default.html.ep
<!DOCTYPE html>
<html>
<head><title><%= title %></title></head>
<body><%= content %></body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment