SlideShare a Scribd company logo
ELIXIR AND PHOENIX FOR RUBYSISTS
BROOKLYN ZELENKA
TABLE OF CONTENTS
WHAT WE’RE GOING TO COVER
▸ Background
▸ Syntax
▸ Compare with Ruby
▸ Extra features
▸ Functional Programming Basics
▸ Tooling (Mix, Hex, Dialyzer, and ExUnit)
▸ A tiny bit of OTP
▸ Project layout
▸ Compare with Rails
▸ Similarities
▸ Differences
▸ Extra features
▸ Live code a simple app
ELIXIR (LANGUAGE) PHOENIX (WEB FRAMEWORK)
ELIXIR
PART ONE
ELIXIR: BACKGROUND
WHAT IS ELIXIR?
▸ Runs on BEAM (Erlang virtual machine)
▸ Developed by Ericsson
▸ Battled tested
▸ Major telecom
▸ Almost 30 years
▸ Compiled, dynamically typed language
▸ Focus on scalability, concurrency,

and fault tolerance
▸ Functional language
▸ Immutable by default
WHAT ELIXIR IS NOT
▸ Ruby++
▸ Friendly syntax for Erlang
▸ Object-oriented
I WOULDN’T CLASSIFY ELIXIR AS A BETTER
RUBY. SURE, RUBY WAS MY MAIN LANGUAGE
BEFORE ELIXIR, BUT PART OF MY WORK/
RESEARCH ON CREATING ELIXIR WAS
EXACTLY TO BROADEN THIS EXPERIENCE AS
MUCH AS POSSIBLE AND GET SOME MILEAGE
ON OTHER ECOSYSTEMS SO I DIDN’T BRING

A BIASED VIEW TO ELIXIR. IT IS NOT

(A BETTER) RUBY, IT IS NOT (A BETTER)
ERLANG, IT IS ITS OWN LANGUAGE.
José Valim, Elixir’s BDFL
FP + RUBY
BUT I WANT A FAST, FUNCTIONAL RUBY!
▸ You should check out Clojure
▸ Once you get over the parentheses, the semantics are much closer
▸ Legend has it that Matz originally started Ruby as a Lisp
▸ Great community, tons of libs, Java & JS interop, and so on…
ANYWAY…
FUNCTIONAL PROGRAMMING
FUNCTIONAL PROGRAMMING: 101
▸ Data-first
▸ Explicit state rather than data hiding
▸ Limit and isolate side effects
▸ Referential transparency
▸ Composition over inheritance
▸ Expressions rather than objects & messages
▸ Everything is an expression
▸ Not mutually exclusive with OO (see Scala, Swift, and Rust)
FUNCTIONAL PROGRAMMING
WHY CARE ABOUT FUNCTIONAL PROGRAMMING?
▸ The free lunch is over
▸ Clean, maintainable systems
▸ Abstractions
▸ Even higher level code
▸ Focused on meaning and intent, rather than machine instructions
▸ Highly reusable
TYPES, TYPES, TYPES
ELIXIR IS “WEAKLY TYPED”
▸ “Weak” is technical, not derogatory
▸ Does its own type conversion as needed
▸ Nice for integers vs floats
▸ No built-in ADTs
▸ Shameless self-plug: ADTs coming soon in a lib!
▸ Type annotations
▸ @spec add(integer, integer) :: integer
TYPES OF TYPES
ELIXIR’S BUILT-IN TYPES
▸ Atoms (similar to Ruby’s symbols)
▸ :ok
▸ :foo
▸ “pid”s
▸ Integers
▸ Floats
▸ Keyword lists
▸ Binaries
▸ Characters
▸ Character lists
▸ Strings
▸ Maps
▸ Structs
▸ Dicts
TRUTHINESS
ELIXIR’S TRUTHINESS TABLE
TRUTHY FALSEY
TRUE ✓
FALSE ✓
nil ✓
“” ✓
[] ✓
anything else ✓
ERLANGISH
ERLANG’S LEGACY
▸ Transmits binary streams <<1,0,1>>
▸ OTP all the things
▸ Explicit goal to match (or beat) Erlang in terms of performance
▸ Runs pretty much everywhere
SYNTAX
RUBY
# Cool stuff ahead

module Foo
def hello(name = nil, *names)
case name
when nil
“Hello, world!”
when names.empty?
“Hello, #{ name }”
else
hello(name) + hello(names)
end
end
# Cool stuff ahead

defmodule Foo do
def hello, do: “Hello, world!”
def hello([head|tail]) do
hello(head) <> hello(tail)
end
def hello(name), do: “Hi, #{ name }”
end
ELIXIR
hello/0
hello/1 on lists
hello/1 on anything
pattern
matching
COMPOSITION
FUNCTION COMPOSITION
▸ Pipeline operator
▸ |>
▸ Remember “g o f” from way back in high school?
▸ Pipeline is backwards
▸ ie: The “forward”, or operational order
▸ g(f(x)) == (g o f) x == x |> f |> g
PIPELINING
THE PIPELINE OPERATOR |>
Ruby: message chaining
[1,2,3].sum.divide(5).floor
[1,2,3].sum = 6
6.divide(5) = 1.2
1.2.floor = 1
Elixir: pipe, or (forward) composition
[1,2,3] |> Enum.sum |> divide(5) |> floor
Enum.sum([1,2,3]) = 6
divide(6, 5) = 1.2
Float.floor(1.2) = 1
First argument
ENCAPSULATION & POLYMORPHISM
CLASSES VS MODULES, PROTOCOLS, AND STRUCTS
class Foo

def initialize(bar, quux)

@bar = bar

@quux = quux

end



def add

@bar + @quux

end

end
module Bar

def add(a, b)

a + b

end

end
Foo.new(1, 2).add
defmodule Foo do

defstruct bar: nil, quux: nil



def add(%Foo{bar: b, quux: q}), do: b + q

end
defprotocol Mathy do

def add(struct)

def add(a, b)

end



defimpl Mathy, for: Foo do

def add(%Foo{bar: b, quux: q}), do: b + q

end
defimpl Mathy, for: Bar do

def add(%Bar{a: a, b: b}), do: a + b

