Class: Skriptorium::DevTo::Destination
- Inherits:
-
BaseDestination
- Object
- BaseDestination
- Skriptorium::DevTo::Destination
- Defined in:
- lib/skriptorium/dev_to/destination.rb
Instance Attribute Summary
Attributes inherited from BaseDestination
Instance Method Summary collapse
- #exists?(article, force: false) ⇒ Boolean
-
#initialize(config) ⇒ Destination
constructor
A new instance of Destination.
- #publish(article) ⇒ Object
- #with_client(*args, **kwargs, &block) ⇒ Object
Methods inherited from BaseDestination
Constructor Details
#initialize(config) ⇒ Destination
Returns a new instance of Destination.
6 7 8 9 10 |
# File 'lib/skriptorium/dev_to/destination.rb', line 6 def initialize(config) super @api_key = config['api_key'] @organization_id = config['organization_id'] end |
Instance Method Details
#exists?(article, force: false) ⇒ Boolean
12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 |
# File 'lib/skriptorium/dev_to/destination.rb', line 12 def exists?(article, force: false) response = with_cache(:articles, force: force) do with_client(url: 'https://dev.to/api/') do |client| client.get('articles/me.json', { 'per_page' => 20 }) end end return false unless response.success? articles = JSON.parse(response.body).map(&:with_indifferent_access).map(&DevTo::Source.method(:to_article)) articles.any? do |a| article.same?(a) end end |
#publish(article) ⇒ Object
28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 |
# File 'lib/skriptorium/dev_to/destination.rb', line 28 def publish(article) raise 'Article already published!' if exists?(article, force: true) with_client(url: 'https://dev.to/api/') do |client| payload = { article: { title: article.title, body_markdown: article.to_markdown(published: true), tags: article., canonical_url: article.canonical_url, slug: article.stable_slug, published: true } } payload[:article][:organization_id] = @organization_id if @organization_id response = client.post('articles.json', JSON.generate(payload)) raise "Dev.to publish error: #{response.status} - #{response.body}" unless response.success? puts " Published to Dev.to: #{JSON.parse(response.body)['url']}" end end |
#with_client(*args, **kwargs, &block) ⇒ Object
53 54 55 56 57 58 59 |
# File 'lib/skriptorium/dev_to/destination.rb', line 53 def with_client(*args, **kwargs, &block) Faraday.new(*args, **kwargs) do |builder| builder.headers['api-key'] = @api_key builder.headers['Content-Type'] = 'application/json' builder.adapter Faraday.default_adapter end.then(&block) end |