# 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) 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] return unless value && value.length Time.parse(value) 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| return [] unless raw[camelcase] raw[camelcase].map { |val| OpenStruct.new(val) if val } end alias cache_key digest end end