Sha256: a2c1b01e92f62234e6b91670dc3f8b329f87132e36e5856148a9c111ab6ec621

Contents?: true

Size: 1.89 KB

Versions: 2

Compression:

Stored size: 1.89 KB

Contents

# frozen_string_literal: true

module WCC::Blogs
  class Post
    extend WCC::Blogs::Utils
    require 'time'

    def self.find(slug)
      path = '/blog/' + slug.sub(%r{^/}, '') + '.json'
      new(JSON.parse(WCC::Blogs.client.get(path))).tap do |blog|
        raise WCC::Blogs::NotFoundException, "Blog post '#{slug}' is not published" unless blog.published?
      end
    end

    attr_reader :raw

    def initialize(raw)
      @raw = raw
    end

    def author_full_name
      return unless author

      [author.firstName, author.lastName].compact.join(' ')
    end

    def html
      @html ||=
        WCC::Blogs.config.cache.fetch(['BlogPost', fragment_path]) do
          WCC::Blogs.client
                    .get(fragment_path, host || WCC::Blogs.config.base_url)
                    .force_encoding('UTF-8')
        end
    end

    def metadata
      WCC::Blogs::Metadata.new(raw['metadata']) if raw['metadata']
    end

    def published?
      return false if publishing_targets.empty?

      publishing_targets.any? { |t| t['key'] == WCC::Blogs.config.publishing_target }
    end

    def time_to_read
      # TODO
      nil
    end

    def to_param
      slug.sub(%r{^/}, '')
    end

    define_camelcase_alias(
      'id',
      'title',
      'subtitle',
      'slug',
      'host',
      'path',
      'digest',
      'fragment_path'
    ) do |camelcase|
      raw[camelcase]
    end

    define_camelcase_alias(
      'date'
    ) do |camelcase|
      value = raw[camelcase]

      Time.parse(value) if value && value.length
    end

    define_camelcase_alias(
      'author',
      'hero_image',
      'thumbnail_image'
    ) do |camelcase|
      OpenStruct.new(raw[camelcase]) if raw[camelcase]
    end

    define_camelcase_alias('publishing_targets') do |camelcase|
      targets = raw[camelcase] || []

      targets.map { |val| OpenStruct.new(val) if val }
    end

    alias cache_key digest
  end
end

Version data entries

2 entries across 2 versions & 1 rubygems

Version Path
wcc-blogs-client-0.3.3 lib/wcc/blogs/post.rb
wcc-blogs-client-0.3.2 lib/wcc/blogs/post.rb