Add post visibility and days_until_live helpers
This commit is contained in:
@@ -44,6 +44,23 @@ defmodule Blogex.Post do
|
||||
published: boolean()
|
||||
}
|
||||
|
||||
@type visibility :: :draft | :scheduled | :live
|
||||
|
||||
@doc "Returns the visibility of a post: :draft, :scheduled, or :live."
|
||||
def visibility(%__MODULE__{published: false}), do: :draft
|
||||
|
||||
def visibility(%__MODULE__{published: true, date: date}) do
|
||||
if Date.after?(date, Date.utc_today()), do: :scheduled, else: :live
|
||||
end
|
||||
|
||||
@doc "Returns days until a scheduled post goes live, or nil."
|
||||
def days_until_live(%__MODULE__{} = post) do
|
||||
case visibility(post) do
|
||||
:scheduled -> Date.diff(post.date, Date.utc_today())
|
||||
_ -> nil
|
||||
end
|
||||
end
|
||||
|
||||
@doc """
|
||||
Build callback for NimblePublisher.
|
||||
|
||||
|
||||
@@ -0,0 +1,45 @@
|
||||
defmodule Blogex.Post.VisibilityTest do
|
||||
use ExUnit.Case
|
||||
|
||||
import Blogex.Test.PostBuilder
|
||||
|
||||
describe "visibility/1" do
|
||||
test "returns :draft when post is not published" do
|
||||
post = build(published: false, date: ~D[2026-01-01])
|
||||
assert Blogex.Post.visibility(post) == :draft
|
||||
end
|
||||
|
||||
test "returns :scheduled when post is published with future date" do
|
||||
post = build(published: true, date: ~D[2099-01-01])
|
||||
assert Blogex.Post.visibility(post) == :scheduled
|
||||
end
|
||||
|
||||
test "returns :live when post is published with past date" do
|
||||
post = build(published: true, date: ~D[2020-01-01])
|
||||
assert Blogex.Post.visibility(post) == :live
|
||||
end
|
||||
|
||||
test "returns :live when post is published with today's date" do
|
||||
post = build(published: true, date: Date.utc_today())
|
||||
assert Blogex.Post.visibility(post) == :live
|
||||
end
|
||||
end
|
||||
|
||||
describe "days_until_live/1" do
|
||||
test "returns positive integer for scheduled post" do
|
||||
future = Date.add(Date.utc_today(), 10)
|
||||
post = build(published: true, date: future)
|
||||
assert Blogex.Post.days_until_live(post) == 10
|
||||
end
|
||||
|
||||
test "returns nil for draft post" do
|
||||
post = build(published: false, date: ~D[2099-01-01])
|
||||
assert Blogex.Post.days_until_live(post) == nil
|
||||
end
|
||||
|
||||
test "returns nil for live post" do
|
||||
post = build(published: true, date: ~D[2020-01-01])
|
||||
assert Blogex.Post.days_until_live(post) == nil
|
||||
end
|
||||
end
|
||||
end
|
||||
Reference in New Issue
Block a user