end
Interface, not implementation
{
Implementation
{
Implementation
{
METAPROGRAMMING
SOMEWHAT-DIFFERENT-FROM-USUAL MACROS
▸ Macros are functions that run at compile time, not runtime
▸ “Code that writes code”
▸ quote and unquote
▸ Elixir gives an AST, rather than tokens or syntax
▸ WARNING: harder to reason about!
▸ Only use when a regular function can’t get the job
done
▸ Can switch behaviours based on environment (prod vs
dev vs test)
▸ Generate large scaffolds
▸ Make cleaner code
▸ and more!
▸ Canonical “unless” example:
defmodule MyCoolUnless do

defmacro unless_m do

quote do

if(!unquote(clause), do: unquote(expression))

end

end

end
iex> require MyCoolUnless

iex> Unless.unless_m true, IO.puts “don’t print this"

nil
iex> Unless.unless_fun true, IO.puts “don’t print this"

“don’t print this”

nil
TOOLING
IEX, MIX, HEX, ECTO, DIALYZER, & EXUNIT
▸ IEx is Elixir’s IRB
▸ Mix is roughly Elixir’s Bundler
▸ Hex is roughly `gem` + RubyGems
▸ Ecto is a database interface (will see bit more in Phoenix section)
▸ Dialyzer is a static analysis tool
▸ Annotate your code with @spec to ensure that types will line up
▸ Will tell you about errors in branching paths, error handling, and so on
▸ ExUnit
▸ Built-in unit testing framework with nice `assert` syntax
▸ ex. assert response.status == 200
KILLER FEATURE: CONCURRENCY
PART TWO
CONCURRENCY
THE ACTOR MODEL
▸ Concurrency is hard
▸ Erlang/Elixir tries to make it easier
▸ Processes are “actors”
▸ Mailboxes (queue)
▸ Do something when receive a message
▸ Optionally, reply to sender
▸ Don’t be afraid to “kill your children”
CONCURRENCY
SENDING MESSAGES IS SIMPLE!
iex> a = spawn(Foo, :bar, []) <~Module, function, args

iex> a |> send({self, {3, 2, 1}})

iex> flush
12 3

:ok
CONCURRENCY + TELECOMMUNICATION = ♥
OPEN TELECOM PLATFORM (OTP)
▸ Library, framework, and much more!
▸ Debugger, databases
▸ Common patterns, including
▸ Supervisors and workers
▸ GenServer (Generic Server, behaviours for OTP to call)
▸ Sync and async
▸ Restart strategies
▸ one_for_one, rest_for_all, rest_for_one
SHORT INTERMISSION
PART THREE
PHOENIX
PART FOUR
BACKGROUND
WHAT IS PHOENIX?
▸ Server-side web framework
▸ Soft-realtime features
▸ Channels
▸ Distributed
▸ Attention to serving web APIs
▸ Well separated concerns
▸ Just hit 1.0
RAILS
SIMILAR TO RAILS
▸ MVC (and then some)
▸ Plugins
▸ Migrations
▸ EEx is similar to ERB
▸ <%= some stuff %>
▸ Path helpers
▸ Router
▸ Schema
▸ Generators
RAILS
MAJOR DIFFERENCES FROM RAILS
▸ No ActiveRecord
▸ Closer to Data Mapper
▸ Request cycle is clearer
▸ Soft real time
▸ Sockets, etc
▸ View models
▸ Schemas are kept in each model
RAILS
PERFORMANCE
▸ In Rails, a 200-300ms response time is not uncommon (without a cache)
▸ Can get that down to ~50ms range
▸ With Phoenix, we often see results in the μs (microsecond) range
▸ Hear various stats, most roughly 10-40x performance over Rails
μs
DIRECTORY STRUCTURE
mix phoenix.new awesome
awesome/

README.md

mix.exs

package.json

brunch-config.js

_build/

config/

deps/

lib/

awesome.ex

awesome/

endpoint.ex

repo.ex

node_modules/

priv/

test/

web/

router.ex

web.ex

channels/

controllers/

models/

static/

templates/

views/
rails new awesome
awesome/

README.rdoc

Gemfile

Rakefile

config.ru

app/

assets/

controllers/

helpers/

mailers/

models/

views/

bin/

config/

db/

lib/

log/

public/

test/

tmp/

vendor/
PHOENIX CONCURRENCY
CHANNELS VS PROCESSES
▸ Channels are layers
▸ PubSub on steroids
▸ Senders and receivers can switch roles on the topic at any time
▸ Don’t even have to be Elixir/Erlang processes
▸ Could be a Rails server, JS client, Android app, mix & match, and so on
▸ Have their own routing system
▸ Fallback
▸ Ex. sockets will fall back to polling
LIVE CODING
PART FIVE
“WHAT COULD POSSIBLY GO WRONG?”

More Related Content

What's hot

How much performance can you get out of Javascript? - Massimiliano Mantione -...
How much performance can you get out of Javascript? - Massimiliano Mantione -...How much performance can you get out of Javascript? - Massimiliano Mantione -...
How much performance can you get out of Javascript? - Massimiliano Mantione -...
Codemotion
 
Scala : language of the future
Scala : language of the futureScala : language of the future
Scala : language of the future
AnsviaLab
 
The Joy Of Ruby
The Joy Of RubyThe Joy Of Ruby
The Joy Of Ruby
Clinton Dreisbach
 
Elixir and elm
Elixir and elmElixir and elm
Elixir and elm
Mix & Go
 
Code Generation idioms with Xtend
Code Generation idioms with XtendCode Generation idioms with Xtend
Code Generation idioms with Xtend
Holger Schill
 
Elixir introduction
Elixir introductionElixir introduction
Elixir introduction
Al Sayed Gamal
 
Class 3 - PHP Functions
Class 3 - PHP FunctionsClass 3 - PHP Functions
Class 3 - PHP Functions
Ahmed Swilam
 
Variables and User Input
Variables and User InputVariables and User Input
Variables and User Input
primeteacher32
 
Doing It Wrong with Puppet -
Doing It Wrong with Puppet - Doing It Wrong with Puppet -
Doing It Wrong with Puppet -
Puppet
 
Perl Basics with Examples
Perl Basics with ExamplesPerl Basics with Examples
Perl Basics with Examples
Nithin Kumar Singani
 
Perl
PerlPerl
Scala: functional programming for the imperative mind
Scala: functional programming for the imperative mindScala: functional programming for the imperative mind
Scala: functional programming for the imperative mind
Sander Mak (@Sander_Mak)
 
Domain Specific Languages In Scala Duse3
Domain Specific Languages In Scala Duse3Domain Specific Languages In Scala Duse3
Domain Specific Languages In Scala Duse3
Peter Maas
 
Bioinformatics p1-perl-introduction v2013
Bioinformatics p1-perl-introduction v2013Bioinformatics p1-perl-introduction v2013
Bioinformatics p1-perl-introduction v2013
Prof. Wim Van Criekinge
 
What's a macro?: Learning by Examples / Scalaのマクロに実用例から触れてみよう!
What's a macro?: Learning by Examples / Scalaのマクロに実用例から触れてみよう!What's a macro?: Learning by Examples / Scalaのマクロに実用例から触れてみよう!
What's a macro?: Learning by Examples / Scalaのマクロに実用例から触れてみよう!
scalaconfjp
 
Class 2 - Introduction to PHP
Class 2 - Introduction to PHPClass 2 - Introduction to PHP
Class 2 - Introduction to PHP
Ahmed Swilam
 
What You Need to Know About Lambdas - Jamie Allen (Typesafe)
What You Need to Know About Lambdas - Jamie Allen (Typesafe)What You Need to Know About Lambdas - Jamie Allen (Typesafe)
What You Need to Know About Lambdas - Jamie Allen (Typesafe)
jaxLondonConference
 
How Symfony Changed My Life
How Symfony Changed My LifeHow Symfony Changed My Life
How Symfony Changed My Life
Matthias Noback
 
Damien seguy php 5.6
Damien seguy php 5.6Damien seguy php 5.6
Damien seguy php 5.6
Damien Seguy
 
PHP: GraphQL consistency through code generation
PHP: GraphQL consistency through code generationPHP: GraphQL consistency through code generation
PHP: GraphQL consistency through code generation
Alexander Obukhov
 

What's hot (20)

How much performance can you get out of Javascript? - Massimiliano Mantione -...
How much performance can you get out of Javascript? - Massimiliano Mantione -...How much performance can you get out of Javascript? - Massimiliano Mantione -...
How much performance can you get out of Javascript? - Massimiliano Mantione -...
 
Scala : language of the future
Scala : language of the futureScala : language of the future
Scala : language of the future
 
The Joy Of Ruby
The Joy Of RubyThe Joy Of Ruby
The Joy Of Ruby
 
Elixir and elm
Elixir and elmElixir and elm
Elixir and elm
 
Code Generation idioms with Xtend
Code Generation idioms with XtendCode Generation idioms with Xtend
Code Generation idioms with Xtend
 
Elixir introduction
Elixir introductionElixir introduction
Elixir introduction
 
Class 3 - PHP Functions
Class 3 - PHP FunctionsClass 3 - PHP Functions
Class 3 - PHP Functions
 
Variables and User Input
Variables and User InputVariables and User Input
Variables and User Input
 
Doing It Wrong with Puppet -
Doing It Wrong with Puppet - Doing It Wrong with Puppet -
Doing It Wrong with Puppet -
 
Perl Basics with Examples
Perl Basics with ExamplesPerl Basics with Examples
Perl Basics with Examples
 
Perl
PerlPerl
Perl
 
Scala: functional programming for the imperative mind
Scala: functional programming for the imperative mindScala: functional programming for the imperative mind
Scala: functional programming for the imperative mind
 
Domain Specific Languages In Scala Duse3
Domain Specific Languages In Scala Duse3Domain Specific Languages In Scala Duse3
Domain Specific Languages In Scala Duse3
 
Bioinformatics p1-perl-introduction v2013
Bioinformatics p1-perl-introduction v2013Bioinformatics p1-perl-introduction v2013
Bioinformatics p1-perl-introduction v2013
 
What's a macro?: Learning by Examples / Scalaのマクロに実用例から触れてみよう!
What's a macro?: Learning by Examples / Scalaのマクロに実用例から触れてみよう!What's a macro?: Learning by Examples / Scalaのマクロに実用例から触れてみよう!
What's a macro?: Learning by Examples / Scalaのマクロに実用例から触れてみよう!
 
Class 2 - Introduction to PHP
Class 2 - Introduction to PHPClass 2 - Introduction to PHP
Class 2 - Introduction to PHP
 
What You Need to Know About Lambdas - Jamie Allen (Typesafe)
What You Need to Know About Lambdas - Jamie Allen (Typesafe)What You Need to Know About Lambdas - Jamie Allen (Typesafe)
What You Need to Know About Lambdas - Jamie Allen (Typesafe)
 
How Symfony Changed My Life
How Symfony Changed My LifeHow Symfony Changed My Life
How Symfony Changed My Life
 
Damien seguy php 5.6
Damien seguy php 5.6Damien seguy php 5.6
Damien seguy php 5.6
 
PHP: GraphQL consistency through code generation
PHP: GraphQL consistency through code generationPHP: GraphQL consistency through code generation
PHP: GraphQL consistency through code generation
 

Viewers also liked

Introduction to Phoenix Framework (Elixir) 2016-01-07
Introduction to Phoenix Framework (Elixir) 2016-01-07Introduction to Phoenix Framework (Elixir) 2016-01-07
Introduction to Phoenix Framework (Elixir) 2016-01-07
Svein Fidjestøl
 
Witchcraft & Quark
Witchcraft & QuarkWitchcraft & Quark
Witchcraft & Quark
Brooklyn Zelenka
 
Gourmet Service Object
Gourmet Service ObjectGourmet Service Object
Gourmet Service Object
Brooklyn Zelenka
 
Relay: Seamless Syncing for React (VanJS)
Relay: Seamless Syncing for React (VanJS)Relay: Seamless Syncing for React (VanJS)
Relay: Seamless Syncing for React (VanJS)
Brooklyn Zelenka
 
Bottleneck in Elixir Application - Alexey Osipenko
 Bottleneck in Elixir Application - Alexey Osipenko  Bottleneck in Elixir Application - Alexey Osipenko
Bottleneck in Elixir Application - Alexey Osipenko
Elixir Club
 
Elixir – Peeking into Elixir's Processes, OTP and Supervisors
Elixir – Peeking into Elixir's Processes, OTP and SupervisorsElixir – Peeking into Elixir's Processes, OTP and Supervisors
Elixir – Peeking into Elixir's Processes, OTP and Supervisors
Benjamin Tan
 
My adventure with Elm
My adventure with ElmMy adventure with Elm
My adventure with Elm
Yan Cui
 
reveal.js 3.0.0
reveal.js 3.0.0reveal.js 3.0.0
reveal.js 3.0.0
Hakim El Hattab
 

Viewers also liked (8)

Introduction to Phoenix Framework (Elixir) 2016-01-07
Introduction to Phoenix Framework (Elixir) 2016-01-07Introduction to Phoenix Framework (Elixir) 2016-01-07
Introduction to Phoenix Framework (Elixir) 2016-01-07
 
Witchcraft & Quark
Witchcraft & QuarkWitchcraft & Quark
Witchcraft & Quark
 
Gourmet Service Object
Gourmet Service ObjectGourmet Service Object
Gourmet Service Object
 
Relay: Seamless Syncing for React (VanJS)
Relay: Seamless Syncing for React (VanJS)Relay: Seamless Syncing for React (VanJS)
Relay: Seamless Syncing for React (VanJS)
 
Bottleneck in Elixir Application - Alexey Osipenko
 Bottleneck in Elixir Application - Alexey Osipenko  Bottleneck in Elixir Application - Alexey Osipenko
Bottleneck in Elixir Application - Alexey Osipenko
 
Elixir – Peeking into Elixir's Processes, OTP and Supervisors
Elixir – Peeking into Elixir's Processes, OTP and SupervisorsElixir – Peeking into Elixir's Processes, OTP and Supervisors
Elixir – Peeking into Elixir's Processes, OTP and Supervisors
 
My adventure with Elm
My adventure with ElmMy adventure with Elm
My adventure with Elm
 
reveal.js 3.0.0
reveal.js 3.0.0reveal.js 3.0.0
reveal.js 3.0.0
 

Similar to Elixir and Phoenix for Rubyists

Elixir talk
Elixir talkElixir talk
Elixir talk
Cory Gwin
 
IN4308 1
IN4308 1IN4308 1
IN4308 1
Eelco Visser
 
Introduction to Elixir
Introduction to ElixirIntroduction to Elixir
Introduction to Elixir
Diacode
 
Intro to Elixir talk
Intro to Elixir talkIntro to Elixir talk
Intro to Elixir talk
Carlos I. Peña
 
Sharper tools with F#
Sharper tools with F#Sharper tools with F#
Sharper tools with F#
Kevin Avignon
 
cs262_intro_slides.pptx
cs262_intro_slides.pptxcs262_intro_slides.pptx
cs262_intro_slides.pptx
AnaLoreto13
 
蔡学镛 Rebol漫谈
蔡学镛   Rebol漫谈蔡学镛   Rebol漫谈
蔡学镛 Rebol漫谈
d0nn9n
 
Anko - The Ultimate Ninja of Kotlin Libraries?
Anko - The Ultimate Ninja of Kotlin Libraries?Anko - The Ultimate Ninja of Kotlin Libraries?
Anko - The Ultimate Ninja of Kotlin Libraries?
Kai Koenig
 
Ruby -the wheel Technology
Ruby -the wheel TechnologyRuby -the wheel Technology
Ruby -the wheel Technology
ppparthpatel123
 
Making software maintainable
Making software maintainableMaking software maintainable
Making software maintainable
Peter Sumskas
 
Introduction to Elixir
Introduction to ElixirIntroduction to Elixir
Introduction to Elixir
brien_wankel
 
2017: Kotlin - now more than ever
2017: Kotlin - now more than ever2017: Kotlin - now more than ever
2017: Kotlin - now more than ever
Kai Koenig
 
Python1
Python1Python1
Ruby on Rails Training - Module 1
Ruby on Rails Training - Module 1Ruby on Rails Training - Module 1
Ruby on Rails Training - Module 1
Mark Menard
 
Summer of Tech 2017 - Kotlin/Android bootcamp
Summer of Tech 2017 - Kotlin/Android bootcampSummer of Tech 2017 - Kotlin/Android bootcamp
Summer of Tech 2017 - Kotlin/Android bootcamp
Kai Koenig
 
Sugar Presentation - YULHackers March 2009
Sugar Presentation - YULHackers March 2009Sugar Presentation - YULHackers March 2009
Sugar Presentation - YULHackers March 2009
spierre
 
Remix Your Language Tooling (JSConf.eu 2012)
Remix Your Language Tooling (JSConf.eu 2012)Remix Your Language Tooling (JSConf.eu 2012)
Remix Your Language Tooling (JSConf.eu 2012)
lennartkats
 
Elixir
ElixirElixir
Elixir
Robert Brown
 
AestasIT - Internal DSLs in Scala
AestasIT - Internal DSLs in ScalaAestasIT - Internal DSLs in Scala
AestasIT - Internal DSLs in Scala
Dmitry Buzdin
 
ppt7
ppt7ppt7
ppt7
callroom
 

Similar to Elixir and Phoenix for Rubyists (20)

Elixir talk
Elixir talkElixir talk
Elixir talk
 
IN4308 1
IN4308 1IN4308 1
IN4308 1
 
Introduction to Elixir
Introduction to ElixirIntroduction to Elixir
Introduction to Elixir
 
Intro to Elixir talk
Intro to Elixir talkIntro to Elixir talk
Intro to Elixir talk
 
Sharper tools with F#
Sharper tools with F#Sharper tools with F#
Sharper tools with F#
 
cs262_intro_slides.pptx
cs262_intro_slides.pptxcs262_intro_slides.pptx
cs262_intro_slides.pptx
 
蔡学镛 Rebol漫谈
蔡学镛   Rebol漫谈蔡学镛   Rebol漫谈
蔡学镛 Rebol漫谈
 
Anko - The Ultimate Ninja of Kotlin Libraries?
Anko - The Ultimate Ninja of Kotlin Libraries?Anko - The Ultimate Ninja of Kotlin Libraries?
Anko - The Ultimate Ninja of Kotlin Libraries?
 
Ruby -the wheel Technology
Ruby -the wheel TechnologyRuby -the wheel Technology
Ruby -the wheel Technology
 
Making software maintainable
Making software maintainableMaking software maintainable
Making software maintainable
 
Introduction to Elixir
Introduction to ElixirIntroduction to Elixir
Introduction to Elixir
 
2017: Kotlin - now more than ever
2017: Kotlin - now more than ever2017: Kotlin - now more than ever
2017: Kotlin - now more than ever
 
Python1
Python1Python1
Python1
 
Ruby on Rails Training - Module 1
Ruby on Rails Training - Module 1Ruby on Rails Training - Module 1
Ruby on Rails Training - Module 1
 
Summer of Tech 2017 - Kotlin/Android bootcamp
Summer of Tech 2017 - Kotlin/Android bootcampSummer of Tech 2017 - Kotlin/Android bootcamp
Summer of Tech 2017 - Kotlin/Android bootcamp
 
Sugar Presentation - YULHackers March 2009
Sugar Presentation - YULHackers March 2009Sugar Presentation - YULHackers March 2009
Sugar Presentation - YULHackers March 2009
 
Remix Your Language Tooling (JSConf.eu 2012)
Remix Your Language Tooling (JSConf.eu 2012)Remix Your Language Tooling (JSConf.eu 2012)
Remix Your Language Tooling (JSConf.eu 2012)
 
Elixir
ElixirElixir
Elixir
 
AestasIT - Internal DSLs in Scala
AestasIT - Internal DSLs in ScalaAestasIT - Internal DSLs in Scala
AestasIT - Internal DSLs in Scala
 
ppt7
ppt7ppt7
ppt7
 

Recently uploaded

Empowering Growth with Best Software Development Company in Noida - Deuglo
Empowering Growth with Best Software  Development Company in Noida - DeugloEmpowering Growth with Best Software  Development Company in Noida - Deuglo
Empowering Growth with Best Software Development Company in Noida - Deuglo
Deuglo Infosystem Pvt Ltd
 
DDS-Security 1.2 - What's New? Stronger security for long-running systems
DDS-Security 1.2 - What's New? Stronger security for long-running systemsDDS-Security 1.2 - What's New? Stronger security for long-running systems
DDS-Security 1.2 - What's New? Stronger security for long-running systems
Gerardo Pardo-Castellote
 
Microservice Teams - How the cloud changes the way we work
Microservice Teams - How the cloud changes the way we workMicroservice Teams - How the cloud changes the way we work
Microservice Teams - How the cloud changes the way we work
Sven Peters
 
LORRAINE ANDREI_LEQUIGAN_HOW TO USE ZOOM
LORRAINE ANDREI_LEQUIGAN_HOW TO USE ZOOMLORRAINE ANDREI_LEQUIGAN_HOW TO USE ZOOM
LORRAINE ANDREI_LEQUIGAN_HOW TO USE ZOOM
lorraineandreiamcidl
 
GOING AOT WITH GRAALVM FOR SPRING BOOT (SPRING IO)
GOING AOT WITH GRAALVM FOR  SPRING BOOT (SPRING IO)GOING AOT WITH GRAALVM FOR  SPRING BOOT (SPRING IO)
GOING AOT WITH GRAALVM FOR SPRING BOOT (SPRING IO)
Alina Yurenko
 
E-commerce Application Development Company.pdf
E-commerce Application Development Company.pdfE-commerce Application Development Company.pdf
E-commerce Application Development Company.pdf
Hornet Dynamics
 
Utilocate provides Smarter, Better, Faster, Safer Locate Ticket Management
Utilocate provides Smarter, Better, Faster, Safer Locate Ticket ManagementUtilocate provides Smarter, Better, Faster, Safer Locate Ticket Management
Utilocate provides Smarter, Better, Faster, Safer Locate Ticket Management
Utilocate
 
openEuler Case Study - The Journey to Supply Chain Security
openEuler Case Study - The Journey to Supply Chain SecurityopenEuler Case Study - The Journey to Supply Chain Security
openEuler Case Study - The Journey to Supply Chain Security
Shane Coughlan
 
Need for Speed: Removing speed bumps from your Symfony projects ⚡️
Need for Speed: Removing speed bumps from your Symfony projects ⚡️Need for Speed: Removing speed bumps from your Symfony projects ⚡️
Need for Speed: Removing speed bumps from your Symfony projects ⚡️
Łukasz Chruściel
 
Atelier - Innover avec l’IA Générative et les graphes de connaissances
Atelier - Innover avec l’IA Générative et les graphes de connaissancesAtelier - Innover avec l’IA Générative et les graphes de connaissances
Atelier - Innover avec l’IA Générative et les graphes de connaissances
Neo4j
 
Neo4j - Product Vision and Knowledge Graphs - GraphSummit Paris
Neo4j - Product Vision and Knowledge Graphs - GraphSummit ParisNeo4j - Product Vision and Knowledge Graphs - GraphSummit Paris
Neo4j - Product Vision and Knowledge Graphs - GraphSummit Paris
Neo4j
 
OpenMetadata Community Meeting - 5th June 2024
OpenMetadata Community Meeting - 5th June 2024OpenMetadata Community Meeting - 5th June 2024
OpenMetadata Community Meeting - 5th June 2024
OpenMetadata
 
May Marketo Masterclass, London MUG May 22 2024.pdf
May Marketo Masterclass, London MUG May 22 2024.pdfMay Marketo Masterclass, London MUG May 22 2024.pdf
May Marketo Masterclass, London MUG May 22 2024.pdf
Adele Miller
 
Why Choose Odoo 17 Community & How it differs from Odoo 17 Enterprise Edition
Why Choose Odoo 17 Community & How it differs from Odoo 17 Enterprise EditionWhy Choose Odoo 17 Community & How it differs from Odoo 17 Enterprise Edition
Why Choose Odoo 17 Community & How it differs from Odoo 17 Enterprise Edition
Envertis Software Solutions
 
socradar-q1-2024-aviation-industry-report.pdf
socradar-q1-2024-aviation-industry-report.pdfsocradar-q1-2024-aviation-industry-report.pdf
socradar-q1-2024-aviation-industry-report.pdf
SOCRadar
 
What is Augmented Reality Image Tracking
What is Augmented Reality Image TrackingWhat is Augmented Reality Image Tracking
What is Augmented Reality Image Tracking
pavan998932
 
AI Fusion Buddy Review: Brand New, Groundbreaking Gemini-Powered AI App
AI Fusion Buddy Review: Brand New, Groundbreaking Gemini-Powered AI AppAI Fusion Buddy Review: Brand New, Groundbreaking Gemini-Powered AI App
AI Fusion Buddy Review: Brand New, Groundbreaking Gemini-Powered AI App
Google
 
Revolutionizing Visual Effects Mastering AI Face Swaps.pdf
Revolutionizing Visual Effects Mastering AI Face Swaps.pdfRevolutionizing Visual Effects Mastering AI Face Swaps.pdf
Revolutionizing Visual Effects Mastering AI Face Swaps.pdf
Undress Baby
 
How to write a program in any programming language
How to write a program in any programming languageHow to write a program in any programming language
How to write a program in any programming language
Rakesh Kumar R
 
GreenCode-A-VSCode-Plugin--Dario-Jurisic
GreenCode-A-VSCode-Plugin--Dario-JurisicGreenCode-A-VSCode-Plugin--Dario-Jurisic
GreenCode-A-VSCode-Plugin--Dario-Jurisic
Green Software Development
 

Recently uploaded (20)

Empowering Growth with Best Software Development Company in Noida - Deuglo
Empowering Growth with Best Software  Development Company in Noida - DeugloEmpowering Growth with Best Software  Development Company in Noida - Deuglo
Empowering Growth with Best Software Development Company in Noida - Deuglo
 
DDS-Security 1.2 - What's New? Stronger security for long-running systems
DDS-Security 1.2 - What's New? Stronger security for long-running systemsDDS-Security 1.2 - What's New? Stronger security for long-running systems
DDS-Security 1.2 - What's New? Stronger security for long-running systems
 
Microservice Teams - How the cloud changes the way we work
Microservice Teams - How the cloud changes the way we workMicroservice Teams - How the cloud changes the way we work
Microservice Teams - How the cloud changes the way we work
 
LORRAINE ANDREI_LEQUIGAN_HOW TO USE ZOOM
LORRAINE ANDREI_LEQUIGAN_HOW TO USE ZOOMLORRAINE ANDREI_LEQUIGAN_HOW TO USE ZOOM
LORRAINE ANDREI_LEQUIGAN_HOW TO USE ZOOM
 
GOING AOT WITH GRAALVM FOR SPRING BOOT (SPRING IO)
GOING AOT WITH GRAALVM FOR  SPRING BOOT (SPRING IO)GOING AOT WITH GRAALVM FOR  SPRING BOOT (SPRING IO)
GOING AOT WITH GRAALVM FOR SPRING BOOT (SPRING IO)
 
E-commerce Application Development Company.pdf
E-commerce Application Development Company.pdfE-commerce Application Development Company.pdf
E-commerce Application Development Company.pdf
 
Utilocate provides Smarter, Better, Faster, Safer Locate Ticket Management
Utilocate provides Smarter, Better, Faster, Safer Locate Ticket ManagementUtilocate provides Smarter, Better, Faster, Safer Locate Ticket Management
Utilocate provides Smarter, Better, Faster, Safer Locate Ticket Management
 
openEuler Case Study - The Journey to Supply Chain Security
openEuler Case Study - The Journey to Supply Chain SecurityopenEuler Case Study - The Journey to Supply Chain Security
openEuler Case Study - The Journey to Supply Chain Security
 
Need for Speed: Removing speed bumps from your Symfony projects ⚡️
Need for Speed: Removing speed bumps from your Symfony projects ⚡️Need for Speed: Removing speed bumps from your Symfony projects ⚡️
Need for Speed: Removing speed bumps from your Symfony projects ⚡️
 
Atelier - Innover avec l’IA Générative et les graphes de connaissances
Atelier - Innover avec l’IA Générative et les graphes de connaissancesAtelier - Innover avec l’IA Générative et les graphes de connaissances
Atelier - Innover avec l’IA Générative et les graphes de connaissances
 
Neo4j - Product Vision and Knowledge Graphs - GraphSummit Paris
Neo4j - Product Vision and Knowledge Graphs - GraphSummit ParisNeo4j - Product Vision and Knowledge Graphs - GraphSummit Paris
Neo4j - Product Vision and Knowledge Graphs - GraphSummit Paris
 
OpenMetadata Community Meeting - 5th June 2024
OpenMetadata Community Meeting - 5th June 2024OpenMetadata Community Meeting - 5th June 2024
OpenMetadata Community Meeting - 5th June 2024
 
May Marketo Masterclass, London MUG May 22 2024.pdf
May Marketo Masterclass, London MUG May 22 2024.pdfMay Marketo Masterclass, London MUG May 22 2024.pdf
May Marketo Masterclass, London MUG May 22 2024.pdf
 
Why Choose Odoo 17 Community & How it differs from Odoo 17 Enterprise Edition
Why Choose Odoo 17 Community & How it differs from Odoo 17 Enterprise EditionWhy Choose Odoo 17 Community & How it differs from Odoo 17 Enterprise Edition
Why Choose Odoo 17 Community & How it differs from Odoo 17 Enterprise Edition
 
socradar-q1-2024-aviation-industry-report.pdf
socradar-q1-2024-aviation-industry-report.pdfsocradar-q1-2024-aviation-industry-report.pdf
socradar-q1-2024-aviation-industry-report.pdf
 
What is Augmented Reality Image Tracking
What is Augmented Reality Image TrackingWhat is Augmented Reality Image Tracking
What is Augmented Reality Image Tracking
 
AI Fusion Buddy Review: Brand New, Groundbreaking Gemini-Powered AI App
AI Fusion Buddy Review: Brand New, Groundbreaking Gemini-Powered AI AppAI Fusion Buddy Review: Brand New, Groundbreaking Gemini-Powered AI App
AI Fusion Buddy Review: Brand New, Groundbreaking Gemini-Powered AI App
 
Revolutionizing Visual Effects Mastering AI Face Swaps.pdf
Revolutionizing Visual Effects Mastering AI Face Swaps.pdfRevolutionizing Visual Effects Mastering AI Face Swaps.pdf
Revolutionizing Visual Effects Mastering AI Face Swaps.pdf
 
How to write a program in any programming language
How to write a program in any programming languageHow to write a program in any programming language
How to write a program in any programming language
 
GreenCode-A-VSCode-Plugin--Dario-Jurisic
GreenCode-A-VSCode-Plugin--Dario-JurisicGreenCode-A-VSCode-Plugin--Dario-Jurisic
GreenCode-A-VSCode-Plugin--Dario-Jurisic
 

Elixir and Phoenix for Rubyists

  • 1. ELIXIR AND PHOENIX FOR RUBYSISTS BROOKLYN ZELENKA
  • 2. TABLE OF CONTENTS WHAT WE’RE GOING TO COVER ▸ Background ▸ Syntax ▸ Compare with Ruby ▸ Extra features ▸ Functional Programming Basics ▸ Tooling (Mix, Hex, Dialyzer, and ExUnit) ▸ A tiny bit of OTP ▸ Project layout ▸ Compare with Rails ▸ Similarities ▸ Differences ▸ Extra features ▸ Live code a simple app ELIXIR (LANGUAGE) PHOENIX (WEB FRAMEWORK)
  • 4. ELIXIR: BACKGROUND WHAT IS ELIXIR? ▸ Runs on BEAM (Erlang virtual machine) ▸ Developed by Ericsson ▸ Battled tested ▸ Major telecom ▸ Almost 30 years ▸ Compiled, dynamically typed language ▸ Focus on scalability, concurrency,
 and fault tolerance ▸ Functional language ▸ Immutable by default WHAT ELIXIR IS NOT ▸ Ruby++ ▸ Friendly syntax for Erlang ▸ Object-oriented
  • 5. I WOULDN’T CLASSIFY ELIXIR AS A BETTER RUBY. SURE, RUBY WAS MY MAIN LANGUAGE BEFORE ELIXIR, BUT PART OF MY WORK/ RESEARCH ON CREATING ELIXIR WAS EXACTLY TO BROADEN THIS EXPERIENCE AS MUCH AS POSSIBLE AND GET SOME MILEAGE ON OTHER ECOSYSTEMS SO I DIDN’T BRING
 A BIASED VIEW TO ELIXIR. IT IS NOT
 (A BETTER) RUBY, IT IS NOT (A BETTER) ERLANG, IT IS ITS OWN LANGUAGE. José Valim, Elixir’s BDFL
  • 6. FP + RUBY BUT I WANT A FAST, FUNCTIONAL RUBY! ▸ You should check out Clojure ▸ Once you get over the parentheses, the semantics are much closer ▸ Legend has it that Matz originally started Ruby as a Lisp ▸ Great community, tons of libs, Java & JS interop, and so on… ANYWAY…
  • 7. FUNCTIONAL PROGRAMMING FUNCTIONAL PROGRAMMING: 101 ▸ Data-first ▸ Explicit state rather than data hiding ▸ Limit and isolate side effects ▸ Referential transparency ▸ Composition over inheritance ▸ Expressions rather than objects & messages ▸ Everything is an expression ▸ Not mutually exclusive with OO (see Scala, Swift, and Rust)
  • 8. FUNCTIONAL PROGRAMMING WHY CARE ABOUT FUNCTIONAL PROGRAMMING? ▸ The free lunch is over ▸ Clean, maintainable systems ▸ Abstractions ▸ Even higher level code ▸ Focused on meaning and intent, rather than machine instructions ▸ Highly reusable
  • 9. TYPES, TYPES, TYPES ELIXIR IS “WEAKLY TYPED” ▸ “Weak” is technical, not derogatory ▸ Does its own type conversion as needed ▸ Nice for integers vs floats ▸ No built-in ADTs ▸ Shameless self-plug: ADTs coming soon in a lib! ▸ Type annotations ▸ @spec add(integer, integer) :: integer
  • 10. TYPES OF TYPES ELIXIR’S BUILT-IN TYPES ▸ Atoms (similar to Ruby’s symbols) ▸ :ok ▸ :foo ▸ “pid”s ▸ Integers ▸ Floats ▸ Keyword lists ▸ Binaries ▸ Characters ▸ Character lists ▸ Strings ▸ Maps ▸ Structs ▸ Dicts
  • 11. TRUTHINESS ELIXIR’S TRUTHINESS TABLE TRUTHY FALSEY TRUE ✓ FALSE ✓ nil ✓ “” ✓ [] ✓ anything else ✓
  • 12. ERLANGISH ERLANG’S LEGACY ▸ Transmits binary streams <<1,0,1>> ▸ OTP all the things ▸ Explicit goal to match (or beat) Erlang in terms of performance ▸ Runs pretty much everywhere
  • 13. SYNTAX RUBY # Cool stuff ahead
 module Foo def hello(name = nil, *names) case name when nil “Hello, world!” when names.empty? “Hello, #{ name }” else hello(name) + hello(names) end end # Cool stuff ahead
 defmodule Foo do def hello, do: “Hello, world!” def hello([head|tail]) do hello(head) <> hello(tail) end def hello(name), do: “Hi, #{ name }” end ELIXIR hello/0 hello/1 on lists hello/1 on anything pattern matching
  • 14. COMPOSITION FUNCTION COMPOSITION ▸ Pipeline operator ▸ |> ▸ Remember “g o f” from way back in high school? ▸ Pipeline is backwards ▸ ie: The “forward”, or operational order ▸ g(f(x)) == (g o f) x == x |> f |> g
  • 15. PIPELINING THE PIPELINE OPERATOR |> Ruby: message chaining [1,2,3].sum.divide(5).floor [1,2,3].sum = 6 6.divide(5) = 1.2 1.2.floor = 1 Elixir: pipe, or (forward) composition [1,2,3] |> Enum.sum |> divide(5) |> floor Enum.sum([1,2,3]) = 6 divide(6, 5) = 1.2 Float.floor(1.2) = 1 First argument
  • 16. ENCAPSULATION & POLYMORPHISM CLASSES VS MODULES, PROTOCOLS, AND STRUCTS class Foo
 def initialize(bar, quux)
 @bar = bar
 @quux = quux
 end
 
 def add
 @bar + @quux
 end
 end module Bar
 def add(a, b)
 a + b
 end
 end Foo.new(1, 2).add defmodule Foo do
 defstruct bar: nil, quux: nil
 
 def add(%Foo{bar: b, quux: q}), do: b + q
 end defprotocol Mathy do
 def add(struct)
 def add(a, b)
 end
 
 defimpl Mathy, for: Foo do
 def add(%Foo{bar: b, quux: q}), do: b + q
 end defimpl Mathy, for: Bar do
 def add(%Bar{a: a, b: b}), do: a + b
 end Interface, not implementation { Implementation { Implementation {
  • 17. METAPROGRAMMING SOMEWHAT-DIFFERENT-FROM-USUAL MACROS ▸ Macros are functions that run at compile time, not runtime ▸ “Code that writes code” ▸ quote and unquote ▸ Elixir gives an AST, rather than tokens or syntax ▸ WARNING: harder to reason about! ▸ Only use when a regular function can’t get the job done ▸ Can switch behaviours based on environment (prod vs dev vs test) ▸ Generate large scaffolds ▸ Make cleaner code ▸ and more! ▸ Canonical “unless” example: defmodule MyCoolUnless do
 defmacro unless_m do
 quote do
 if(!unquote(clause), do: unquote(expression))
 end
 end
 end iex> require MyCoolUnless
 iex> Unless.unless_m true, IO.puts “don’t print this"
 nil iex> Unless.unless_fun true, IO.puts “don’t print this"
 “don’t print this”
 nil
  • 18. TOOLING IEX, MIX, HEX, ECTO, DIALYZER, & EXUNIT ▸ IEx is Elixir’s IRB ▸ Mix is roughly Elixir’s Bundler ▸ Hex is roughly `gem` + RubyGems ▸ Ecto is a database interface (will see bit more in Phoenix section) ▸ Dialyzer is a static analysis tool ▸ Annotate your code with @spec to ensure that types will line up ▸ Will tell you about errors in branching paths, error handling, and so on ▸ ExUnit ▸ Built-in unit testing framework with nice `assert` syntax ▸ ex. assert response.status == 200
  • 20. CONCURRENCY THE ACTOR MODEL ▸ Concurrency is hard ▸ Erlang/Elixir tries to make it easier ▸ Processes are “actors” ▸ Mailboxes (queue) ▸ Do something when receive a message ▸ Optionally, reply to sender ▸ Don’t be afraid to “kill your children”
  • 21. CONCURRENCY SENDING MESSAGES IS SIMPLE! iex> a = spawn(Foo, :bar, []) <~Module, function, args
 iex> a |> send({self, {3, 2, 1}})
 iex> flush 12 3
 :ok
  • 22. CONCURRENCY + TELECOMMUNICATION = ♥ OPEN TELECOM PLATFORM (OTP) ▸ Library, framework, and much more! ▸ Debugger, databases ▸ Common patterns, including ▸ Supervisors and workers ▸ GenServer (Generic Server, behaviours for OTP to call) ▸ Sync and async ▸ Restart strategies ▸ one_for_one, rest_for_all, rest_for_one
  • 25. BACKGROUND WHAT IS PHOENIX? ▸ Server-side web framework ▸ Soft-realtime features ▸ Channels ▸ Distributed ▸ Attention to serving web APIs ▸ Well separated concerns ▸ Just hit 1.0
  • 26. RAILS SIMILAR TO RAILS ▸ MVC (and then some) ▸ Plugins ▸ Migrations ▸ EEx is similar to ERB ▸ <%= some stuff %> ▸ Path helpers ▸ Router ▸ Schema ▸ Generators
  • 27. RAILS MAJOR DIFFERENCES FROM RAILS ▸ No ActiveRecord ▸ Closer to Data Mapper ▸ Request cycle is clearer ▸ Soft real time ▸ Sockets, etc ▸ View models ▸ Schemas are kept in each model
  • 28. RAILS PERFORMANCE ▸ In Rails, a 200-300ms response time is not uncommon (without a cache) ▸ Can get that down to ~50ms range ▸ With Phoenix, we often see results in the μs (microsecond) range ▸ Hear various stats, most roughly 10-40x performance over Rails μs
  • 29. DIRECTORY STRUCTURE mix phoenix.new awesome awesome/
 README.md
 mix.exs
 package.json
 brunch-config.js
 _build/
 config/
 deps/
 lib/
 awesome.ex
 awesome/
 endpoint.ex
 repo.ex
 node_modules/
 priv/
 test/
 web/
 router.ex
 web.ex
 channels/
 controllers/
 models/
 static/
 templates/
 views/ rails new awesome awesome/
 README.rdoc
 Gemfile
 Rakefile
 config.ru
 app/
 assets/
 controllers/
 helpers/
 mailers/
 models/
 views/
 bin/
 config/
 db/
 lib/
 log/
 public/
 test/
 tmp/
 vendor/
  • 30. PHOENIX CONCURRENCY CHANNELS VS PROCESSES ▸ Channels are layers ▸ PubSub on steroids ▸ Senders and receivers can switch roles on the topic at any time ▸ Don’t even have to be Elixir/Erlang processes ▸ Could be a Rails server, JS client, Android app, mix & match, and so on ▸ Have their own routing system ▸ Fallback ▸ Ex. sockets will fall back to polling
  • 31. LIVE CODING PART FIVE “WHAT COULD POSSIBLY GO WRONG?”