# frozen_string_literal: true module WCC::Blogs class Post 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 date publish_at || created_at 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 published? return false if publishing_targets.empty? publishing_targets.any? { |t| t['key'] == WCC::Blogs.config.publishing_target } && (publish_at.nil? || publish_at.empty? || (Time.parse(publish_at) <= Time.now)) end def time_to_read # TODO nil end def to_param slug.sub(%r{^/}, '') end def self.camelcase(str) str.gsub(/_(\w)/) { Regexp.last_match(1).upcase } end %w[ id title subtitle slug host path digest updated_at created_at publish_at fragment_path ].each do |method| attribute = camelcase(method) define_method method do raw[attribute] end alias_method attribute, method if attribute != method end %w[ author hero_image thumbnail_image ].each do |method| attribute = camelcase(method) define_method method do OpenStruct.new(raw[attribute]) if raw[attribute] end alias_method attribute, method if attribute != method end %w[ publishing_targets ].each do |method| attribute = camelcase(method) define_method method do return [] unless raw[attribute] raw[attribute].map { |val| OpenStruct.new(val) if val } end alias_method attribute, method if attribute != method end alias cache_key digest end end