| 1 | package WWW::MenuGrinder::Plugin::FileReloader; | ||
| 2 | BEGIN { | ||
| 3 | $WWW::MenuGrinder::Plugin::FileReloader::VERSION = '0.06'; | ||
| 4 | } | ||
| 5 | |||
| 6 | # ABSTRACT: WWW::MenuGrinder plugin to reload the menu when a file changes. | ||
| 7 | |||
| 8 | use Moose; | ||
| 9 | |||
| 10 | with 'WWW::MenuGrinder::Role::OnInit'; | ||
| 11 | with 'WWW::MenuGrinder::Role::BeforeMogrify'; | ||
| 12 | |||
| 13 | # New versions of Time::HiRes give us subsecond times on stat(). Use it if we | ||
| 14 | # can just in case we find ourselves racing against two crazy-fast updates. | ||
| 15 | BEGIN { | ||
| 16 | eval { | ||
| 17 | require Time::HiRes; | ||
| 18 | Time::HiRes->import(qw(stat)); | ||
| 19 | }; | ||
| 20 | } | ||
| 21 | |||
| 22 | has filename => ( | ||
| 23 | is => 'rw', | ||
| 24 | ); | ||
| 25 | |||
| 26 | has timestamp => ( | ||
| 27 | is => 'rw' | ||
| 28 | ); | ||
| 29 | |||
| 30 | sub on_init { | ||
| 31 | my ($self) = @_; | ||
| 32 | my $time = (stat $self->filename)[9]; | ||
| 33 | $self->timestamp( $time ) if defined $time; | ||
| 34 | } | ||
| 35 | |||
| 36 | sub before_mogrify { | ||
| 37 | my ($self) = @_; | ||
| 38 | |||
| 39 | my $time = (stat $self->filename)[9]; | ||
| 40 | |||
| 41 | # It seems odd that we're not setting $self->timestamp here but our on_init | ||
| 42 | # is about to get called anyway... | ||
| 43 | if (defined $time and $time > $self->timestamp) { | ||
| 44 | $self->grinder->init_menu; | ||
| 45 | } | ||
| 46 | |||
| 47 | return $self->grinder->menu; | ||
| 48 | |||
| 49 | } | ||
| 50 | |||
| 51 | sub BUILD { | ||
| 52 | my ($self) = @_; | ||
| 53 | |||
| 54 | my $filename = $self->grinder->config->{filename}; | ||
| 55 | die "config->{filename} is required" unless defined $filename; | ||
| 56 | |||
| 57 | $self->filename($filename); | ||
| 58 | } | ||
| 59 | |||
| 60 | __PACKAGE__->meta->make_immutable; | ||
| 61 | |||
| 62 | no Moose; | ||
| 63 | 1; | ||
| 64 | |||
| 65 | |||
| 66 | __END__ |