App-Pod

 view release on metacpan or  search on metacpan

lib/App/Pod.pm  view on Meta::CPAN

sub _dumper {
    require Data::Dumper;
    my $data = Data::Dumper
      ->new( [@_] )
      ->Indent( 1 )
      ->Sortkeys( 1 )
      ->Terse( 1 )
      ->Useqq( 1 )
      ->Dump;
    return $data if defined wantarray;
    say $data;
}

#
# Run
#

=head2 run

Run the main program.

lib/App/Pod.pm  view on Meta::CPAN

    if ( $dump >= 2 ) {    # Dump all.
        $data = $self;
    }
    elsif ( $dump >= 1 ) {    # Skip lol and tree.
        $data = {%$self};        # Shallow copy.
        for ( keys %$data ) {    # Keep the dump simple.
            delete $data->{$_} if /^_cache_/ and !/path/;
        }
    }

    say "self=" . _dumper $data;
}

# Spec

sub _define_spec {
    my @spec = (

        # If given a handler, will be auto processed.
        # Core options will be processed early.

lib/App/Pod.pm  view on Meta::CPAN

}

#
# Core
#

sub _process_core_flags {
    my ( $self ) = @_;

    for ( $self->_core_flags->@* ) {
        say "Processing: $_->{name}" if $self->_opts->{dump};
        my $handler = $_->{handler};
        return 1 if $self->$handler;
    }

    return 0;
}

# Help

sub _show_help {
    my ( $self ) = @_;

    say $self->_process_template(
        $self->_define_help_template,
        $self->_build_help_options,
    );

    return 1;
}

sub _define_help_template {
    <<"HELP";

lib/App/Pod.pm  view on Meta::CPAN


    $options;
}

# Version

sub _show_version {
    my ( $self ) = @_;
    my $version = $self->VERSION;

    say "pod (App::Pod) $version";

    return 1;
}

# List

=head2 list_tool_options

Returns a list of the possible command line options
to this tool.

lib/App/Pod.pm  view on Meta::CPAN

#
# Abort
#

sub _abort {
    my ( $self ) = @_;
    my $class = $self->_class;

    if ( not $class ) {
        if ( not $self->_opts->{no_error} ) {
            say "";
            say _red( "Class name not provided!" );
            say _reset( "" );
        }
        return 1;
    }

    # No wierd class names.
    if ( $class !~ m{ ^ [-~\w_:\\/. ]+ $ }x ) {
        if ( not $self->_opts->{no_error} ) {
            say "";
            say _red( "Invalid class name: $class" );
            say _reset( "" );
        }
        return 1;
    }

    # Make sure the path is not empty (error signal from Pod::Query).
    if ( not $self->_get_path ) {
        if ( not $self->_opts->{no_error} ) {
            say "";
            say _red( "Class not found: $class" );
            say _reset( "" );
        }
        return 1;
    }

    return 0;
}

sub _get_path {
    my ( $self ) = @_;

lib/App/Pod.pm  view on Meta::CPAN


    $path;
}

#
# Non Main
#

sub _process_non_main {
    my ( $self ) = @_;
    say "_process_non_main()" if $self->_opts->{dump};

    for ( $self->_non_main_flags->@* ) {
        say "Processing: $_->{name}" if $self->_opts->{dump};
        my $handler = $_->{handler};
        return 1 if $self->$handler;
    }
}

# List

=head2 list_class_options

Shows a list of all the available class options

lib/App/Pod.pm  view on Meta::CPAN


    # Use cache if available.
    my $cache = $self->retrieve_cache();

    # Make class specific cache if missing.
    if ( $cache->{class} ne $self->_class ) {
        $cache = $self->store_cache;
    }

    # Show possible options
    say for $cache->{options}->@*;
}

# Edit

=head2 edit_class

Edit a class using vim.
Can optionally just to a specific keyword.

=cut

lib/App/Pod.pm  view on Meta::CPAN

Use --dump option to show the data structure.
(For debugging use).

=cut

sub query_class {
    my ( $self ) = @_;

    local $Pod::Query::DEBUG_FIND_DUMP = 1 if $self->_opts->{dump};

    say for $self->_get_pod->find( $self->_opts->{query} );
}

#
# Main
#

sub _process_main {
    my ( $self ) = @_;
    say "_process_main()" if $self->_opts->{dump};

    # Go on.
    $self->show_header;
    if ( $self->_method ) {
        $self->show_method_doc;
    }
    else {
        $self->show_inheritance;
        $self->show_events;
        $self->show_methods;

lib/App/Pod.pm  view on Meta::CPAN

                  . _grey( ")" )
                : ""
            ),
        ),
    );
    my @path_line = ( _grey( "Path:" ), _grey( $self->_get_path ), );

    my $max    = max map { length } $package_line[0], $path_line[0];
    my $format = "%-${max}s %s";

    say "";
    _sayt sprintf( $format, @package_line );
    _sayt sprintf( $format, @path_line );

    say "";
    my ( $name, $summary ) = $self->_get_name_and_summary->@*;
    return unless $name and $summary;

    _sayt _yellow( $name ) . " - " . _green( $summary );
    say _reset( "" );
}

