chained translator with store
Matt S Trout [Mon, 2 Mar 2009 16:30:20 +0000 (11:30 -0500)]
lib/LolCatalyst/Lite/Controller/Root.pm
lib/LolCatalyst/Lite/Controller/Translate.pm [new file with mode: 0644]
lib/LolCatalyst/Lite/Model/SnippetStore.pm [new file with mode: 0644]
root/translate/create.tt [new file with mode: 0644]
root/translate/view.tt [new file with mode: 0644]

index 395e4a9..252b1bc 100644 (file)
@@ -16,7 +16,7 @@ sub default :Path {
     $c->response->body( 'Page not found' );
 }
 
-sub translate :Local {
+sub translate :Private {
      my ($self, $c) = @_;
      my $lol = $c->req->body_params->{lol}; # only for a POST request
          # $c->req->params->{lol} would catch GET or POST
diff --git a/lib/LolCatalyst/Lite/Controller/Translate.pm b/lib/LolCatalyst/Lite/Controller/Translate.pm
new file mode 100644 (file)
index 0000000..8df27b7
--- /dev/null
@@ -0,0 +1,38 @@
+package LolCatalyst::Lite::Controller::Translate;
+
+use strict;
+use warnings;
+use parent qw(Catalyst::Controller);
+
+sub base :Chained('/') :PathPart('translate') :CaptureArgs(0) {
+  my ($self, $c) = @_;
+  $c->stash(collection => $c->model('SnippetStore'));
+}
+
+sub create :Chained('base') :PathPart('') :Args(0) {
+  my ($self, $c) = @_;
+  my $req = $c->req;
+  if ($req->method eq 'POST' && (my $lol = $req->body_params->{lol})) {
+    my $snippet = $c->stash->{collection}->create({ text => $lol });
+    $c->stash(object => $snippet);
+    $c->detach('view');
+  }
+}
+
+sub object :Chained('base') :PathPart('') :CaptureArgs(1) {
+  my ($self, $c, $id) = @_;
+  my $object = $c->stash->{collection}->find($id);
+  $c->detach('/error_404') unless $object;
+  $c->stash(object => $object);
+}
+
+sub view :Chained('object') :PathPart('') :Args(0) {
+  my ($self, $c) = @_;
+  my $object = $c->stash->{object};
+  $c->stash(
+    result => $c->model('Translator')
+                ->translate($object->{text})
+  );
+}
+
+1;
diff --git a/lib/LolCatalyst/Lite/Model/SnippetStore.pm b/lib/LolCatalyst/Lite/Model/SnippetStore.pm
new file mode 100644 (file)
index 0000000..775919e
--- /dev/null
@@ -0,0 +1,9 @@
+package LolCatalyst::Lite::Model::SnippetStore;
+
+use strict;
+use warnings;
+use aliased 'LolCatalyst::Lite::SnippetStore';
+
+sub COMPONENT { SnippetStore->new }
+
+1;
diff --git a/root/translate/create.tt b/root/translate/create.tt
new file mode 100644 (file)
index 0000000..051c332
--- /dev/null
@@ -0,0 +1,5 @@
+[% IF result; INCLUDE translate/view.tt; END %]
+<form name="translate" method=POST action="translate">
+   <input type="text" name="lol" value="" title="enter text to translate">
+   <input type="submit" value="Translate">
+</form>
diff --git a/root/translate/view.tt b/root/translate/view.tt
new file mode 100644 (file)
index 0000000..ab65af4
--- /dev/null
@@ -0,0 +1 @@
+<p>[% object.text _ ": " _ result %]</p>