Skip to content

Commit

Permalink
Merge pull request #28 from dwyl/html-body-field-#27
Browse files Browse the repository at this point in the history
Creates Html body field #27
  • Loading branch information
nelsonic authored Dec 18, 2018
2 parents c447215 + 5bd91f2 commit a979abb
Show file tree
Hide file tree
Showing 3 changed files with 68 additions and 1 deletion.
30 changes: 30 additions & 0 deletions lib/html-body.ex
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
defmodule Fields.HtmlBody do
@moduledoc """
An Ecto Type for bodies of html text.
Strips out all HTML script tags to avoid XSS but allows other basic HTML
elements to remain.
## Example
schema "article" do
field(:body, Fields.HtmlBody)
end
"""
@behaviour Ecto.Type

def type, do: :string

def cast(value) do
{:ok, to_string(value)}
end

def dump(value) do
{:ok, HtmlSanitizeEx.basic_html(value)}
end

def load(value) do
{:ok, value}
end

def input_type, do: :textarea
end
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
defmodule Fields.DescriptionPlaintextUnlimitedTest do
use ExUnit.Case
alias Fields.DescriptionPlaintextUnlimited as Description
alias Fields.DescriptionPlaintextUnlimited, as: Description

describe "types" do
test "Desription.type is :string" do
Expand Down
37 changes: 37 additions & 0 deletions test/html_body_test.exs
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
defmodule Fields.HtmlBodyTest do
use ExUnit.Case
alias Fields.HtmlBody, as: Body

describe "types" do
test "Body.type is :string" do
assert Body.type() == :string
end
end

describe "cast" do
test "Body.cast accepts a string" do
assert {:ok, "testing"} == Body.cast("testing")
end
end

describe "dump" do
test "Body.dump strips html script tags only" do
{:ok, stripped} = Body.dump("<h1>Hello <script>World!</script></h1>")

assert stripped != "<h1>Hello <script>World!</script></h1>"
assert stripped == "<h1>Hello World!</h1>"
end
end

describe "load" do
test "Body.load returns a string" do
assert {:ok, "testing"} == Body.load("testing")
end
end

describe "input_type" do
test "Body.input_type returns :textarea" do
assert Body.input_type() == :textarea
end
end
end

0 comments on commit a979abb

Please sign in to comment.