Skip to content

Commit

Permalink
CVN-141 Add ability to replace html from values
Browse files Browse the repository at this point in the history
  • Loading branch information
Pasquale Pinto committed Oct 11, 2024
1 parent d7759fd commit 72cb3c2
Showing 1 changed file with 36 additions and 1 deletion.
37 changes: 36 additions & 1 deletion modules/mod_ginger_rdf/models/m_rdf_triple.erl
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,9 @@
m_to_list/2,
m_value/2,

remove_empty/1
remove_empty/1,
replace_html/1,
replace_html/2
]).

-include_lib("zotonic.hrl").
Expand Down Expand Up @@ -167,3 +169,36 @@ is_empty_object(#rdf_value{value = Value}) ->
is_empty_object(Value);
is_empty_object(_) ->
false.

% Like 'replace_html/2' with 'z_html:strip/1' being the chosen modifier.
replace_html(In) -> replace_html(In, fun z_html:strip/1).

% Replaces all html values with the given modifier function, recursively, from
% an 'rdf_value', an 'rdf_resource', a 'triple' or a list of either;
% returns any other value unaltered.
% Note: the type of the output is always the same as the input's.
replace_html(List, ReplaceFun) when is_list(List) ->
lists:map(fun(Item) -> replace_html(Item, ReplaceFun) end, List);
replace_html(Triple, ReplaceFun) when is_record(Triple, triple) ->
NewObject = replace_html(Triple#triple.object, ReplaceFun),
Triple#triple{object=NewObject};
replace_html(Resource, ReplaceFun) when is_record(Resource, rdf_resource) ->
NewTriples = replace_html(Resource#rdf_resource.triples, ReplaceFun),
Resource#rdf_resource{triples=NewTriples};
replace_html(Value, ReplaceFun) when is_record(Value, rdf_value) ->
ValueTerm = Value#rdf_value.value,
NewValueTerm =case is_html_value(ValueTerm) of
true -> ReplaceFun(ValueTerm);
false -> replace_html(ValueTerm, ReplaceFun)
end,
Value#rdf_value{value=NewValueTerm};
replace_html(Other, _ReplaceFun) ->
Other.

% Returns 'true' iff the input is a binary string of html, 'false' otherwise.
is_html_value(Term) when is_binary(Term) ->
case z_html_parse:parse(Term) of
{ok, _HtmlNode} -> true;
{error, nohtml} -> false
end;
is_html_value(_) -> false.

0 comments on commit 72cb3c2

Please sign in to comment.