# Inheritance

sub _get_isa {
    my ( $self ) = @_;

    # Use in-memory cache if present.
    my $isa_cache = $self->_cache_isa;
    return $isa_cache if $isa_cache;

lib/App/Pod.pm  view on Meta::CPAN


Show the Inheritance chain of a class/module.

=cut

sub show_inheritance {
    my ( $self ) = @_;
    my $isa      = $self->_get_isa;
    my $size     = @$isa;
    return if $size <= 1;
    say _neon( "Inheritance ($size):" );
    say _grey( " $_" ) for @$isa;
    say _reset( "" );
}

# Events

sub _get_events {
    my ( $self ) = @_;

    # Use in-memory cache if present.
    my $mem_cache = $self->_cache_events;
    return $mem_cache if $mem_cache;

lib/App/Pod.pm  view on Meta::CPAN

sub show_events {
    my ( $self ) = @_;
    my $events   = $self->_get_events;
    my @names    = sort keys %$events;
    my $size     = @names;
    return unless $size;

    my $len    = max map { length( _green( $_ ) ) } @names;
    my $format = " %-${len}s - %s";

    say _neon( "Events ($size):" );
    for ( @names ) {
        _sayt sprintf $format, _green( $_ ), _grey( $events->{$_} );
    }
    say _reset( "" );
}

# Methods

sub _get_methods {
    my ( $self ) = @_;

    # Use in-memory cache if present.
    my $mem_cache = $self->_cache_methods;
    return $mem_cache if $mem_cache;

lib/App/Pod.pm  view on Meta::CPAN

    if ( not $self->_opts->{all} ) {
        @$all_method_names_and_docs =
          grep { not $skip_methods{ $_->[0] } } @$all_method_names_and_docs;
    }

    # Documented methods
    my @all_method_docs = grep { $_->[1] } @$all_method_names_and_docs;

    # If we have methods, but none are documented (or found).
    if ( @$all_method_names_and_docs and not @all_method_docs ) {
        say _grey(
            "Warning: All methods are undocumented! (reverting to --all)\n" );
        $self->_opts->{all} = 1;
    }

    my @methods =
      $self->_opts->{all} ? @$all_method_names_and_docs : @all_method_docs;
    my $max              = max 0, map { length _green( $_->[0] ) } @methods;
    my $format_with_desc = " %-${max}s%s";
    my $format_no_desc   = " %s%s";
    my $size             = @methods;
    say _neon( "Methods ($size):" );

    for my $list ( @methods ) {
        my ( $method, $doc_raw ) = @$list;
        my $doc = $doc_raw ? " - $doc_raw" : "";
        $doc =~ s/\n+/ /g;

        my $format = $doc_raw ? $format_with_desc : $format_no_desc;
        _sayt sprintf $format, _green( $method ), _grey( $doc );
    }

    say _grey( "\nUse --all (or -a) to see all methods." )
      unless $self->_opts->{all};
    say _reset( "" );
}

=head2 show_method_doc

Show documentation for a specific module method.

=cut

sub show_method_doc {
    my ( $self ) = @_;

lib/App/Pod.pm  view on Meta::CPAN

    for ( $doc ) {
        chomp;

        # Headings.
        s/ ^ \s* \K (\S+:) (?= \s* $ ) / _green($1) /xgem;

        # Comments.
        s/ (\#.+) / _grey($1) /xge;
    }

    say $doc;
    say _reset( "" );
}

#
# Caching
#

=head2 define_last_run_cache_file

Defined where to save the results from the last run.
This is done for performance reasons.

lib/App/Pod.pm  view on Meta::CPAN


        $so_far_len += $part->{len};
        push @parts, $part->{data};
    }

    join "", @parts;
}

sub _sayt {

    say trim( @_ );
}

sub _red {

    colored( "@_", "RESET RED" );
}

sub _yellow {

    colored( "@_", "RESET YELLOW" );

lib/App/Pod.pm  view on Meta::CPAN

- #     next if $key =~ /^ _ /x;               # Not private method
-       next if ref $stash;                    # Stash name should not be a reference
-       next if not defined *$stash{CODE};     # Stash function should be defined
-       push @keys_raw, $key;
-    }
-
-    my @keys = sort @keys_raw;
-
-    return @keys if defined wantarray;
-
-    say join "\n  ", "\n$class", @keys;
- }

=head1 ENVIRONMENT

Install bash completion support.

 % apt install bash-completion

Install tab completion.

t/01-usage-simple.t  view on Meta::CPAN

sub _dumper {
    require Data::Dumper;
    my $data = Data::Dumper
      ->new( [@_] )
      ->Indent( 1 )
      ->Sortkeys( 1 )
      ->Terse( 1 )
      ->Useqq( 1 )
      ->Dump;
    return $data if defined wantarray;
    say $data;
}

BEGIN {
    use_ok( 'App::Pod' ) || print "Bail out!\n";
}

diag( "Testing App::Pod $App::Pod::VERSION, Perl $], $^X" );

