Ruby openfest

1,709 views

Published on

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

0 Comments
2 Likes
Statistics
Notes
  • Be the first to comment

No Downloads
Views
Total views
1,709
On SlideShare
0
From Embeds
0
Number of Embeds
10
Actions
Shares
0
Downloads
6
Comments
0
Likes
2
Embeds 0
No embeds

No notes for slide

Ruby openfest

  1. 1. In Ruby s arms by Tom Waits The sexy programming language that will change you career as a developer OpenFest
  2. 2. Look mam, PHP! I can makez webzitezThere are people who actually like programming.I dont understand why they like programming.- Rasmus Lerdorf (creator of php) OpenFest 2011
  3. 3. Who am I?xPHP-er who learned Ruby and maturedFounder at Sfalma.comPartner at NiobiumLabs http://6pna.com @panosjee
  4. 4. What is special about Ruby? Open Source Simple (before you dive in the deep) Elegant Dynamic Made for programmers productivity and sanity Modern Has a vibrant community Huge amount of libraries and framework Great VMs (take a look at JRuby) Not meant to be server-side only (I look at you php) Sexy! (how much sexy?) OpenFest
  5. 5. EvenBerlusconitook Rubyfor a spin!
  6. 6. Let s start from the basic Everything is an Object Functions (methods) are messages Object communicate with messages No type casting. Each method should know what is expecting. Maybe that s why Rubyists are so Test Paranoid Operators are syntactic sugar for methods. You can redefine them as well. Blocks and Closures (start thinking functionally and reach developers Nirvana) Mixins IRB (console) OpenFest
  7. 7. Open an IRB, load anything, play, explore, learn, debug!
  8. 8. 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 OpenFest
  9. 9. Some Magic Included# We want a small DSL* that gives us relevant dates# to today# Normally we typenow = 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 OpenFest
  10. 10. 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 OpenFest
  11. 11. 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 OpenFest
  12. 12. What the heck is DSL?DSL = Domain Specific LanguageDSLs allow you to create a mini language thatsolved specific problem. So instead of expressingeverything in a language made for computers youcan create a language that solves problem *BUT*humans can understand them too.The DSL concept was introduced by Lisp. SinceLisp is only for the enlightened ones you can useRuby *TODAY* to create your DSLs. OpenFest
  13. 13. A wealth of librariesInstalling a library in Ruby is as easier thangetting 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 OpenFest
  14. 14. 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. OpenFest
  15. 15. Let s dive into the Web (Rack)Have you heard of CGI, FastCGI? You know the old way aserver (Apache) could talk to a script?Well in Ruby we have Rack. Rack provides a minimalinterface between webservers supporting Ruby and Rubyframeworks.Whatever programs sits between our Ruby application andthe server we call it middleware.Rack enables you to talk HTTP. OpenFest
  16. 16. Let s dive into the Web (Rack)You can even expose any Ruby object as a Web Service!BEWARE: Try only at home!require rubygemsrequire rackclass 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 endendRack::Handler::Mongrel.run [].webapp, :Port => 8080# http://localhost:8080/push/1 -> 1# http://localhost:8080/to_a -> 1 OpenFest
  17. 17. * it does not make you a Rock Star hard work, love and coden roll does
  18. 18. You speak HTTP, now sing HTMLRails is collection of Ruby libraries that sit on top of Rackand allow you to create well organized web applications.Rails started by DHH at 37signals around 2004. At thebeginning it was a very opinionated framework and causeda tsunami in the web development world. Nowadays mostweb frameworks are based on the Rails philosophy.Rails favors convention over configuration so you shouldthings the Rails way and stop writing XML files (hey Java-ers) or spaghetti code (hello PHPers) OpenFest
  19. 19. Why do people use Rails?Rails is magnificent tools for creating Web Applications. Ifyour main focus is Content Websites of course you can dogreat stuff with Rails but you can stick to Drupal.Some famous Ruby on Rails Web (sites/apps) are: Twitter - http://twitter.com Groupon - http://www.groupon.com Soundcloud - http://www.soundcloud.com Github - http://www.github.com Basecamp - http://www.basecamphq.com Slideshare - http://www.slideshare.com Skroutz.gr - http://www.skroutz.gr OpenFest
  20. 20. 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_bills Controllers, 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 views View, the view can be an HTML file, JSON, XML, PDF, a mobile friendly HTML page. You name it! OpenFest
  21. 21. 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=2Rails uses all HTTP verbs GET, POST, DELETE, PUT,HEAD and matches them to a URL. For example. GET /category/1 # show category info POST /category # creates a category PUT /category/1 # updates a category OpenFest
  22. 22. 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 data 5. 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 giveshttp://gmoeck.github.com/2011/03/10/sproutcore-mvc-vs-rails-mvc.html him the web page.
  23. 23. Use the command lineIt is easier than what you think. I guess you can understandthe following:rails new awesome_apprails generate model Person name:string money:integerrails generate controller Main index about contactrails generate scaffold Category name:stringRails uses migrations to create your database schema. Nomore manual changes. If you work in a team there is notother way to go!rake db:migraterake db:migrate:resetrake db:seed OpenFest
  24. 24. Routes (URLs) to functions not files!A url is routes to code a function inside a controller. Youcan 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 end end OpenFest
  25. 25. Bye bye SQL, we wont miss ya!ActiveRecord (the Model) will abstract the database fromus. You can switch your app from SQLite to Oracle and donot 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 OpenFest
  26. 26. Get your hands dirty now!Probably there are too many new notions and words youcannot understand the only way to go is get down to writesome code. The Ruby community is very enthousiastic andactive. So head your browser to the following links anddive into Ruby and Rails: http://www.ruby-lang.org/en/ http://railscasts.com/ http://railsforzombies.org/ http://ruby5.envylabs.com/ http://rubyst.es OpenFest
  27. 27. Thank you! @panosjee - http://6pna.comRuby and Rails are not silver bullets but they can open a window tobetter 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! OpenFest

×