lib/redd/models/submission.rb in redd-0.8.1 vs lib/redd/models/submission.rb in redd-0.8.2

- old
+ new

@@ -1,8 +1,9 @@ # frozen_string_literal: true require_relative 'lazy_model' +require_relative 'gildable' require_relative 'moderatable' require_relative 'postable' require_relative 'replyable' require_relative 'user' @@ -10,29 +11,21 @@ module Redd module Models # A text or link post. class Submission < LazyModel + include Gildable include Moderatable include Postable include Replyable - coerce_attribute :author, User - coerce_attribute :subreddit, Subreddit - - # Make a Submission from its id. - # @option hash [String] :id the post's id (e.g. abc123) + # Create a Subreddit from its fullname. + # @param client [APIClient] the api client to initialize the object with + # @param id [String] the fullname # @return [Submission] - def self.from_response(client, hash) - link_id = hash.fetch(:id) - new(client, hash) do |c| - # `data` is a pair (2-element array): - # - data[0] is a one-item listing containing the submission - # - data[1] is listing of comments - data = c.get("/comments/#{link_id}").body - data[0][:data][:children][0][:data].merge(comments: c.unmarshal(data[1])) - end + def self.from_id(client, id) + new(client, name: id) end # Get all submissions for the same url. # @param params [Hash] A list of optional params to send with the request. # @option params [String] :after return results after the given fullname @@ -95,9 +88,28 @@ end # Allow users to comment on the link again. def unlock @client.post('/api/unlock', id: get_attribute(:name)) + end + + private + + def default_loader + # Ensure we have the link's id. + id = @attributes[:id] ? @attributes[:id] : @attributes.fetch(:name).sub('t3_', '') + response = @client.get("/comments/#{id}").body + # `response` is a pair (2-element array): + # - response[0] is a one-item listing containing the submission + # - response[1] is listing of comments + response[0][:data][:children][0][:data].merge(comments: @client.unmarshal(response[1])) + end + + def after_initialize + if @attributes[:subreddit] + @attributes[:subreddit] = Subreddit.from_id(@client, @attributes[:subreddit]) + end + @attributes[:author] = User.from_id(@client, @attributes[:author]) if @attributes[:author] end end end end