Snippets

Brian Medley Thoughts on a Mojo::Host object?

Created by Brian Medley
package Mojo::Host;
use Mojo::Base -base;
use overload
  '@{}'    => sub { shift->parts },
  bool     => sub {1},
  '""'     => sub { shift->to_string },
  fallback => 1;

use Mojo::Util qw(decode encode url_escape url_unescape);

has charset => 'UTF-8';
has qw(levels);

sub clone {
  my $self = shift;

  my $clone = $self->new;

  $clone->parse($self->to_string);

  return $clone;
}

sub new { @_ > 1 ? shift->SUPER::new->parse(@_) : shift->SUPER::new }

sub parts {
  my $self = shift;

  return $self->levels unless @_;

  $self->levels(shift);
}

sub tld {
  my $self = shift;
  my $levels = $self->levels // [];
  $levels->[-1] = shift;
  $self->levels($levels);
  return $self;
}

sub parse {
  my $self = shift;
  if (!defined $_[0]) {
      $self->levels(undef);
      return $self;
  }

  $self->levels([split(/\./, shift)]);
  return $self;
}

sub to_string {
  my $self = shift;

  return undef unless $self->levels;

  return join(".", @{ $self->levels });
}

1;

Comments (0)

HTTPS SSH

You can clone a snippet to your computer for local editing. Learn more.