{
    no warnings qw( redefine once );

t/01-usage-simple.t  view on Meta::CPAN

            "Path:    <PATH>",
            "",
            "ojo - Fun one-liners with Mojo",
            "",
            "x:",
            "",
            "  my \$dom = x('<div>Hello!</div>');",
            "",
            "  Turn HTML/XML input into Mojo::DOM object.",
            "",
"  \$ perl -Mojo -E 'say x(f(\"test.html\")->slurp)->at(\"title\")->text'",
            "",
            "  [UnicodeTest: I ♥ Mojolicious!]",
        ]
    },

    # --query bad
    {
        name            => "query with no class",
        input           => [qw( --query head1[0]/Para )],
        expected_output => [ "", "Class name not provided!" ],

t/01-usage-simple.t  view on Meta::CPAN

    for ( @lines ) {
        s/$is_path/<PATH>/;
        s/$is_cache_path/ "PATH"/g;
    }

    # Normalize Version
    if ( "$input" eq "--version" ) {
        $lines[0] =~ s/$is_version/<VERSION>/;
    }

    say STDERR _dumper \@lines
      and last
      unless is_deeply( \@lines, $case->{expected_output}, $case->{name} );
}

t/02-trim.t  view on Meta::CPAN


{
    no warnings qw( redefine once );
    *red                        = *App::Pod::_red;
    *yellow                     = *App::Pod::_yellow;
    *green                      = *App::Pod::_green;
    *Pod::Query::get_term_width = sub { 9 };
}

# Snippet for manually testing on the CLI:
# perl -Ilib -MApp::Pod -E 'say Pod::Query::get_term_width; App::Pod::_sayt( App::Pod::_red("1234567890") . App::Pod::_yellow("1234567890") . App::Pod::_green("1234567890") )'

