Last active
February 28, 2018 16:28
-
-
Save thescubageek/254dc19a3d1b80c86112aa0c6091ff38 to your computer and use it in GitHub Desktop.
SteemPostFinder
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
require 'radiator' | |
class SteemPostFinder | |
# the max results we can return for a single API query | |
BATCH_SIZE = 100 | |
def initialize(tag_name) | |
@tag_name = tag_name | |
end | |
# find posts for a tag in a datetime range | |
def posts_in_time_range(start_date, end_date) | |
start_date = start_date.is_a?(String) ? DateTime.parse(start_date) : start_date | |
end_date = end_date.is_a?(String) ? DateTime.parse(end_date) : end_date | |
posts = [] | |
# this is the equivalent of a do-while loop in other languages | |
loop do | |
# find author / permlink info if last_post exists | |
last_post = posts.last | |
last_author = last_post.try(:author) | |
last_permlink = last_post.try(:permlink) | |
# concats the posts array results to the existing posts array | |
posts << get_posts_by_created(last_author, last_permlink) | |
# makes the array 1-dimensional and removes duplicates and empty elements | |
posts = posts.flatten.compact.uniq | |
# exit the do-while loop under the following circumstances: | |
# 1. no posts are found in the response, or | |
# 2. the posts returned the same list of posts as the previous response | |
# 3. the last post was created before the start date | |
should_break = posts.blank? || posts.last == last_post || DateTime.parse(disc.last.try(:created)) < start_date | |
break if should_break | |
end | |
# reject all posts out of time range | |
posts.reject! do |post| | |
created = DateTime.parse(d.created) | |
created < start_date || created > end_date | |
end | |
posts | |
end | |
# gets posts from Steem API | |
def get_posts_by_created(author="", permlink="") | |
params = {tag: @tag_name, limit: BATCH_SIZE} | |
params.merge!({ | |
start_author: author, | |
start_permlink: permlink | |
}) unless author.blank? || permlink.blank? | |
# get posts from the Steem API | |
response = api.get_discussions_by_created(params) | |
return [] if response.blank? | |
# format response results has indifferent access array of hashes | |
response['result'].map(&:with_indifferent_access) | |
end | |
def get_post(author, permlink) | |
params = { tag: @tag_name, limit: 1, start_author: author, start_permlink: permlink } | |
response = api.get_discussions_by_created(params) | |
response.blank? ? [] : response['result'].try(:first).try(:with_indifferent_access) | |
end | |
private | |
def api | |
@api ||= Radiator::Api.new | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment