class Spooky::Client

Attributes

api_key[RW]
api_url[RW]
endpoint[RW]
error[RW]

Public Class Methods

new(attrs = {}) click to toggle source
# File lib/spooky/client.rb, line 9
def initialize(attrs = {})
  @api_url = ENV["GHOST_API_URL"] || attrs[:api_url]
  @api_key = ENV["GHOST_CONTENT_API_KEY"] || attrs[:api_key]
  @endpoint = "#{@api_url}/ghost/api/v3/content"
end

Public Instance Methods

fetch(resource, options = {}) click to toggle source
# File lib/spooky/client.rb, line 31
def fetch(resource, options = {})
  resource_name = resource.split("/").first
  response, pagination = fetch_json(resource, options)

  resource_class = "Spooky::#{resource_name.singularize.classify}".constantize

  response.present? && [response.map { |attrs| resource_class.send(:new, attrs) }, pagination]
end
fetch_json(resource, options = {}) click to toggle source
# File lib/spooky/client.rb, line 15
def fetch_json(resource, options = {})
  options.merge!(key: @api_key)
  url = "#{@endpoint}/#{resource}/"
  response = HTTP.get(url, params: options).parse

  if response["errors"].present?
    @error = response["errors"]
    false
  else
    collection = response[resource.split("/").first]
    pagination = response.dig("meta", "pagination")

    [collection, pagination]
  end
end
post_by(id: nil, slug: nil, tags: false, authors: false) click to toggle source
# File lib/spooky/client.rb, line 54
def post_by(id: nil, slug: nil, tags: false, authors: false)
  inc = []
  inc << "tags" if tags
  inc << "authors" if authors

  options = {}
  options[:include] = inc if inc.present?

  if id.present?
    response, _ = fetch("posts/#{id}", options)
    response.present? && response.first
  elsif slug.present?
    response, _ = fetch("posts/slug/#{slug}", options)
    response.present? && response.first
  else
    false
  end
end
posts(tags: false, authors: false, filter: false, page: false, limit: false) click to toggle source
# File lib/spooky/client.rb, line 40
def posts(tags: false, authors: false, filter: false, page: false, limit: false)
  inc = []
  inc << "tags" if tags
  inc << "authors" if authors

  options = {}
  options[:include] = inc if inc.present?

  options = apply_filter(options, filter)
  options = apply_pagination(options, { page: page, limit: limit })

  fetch("posts", options)
end

Private Instance Methods

apply_filter(options, filter) click to toggle source
# File lib/spooky/client.rb, line 75
def apply_filter(options, filter)
  if filter.present?
    if filter.is_a?(Hash)
      options[:filter] = filter.map { |k, v| "#{k}:#{v}" }.join("+")
    else
      options[:filter] = filter
    end
  end

  options
end
apply_pagination(options, pagination) click to toggle source
# File lib/spooky/client.rb, line 87
def apply_pagination(options, pagination)
  options[:page] = pagination[:page] if pagination[:page]
  options[:limit] = pagination[:limit] if pagination[:limit]

  options
end