my $replacement = " ...";
my @cases       = (

    # Less than term_width.
    {
        name            => "Less than term_width",
        input           => "12345678",
        expected_output => "12345678",
    },

t/cpan/Mojo2/File.pm  view on Meta::CPAN

=head1 NAME

Mojo::File - File system paths

=head1 SYNOPSIS

  use Mojo::File;

  # Portably deal with file system paths
  my $path = Mojo::File->new('/home/sri/.vimrc');
  say $path->slurp;
  say $path->dirname;
  say $path->basename;
  say $path->extname;
  say $path->sibling('.bashrc');

  # Use the alternative constructor
  use Mojo::File qw(path);
  my $path = path('/tmp/foo/bar')->make_path;
  $path->child('test.txt')->spurt('Hello Mojo!');

=head1 DESCRIPTION

L<Mojo::File> is a scalar-based container for file system paths that provides a friendly API for dealing with different
operating systems.

t/cpan/Mojo2/File.pm  view on Meta::CPAN


=head2 list

  my $collection = $path->list;
  my $collection = $path->list({hidden => 1});

List all files in the directory and return a L<Mojo::Collection> object containing the results as L<Mojo::File>
objects. The list does not include C<.> and C<..>.

  # List files
  say for path('/home/sri/myapp')->list->each;

These options are currently available:

=over 2

=item dir

  dir => 1

Include directories.

t/cpan/Mojo2/File.pm  view on Meta::CPAN


=head2 list_tree

  my $collection = $path->list_tree;
  my $collection = $path->list_tree({hidden => 1});

List all files recursively in the directory and return a L<Mojo::Collection> object containing the results as
L<Mojo::File> objects. The list does not include C<.> and C<..>.

  # List all templates
  say for path('/home/sri/myapp/templates')->list_tree->each;

These options are currently available:

=over 2

=item dir

  dir => 1

Include directories.

t/cpan/Mojo2/File.pm  view on Meta::CPAN


=back

=head2 lstat

  my $stat = $path->lstat;

Return a L<File::stat> object for the symlink.

  # Get symlink size
  say path('/usr/sbin/sendmail')->lstat->size;

  # Get symlink modification time
  say path('/usr/sbin/sendmail')->lstat->mtime;

=head2 make_path

  $path = $path->make_path;
  $path = $path->make_path({mode => 0711});

Create the directories if they don't already exist, any additional arguments are passed through to L<File::Path>.

=head2 move_to

t/cpan/Mojo2/File.pm  view on Meta::CPAN


Write all data at once to the file.

=head2 stat

  my $stat = $path->stat;

Return a L<File::stat> object for the path.

  # Get file size
  say path('/home/sri/.bashrc')->stat->size;

  # Get file modification time
  say path('/home/sri/.bashrc')->stat->mtime;

=head2 tap

  $path = $path->tap(sub {...});

Alias for L<Mojo::Base/"tap">.

=head2 to_abs

  my $absolute = $path->to_abs;

t/cpan/Mojo2/File.pm  view on Meta::CPAN


Stringify the path.

=head2 touch

  $path = $path->touch;

Create file if it does not exist or change the modification and access time to the current time.

  # Safely read file
  say path('.bashrc')->touch->slurp;

=head2 with_roles

  my $new_class = Mojo::File->with_roles('Mojo::File::Role::One');
  my $new_class = Mojo::File->with_roles('+One', '+Two');
  $path         = $path->with_roles('+One', '+Two');

Alias for L<Mojo::Base/"with_roles">.

=head1 OPERATORS

t/cpan/Mojo2/UserAgent.pm  view on Meta::CPAN


Mojo::UserAgent - Non-blocking I/O HTTP and WebSocket user agent

=head1 SYNOPSIS

  use Mojo::UserAgent;

  # Fine grained response handling (dies on connection errors)
  my $ua  = Mojo::UserAgent->new;
  my $res = $ua->get('docs.mojolicious.org')->result;
  if    ($res->is_success)  { say $res->body }
  elsif ($res->is_error)    { say $res->message }
  elsif ($res->code == 301) { say $res->headers->location }
  else                      { say 'Whatever...' }

  # Say hello to the Unicode snowman and include an Accept header
  say $ua->get('www.☃.net?hello=there' => {Accept => '*/*'})->result->body;

  # Extract data from HTML and XML resources with CSS selectors
  say $ua->get('www.perl.org')->result->dom->at('title')->text;

  # Scrape the latest headlines from a news site
  say $ua->get('blogs.perl.org')->result->dom->find('h2 > a')->map('text')->join("\n");

  # IPv6 PUT request with Content-Type header and content
  my $tx = $ua->put('[::1]:3000' => {'Content-Type' => 'text/plain'} => 'Hi!');

  # Quick JSON API request with Basic authentication
  my $url = Mojo::URL->new('https://example.com/test.json')->userinfo('sri:☃');
  my $value = $ua->get($url)->result->json;

  # JSON POST (application/json) with TLS certificate authentication
  my $tx = $ua->cert('tls.crt')->key('tls.key')->post('https://example.com' => json => {top => 'secret'});

  # Form POST (application/x-www-form-urlencoded)
  my $tx = $ua->post('https://metacpan.org/search' => form => {q => 'mojo'});

  # Search DuckDuckGo anonymously through Tor
  $ua->proxy->http('socks://127.0.0.1:9050');
  say $ua->get('api.3g2upl4pq6kufc4m.onion/?q=mojolicious&format=json')->result->json('/Abstract');

  # GET request via UNIX domain socket "/tmp/myapp.sock" (percent encoded slash)
  say $ua->get('http+unix://%2Ftmp%2Fmyapp.sock/test')->result->body;

  # Follow redirects to download Mojolicious from GitHub
  $ua->max_redirects(5)
    ->get('https://www.github.com/mojolicious/mojo/tarball/main')
    ->result->save_to('/home/sri/mojo.tar.gz');

  # Non-blocking request
  $ua->get('mojolicious.org' => sub ($ua, $tx) { say $tx->result->dom->at('title')->text });
  Mojo::IOLoop->start unless Mojo::IOLoop->is_running;

  # Concurrent non-blocking requests (synchronized with promises)
  my $mojo_promise = $ua->get_p('mojolicious.org');
  my $cpan_promise = $ua->get_p('cpan.org');
  Mojo::Promise->all($mojo_promise, $cpan_promise)->then(sub ($mojo, $cpan) {
    say $mojo->[0]->result->dom->at('title')->text;
    say $cpan->[0]->result->dom->at('title')->text;
  })->wait;

  # WebSocket connection sending and receiving JSON via UNIX domain socket
  $ua->websocket('ws+unix://%2Ftmp%2Fmyapp.sock/echo.json' => sub ($ua, $tx) {
    say 'WebSocket handshake failed!' and return unless $tx->is_websocket;
    $tx->on(json => sub ($tx, $hash) {
      say "WebSocket message via JSON: $hash->{msg}";
      $tx->finish;
    });
    $tx->send({json => {msg => 'Hello World!'}});
  });
  Mojo::IOLoop->start unless Mojo::IOLoop->is_running;

=head1 DESCRIPTION

L<Mojo::UserAgent> is a full featured non-blocking I/O HTTP and WebSocket user agent, with IPv6, TLS, SNI, IDNA,
HTTP/SOCKS5 proxy, UNIX domain socket, Comet (long polling), Promises/A+, keep-alive, connection pooling, timeout,

t/cpan/Mojo2/UserAgent.pm  view on Meta::CPAN


=head2 ca

  my $ca = $ua->ca;
  $ua    = $ua->ca('/etc/tls/ca.crt');

Path to TLS certificate authority file used to verify the peer certificate, defaults to the value of the
C<MOJO_CA_FILE> environment variable.

  # Show certificate authorities for debugging
  IO::Socket::SSL::set_defaults(SSL_verify_callback => sub { say "Authority: $_[2]" and return $_[0] });

=head2 cert

  my $cert = $ua->cert;
  $ua      = $ua->cert('/etc/tls/client.crt');

Path to TLS certificate file, defaults to the value of the C<MOJO_CERT_FILE> environment variable.

=head2 connect_timeout

t/cpan/Mojo2/UserAgent.pm  view on Meta::CPAN


=head2 insecure

  my $bool = $ua->insecure;
  $ua      = $ua->insecure($bool);

Do not require a valid TLS certificate to access HTTPS/WSS sites, defaults to the value of the C<MOJO_INSECURE>
environment variable.

  # Disable TLS certificate verification for testing
  say $ua->insecure(1)->get('https://127.0.0.1:3000')->result->code;

=head2 ioloop

  my $loop = $ua->ioloop;
  $ua      = $ua->ioloop(Mojo::IOLoop->new);

Event loop object to use for blocking I/O operations, defaults to a L<Mojo::IOLoop> object.

=head2 key

t/cpan/Mojo2/UserAgent.pm  view on Meta::CPAN

  $ua->server->app(Mojolicious->new);
  $ua->server->app->routes->get('/time' => sub ($c) {
    $c->render(json => {now => time});
  });
  my $time = $ua->get('/time')->result->json->{now};

  # Change log level
  $ua->server->app->log->level('fatal');

  # Port currently used for processing relative URLs blocking
  say $ua->server->url->port;

  # Port currently used for processing relative URLs non-blocking
  say $ua->server->nb_url->port;

=head2 socket_options

  my $options = $ua->socket_options;
  $ua         = $ua->socket_options({LocalAddr => '127.0.0.1'});

Additional options for L<IO::Socket::IP> when opening new connections.

=head2 transactor

t/cpan/Mojo2/UserAgent.pm  view on Meta::CPAN


  my $tx = $ua->build_websocket_tx('ws://example.com');
  my $tx = $ua->build_websocket_tx( 'ws://example.com' => {DNT => 1} => ['v1.proto']);

Generate L<Mojo::Transaction::HTTP> object with L<Mojo::UserAgent::Transactor/"websocket">.

  # Custom WebSocket handshake with cookie
  my $tx = $ua->build_websocket_tx('wss://example.com/echo');
  $tx->req->cookies({name => 'user', value => 'sri'});
  $ua->start($tx => sub ($ua, $tx) {
    say 'WebSocket handshake failed!' and return unless $tx->is_websocket;
    $tx->on(message => sub ($tx, $msg) {
      say "WebSocket message: $msg";
      $tx->finish;
    });
    $tx->send('Hi!');
  });
  Mojo::IOLoop->start unless Mojo::IOLoop->is_running;

=head2 delete

  my $tx = $ua->delete('example.com');
  my $tx = $ua->delete('http://example.com' => {Accept => '*/*'} => 'Content!');
  my $tx = $ua->delete('http://example.com' => {Accept => '*/*'} => form => {a => 'b'});
  my $tx = $ua->delete('http://example.com' => {Accept => '*/*'} => json => {a => 'b'});

Perform blocking C<DELETE> request and return resulting L<Mojo::Transaction::HTTP> object, takes the same arguments as
L<Mojo::UserAgent::Transactor/"tx"> (except for the C<DELETE> method, which is implied). You can also append a callback
to perform requests non-blocking.

  $ua->delete('http://example.com' => json => {a => 'b'} => sub ($ua, $tx) { say $tx->result->body });
  Mojo::IOLoop->start unless Mojo::IOLoop->is_running;

=head2 delete_p

  my $promise = $ua->delete_p('http://example.com');

Same as L</"delete">, but performs all requests non-blocking and returns a L<Mojo::Promise> object instead of accepting
a callback.

  $ua->delete_p('http://example.com' => json => {a => 'b'})->then(sub ($tx) {
    say $tx->result->body;
  })->catch(sub ($err) {
    warn "Connection error: $err";
  })->wait;

=head2 get

  my $tx = $ua->get('example.com');
  my $tx = $ua->get('http://example.com' => {Accept => '*/*'} => 'Content!');
  my $tx = $ua->get('http://example.com' => {Accept => '*/*'} => form => {a => 'b'});
  my $tx = $ua->get('http://example.com' => {Accept => '*/*'} => json => {a => 'b'});

Perform blocking C<GET> request and return resulting L<Mojo::Transaction::HTTP> object, takes the same arguments as
L<Mojo::UserAgent::Transactor/"tx"> (except for the C<GET> method, which is implied). You can also append a callback to
perform requests non-blocking.

  $ua->get('http://example.com' => json => {a => 'b'} => sub ($ua, $tx) { say $tx->result->body });
  Mojo::IOLoop->start unless Mojo::IOLoop->is_running;

=head2 get_p

  my $promise = $ua->get_p('http://example.com');

Same as L</"get">, but performs all requests non-blocking and returns a L<Mojo::Promise> object instead of accepting a
callback.

  $ua->get_p('http://example.com' => json => {a => 'b'})->then(sub ($tx) {
    say $tx->result->body;
  })->catch(sub ($err) {
    warn "Connection error: $err";
  })->wait;

=head2 head

  my $tx = $ua->head('example.com');
  my $tx = $ua->head('http://example.com' => {Accept => '*/*'} => 'Content!');
  my $tx = $ua->head('http://example.com' => {Accept => '*/*'} => form => {a => 'b'});
  my $tx = $ua->head('http://example.com' => {Accept => '*/*'} => json => {a => 'b'});

Perform blocking C<HEAD> request and return resulting L<Mojo::Transaction::HTTP> object, takes the same arguments as
L<Mojo::UserAgent::Transactor/"tx"> (except for the C<HEAD> method, which is implied). You can also append a callback
to perform requests non-blocking.

  $ua->head('http://example.com' => json => {a => 'b'} => sub ($ua, $tx) { say $tx->result->body });
  Mojo::IOLoop->start unless Mojo::IOLoop->is_running;

=head2 head_p

  my $promise = $ua->head_p('http://example.com');

Same as L</"head">, but performs all requests non-blocking and returns a L<Mojo::Promise> object instead of accepting a
callback.

  $ua->head_p('http://example.com' => json => {a => 'b'})->then(sub ($tx) {
    say $tx->result->body;
  })->catch(sub ($err) {
    warn "Connection error: $err";
  })->wait;

=head2 options

  my $tx = $ua->options('example.com');
  my $tx = $ua->options('http://example.com' => {Accept => '*/*'} => 'Content!');
  my $tx = $ua->options('http://example.com' => {Accept => '*/*'} => form => {a => 'b'});
  my $tx = $ua->options('http://example.com' => {Accept => '*/*'} => json => {a => 'b'});

Perform blocking C<OPTIONS> request and return resulting L<Mojo::Transaction::HTTP> object, takes the same arguments as
L<Mojo::UserAgent::Transactor/"tx"> (except for the C<OPTIONS> method, which is implied). You can also append a
callback to perform requests non-blocking.

  $ua->options('http://example.com' => json => {a => 'b'} => sub ($ua, $tx) { say $tx->result->body });
  Mojo::IOLoop->start unless Mojo::IOLoop->is_running;

=head2 options_p

  my $promise = $ua->options_p('http://example.com');

Same as L</"options">, but performs all requests non-blocking and returns a L<Mojo::Promise> object instead of
accepting a callback.

  $ua->options_p('http://example.com' => json => {a => 'b'})->then(sub ($tx) {
    say $tx->result->body;
  })->catch(sub ($err) {
    warn "Connection error: $err";
  })->wait;

=head2 patch

  my $tx = $ua->patch('example.com');
  my $tx = $ua->patch('http://example.com' => {Accept => '*/*'} => 'Content!');
  my $tx = $ua->patch('http://example.com' => {Accept => '*/*'} => form => {a => 'b'});
  my $tx = $ua->patch('http://example.com' => {Accept => '*/*'} => json => {a => 'b'});

Perform blocking C<PATCH> request and return resulting L<Mojo::Transaction::HTTP> object, takes the same arguments as
L<Mojo::UserAgent::Transactor/"tx"> (except for the C<PATCH> method, which is implied). You can also append a callback
to perform requests non-blocking.

  $ua->patch('http://example.com' => json => {a => 'b'} => sub ($ua, $tx) { say $tx->result->body });
  Mojo::IOLoop->start unless Mojo::IOLoop->is_running;

=head2 patch_p

  my $promise = $ua->patch_p('http://example.com');

Same as L</"patch">, but performs all requests non-blocking and returns a L<Mojo::Promise> object instead of accepting
a callback.

  $ua->patch_p('http://example.com' => json => {a => 'b'})->then(sub ($tx) {
    say $tx->result->body;
  })->catch(sub ($err) {
    warn "Connection error: $err";
  })->wait;

=head2 post

  my $tx = $ua->post('example.com');
  my $tx = $ua->post('http://example.com' => {Accept => '*/*'} => 'Content!');
  my $tx = $ua->post('http://example.com' => {Accept => '*/*'} => form => {a => 'b'});
  my $tx = $ua->post('http://example.com' => {Accept => '*/*'} => json => {a => 'b'});

Perform blocking C<POST> request and return resulting L<Mojo::Transaction::HTTP> object, takes the same arguments as
L<Mojo::UserAgent::Transactor/"tx"> (except for the C<POST> method, which is implied). You can also append a callback
to perform requests non-blocking.

  $ua->post('http://example.com' => json => {a => 'b'} => sub ($ua, $tx) { say $tx->result->body });
  Mojo::IOLoop->start unless Mojo::IOLoop->is_running;

=head2 post_p

  my $promise = $ua->post_p('http://example.com');

Same as L</"post">, but performs all requests non-blocking and returns a L<Mojo::Promise> object instead of accepting a
callback.

  $ua->post_p('http://example.com' => json => {a => 'b'})->then(sub ($tx) {
    say $tx->result->body;
  })->catch(sub ($err) {
    warn "Connection error: $err";
  })->wait;

=head2 put

  my $tx = $ua->put('example.com');
  my $tx = $ua->put('http://example.com' => {Accept => '*/*'} => 'Content!');
  my $tx = $ua->put('http://example.com' => {Accept => '*/*'} => form => {a => 'b'});
  my $tx = $ua->put('http://example.com' => {Accept => '*/*'} => json => {a => 'b'});

Perform blocking C<PUT> request and return resulting L<Mojo::Transaction::HTTP> object, takes the same arguments as
L<Mojo::UserAgent::Transactor/"tx"> (except for the C<PUT> method, which is implied). You can also append a callback to
perform requests non-blocking.

  $ua->put('http://example.com' => json => {a => 'b'} => sub ($ua, $tx) { say $tx->result->body });
  Mojo::IOLoop->start unless Mojo::IOLoop->is_running;

=head2 put_p

  my $promise = $ua->put_p('http://example.com');

Same as L</"put">, but performs all requests non-blocking and returns a L<Mojo::Promise> object instead of accepting a
callback.

  $ua->put_p('http://example.com' => json => {a => 'b'})->then(sub ($tx) {
    say $tx->result->body;
  })->catch(sub ($err) {
    warn "Connection error: $err";
  })->wait;

=head2 start

  my $tx = $ua->start(Mojo::Transaction::HTTP->new);

Perform blocking request for a custom L<Mojo::Transaction::HTTP> object, which can be prepared manually or with
L</"build_tx">. You can also append a callback to perform requests non-blocking.

  my $tx = $ua->build_tx(GET => 'http://example.com');
  $ua->start($tx => sub ($ua, $tx) { say $tx->result->body });
  Mojo::IOLoop->start unless Mojo::IOLoop->is_running;

=head2 start_p

  my $promise = $ua->start_p(Mojo::Transaction::HTTP->new);

Same as L</"start">, but performs all requests non-blocking and returns a L<Mojo::Promise> object instead of accepting
a callback.

  my $tx = $ua->build_tx(GET => 'http://example.com');
  $ua->start_p($tx)->then(sub ($tx) {
    say $tx->result->body;
  })->catch(sub ($err) {
    warn "Connection error: $err";
  })->wait;

=head2 websocket

  $ua->websocket('ws://example.com' => sub {...});
  $ua->websocket('ws://example.com' => {DNT => 1} => ['v1.proto'] => sub {...});

Open a non-blocking WebSocket connection with transparent handshake, takes the same arguments as
L<Mojo::UserAgent::Transactor/"websocket">. The callback will receive either a L<Mojo::Transaction::WebSocket> or
L<Mojo::Transaction::HTTP> object, depending on if the handshake was successful.

  $ua->websocket('wss://example.com/echo' => ['v1.proto'] => sub ($ua, $tx) {
    say 'WebSocket handshake failed!' and return unless $tx->is_websocket;
    say 'Subprotocol negotiation failed!' and return unless $tx->protocol;
    $tx->on(finish => sub ($tx, $code, $reason) { say "WebSocket closed with status $code." });
    $tx->on(message => sub ($tx, $msg) {
      say "WebSocket message: $msg";
      $tx->finish;
    });
    $tx->send('Hi!');
  });
  Mojo::IOLoop->start unless Mojo::IOLoop->is_running;

You can activate C<permessage-deflate> compression by setting the C<Sec-WebSocket-Extensions> header, this can result
in much better performance, but also increases memory usage by up to 300KiB per connection.

  $ua->websocket('ws://example.com/foo' => {

t/cpan/Mojo2/UserAgent.pm  view on Meta::CPAN

=head2 websocket_p

  my $promise = $ua->websocket_p('ws://example.com');

Same as L</"websocket">, but returns a L<Mojo::Promise> object instead of accepting a callback.

  $ua->websocket_p('wss://example.com/echo')->then(sub ($tx) {
    my $promise = Mojo::Promise->new;
    $tx->on(finish => sub { $promise->resolve });
    $tx->on(message => sub ($tx, $msg) {
      say "WebSocket message: $msg";
      $tx->finish;
    });
    $tx->send('Hi!');
    return $promise;
  })->catch(sub ($err) {
    warn "WebSocket error: $err";
  })->wait;

=head1 DEBUGGING

t/cpan/ojo.pm  view on Meta::CPAN

    monkey_patch $caller,
      a => sub { $caller->can( 'any' )->( @_ ) and return $ua->server->app },
      b => \&b,
      c => \&c,
      d => sub { $ua->delete( @_ )->result },
      f => \&path,
      g => sub { $ua->get( @_ )->result },
      h => sub { $ua->head( @_ )->result },
      j => \&j,
      l => sub { Mojo::URL->new( @_ ) },
      n => sub (&@) { say STDERR timestr timeit( $_[1] // 1, $_[0] ) },
      o => sub { $ua->options( @_ )->result },
      p => sub { $ua->post( @_ )->result },
      r => \&dumper,
      t => sub { $ua->patch( @_ )->result },
      u => sub { $ua->put( @_ )->result },
      x => sub { Mojo::DOM->new( @_ ) };
}

1;

=encoding utf8

=head1 NAME

ojo - Fun one-liners with Mojo

=head1 SYNOPSIS

  $ perl -Mojo -E 'say g("mojolicious.org")->dom->at("title")->text'

=head1 DESCRIPTION

A collection of automatically exported functions for fun Perl one-liners. Ten redirects will be followed by default,
you can change this behavior with the C<MOJO_MAX_REDIRECTS> environment variable.

  $ MOJO_MAX_REDIRECTS=0 perl -Mojo -E 'say g("example.com")->code'

Proxy detection is enabled by default, but you can disable it with the C<MOJO_PROXY> environment variable.

  $ MOJO_PROXY=0 perl -Mojo -E 'say g("example.com")->body'

TLS certificate verification can be disabled with the C<MOJO_INSECURE> environment variable.

  $ MOJO_INSECURE=1 perl -Mojo -E 'say g("https://127.0.0.1:3000")->body'

Every L<ojo> one-liner is also a L<Mojolicious::Lite> application.

  $ perl -Mojo -E 'get "/" => {inline => "%= time"}; app->start' get /

On Perl 5.20+ L<subroutine signatures|perlsub/"Signatures"> will be enabled automatically.

  $ perl -Mojo -E 'a(sub ($c) { $c->render(text => "Hello!") })->start' get /

If it is not already defined, the C<MOJO_LOG_LEVEL> environment variable will be set to C<fatal>.

t/cpan/ojo.pm  view on Meta::CPAN

  my $res = d('http://example.com' => {Accept => '*/*'} => json => {a => 'b'});

Perform C<DELETE> request with L<Mojo::UserAgent/"delete"> and return resulting L<Mojo::Message::Response> object.

=head2 f

  my $path = f('/home/sri/foo.txt');

Turn string into a L<Mojo::File> object.

  $ perl -Mojo -E 'say r j f("hello.json")->slurp'

=head2 g

  my $res = g('example.com');
  my $res = g('http://example.com' => {Accept => '*/*'} => 'Hi!');
  my $res = g('http://example.com' => {Accept => '*/*'} => form => {a => 'b'});
  my $res = g('http://example.com' => {Accept => '*/*'} => json => {a => 'b'});

Perform C<GET> request with L<Mojo::UserAgent/"get"> and return resulting L<Mojo::Message::Response> object.

  $ perl -Mojo -E 'say g("mojolicious.org")->dom("h1")->map("text")->join("\n")'

=head2 h

  my $res = h('example.com');
  my $res = h('http://example.com' => {Accept => '*/*'} => 'Hi!');
  my $res = h('http://example.com' => {Accept => '*/*'} => form => {a => 'b'});
  my $res = h('http://example.com' => {Accept => '*/*'} => json => {a => 'b'});

Perform C<HEAD> request with L<Mojo::UserAgent/"head"> and return resulting L<Mojo::Message::Response> object.

t/cpan/ojo.pm  view on Meta::CPAN

Encode Perl data structure or decode JSON with L<Mojo::JSON/"j">.

  $ perl -Mojo -E 'f("hello.json")->spurt(j {hello => "world!"})'

=head2 l

  my $url = l('https://mojolicious.org');

Turn a string into a L<Mojo::URL> object.

  $ perl -Mojo -E 'say l("/perldoc")->to_abs(l("https://mojolicious.org"))'

=head2 n

  n {...};
  n {...} 100;

Benchmark block and print the results to C<STDERR>, with an optional number of iterations, which defaults to C<1>.

  $ perl -Mojo -E 'n { say g("mojolicious.org")->code }'

=head2 o

  my $res = o('example.com');
  my $res = o('http://example.com' => {Accept => '*/*'} => 'Hi!');
  my $res = o('http://example.com' => {Accept => '*/*'} => form => {a => 'b'});
  my $res = o('http://example.com' => {Accept => '*/*'} => json => {a => 'b'});

Perform C<OPTIONS> request with L<Mojo::UserAgent/"options"> and return resulting L<Mojo::Message::Response> object.

t/cpan/ojo.pm  view on Meta::CPAN

  my $res = p('http://example.com' => {Accept => '*/*'} => json => {a => 'b'});

Perform C<POST> request with L<Mojo::UserAgent/"post"> and return resulting L<Mojo::Message::Response> object.

=head2 r

  my $perl = r({data => 'structure'});

Dump a Perl data structure with L<Mojo::Util/"dumper">.

  perl -Mojo -E 'say r g("example.com")->headers->to_hash'

=head2 t

  my $res = t('example.com');
  my $res = t('http://example.com' => {Accept => '*/*'} => 'Hi!');
  my $res = t('http://example.com' => {Accept => '*/*'} => form => {a => 'b'});
  my $res = t('http://example.com' => {Accept => '*/*'} => json => {a => 'b'});

Perform C<PATCH> request with L<Mojo::UserAgent/"patch"> and return resulting L<Mojo::Message::Response> object.

t/cpan/ojo.pm  view on Meta::CPAN

  my $res = u('http://example.com' => {Accept => '*/*'} => json => {a => 'b'});

Perform C<PUT> request with L<Mojo::UserAgent/"put"> and return resulting L<Mojo::Message::Response> object.

=head2 x

  my $dom = x('<div>Hello!</div>');

Turn HTML/XML input into L<Mojo::DOM> object.

  $ perl -Mojo -E 'say x(f("test.html")->slurp)->at("title")->text'

  [UnicodeTest: I ♥ Mojolicious!]

=head1 SEE ALSO

L<Mojolicious>, L<Mojolicious::Guides>, L<https://mojolicious.org>.

=cut



( run in 1.046 second using v1.01-cache-2.11-cpan-d7a12ab2c7f )