@@ -5,25 +5,34 @@ defmodule CodeCorps.Services.MarkdownRendererService do
55
66 alias Ecto.Changeset
77
8- @ spec render_markdown_to_html ( Changeset . t , atom , atom ) :: Changeset . t
8+ @ spec render_markdown_to_html ( Changeset . t ( ) , atom , atom ) :: Changeset . t ( )
99 def render_markdown_to_html ( % Changeset { valid?: false } = changeset , _ , _ ) , do: changeset
1010 def render_markdown_to_html ( changeset , source_field , destination_field ) do
11- case Changeset . get_change ( changeset , source_field ) do
12- "" -> Changeset . put_change ( changeset , destination_field , nil )
13- nil -> changeset
14- markdown -> markdown |> convert_into_html ( ) |> put_into ( changeset , destination_field )
15- end
11+ change = changeset |> Changeset . get_change ( source_field )
12+ changeset |> handle_change ( change , destination_field )
1613 end
1714
18- @ spec convert_into_html ( String . t ) :: String . t
19- defp convert_into_html ( markdown ) do
20- # Prism.js requires a `language-` prefix in code classes
21- # See: https://github.com/pragdave/earmark#syntax-highlightning
22- Earmark . as_html! ( markdown , % Earmark.Options { code_class_prefix: "language-" } )
15+ @ spec handle_change ( Changeset . t ( ) , String . t ( ) | nil , atom ) :: Changeset . t ( )
16+ defp handle_change ( changeset , nil , _ ) , do: changeset
17+ defp handle_change ( changeset , "" , destination_field ) do
18+ Changeset . put_change ( changeset , destination_field , nil )
19+ end
20+ defp handle_change ( changeset , lines , destination_field ) when is_binary ( lines ) do
21+ lines
22+ |> convert_into_html ( )
23+ |> put_into ( changeset , destination_field )
24+ end
25+
26+ # Prism.js requires a `language-` prefix in code classes
27+ # See: https://github.com/pragdave/earmark#syntax-highlightning
28+ @ spec convert_into_html ( String . t ( ) ) :: String . t ( )
29+ defp convert_into_html ( lines ) do
30+ lines
31+ |> Earmark . as_html! ( % Earmark.Options { code_class_prefix: "language-" } )
2332 end
2433
25- @ spec put_into ( String . t , Changeset . t , atom ) :: Changeset . t
34+ @ spec put_into ( String . t ( ) , Changeset . t ( ) , atom ) :: Changeset . t ( )
2635 defp put_into ( html , changeset , destination_field ) do
27- Changeset . put_change ( changeset , destination_field , html )
36+ changeset |> Changeset . put_change ( destination_field , html )
2837 end
2938end
0 commit comments