28
In Ruby 's arms The sexy programming language that will change you career as a developer OpenFest 2011 by Tom Waits

Ruby openfest

Embed Size (px)

DESCRIPTION

Introduction to Ruby and Ruby on Rails. Harmful for PHP developers

Citation preview

Page 1: Ruby openfest

In Ruby 's armsThe sexy programming language that will

change you career as a developer

OpenFest 2011

by Tom Waits

Page 2: Ruby openfest

Look mam, PHP! I can makez webzitez

OpenFest 2011

There are people who actually like programming. I don't understand why they like programming.

- Rasmus Lerdorf (creator of php)

Page 3: Ruby openfest

Who am I?

xPHP-er who learned Ruby and matured

Founder at Sfalma.comPartner at NiobiumLabs

http://6pna.com@panosjee

Page 4: Ruby openfest

OpenFest 2011

What is special about Ruby?Open SourceSimple (before you dive in the deep)ElegantDynamic Made for programmers' productivity and sanityModernHas a vibrant communityHuge amount of libraries and frameworkGreat VMs (take a look at JRuby)Not meant to be server-side only (I look at you php)Sexy! (how much sexy?)

Page 5: Ruby openfest

Even Berlusconi took Ruby for a spin!

Page 6: Ruby openfest

OpenFest 2011

Let 's start from the basic

Everything is an ObjectFunctions (methods) are messagesObject communicate with messagesNo type casting. Each method should know what is expecting. Maybe that 's why Rubyists are so Test ParanoidOperators are syntactic sugar for methods. You can redefine them as well.Blocks and Closures (start thinking functionally and reach developers' Nirvana)MixinsIRB (console)

Page 7: Ruby openfest

Open an IRB, load anything, play, explore, learn, debug!

Page 8: Ruby openfest

OpenFest 2011

Some Syntactic Sugar# define a hashhash = {a: 1, b:2, c:3, d:0, e:9, f:4}# get key, values that are greater than 3hash.select{ |k,v| v > 3 }

# multiple all values by 2 and store in new arraynew_array = hash.values.map { |v| v * 2 }

# You know now about block and closures!# Get all odd numbers from 1 to 10 multiplied by 101.upto(10).map { |i| i*10 if i.odd? }.compact

Page 9: Ruby openfest

OpenFest 2011

Some Magic Included# We want a small DSL* that gives us relevant dates# to today# Normally we type

now = Time.now # => 2011-04-09 19:02:22 +0300 # We add the seconds (of a day) to advance in Timenow + 60 * 60 * 24 # => 2011-04-10 19:02:22 +0300# Not cool enough, let 's see what we can do

Page 10: Ruby openfest

OpenFest 2011

Some Magic Included (II)# Remember everything is an object that we can # always overloadclass Fixnum def days self * 60 * 60 * 24 endend

# Let 's see what it does3.days# => 172800 # the total number of seconds of 3 days

Page 11: Ruby openfest

OpenFest 2011

Some Magic Included (III)# Let 's reopen and add spell some magicclass Fixnum def from_now Time.now + self endend

# Let 's see what it does3.days.from_now# => 2011-04-12 19:10:45 +0300# Congratulations! You just created your first DSL

Page 12: Ruby openfest

OpenFest 2011

What the heck is DSL?DSL = Domain Specific Language

DSLs allow you to create a mini language that solved specific problem. So instead of expressing everything in a language made for computers you can create a language that solves problem *BUT* humans can understand them too.

The DSL concept was introduced by Lisp. Since Lisp is only for the enlightened ones you can use Ruby *TODAY* to create your DSLs.

Page 13: Ruby openfest

OpenFest 2011

A wealth of librariesInstalling a library in Ruby is as easier than getting off your bed:gem install rails

Ruby libraries are distributed as gems. You can find some millions at http://www.rubygems.org and of course study the code (usually at Github).Gem commands resemble apt-get of Debian

Sometimes though libraries have a tendency to create nightmares due to dependencies. Bundler helps you sleep tight

Page 14: Ruby openfest

OpenFest 2011

Hey I want to learn Rails!Hold your horses pow! Rails is a great tools but your Rails app will look like PHP if you do not learn and master Ruby, the language.

Most Rails noobs that come from PHP continue the PHP attrocities thus creating

terrible spaggheti code.

Rails will not make you write excellent apps. Learning, persistence and coding will. So we

have to master Ruby, the language.

Page 15: Ruby openfest

OpenFest 2011

Let 's dive into the Web (Rack)Have you heard of CGI, FastCGI? You know the old way a server (Apache) could talk to a script?

Well in Ruby we have Rack. Rack provides a minimal interface between webservers supporting Ruby and Ruby frameworks.

Whatever programs sits between our Ruby application and the server we call it middleware.

Rack enables you to talk HTTP.

Page 16: Ruby openfest

OpenFest 2011

Let 's dive into the Web (Rack)You can even expose any Ruby object as a Web Service!BEWARE: Try only at home!require 'rubygems'require 'rack'

