Search code examples
perlattributesdeprecatedmoose

How do I deprecate an attribute in a Moose based class


I have a Moose based class, with a couple of attributes that I want to remove.

I want any use of them to generate a deprecation warning.
Possibly with a way to disable the warnings.

package JSON::RPC::LWP;
...
use Moose;
...

has previous_id => (
  is => 'ro',
  isa => JSONValue,
  init_arg => undef,
  writer => '_previous_id',
  predicate => 'has_previous_id',
  clearer => 'clear_previous_id',
);

# default id generator is a simple incrementor
my $default_id_gen = sub{
  my($self,$prev) = @_;
  $prev ||= 0;
  return $prev + 1;
};

has id_generator => (
  is => 'rw',
  isa => 'Maybe[CodeRef]',
  default => sub{ $default_id_gen },
  trigger => sub{
    my($self,$coderef) = @_;
    unless( $coderef ){
      $self->{id_generator} = $default_id_gen;
    }
  },
);

I have already removed the only place id_generator was used.


Right now the only known user of this module sets id_generator to a code ref that effectively sets it to the future behaviour.
I have modified it to only do this on older versions of my module. ( not yet released )

package Games::Lacuna::Client::RPC;
...
use Moose;

extends 'JSON::RPC::LWP';
...

has '+id_generator' => (
  default => sub{sub{1}},
);

Solution

  • Here's another way to do it! Use MooseX::Deprecated :-)

    with "MooseX::Deprecated" => {
       attributes => [ "id_generator" ],
    };
    

    I wrote MooseX::Deprecated inspired by my previous answer to this question. It encapsulates the application of method modifiers, checking init_args, fiddling with %Carp::Internal and warnings::enabled, all into one tidy little package.