Sha256: b536dc9907cbe0074ecfaf1e88ad5be5522c9f920f32b9e4828a3b467c2e75d3

Contents?: true

Size: 1.32 KB

Versions: 6

Compression:

Stored size: 1.32 KB

Contents

module AppleNews
  class Article
    module Persistence
      extend ActiveSupport::Concern

      included do
        def save!
          request = Request::Post.new(endpoint_url)
          request.fields = {
            'metadata' => metadata_field,
            'article.json' => document_json
          }.merge(@files)

          resp = request.call

          return resp['errors'] if resp.has_key?('errors')

          @id = resp['data']['id']
          load_properties(resp['data'])

          true
        end

        def persisted?
          !@id.nil?
        end
        alias_method :saved?, :persisted?

        def delete!
          request = Request::Delete.new(endpoint_url)
          resp = request.call

          return resp['errors'] if resp.is_a?(Hash) && resp.has_key?('errors')
          @id = nil

          true
        end

        private

        def endpoint_url
          if persisted?
            "/articles/#{id}"
          else
            "/channels/#{AppleNews.config.channel_id}/articles"
          end
        end

        def metadata_field
          JSON.dump({ data: self.as_json })
        end

        def document_json
          UploadIO.new(
            StringIO.new(JSON.dump(document.as_json)),
            "application/json",
            "article.json"
          )
        end
      end
    end
  end
end

Version data entries

6 entries across 6 versions & 1 rubygems

Version Path
apple-news-0.2.5 lib/apple-news/article/persistence.rb
apple-news-0.2.4 lib/apple-news/article/persistence.rb
apple-news-0.2.3 lib/apple-news/article/persistence.rb
apple-news-0.2.2 lib/apple-news/article/persistence.rb
apple-news-0.2.1 lib/apple-news/article/persistence.rb
apple-news-0.2.0 lib/apple-news/article/persistence.rb