class Object def webapp class << self define_method :call do |env| func, *attrs = env['PATH_INFO'].split('/').reject(&:empty?) [200, {}, send(func, *attrs)] end end self endend

Rack::Handler::Mongrel.run [].webapp, :Port => 8080# http://localhost:8080/push/1 -> 1# http://localhost:8080/to_a -> 1

Page 17: Ruby openfest

* it does not make you a Rock Star hard work, love and code'n' roll does

Page 18: Ruby openfest

OpenFest 2011

You speak HTTP, now sing HTMLRails is collection of Ruby libraries that sit on top of Rack and allow you to create well organized web applications.

Rails started by DHH at 37signals around 2004. At the beginning it was a very opinionated framework and caused a tsunami in the web development world. Nowadays most web frameworks are based on the Rails philosophy.

Rails favors convention over configuration so you should things the Rails way and stop writing XML files (hey Java-ers) or spaghetti code (hello PHPers)

Page 19: Ruby openfest

OpenFest 2011

Why do people use Rails?Rails is magnificent tools for creating Web Applications. If your main focus is Content Websites of course you can do great stuff with Rails but you can stick to Drupal.

Some famous Ruby on Rails Web (sites/apps) are:Twitter - http://twitter.comGroupon - http://www.groupon.comSoundcloud - http://www.soundcloud.comGithub - http://www.github.comBasecamp - http://www.basecamphq.comSlideshare - http://www.slideshare.comSkroutz.gr - http://www.skroutz.gr

Page 20: Ruby openfest
Page 21: Ruby openfest

OpenFest 2011

Everything at its placeRails is an MVC framework. MVC stands for:

Model, an ORM, a class that talks and abstracts your database. We also add logic here. So for example the model Person will contain the logic. ex. person.write_me_code, person.pay_your_billsControllers, controller will orchestrate your app. They take a user 's request spin up some models (if needed) collect the results and pass the to the viewsView, the view can be an HTML file, JSON, XML, PDF, a mobile friendly HTML page. You name it!

Page 22: Ruby openfest

OpenFest 2011

Stay RESTful!Rails + REST = L.F.E.

REST stands for Representional State Transfer.Rails wants you to think in terms of objects. Your URLs are not pointer to some stupid files:ex. /edit_category.php?c_id=2

Rails uses all HTTP verbs GET, POST, DELETE, PUT, HEAD and matches them to a URL. For example.

GET /category/1 # show category infoPOST /category # creates a categoryPUT /category/1 # updates a category

Page 23: Ruby openfest

1. The user hits the server that talks to Rack. Rack calls the Routes.

2. The Routes will match the URL that user asked and dispatch the request data to the Controller.

3. The Controller gets the request data and calls the Models (database) if need.

4. The model returns data5. The Controller collects

the data from the model and spits them to the View.

6. The View returns the formatted data (HTML, JSON etc) to the Controller.

7. The Controller talks to the Server and gives him the web page.

8. The Server returns the page to the user.

http://gmoeck.github.com/2011/03/10/sproutcore-mvc-vs-rails-mvc.html

Page 24: Ruby openfest

OpenFest 2011

Use the command lineIt is easier than what you think. I guess you can understand the following:

Rails uses migrations to create your database schema. No more manual changes. If you work in a team there is not other way to go!

rails new awesome_apprails generate model Person name:string money:integerrails generate controller Main index about contactrails generate scaffold Category name:string

rake db:migraterake db:migrate:resetrake db:seed

Page 25: Ruby openfest

OpenFest 2011

Routes (URLs) to functions not files!

A url is routes to code a function inside a controller. You can change it a breeze and create meaningful urls:Guitar121::Application.routes.draw do match "/account" => "users#edit", :as => 'account' resources :attachments get "courses/missing", :as => :missing_course

resources :courses do resources :attachments member do get :invite put :uninvite end endend

Page 26: Ruby openfest

OpenFest 2011

Bye bye SQL, we won't miss ya!

ActiveRecord (the Model) will abstract the database from us. You can switch your app from SQLite to Oracle and do not change any query (hopefully).:

# Get the first user with specific id and rank > 0User.where(:id=>params[:id], :rank > 10).first

# Get all videos in category 3 order by viewsVideo.where(:category_id=>3).order("views").all

Page 27: Ruby openfest

OpenFest 2011

Get your hands dirty now!

Probably there are too many new notions and words you cannot understand the only way to go is get down to write some code. The Ruby community is very enthousiastic and active. So head your browser to the following links and dive into Ruby and Rails:

http://www.ruby-lang.org/en/http://railscasts.com/http://railsforzombies.org/http://ruby5.envylabs.com/http://rubyst.es

Page 28: Ruby openfest

OpenFest 2011

Thank you!@panosjee - http://6pna.com

Ruby and Rails are not silver bullets but they can open a window to better productivity, developer happiness and cool hacks. Use at your

own risk!You may also learn Python or Node.js just stop using PHP! Special thanx to @Drakevr for fixing my typos!