Skip to content

Instantly share code, notes, and snippets.

@robhammond
Created June 4, 2014 08:08
Show Gist options
  • Save robhammond/bcfb61eadac4a88d2923 to your computer and use it in GitHub Desktop.
Save robhammond/bcfb61eadac4a88d2923 to your computer and use it in GitHub Desktop.
package Apis::Reddit;
use strict;
use warnings;
use Mojo::Log;
use DateTime;
use Mojo::UserAgent;
my $log = Mojo::Log->new();
sub new {
my $class = shift;
my $self = { @_ };
bless ($self, $class);
return $self;
}
# top|hot|controversial|new|random
# http://www.reddit.com/dev/api#GET_search
sub fetch {
my ($self, $params) = @_;
my $url = 'http://www.reddit.com/';
if ($params->{'subreddit'}) {
$params->{'subreddit'} = "r/" . $params->{'subreddit'};
$url .= $params->{'subreddit'};
}
if ($params->{'type'}) {
$url .= "/$params->{type}";
}
if ($params->{'search'}) {
$url .= "/search";
}
$url .= '.json';
if ($params->{'search'}) {
$url .= "?q=$params->{search}";
}
if ($params->{'sort'}) {
$url .= "&sort=$params->{sort}";
}
my $ua = Mojo::UserAgent->new;
my $tx = $ua->get($url);
my $results;
if (my $res = $tx->success) {
my $json = Mojo::JSON->new;
if ($json->decode($res->body)) {
$results = $json->decode($res->body);
} else {
$log->info("Error getting $url");
return;
}
} else {
return;
}
return $results;
}
sub trending {
my $self = shift;
my $url = "http://api.redditanalytics.com/trending";
my $ua = Mojo::UserAgent->new;
my $tx = $ua->get($url);
if (my $res = $tx->success) {
my $json = Mojo::JSON->new;
return $json->decode($res->body);
}
}
1;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment