feed_parser/lib/feed_parser.ex

31 lines
829 B
Elixir
Raw Normal View History

2019-08-31 23:02:41 +00:00
defmodule FeedParser do
2019-08-31 23:18:03 +00:00
@default_parsers [
FeedParser.RSS2.Parser,
FeedParser.Atom.Parser,
FeedParser.JSONFeed.Parser,
FeedParser.RSSInJSON.Parser
]
2019-08-31 23:02:41 +00:00
2019-08-31 23:18:03 +00:00
@spec parse(data :: String.t(), content_type :: String.t(), parsers :: [module()]) ::
2019-08-31 23:02:41 +00:00
{:ok, feed :: FeedParser.Feed.t()} | {:error, reason :: String.t()}
2019-08-31 23:18:03 +00:00
def parse(data, content_type, parsers \\ @default_parsers) when is_binary(data) do
2019-08-31 23:02:41 +00:00
parsers
|> Enum.reduce_while(false, fn parser, acc ->
case parser.accepts(data, content_type) do
{true, result} ->
{:halt, {parser, result}}
_ ->
{:cont, acc}
end
end)
|> case do
{parser, result} ->
parser.parse_feed(result)
false ->
{:error, "no parser matched the given content type and data"}
end
end
end