Skip to content

Instantly share code, notes, and snippets.

@omar-m-othman
Created April 15, 2015 22:31
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save omar-m-othman/fcf2780845b381b4a7fd to your computer and use it in GitHub Desktop.
Save omar-m-othman/fcf2780845b381b4a7fd to your computer and use it in GitHub Desktop.
So, I have an app that acts like a background process to do a lot of host monitoring (CPU usage, RAM, some services running on the host and what not)
These are stored using some sort of a unified file system, so that the storage code is almost the same but different directories.
There are a lot of CRUD handlers (e.g. dashboard_my_create, dashboards_my_read, dashboard_my_update, dashboards_my_delete)
And there are two generic handlers, one called _common_cu (create, update) and one called _common_rd (read, delete)
sub dashboard_my_create { shift->_common_cu('dashboard_my_create'); }
sub dashboards_my_read { shift->_common_rd('dashboards_my_read' ); }
sub _common_rd {
my ( $self, $method ) = @_;
# I have to do this now myself.
my $params = $self->req->params->to_hash();
my $captures = $self->get_all_unreserved_keys();
# state() is a helper we define that gives access to all storage classes.
my $certain_storage = $self->state->{'certain_storage'};
return $self->render(
'json',
{ result => $certain_storage->$method( $captures, $params ) }
);
}
sub get_all_unreserved_keys {
my $self = shift;
state $reserved_keys = {
action => 1,
app => 1,
cb => 1,
controller => 1,
data => 1,
extends => 1,
format => 1,
handler => 1,
json => 1,
layout => 1,
namespace => 1,
path => 1,
status => 1,
template => 1,
text => 1,
variant => 1
};
my %unreserved_keys = ();
my $stash = $self->stash;
for (keys %{ $stash }) {
exists $reserved_keys->{$_} || $_ =~ m/^mojo[.]/
or $unreserved_keys{$_} = $stash->{$_};
}
return \%unreserved_keys;
}
As you can see here, it is convenient to send the state class a structure for parameters and another one for captures in the URL, since the API is restful and you try to give as descriptive of a URL as possible (even on the code level).
Here is an example URL:
q{/certain_storage/(:user_id)/dashboards/my/(:dashboard_id)}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment