Posted on October 12, 2014 by Clive
In the last of these articles on the link shortener, I am going to discuss static assets.
There are two ways of serving static assets - through a webserver like Apache (Apache Webserver) or using Webmachine.
We'll add some simple static serving capability to the project.
First off add the following directories to your project: assets/css
$ mkdir -p assets/css
into this new directory add bootstrap.min.css from (Bootstrap)
and an empty file shorten.css.
To the file templates/latest.html.mustache from the last post, add the following lines to the head section:
<link href="css/bootstrap.min.css" rel="stylesheet" type="text/css" />
<link href="css/shorten.css" rel="stylesheet" type="text/css" />
Once these changes have been made, add a new file into the lib/ directory: ShortenerStaticResource
defmodule ShortenerStaticResource do
use Ewebmachine
resource ['css', :filename] do
resource_exists do
dispath = :wrq.path_info(:filename, _req)
filepath = "assets/css/#{dispath}"
case File.stat(filepath) do
{:ok, fileinfo} ->
case {fileinfo.type, fileinfo.access} do
{:regular, access} when access == :read or access == :read_write ->
pass filepath != nil, filepath: filepath
_ -> false
end
{:error, _} -> false
end
end
content_types_provided do
mime = :webmachine_util.guess_mime(:wrq.path(_req))
{[{mime, :provide_content}], _req, _ctx}
end
defp provide_content(_req, _ctx) do
{:ok, body} = File.read(_ctx[:filepath])
{body, _req, _ctx}
end
end
end
The last thing that will need to happen is that the resource needs adding to the supervisor.
Change the lib/shortener_supervisor.ex:
supervisor(Ewebmachine.Sup,[[modules: [ShortenerStaticResource, ShortenerLatestResource, ShortenerShortenResource, ShortenerFetchResource],port: 18080]]),
Build and restart the project in the normal way:
$ iex -S mix
To test the page, you will need to add some content to the store.
ShortenUrlSrv.put_url("http://www.distortedthinking.agency")
Then in a web browser, navigate to http://localhost:18080/latest.
You should now see a rendered page. I am not vouching for the design, but this is easily cleaned up.