From: Tomas Doran Date: Wed, 10 Aug 2011 15:59:57 +0000 (+0100) Subject: Show current_user as the preferred schema accessor X-Git-Url: http://git.shadowcat.co.uk/gitweb/gitweb.cgi?a=commitdiff_plain;h=refs%2Fheads%2Fmaster;p=dbsrgits%2FDBIx-Class-UserStamp.git Show current_user as the preferred schema accessor Fits in Better with Catalyst-TraitFor-Model-DBIC-Schema-WithCurrentUser, which takes less code / config to get working. However we still support ->current_user_id being called, if present, although ->current_user will be used in preference --- diff --git a/lib/DBIx/Class/UserStamp.pm b/lib/DBIx/Class/UserStamp.pm index 183c36c..3d2baf7 100644 --- a/lib/DBIx/Class/UserStamp.pm +++ b/lib/DBIx/Class/UserStamp.pm @@ -4,6 +4,7 @@ use base qw(DBIx::Class); use warnings; use strict; +use Carp qw/ confess /; our $VERSION = '0.11'; @@ -24,7 +25,7 @@ added or updated. package MyApp::Schema; - __PACKAGE__->mk_group_accessors('simple' => qw/current_user_id/); + __PACKAGE__->mk_group_accessors('simple' => qw/current_user/); package MyApp::Model::MyAppDB; @@ -32,19 +33,10 @@ added or updated. use namespace::autoclean; extends 'Catalyst::Model::DBIC::Schema'; - with 'Catalyst::Component::InstancePerContext'; - - sub build_per_context_instance { - my ($meth, $self) = (shift, shift); - my ($c) = @_; # There are other params but we dont care about them - my $new = bless({ %$self }, ref($self)); - my $user_info = $c->_user_in_session; - $new->schema($new->schema->clone); - my $user = $new->schema->resultset('User')->new_result({ %$user_info }); - $new->schema->current_user_id($user->id) if (defined $user_info); - return $new; - } + __PACKAGE->config( + traits => ['WithCurrentUser'], # Requires Catalyst::TraitFor::Model::DBIC::Schema::WithCurrentUser + ); package MyApp::Schema::SomeTable; @@ -88,11 +80,26 @@ sub add_columns { =head2 get_current_user_id -This method is meant to be overridden. The default is to return a -schema accessor called current_user_id which should be populated as such. +This method is meant to be overridden. The default is to look for a +'current_user' accessor on the schema, and call an ->id method +on it. =cut -sub get_current_user_id { shift->result_source->schema->current_user_id } + +sub get_current_user_id { + my $self = shift; + my $schema = $self->result_source->schema; + if ($schema->can('current_user')) { + return $schema->current_user->id + if $schema->current_user; + } + elsif ($schema->can('current_user_id')) { + return $schema->current_user_id; + } + else { + confess("Your schema $schema does not have either a 'current_user' or 'current_user_id' accessors needed by " . __PACKAGE__); + } +} =head1 AUTHOR