Rails to Phoenix: How Elixir can level-you-up in Rails

Video in TIB AV-Portal: Rails to Phoenix: How Elixir can level-you-up in Rails

Formal Metadata

Rails to Phoenix: How Elixir can level-you-up in Rails
Title of Series
Part Number
Number of Parts
CC Attribution - ShareAlike 3.0 Unported:
You are free to use, adapt and copy, distribute and transmit the work or content in adapted or unchanged form for any legal and non-commercial purpose as long as the work is attributed to the author in the manner specified by the author or licensor and the work or content is shared also in adapted form only under the conditions of this license.
Release Date

Content Metadata

Subject Area
Elixir has rapidly developed into a mature language with an ever-growing library of packages that excels at running web apps. And because both Elixir and Phoenix were developed by Ruby / Rails programmers, the ease with which you can learn Elixir as a Ruby developer, is much greater than many other languages. With numerous code examples, this talk will discuss how learning a functional approach to handling web requests can improve what we do every day with Rails. This talk is aimed at people who have some familiarity with Rails but no experience with Elixir is necessary.
Arithmetic mean Computer animation Term (mathematics) Plastikkarte Software framework
Functional programming Server (computing) Computer animation Elasticity (physics) Coma Berenices Computer-assisted translation Stack (abstract data type)
Functional programming Implementation Group action Connectivity (graph theory) Similarity (geometry) Mereology Number Element (mathematics) Web 2.0 Programmer (hardware) Object-oriented programming Different (Kate Ryan album) Computer programming Software framework Data structure Erlang distribution Social class Infinity Bit Line (geometry) Cartesian coordinate system Exterior algebra Computer animation Configuration space Library (computing)
Axiom of choice Functional programming Building Presentation of a group Run time (program lifecycle phase) Overhead (computing) Real-time operating system Open set Fault-tolerant system Event horizon Coprocessor Scalability Number Product (business) Ideal (ethics) Software framework Computing platform Physical system Programming language High availability Cartesian coordinate system Computer animation Telecommunication Quicksort Communications protocol Library (computing)
Programming language Server (computing) Run time (program lifecycle phase) State of matter Multiplication sign Virtual machine Bit Number Product (business) Web 2.0 Web service Process (computing) Computer animation Single-precision floating-point format Erlang distribution Multi-core processor Traffic reporting Stability theory
Functional programming Presentation of a group Group action Run time (program lifecycle phase) Code State of matter Multiplication sign Parameter (computer programming) Web 2.0 Mathematics Bit rate Different (Kate Ryan album) Single-precision floating-point format Erlang distribution Endliche Modelltheorie Recursion Exception handling Social class Electric generator Mapping Instance (computer science) Angle Hash function Order (biology) Quicksort Resultant Web page Game controller Computer file Virtual machine Similarity (geometry) Control flow Number 2 (number) Element (mathematics) Object-oriented programming String (computer science) Data structure Initial value problem Module (mathematics) Key (cryptography) Projective plane Cartesian coordinate system System call Symbol table Equivalence relation Human migration Loop (music) Computer animation Personal digital assistant √úbertragungsfunktion Mixed reality Iteration Tuple
Web page Default (computer science) Presentation of a group Game controller Computer animation Sequel Software repository Adaptive behavior Energy level Software framework
Web 2.0 Group action Game controller Arithmetic mean Computer animation Different (Kate Ryan album) Software developer Bit Parameter (computer programming) Cartesian coordinate system Mereology Usability
Module (mathematics) Functional programming Code Transformation (genetics) Multiplication sign Plotter ACID Cartesian coordinate system Dirac equation System call Web 2.0 Latent heat Computer animation Data structure
Discrete group Functional programming Group action Code View (database) Plotter Range (statistics) Parameter (computer programming) Food energy Software framework Endliche Modelltheorie Series (mathematics) Social class Theory of relativity Mapping Sound effect Bit Instance (computer science) Variable (mathematics) Software repository Volumenvisualisierung Right angle Quicksort Cycle (graph theory) Resultant Dataflow Mobile app Implementation Game controller Overhead (computing) Rule of inference Template (C++) Revision control Object-oriented programming Boundary value problem Data structure Module (mathematics) Dependent and independent variables Key (cryptography) Interface (computing) Database Cartesian coordinate system System call Vector potential Computer animation Query language Personal digital assistant Video game Table (information) Logische Programmiersprache
Discrete group Functional programming Slide rule Game controller Computer file Transformation (genetics) State of matter Code 1 (number) Insertion loss Field (computer science) Formal language Number Web 2.0 Mathematics Software framework Data structure Series (mathematics) Endliche Modelltheorie Error message Module (mathematics) Addition Default (computer science) Dependent and independent variables Information Validity (statistics) Key (cryptography) Moment (mathematics) Boilerplate (text) Database Cartesian coordinate system Limit (category theory) System call Type theory Pointer (computer programming) Computer animation Software repository Query language Internet service provider Order (biology) Table (information) Row (database)
Functional programming Group action Game controller Code Correspondence (mathematics) Insertion loss 2 (number) Mathematics Pattern matching Cross-validation (statistics) Endliche Modelltheorie Extension (kinesiology) Error message Position operator Dependent and independent variables Matching (graph theory) Validity (statistics) Database Performance appraisal Message passing Computer animation Personal digital assistant Software repository Resultant Tuple Row (database)
Axiom of choice Complex (psychology) Functional programming Game controller Code View (database) Usability Template (C++) Formal language Software design pattern Authorization Software framework Endliche Modelltheorie Data structure Module (mathematics) Validity (statistics) Reflexive space Cartesian coordinate system Variable (mathematics) Flow separation Computer animation Algebraic closure Volumenvisualisierung Configuration space Table (information)
Web 2.0 Functional programming Computer animation Code Block (periodic table) View (database) Similarity (geometry) Endliche Modelltheorie Mereology Reading (process) Template (C++)
Functional programming Beat (acoustics) Mobile app Group action Implementation Computer file Link (knot theory) Code Java applet Virtual machine Similarity (geometry) Fault-tolerant system Automatic differentiation Medical imaging Programmer (hardware) Response time (technology) Mathematics Coefficient of determination Different (Kate Ryan album) Profil (magazine) Core dump Software framework Software testing Erlang distribution Physical system Addition Curve Inheritance (object-oriented programming) Key (cryptography) Information Weight Software developer Projective plane Bit Cartesian coordinate system Measurement Connected space Process (computing) Computer animation Personal digital assistant Network topology Self-organization Pattern language Right angle Library (computing) Row (database)
genes and the human
mind the the so everybody welcome to I top without about the Phoenix framework many my name is christian got From and CSA in Chicago
we the couple people's replaced top award familiarize you with the Phoenix framework generally they also to root our discussion of the Phoenix framework in terms of of Phoenix elixir the OTP then stop will to explain some of those in a minute here so what this talk is not no bonds I'm very sorry no means and you're smart rails comp crowd I
certainly don't independent you by showing the pictures of my cats because that would just
insult you so why not rails so a reasonable question to ask rails com and income you tell you blow up your Rails apps I'm not kind of guy rails is great and I enjoy working with I know it very well it's fast liver functionality developed however I don't really love China Grove my Rails apps usually requires more than just spinning up additional servers and often requires new technology in the stack readiness sidekick Q agent maybe elastic search something like that the FIL consider 1
alternative the Phoenix framework there's a lot of similarities to rails and shares many of the same motivations Chris on was a real programmer for writing the and framework the many a static and structural similarities between rails in Phoenix both are designed to be productive frameworks both emphasize convention over configuration and both a server-side NBC frameworks there are also a number of its of important differences it is written Alexa is a functional language Phoenix ATIS compiled if you that is really not at all it's an implementation of an OTP application written in Alexa so I may use elixir infine it's a little bit interchangeably today in part this is because the Phoenix framework is the implementation of an acronym Alexa and by design Phoenix programming is Alexa programming yes well that's about 2
sizes of so framework is a web framework written Alexa the which is a functional language that grew out of her line so modulation of components implies functional programming offers data immutability many actions taken and data structures always return a copy of a new data structure while leaving the original unchanged there are no objects to classes instead he past data by cash in race to functions with a first-class elements so Erlang
this is a programming language used to build scalable soft real-time systems with requirements and high availability was originally developed by Erickson supporter telecom infrastructure the fault tolerance required to seamlessly failover from 1 switch to another mates Erlang an ideal choice for use in the way the early has a somewhat different syntax that bears some similar you Prologue it's used by a number of copies in production Erickson since they developed it sort of obviously WhatsApp no 1 of the more common and more well known companies running airline the OTP your question is the open telecom protocol would austerity as defined as the open telephony protocol but basically it's not quite of full french fries full-fledged framework is more collection of Berlin libraries and design choices that will create applications that conform to an offer a distributed highly-available supervised and failures as runtime so Solexa this event
is a dynamic functional language has has a sense a syntax it's somewhat similar to Ruby was written by Josie wedding from platform he was previously a member of the rails scorching which offers the promise of building distributed scalable maintainable applications that can run at very low present processor overhead as well as well as very low latency why Phoenix because is written
Alexa which ran for the Erlang virtual machine the functional immutable Asynchronous scalable light and fast the Phoenix ATIS compiled with the added certainty that can provide around runtime stability and is well suited to the current state of the Web with multi-core processors running multiple processes on a single machine or many machines distributed geographically the the so there are a number of companies
are running Phoenix production bleacher report is the 1 in In the example I've heard more but going to their reports they were able to handle 8 times more traffic while reducing the number of servers when they migrated from a rail stacked to Phoenix stack from 150 service 5 and I if I minus that's too that sounds a bit too good to be true and there's probably a little by dream there maybe they dropped a red server or something like that but anyway so that's not talking about programming languages let's look at an example so here we have a Ruby
example we define a class the class method to modify actually giving key by adding the 3rd argument to the initial value when evaluated it does a pretty much what we expect so if we will note that our original hash and new hatch both at the same the but the same value and if you look to the object idea the they be the same object and so try the same thing in Alexa instead of a classroom define a module we define a function within that model because a module just a group of functions there's no concept of instance a class methods we evaluate the example we see the result is similar the new map looks like our modified after the Ruby example but the first one my has remained unchanged but his break little that what's happening within our transfer function so we call this update bang method and we call it a viable that much more we don't call the method on an object because there are no objects I'll call the hatch and set in the reference through the MAPK module end users update bang method In this case at the bank will raise an exception if the key isn't present in the that so the up a function takes 3 arguments and that the key of function the 3rd argument is an anonymous function the takes the value at the map key as its argument and passes that value to its own function code and here the function code uses the angle brackets string concatenation operator to combine the 2 values so let's look back the Ruby example 1 more time we could try to make the Ruby example immutable . 2 would keep the original action unchanged gossip try . 3 is which we all do the same thing in this case by raising a runtime error but both freeze and do only produce a shallow copy so if we were to tabulate change are example I we see the immutability doesn't hold for nested objects quite frankly neither of these approaches is practical across a codebase Anakin a litter . 2 . freeze with every method call right and if I'm trying to make Ruby immutable probably had sort of started down the wrong path from the from the get go so some language-specific concepts that probably already come up that will come up again this so we're all on the same page the lecture lists not arranged maps not hatches 0 there are very similar there objects of the lives as modules and modules pack is package groups of functions together but the being is the elixir vertebrates are the Erlang virtual machine and that's where all Phoenix elixir code is executed uh and we see have a tuple which is the that ordered a collection of elements between the curly braces where the symbol or Adam at the front represents the successor fail state of a function call often and I general there's no FOR loop no iteration which favors recursion in higher order functions like that and reduce to looking at a real sprouted confuse projects there are a number of similarities with other used I mixed module elixir combines the role of bundlers rate Bundler and now rails under the rails 5 world under a single wrapped in a single module injury migrations the number of code generators into the application controllers use etc. unlike rails Phoenix requires you to explicitly defined your play realizations the if you look at project structure a Phoenix projects is reasonably similar to or else right it doesn't look all that different from the underscore build folder contains are compiled project files um depths folder contains are dependencies prove static files allows migrations I you the Web folder the Web folder in Phoenix project is pretty similar to the AP folder rails project the channels in this case are the Phoenix equivalent of action Qabalah WebSockets if you look at the next 1 .
3 which is in release candidate for and is that it is a number of changes to the project that's way beyond the scope of this talk to you and all of them but it's important note the new up with graphene 1 . 3 project it's gonna look a little bit different than your 1 . 2 at
the the the suppose presses the default adapted for a new Phoenix Project and there is support for other adapters present it's not always up to date with the latest release that and person AP was really surprised to see that there's not 1 but 2 Microsoft sequel adapters in both the MSE cool . ecto Indonesia adapters are new lease on the echo repo page since I started working on this presentation things are happening
OK so Phoenix's NBC framework and let's at step level then look at the different pieces of that it's support controller 1st so we have
rails controller iffiness controller and is I'm a whole lot of differences between means said through a high at a glance let's look a little bit more closely at the instant of Phoenix controller action requires 2 arguments the 1st is the common which represents the web request the In rails we get this implicitly Viet application controller if the rail stocks
they they tell you as much becomes invisibly to you as a developer and that's OK that's not a bad thing is part of the speed and ease of development the rails offers the but there's a different way of looking at of approaching your control so as be it
requires the call on acid explicitly maybe you're 1 that made me wonder how the contact there let's look let's jump back up the stack and look so this is the end point module and we'll need to get into like what's happening here in specifics but I just worse recall out that with the Phoenix AP were declaring assume each plot they were put in which a plot represents more or less a transformation the each the beach transformation happens euro web request as a kind and your application where parsable or do all those other things that will convert an HTTP requests into structures that you can then modify with your application code most the time you need to worry about this bike rack in rails but when you do we need to know look into what's happening it's nice to know that mapped out somewhere and you can the this is also really replace that your own custom functionality we need something the correct something to do that thing that you need
the supply Dirac are rather similar and they're actually look the specifications are really similar I plug however can be is almost anywhere will rack is wired in place the beginning of a rock at
life really do that is a rack in rails we can do that but it sort of involves shimmying relative to some other a piece of functionality I'm not a set anywhere you want use it but early in the call stack really something else the get better control saying argument controller is a map in this case which is going to the structure the request parameters in a variable called data sintering NBC framework looks like we're probably developing something restful expect there might be a database query here tools but that energy without look like I know with the query were not invoking the query through the model like a find a refined by instead we specify the repo at the repo module through the application itself and then specify the model Table against which we want In the function arguments other than be a slightly different the interface to the rebo will be slightly different things 1 . 3 again worth noting I we so we can change our query to something other than the primary key In our controls the required that we declare the temple the ranges but don't was it some assumption based on i which which you file rare render again like that so trivial issue in an app like this something's been around since Rails 2 3 4 on 25 review Boulder has 40 subfolders in but certainly no small amount of of our cognitive overhead saved so were is the plot render function to name the view temple we wanna use assigned the results of our query to variable for use by the time In because explicitly rendering begin easily switch out the template we wanna show so step in battle that Phoenix is it an application itself but imagine as earlier but but it's important it's important distinction that becomes apparent if you work to the lecture in Phoenix for a while the it's itself as an implementation of an OTP up written elixir Phoenix layer more or less a routing layer to the the code that you write but with rails you're relying on the often implicit promise that your app offers whether it's rendering of you by naming assumption routing based on a similar assumption or exposing instance variables across responsibility boundaries rules there to help but makes its debates rails the centerpiece of what is more ostensively your business in your application logic we because the way you interact with your with your own code and code the application by passing data structures to functions instead of sharing Rails ActiveRecord objects between classes it's conceptually harder least for me to think of Phoenix is a thing is doing a lot of the heavy lifting I think this can leave application code more isolated and less prone to getting bound up in the MVC framework where ch
to the better it with the example happily structure this and make this a little more functional and then we can use the pipe operator for that piping values of which is passing the value from the left into the function on the right as the 1st argument the more idiomatic way of expressing the flow of data into a function and the so you move our map up are mapped to the left but operator In this past and as the 1st argument of this function and our example that's a small improvement the code executes the same maybe read a little bit better but if you look at another example offer for me This expresses better the way data flows through module as a series of discrete but related steps the this conceptualizes back better to the HTTP request response cycle and expresses what your application code is doing future me appreciates code that self-evident and doesn't rely on an implicit actions and potential side effects and partially that's because current gets my code doesn't in a few days of committing its source control the
the I to any web request can be viewed as a function and for me this is a big aha moment of writing function of the web the call itself has all the information you need to figure out the state of the world and serve the appropriate response web requests stateless functions they have to be work on the world wide web and this is just as true in rails in Phoenix there's no reason you can't shouldn't structure your rails up a way that expresses a discrete series of transformations to get you from request response but I think this is where the structure imposed by your language in your framework can really have an influence on how you write your application code so back to would look
now label step now look at what's happening in Phoenix model a side note as frameworks Delphine's is gonna be 1 of the harder ones to Google for Phoenix model does not get you what you think you're gonna get you most without it definitely need to include the elixir modifier on that 1 we that s so as we saw on the controller shall function database queries don't rely on model functions they rely on the model in order to reference and access the database table name but the queries are functions called on the actor repo module so this really limits are models the handling schema and data validation but so we expand the web model function in the previous slide we just see the wraps the import of a few actor modules including change said in query can define a UUID the primary key and we define the schema within the model itself as opposed to uh schema file such field names name type we also add default null values to schema here said at the change that was 1 of the module we imported changes transforms data structures like and lists into more formal structure which we can then insert or update into the database better provides a number of functions to manipulate our change that data castle make a best-effort attempts using the field type defined schema to cost the brands nondestructively invalid are required and ensuring that operands map as keys for all the values that we expect to be in a database the table we can update change with something more and more invasive cost this is deadly longer and more boilerplate than writing an active record insert but you are explicitly calling out the validation set to 1 it's also let's try you're adding validations which probably duplicate what you this structure the you impose a new database but the by validating the model additional errors and provide error messages back to the user you can also write a
custom validation that nowhere up or pattern matching with invite a case they here on the result of the valid position ID function and we can take our custom validation and
wire back into the change said validation pipeline within a cross-validation we get an error
message back to the change that which will send back with a request response so this is more or less the extent of our pretty basic Phoenix bottle the because were also not using the model to query the database the models naturally get skinnier as the primarily inch concerned with ensuring data validity only a whole lot more to say about working about actin working with a persistence layer that should be entire documents on some gave 1 here last year at the lack of record so that's something reference there anybody wants the so back to a controller which will handle the result of interacting with a model where the model validations we're just looking at come off a change that function so we use our change that example to perform insert action so the create function as the corresponding control actions so it's simple Blair example will that no again Maria match off the result of our Rico insert function the Repo insert will return a total tuple or a collection of items in curly braces and the OK Adam tells us the answer works is expected to continue on with a happy that when the change in there when the change it fails live evaluations we define we can return error messages back to you we take those errors said in each of the status code and Aaron flash warning messages Aaron warning flash and but the entire create function that together we can render review which would look like this
for a very similar Phoenix have
filled brief aside Richie Key the author closure has a great operate out various gasses the perils of easy easy versus complexity at how easy can discuss complexity writing different currently that's watch the rails is easy embraces convention over configuration and it's able to do most of what I want automatically but the ease of rails disguises and high this complexity the rails often performance in complex work under the hood the Phoenix on the other end is less easy it requires more explicit code requires you to think about your application differently explicitness of your Phoenix framework application encourages keeping was simple a model of the it is a good example of this it really only does data validation hades entirely different module to query the same table I of this command separation structure can keep the overall structure of your application simpler and easier to reason about then in general this design pattern is entirely possible within rails that's often the way a language our framework is used the reflexive design choices we make when using it in they move from a controller to model back to a controller and let's look at the view the Phoenix the user pretty simple similar rails views the work recently the functions the invoked by the Phoenix render function usually from the controller aim to explicitly define the view module template and the variables for the function but even this is a basic application template
not particularly interesting really the part we care about is where the template wires up to render function this is similar to the yield block the rails template define our view module get a decorator function to that model and we can render show but this template uses e code which basically is here because similar enough should look all that different and we can take the title functionally defined and added back into a template which would
look like this the the I did have Jack on their 48 h is the keynote yesterday I will coincidence but anyway so the pretty long walk through basic web request I but I really want to emphasize the similarities between Phoenix and rails getting started writing Alex writing which occurred in Phoenix shouldn't be too daunting of a challenge they should feel familiar enough read proto and tried out what the into the rails they're similar but
not same as we start getting into the differences they start to appreciate the strengths the lecture in the Phoenix framework we really even touched testing but take it from me your test run fast this little to no studying system will marking doubling this easy to write and you usually don't require a lot of elaborate set up if you cannot do in the Phoenix I justice of I don't mention microsecond response times with everybody loves but we're not the basically because 1 thing as 1 database record so that's not really a meaningful measure as you grow your application you can add cues and background workers just by adding code you need any additional infrastructure a q and q worker exists as the Erlang deemed virtual machine processes which get started in supervised by your application itself the application has the capability for failure handling delta within the OTP framework provides a supervisory tree that supervisory tree for monitors everything is running mild your application by the rescue workers that you set up other pieces of the connection to your database of within that supervisory tree your app can is designed to crash it just gets restarted it keeps right on going will barely missing a beat but a lecture on feature to image where you might say honest through the lecture in Phoenix a relatively new a Phoenix framework application is NOT at and this is a pretty well understood well defined operational patterns Phoenix is Mexico the lecture trans files Erlang by code that runs on the beam virtual machine this code base has been matured and battle in Belfast CDs which makes older than Java the being like the JVM as the party piece of the Erlang ecosystem it's super lightweight fast fault tolerant scalable and because it's a light weight you can grow your application with less need for additional infrastructure there are cases where a library that you need or some piece of functionality may not exist a military at although that's becoming less and less true every day is more packages are written for the the lecture ecosystem however in many cases similar libraries possibly do exist Erlang and lectures fully interoperable with Erlang so it's no problem to import a libraries the link the should I use Phoenix pardon me what to say categorically yes any should experiment with with Phoenix and it depends out of the subtext of this question is can I do this xyz thing that I need to do the answer is probably yes but you may need to write your own code for your own package for that must have often found a way it really tied to the house of implementation I mean everything in broadly enough about the what and why there may be a different afterward to say that however if the should I use this question is more like is Phoenix right for my company maybe more accurately is my company right for Phoenix that answer depends a lot more in your company and you risk profile for new technology if you wanna be navigated I think it helps if you can develop some core competency within your organization whether that's a group developers who attend meetups right some toy ads for informal learning session like a lunch and learn the key is to grow interests competency in the framework 1st the learning curve however is not as steep as you might think the similarity between rails in Phoenix really works here Euroventures so when you leave you with a quote from the great change Irish film Ghost Dog way of the samurai through the 2nd half of the same for anything it's called away if 1 understands things in this manner should be able to hear about always and the more and more in accord with itself Help us help help you understand the Phoenix framework a bit better and maybe consider using it for upcoming projects without said I'm not advocating abandoning rails it is new and shiny and that has its own appeal but it's a different tool toolbox maybe more suited some problems than others as rails elixir programmers believe there's a lot of benefit exploring different technologies not just been because they provide a different way of doing things because different methods can reflect back but I you don't things can revealed new aspects of what you've been doing all along thank you
at the the happened
currently SHS and