Erlang and Elixir, Part 5: Phoenix Framework

So far we have seen how to use the basic data types and coding principles of the Erlang VM via the Elixir language. Now we will go full circle and create a working web application using the Phoenix Web Framework.

Phoenix uses the MVC server-side pattern and is in fact the top layer of a multi-layer modular system encompassing Plug (the modular specification used for Routing, Controllers, etc.), Ecto (DB wrapper for MongoDB, MySQL, SQLite3, PostgreSQL, and MSSQL) and the HTTP server (Cowboy).

Phoenix’s structure will seem familiar to Django for Python or Ruby on Rails. Both app performance and development speed were key factors in the design of Phoenix, and when combined with its real-time features, they give it powerful potential as a production-quality web-app framework.

Getting Started

Elixir is required, so please refer to the installation instructions at the beginning of this series.

We will also require Hex to get Phoenix working (to install dependencies). Here’s the command to install Hex (if you have Hex already installed, it will upgrade Hex to the latest version):

If you have not yet familiarised yourself with the Elixir language, may I recommend you continue reading the first steps of this guide before going forward in this part. 

Note that if you wish to read a short guide, you can also refer to the Learning Elixir and Erlang Guide that is provided by the Phoenix team.


Note: By default, this is included in an Elixir installation. 

To run Elixir, we need the Erlang virtual machine because Elixir code compiles to Erlang byte code. 

If you’re using a Debian-based system, you may need to explicitly install Erlang to get all the needed packages. 


So now that we have Elixir and Erlang taken care of, you are ready to install the Mix archive. 

A mix archive is just like a Zip file really, except that it contains an application as well as the compiled BEAM files and is tied to a specific version of the app.

The mix archive is what we will use to generate a new, base Phoenix application from which we can build our app!

Run the following in your terminal:

If the Phoenix Mix archive won’t install properly with this command, we can download the package from the Phoenix archives, save it to the filesystem, and then run: mix archive.install /path/to/local/phoenix_new.ez.


We will need node.js version 5 or greater, as Phoenix will use the package to compile static assets such as css and js, which in turn uses npm

Download Node.js from the download page. When selecting a package to download, it’s important to note that Phoenix requires version 5.0.0 or greater.

Mac OS X users can also install Node.js via homebrew.

If you have any issues installing Node, refer to the official Phoenix help guide.


By default, Phoenix configures applications to use the relation db server PostgreSQL, but we can switch to MySQL by passing the --database mysql flag when creating a new application.

Going forward, as we work with Ecto models in this guide, we will use PostgreSQL and the Postgrex adapter. 

So to follow along with the examples, you should install PostgreSQL. The PostgreSQL wiki has installation guides for a number of different operating systems.

Note that Postgrex is a direct Phoenix dependency, and it will be automatically installed along with the rest of our dependencies as we start our app.

The Default User

Phoenix assumes that our PostgreSQL database will have a postgres user account with the correct permissions and a password of “postgres”. If that isn’t how you want to set up, please see the instructions for the ecto.create mix task to customise the credentials.

Skeleton Install

If you only want the bare bones to get your phoenix app running, with no Ecto or Plug (no db or, create your app with the following --no-brunch and --no-ecto flags:

Pre-Flight Check

By this point, you should have:

  • Elixir
  • Erlang (by default provided by Elixir installation)
  • Hex
  • Phoenix mix archive installed
  • Additionally, if you have opted for DB and static-asset support, you will also have PostgreSQL and Node.js >= 5.0.0, in which case you will now be ready to create your app.

Create Your App

You can run mix from any directory in order to bootstrap a Phoenix application. 

For your new project, Phoenix will accept either an absolute or relative path; assuming that the name of our application is hello_world, either of these will work fine:

When you are ready, run the create command and you will get similar to the following output:

So here Phoenix has taken care of creating all of the directory structure and files for your app. You can take a look at what it is creating by navigating directly to the files in your code editor of choice.

When that’s done, we see the prompt asking for dependencies to be installed. Proceed with yes:

Now that everything has downloaded, we can cd to the directory that Elixir has been populating the project files in, and create the database via mix ecto.create.

Note: if this is the first time you are running this command, Phoenix may also ask to install Rebar. Go ahead with the installation as Rebar is used to build Erlang packages.

Database Issues

If you see the following error:

Please ensure PostgreSQL service is running and accessible with the user credentials provided (by default the user postgres with a password of “postgres” is used).

Start Up the Phoenix Web Server!

We can now start the server for our Elixir app! Run the following:

By default, Phoenix is accepting requests on port 4000. 

Visit http://localhost:4000, and you will see the Phoenix Framework welcome page.

The Phoenix Framework Welcome Page

If you can’t see the page above, try accessing it via (in case localhost is not defined on your OS).

Locally, we can now see requests being processed in our terminal session as our application is running in an iex session. To stop it, we hit ctrl-c twice, just as we would to stop iex normally.

Customising Your Application

When Phoenix generates a new application for us, it builds a top-level directory structure, as we’ll see in the following section below.

We created a new application via the mix command, which generated a new application, including the directory structure as so:

For now we will be working on the web directory, which contains the following:

To change the logo at the top of the page, we need to edit the static assets, which are kept in priv/static. The logo is kept in the directory as so: priv/static/images/phoenix.png.

Feel free to add your own graphics here; we will link it in the css and begin modifying the template next. By default, Phoenix will compile any static assets (for example here in the images directory) to the production bundle. 

For when we need a build phase for js or css, we place assets in web/static, and the source files are built into their respective app.js / app.css bundle within priv/static.

Modifying the CSS

The path for your css is web/static/css/phoenix.css. To change the logo, look to lines 29-36.

Make your change and save the file, and the changes will be updated automatically.

Reload your web browser, or load up http://localhost:4000.

An Updated Landing Page

Modifying Templates

To change the contents of your template, just look in the files in web/templates/layout and web/templates/page. You can start modifying the files to see changes live in your app.

The standard Phoenix templating engine uses EEx, which stands for Embedded Elixir. All template files have the extension .eex.

Templates are scoped to a view, which in turn are scoped to a controller. 

Phoenix creates a web/templates directory where we can put all these. For the sake of organisation, it is best to namespace these, so if you want to create a new page, that means you need to create a new directory under web/templates and then create an index.html.eex file within it (e.g. web/templates/<My-New-Page>/index.html.eex).

Let’s do that now. Create web/templates/about/index.html.eex and make it look like this:


In Phoenix, the views part of the MVC design paradigm performs several important jobs. 

For one, views render templates. Additionally, they act as a presentation layer for raw data from the controller, acting as a middle man in preparing it for use in a template. 

For an example, take a common hypothetical data structure which represents a user with a first_name field and a last_name field.  Now, for the template, we want to show the user’s full name. 

For the best approach, we write a function to concatenate first_name and last_name and provide us a helper in the view in order to write clean, concise and easily legible template code. 

In order to render any templates for our AboutController, we need an AboutView

Note: The names are significant here—the first part of the names of the view and controller must match up.

Create web/views/about_view.ex and make it look like this:


In order to see a new page, you will need to set up a route and a controller for your view and template. 

As Phoenix works on the MVC paradigm, we need to fill in all the parts. It’s not much work though.

In plain English: Routes map unique HTTP verb/path pairs to controller/action pairs for further execution. 

Phoenix automatically generates a router file for us in a new application at web/router.ex. This is where we will be working for this following section.

The route for the default “Welcome to Phoenix!” page looks like this.

This means to catch all requests made by visiting http://localhost:4000/ in a browser (which issues an HTTP GET request) to the application’s / root path and send all of those requests to the index function in the HelloPhoenix.PageController module defined in web/controllers/page_controller.ex.

The page we are going to build will simply say “About my app” when we point our browser to http://localhost:4000/about. You can fill in more information to suit your app in the template, so just go ahead and write in your HTML! 

A New Route

For our about page, we need to define a route. So just open up web/router.ex in a text editor. By default, it will contain the following; for more information on routing, refer to the official Routing Guide.

For our about section, let’s add the new route to the router for a GET request to /about. It will be processed by a HelloPhoenix.AboutController, which we will construct in the next part.

For the GET to /about, add this line to the scope "/" block of the router.ex:

The complete block will look like so:

The Controller

We have set up the route, the view, and the template. So let’s now put all the parts together so that we can view it in the browser.

Controllers are defined as Elixir modules, and actions inside a controller are Elixir functions. The purpose of actions is to gather any data and perform any tasks needed for rendering. 

For the /about route, we need a HelloWorld.AboutController module with an index/2 action. 

For that, we need to create a web/controllers/about_controller.ex and put the following inside:

For more information on Controllers, refer to the official Controllers guide.

Controller Structure

All controller actions take two arguments. The first of these is conn, a struct which holds a load of data about the request. 

The second is params, which are the request parameters. Here, we are not using params, and we avoid compiler warnings by adding the leading _.

The core of this action is render conn, "index.html". This tells Phoenix to find a template called index.html.eex and render it. Phoenix will look for the template in a directory named after our controller, so web/templates/hello.

Note: Using an atom as the template name will also work here: render conn, :index, for example when using an :index atom. But the template will be chosen based on the Accept headers, so for example “index.html” or “index.json”.

Testing the New Route

Visiting the http://localhost:4000/about URL will now render the template, controller, view and route we have defined so far!

The About My App Page


So now we have created a page and customised the app a little. But how do we actually do something with user input? Actions.

The requests for our about page will be handled by the HelloWorld.AboutController using the show action. As we already defined the controller in the last steps, we just need to add to the code a way to retain the variable which is passed via a URL like so: http://localhost:4000/about/weather.

We will now modify the code to map the new URL GET request param through the controller and eventually to the template, via using Elixir’s pattern matching. 

Add the following to the module in web/controllers/about_controller.ex:

 A few points of interest here:

  • We pattern match against the params passed into the show function so that the appName variable will be bound to the value from the URL.
  • For our example URL (http://localhost:4000/about/weather), the appName variable would contain the value weather.
  • Within the show action, there is also passed a third argument for the render function: a key/value pair where the atom :appName is the key and the appName variable is passed as the value.

The full listing of web/controllers/about_controller.ex reads as so:

Embedded Elixir 

To finally use the variable in our template first, we need to create a file for our show action. 

Create the file web/templates/about/show.html.eex and add the following:

We use the special EEx <%= %> syntax for Embedded Elixir. The opening tag has a = sign, meaning that the Elixir code between will be executed, and in turn the output will replace the tag.  

Our variable for app name appears as @appName. In this case, this is not a module attribute, but in fact it is a special bit of meta-programmed syntax which stands in for Map.get(assigns, :appName). The result is much nicer on the eyes and much easier to work with in a template.

Defining the Route

For us to be able to see the route http://localhost:4000/about/weather, for example, we need to define the route to link with the show action for the controller we just defined.

Now our work is complete! Try it out by visiting the URL http://localhost:4000/about/weather.

The Landing Page for Weather


You now have the fundamental knowledge to create a Phoenix app, customise it graphically, and create routes, actions, controllers and views for your app. 

We touched on the setup for PostgreSQL features of Ecto, but to go into more detail on the Model part of the MVC paradigm, please continue your reading in the Ecto guide.

As for user interactions and creating authentication, for example, please continue your learning at the Plug guide over at the official Phoenix documentation.

Source link

Curso de HTML5 – 23 – JavaScript com Objetos

HTML5 + JavaScript

Entenda JavaScript e veja como trabalhar com FUNCTION para criar funções que são disparadas de acordo com alguns eventos no HTML5, como ONCLICK e ONMOUSEMOVE.

Aprenda a referenciar objeto dentro do JavaScript com DOCUMENT.GETELEMENTBYID().

Aula do Curso de HTML5 criado pelo professor Gustavo Guanabara para o portal Download de pacotes e curso com certificado GRÁTIS:

Curso em Vídeo



New Findings: State of the Union for Ecommerce Page Speed and Web Performance [Spring 2015]

There are compelling arguments why companies – particularly online retailers – should care about serving faster pages to their users. Countless studies have found an irrefutable connection between load times and key performance indicators ranging from page views to revenue.

For every 1 second of improvement, experienced up to a 2% conversion increase. Firefox reduced average page load time by 2.2 seconds, which increased downloads by 15.4% — resulting in an estimated 10 million additional downloads per year. And when auto parts retailer cut load times in half, it experienced a 13% increase in sales.

Recently at Radware, we released our latest research into the performance and page speed of the world’s top online retailers. This research aims to answer the question: in a world where every second counts, are retailers helping or hurting their users’ experience – and ultimately their own bottom line?

Since 2010, we’ve measured and analyzed the performance of the top 100 ecommerce sites (as ranked by We look at web page metrics such as load time, time to interact (the amount of time it takes for a page to render its feature “above the fold” content), page size, page composition, and adoption of performance best practices. Our goal is to obtain a real-world “shopper’s eye view” of the performance of leading sites, and to track how this performance changes over time.

Here’s a sample of just a few of the findings from our Spring 2015 State of the Union for Ecommerce Page Speed & Web Performance:

Time to interact (TTI) is a crucial indicator of a page’s ability both to deliver a satisfactory user experience (by delivering content that the user is most likely to care about) and fulfill the site owner’s objectives (by allowing the user to engage with the page and perform whatever call to action the site owner has deemed the key action for that page). The median TTI in our research was 5.2 seconds.

Ideally, pages should be interactive in 3 seconds or less. Separate studies have found that 57% of consumers will abandon a page that takes longer than 3 seconds to load. A site that loads in 3 seconds experiences 22% fewer page views, a 50% higher bounce rate, and a 22% fewer conversions than a site that loads in 1 second, while a site that loads in 5 seconds experiences 35% fewer page views, a 105% higher bounce rate, and 38% fewer conversions. Only 14% of the top 100 retail sites rendered feature content in 3 seconds or less.

Page size and complexity typically correlate to slower load times. The median top 100 page is 1354 KB in size and contains 108 resource requests (e.g. images, HTML, third-party scripts). In the past two years, the median number of resources for a top 100 ecommerce page has grown by 26% — from 86 resources in Spring 2013 to 108 resources in Spring 2015. Each of these page resources represents an individual server call.

Images typically comprise between 50 to 60% of a page’s total weight, making them fertile territory for optimization. Yet 43% of the top 100 retail sites fail to compress images. Only 10% received an ‘A’ grade for image compression.

Despite eBay and Walmart’s status as retail giants, both sites have had less than stellar performance rankings in previous ecommerce performance studies. In our Fall 2014 report, these sites ranked 36th and 57th, respectively, out of 100. Our latest research, however, finds that both companies have made an impressive performance comeback – with each site’s home page rendering primary content in fewer than 3 seconds. The report provides insight into what each site did to improve its performance.

The good news is that there are opportunities for every site – even those that are relatively fast already – to fine-tune performance by taking a more aggressive approach to front-end optimization.

Get the report: Spring 2015 State of the Union for Ecommerce Page Speed & Web Performance

The post New Findings: State of the Union for Ecommerce Page Speed and Web Performance [Spring 2015] appeared first on Web Performance Today.

Source link

Happy Birthday Palatino Consulting!

My business turned two years old on Friday. Yay my business!

So, how’s it been?


It’s truly been a joy working for myself over the past two years. I really wish I’d done it sooner.

One thing that’s been a negative is the fact that I haven’t done any writing or speaking engagements since The Uncertain Web was released. It’s a bummer, but that’s the way it’s gone. I’ve been busy with paid work and, to be honest, I was a bit burned out from writing three books in three years, so a long break has been good for me.

I’ve actually got a pretty big backlog of ideas to go through. There’s been a lot of bullshit flowing through front end development over the past couple of years and I have “big thoughts” on all of it. Considering how busy I’ve been so far in 2016, I doubt that I’ll get a change to write about it, but if I do, I promise I’ll make you laugh.

I’ve also had the opportunity to work with a variety of technologies over the past couple of years, so I have opinions (real, working opinions) on just about everything out there right now. That’s fun and would be fun to share.

We’ll see.

(Don’t hold your breath, though!)

One thing that I have kept up with is open source work. I haven’t been a demon or anything, but I have been knocking off some work pretty consistently over this year especially. That’s always fun.

One thing I should mention is that I occasionally need some development help. I’m especially interested in WordPress, Angular and pure HTML+CSS freelancers. Shoot me an email if that sounds like you.

Source link

Create a responsive dashboard with Figma

Figma is a graphics tool for UI designers. It has a simple interface and enables you to collaborate on work with your teammates. If you want to work offline, you can choose to use the desktop app. Alternatively, Figma works on any operating system (hello, Windows), so you don't have to install anything at all. And getting started is easy – you can import your previous layout designs from Sketch.

  • Choose a website builder: 16 top tools

In Figma, you can create everything you need for your interface, from illustrated vector icons to custom layouts. Multiplayer editing could save much time for design teams, as it means all team members can work on the same layout at the same time. And these aren't even all of its great features.

In this tutorial I'll show you how to get set up with Figma, then walk through how to create a mobile app screen, step-by-step. In this case, we'll be designing the dashboard for a fictional statistics app. When you're done, you'll be able to create different interfaces in Figma and work on them with your team in real time.

01. Sign up

First of all, you need to sign up at Decide if you want to use the tool in your browser or download the desktop app. To download the desktop version, go to the hamburger menu in the top left corner and click on 'Get desktop app' .

02. Create an artboard and grid

Add a baseline grid to help you position your elements harmoniously (click image to enlarge)

Hit A to create an artboard. You can choose one of the presets or create your own custom size. For this project, we're going to use  Phone > iPhone 7 (375x667px) . To create a grid, first select the artboard. Then on the right-hand sidebar find 'Layout grid' and press '+'. Set up column count: 6, gutter: 16, margins: 8 and type: Stretch.  

03. Draw a rectangle for the background

Let's start with the background. Press R to bring up the Rectangle tool and draw a rectangle #5F98FA with no borders. Set the dimensions to 375×363 using the properties panel on the right hand side. 

04. Add a status bar

Set the gradient for the status bar using the properties panel on the right on the screen. Here you can adjust the colour options to create a linear gradient (click image to enlarge)

Next we want to place a status bar at the top of the screen. Press R to set width: 375, height: 64, position (x:0; y:0). For our navigation bar let's set the gradient fill using the property inspector panel on the right. Find the 'Fill' option, press on the colour preview and select 'Linear' from the drop-down menu. The colour at the top should be #77A6F7, and at the bottom #5A93F5 (opacity 100 per cent for both). 

05. Import an iOS status bar

Unfortunately, Figma doesn't include iOS UI elements by default. However, there is a file called 'Sample File', which is an iOS app design, so we can borrow the status bar from that. Copy out the light status bar option, paste it into the current file and place it at (x: 0; y:0). Using the Text tool (T), click on your artboard to add a header to the navigation bar. I've gone for Avenir Heavy, 15px, #FFFFFF. Align the heading by horizontal centre, y: 33. 

06. Create a back icon

On the left of the navigation bar should be a 'back' icon. I'm going to create this from scratch. Create a rectangle 14x14px, add 45-degree rotation, x:14; y:43. Duplicate this rectangle and place it at x:18; y:43. Select both rectangles and under the top menu go to Boolean groups > Subtract selection. After that, go back into Boolean groups > Flatten selection, or press cmd+E.

07. Finish the arrow icon

Our arrow icon is almost done. Now we just need to set the width and height to numeric values – in my case width: 12px; height: 20px. The final step is to set the fill colour to #FFFFFF. 

08. Create a graph

Now we are going to create a graph. First, we will put in some guidelines. Select the Rectangle tool (R) and set x:24 y:147; width: 1; height: 166; fill colour #B3DCFF and opacity 20%. 

Duplicate this rectangle four times with 80px margins. On the bottom of each guideline, we need to add a date label using text layers ('Feb 2', 'Feb 9', 'Feb 16', 'Feb 23', 'Mar 1'). I have used Avenir Medium, at 11px, #C1D8FF.

09. Make the data line

Using the Pen tool (P) we need to create a vector to represent the data line. Click and drag to create a Bézier point. This shape should have a 4px stroke and no fill, #FFFFFF. 

Let's add a drop shadow to help the line stand out: click the '+' on the Effects section and choose 'Drop shadow'. Use following settings to make a smooth and elegant shadow: blur: 3px, y: 7px, #2951FF, opacity: 100%.

10. Add detail to the graph

Use the Text tool to add values to the places the guidelines intersect with the data line

At the points where the guidelines intersect with the data line we are going to add circles. This time we'll use the Ellipse tool (O), which you'll find in the drop-down menu accompanying the Rectangle tool. Draw 8x8px circles on each intersection and set the fill colour to #5F98FA. We need to add a stroke: click on the '+' button next to the stroke section, set weight: 2px and align: Center. 

11. Final touches

To finish the graph section, we just need to add values to our intersection points. With the Text tool (T) select Avenir Black, 11px, #1F4991.

12. Three informative boxes

Below the line graph we are going to create three cells that display more information. Using the Text tool (T) let's create our first heading: 'Estimated value of your shares': x:16; y:391, Avenir Medium, 15px, #5D7EB6. To the right of the cell place the value '$1,115', text style: Avenir Heavy, 22px, #5F98FA, text alignment: left, x: 287; y: 387. 

13. Making a separator

Draw a rectangle that is 1px in height and spans the full width of the screen (#F5F5F5; x: 0; y: 435) – this will act as the separator between the cells. Select the heading, value and separator and create a group (cmd+G).

14. Adding headings

Underneath the graph will be three cells showing key pieces of data (click image to enlarge)

Duplicate this group so you have three groups with 24px vertical distance between them. Change second heading to 'Total members' and the third group heading to 'Friends signed up' and update the relevant values. 

15. Draw and align another rectangle

Now we're going to add a call to action. Draw a rectangle below the last cell, width: 195;  height: 44, Y-axis distance from the last separator 21px. 

Using the Align tools, line up the rectangle by horizontal centre. Then set the fill colour to #5F98FA and roundness to 22 (you'll find this field after 'Rotation' in the Properties panel). After that add a drop shadow effect (colour: #ABDAFF; opacity: 100%; y: 5; blur: 11).

16. Put some text on the button

Add text to the button using the Text tool (T): 'Get more Shares!' Set this in Avenir Black, 15px, #FFFFFF. Align the text by the centre of the button. Finally, group all elements together and name them up properly. 

17. Make it responsive

Now we are going to adjust our layout so it's responsive to different iPhones (320×568, 375×667 and 414×736). To do this we have to use constraints, which you'll find under the Properties menu on the right. 

18. Getting the layout right

If you select 'Left' or 'Right' on the horizontal drop-down, the group will pin to your chosen side of the screen, and will not stretch. If you select 'Center', the group or layer will stretch so it fills the width of the screen. We need to make the status bar float in place, so we want the 'Right&left' option (or hold down 'cmd' and click the left and right bars on the diagram). 

19. Test it

Let's try this out. With the status bar selected, hit the 'Right&Left' option. Select an artboard and, instead of iPhone 7, choose iPhone 7 Plus. It works properly even if you select the iPhone SE size. 

20. Check each layer

Let's consider the rest of the layers. For the navigation bar background, we want to use 'Right+Left'. For navigation bar title: 'Center'. For back arrow icon, it's best to use the 'Left' option – this way the arrow will be pinned to left side of the screen. 

21. Set the line graph

Now let's set the line graph. For the guidelines, dates and intersection circles, we want to use 'Center'. For the data line and background, we'll use 'Right&Left'. In the extra data section we want to use 'Left' for each title, 'Right' for each value, and 'Right&Left' for the separator lines. For the CTA button group let's set 'Center'. 

22. Set the vertical constraints

The final step is to set the vertical constraints. The status bar, navigation bar, data line and intersection circles and associated titles should be set to 'Top'. The background of graph, dates and guidelines should be set to 'Center'. Each group of extra data should be set to vertical 'Center', and the CTA button group should be set to 'Bottom'.

23. Make it work for each screen size

Let's duplicate the artboard two times, and set one to the size of an iPhone 7 Plus and the other to the size on an iPhone SE. On the Plus version, you'll need to reduce the gap between the last cell of extra information and the CTA button by selecting the cells group and increasing its height from 195 to 225. On the SE version you'll see that information cells overflow the CTA button, so we have to select the cells group and reduce its height to 150.

24. All done!

Hey, congrats! We have finished the whole app screen in Figma. For now just check everything is done, and you can sit back and feel like an expert. 

This article was originally featured in net magazine issue 288; buy it here.

Related articles:

  • New Behance concept looks like a killer app
  • Designing for social impact
  • 8 tips to ace tech jobs interviews

Source link