ruby on rails
DESCRIPTION
A primer to Ruby on Rails introducing both Ruby and Rails.TRANSCRIPT
![Page 1: Ruby On Rails](https://reader033.vdocument.in/reader033/viewer/2022060108/554f80c6b4c905435d8b49a3/html5/thumbnails/1.jpg)
Ruby on Rails
Rapid, solid, flexible application development
![Page 2: Ruby On Rails](https://reader033.vdocument.in/reader033/viewer/2022060108/554f80c6b4c905435d8b49a3/html5/thumbnails/2.jpg)
I am ...
Bálint Érdi (Budapest, Hungary)
blog: http://bucionrails.comemail: [email protected] My evolution :)
java web developerpython web developer(freelance) ruby web developer and consultant
(with occasional non-web works)
![Page 3: Ruby On Rails](https://reader033.vdocument.in/reader033/viewer/2022060108/554f80c6b4c905435d8b49a3/html5/thumbnails/3.jpg)
Hungary
![Page 4: Ruby On Rails](https://reader033.vdocument.in/reader033/viewer/2022060108/554f80c6b4c905435d8b49a3/html5/thumbnails/4.jpg)
Legend
Facts: (Wisdom :) )Ruby is object oriented
Code: 5.times { print "Hello Fluidtime!" }
![Page 5: Ruby On Rails](https://reader033.vdocument.in/reader033/viewer/2022060108/554f80c6b4c905435d8b49a3/html5/thumbnails/5.jpg)
Outline
1. Ruby basic concepts 2. Rails
History & philosophyBasic modulesIntroducing each moduleOther features (a selection of them)Who uses Rails?
3. Demo app
Questions are welcome anytime
![Page 6: Ruby On Rails](https://reader033.vdocument.in/reader033/viewer/2022060108/554f80c6b4c905435d8b49a3/html5/thumbnails/6.jpg)
Ruby: History
created by Yukihiro Matsumoto ~1995it is a blend of his favorite languages (Smalltalk, Lisp, Perl, ADA)open source [RUBY]now at 1.9
![Page 7: Ruby On Rails](https://reader033.vdocument.in/reader033/viewer/2022060108/554f80c6b4c905435d8b49a3/html5/thumbnails/7.jpg)
Ruby is object orientedBut it really isEverything is an objectEvery object has a classClasses are objects, too
5.times { print "Hello, Fluidtime!" } 3 + 2 # => 53.+(2) # => 53.send(:+, 2) # => 5
![Page 8: Ruby On Rails](https://reader033.vdocument.in/reader033/viewer/2022060108/554f80c6b4c905435d8b49a3/html5/thumbnails/8.jpg)
Ruby is duck-typed (dynamically typed)
behavior is more important than type ("if it walks like a duck and talks like a duck, it is a duck")no type declarations are needed
a = 3a + 2 # => 5a + " jeff" # => TypeError a = "hello"a + 2 # => TypeErrora + " jeff" # =>"hello jeff"
![Page 9: Ruby On Rails](https://reader033.vdocument.in/reader033/viewer/2022060108/554f80c6b4c905435d8b49a3/html5/thumbnails/9.jpg)
Ruby is functional programming like
Functional programmingmethods are first-class citizens of the languagelets you concentrate on what you want instead of how you want to do it (because "for" loops are ugly)Helps keep the code cleaner, more elegant and less error-prone.e.g Lisp
[119, 43, 982, 266].select { |n| n % 7 == 0 }["voodoo", "kayak", "light"].find { |w| w =~ /^(.).*\1$/ }(1..4).map { |n| n**2 }
![Page 10: Ruby On Rails](https://reader033.vdocument.in/reader033/viewer/2022060108/554f80c6b4c905435d8b49a3/html5/thumbnails/10.jpg)
Ruby has strong metaprogramming features
define methods at runtime, on the fly (define_method)evaluate code in the context of an instance or a class (instance_eval, class_eval)get in control when the object does not have a certain method (method_missing)... or when a name is not found(const_missing)
![Page 11: Ruby On Rails](https://reader033.vdocument.in/reader033/viewer/2022060108/554f80c6b4c905435d8b49a3/html5/thumbnails/11.jpg)
Ruby has open classes, all of them
Any class can be reopened, "core" classes, tooyou can define new methods, override new ones, etc.class definitions can thus span files
class Numeric def plus(n) self.+(n) endend
3.plus(2) # => 5
![Page 12: Ruby On Rails](https://reader033.vdocument.in/reader033/viewer/2022060108/554f80c6b4c905435d8b49a3/html5/thumbnails/12.jpg)
Rails résumé
Rails is a powerful yet simple web framework written in RubyHistoryPhilosophy Introducing the main building blocksOther included featuresExtending Rails functionalityWho uses Rails?
![Page 13: Ruby On Rails](https://reader033.vdocument.in/reader033/viewer/2022060108/554f80c6b4c905435d8b49a3/html5/thumbnails/13.jpg)
History
created by David Heinemeier Hansson, ~2003 [ROR]extracted framework from a project called Basecampopen source, community driven, ~1400 contributors during its historynow at 2.3, going for 3.0
![Page 14: Ruby On Rails](https://reader033.vdocument.in/reader033/viewer/2022060108/554f80c6b4c905435d8b49a3/html5/thumbnails/14.jpg)
Rails basic ideologyVery opinionated: encourages "best practices""Convention over configuration" to avoid bloatware and keep things simple in most casesPossibility to change default behavior in special casesSugar and vinegar: easy to do what is encouraged, possible (but probably not simple) to do "unrecommended" things. Test Driven Development (TDD) is extremely important (writing tests first, so an automated test suit that can be easily -and quickly- run is needed)The framework has to stay small and lean but provide a mechanism for easy expansion.
![Page 15: Ruby On Rails](https://reader033.vdocument.in/reader033/viewer/2022060108/554f80c6b4c905435d8b49a3/html5/thumbnails/15.jpg)
Rails: Consequences of the ideology
Why is all this important?
enables you to be more productive by following the "guidelines"enables you to concentrate on the business logic without worrying about the technical details you will feel happy because it is so elegant and and feeling good! you will feel good because it is so efficient
![Page 16: Ruby On Rails](https://reader033.vdocument.in/reader033/viewer/2022060108/554f80c6b4c905435d8b49a3/html5/thumbnails/16.jpg)
Rails main building blocks
Model - View - Controller (MVC) frameworkModel: ActiveRecordController: ActionControllerView: ActionView
Clear separation of concernsAdditional modules
ActionSupport for supporting libsActiveResource for REST complianceActionMailer for sending emails
![Page 17: Ruby On Rails](https://reader033.vdocument.in/reader033/viewer/2022060108/554f80c6b4c905435d8b49a3/html5/thumbnails/17.jpg)
The model: ActiveRecord
Database engine agnosticismDatabase migrationsAssociations between modelsValidationsCallbacks
![Page 18: Ruby On Rails](https://reader033.vdocument.in/reader033/viewer/2022060108/554f80c6b4c905435d8b49a3/html5/thumbnails/18.jpg)
ActiveRecord: database agnosticism
it is an ORM (Object Relational Mapping)you should not have to worry about what lies underneathyou should not have to write SQLAdapters exist for sqlite, mysql, postgresql
Post.find(:all, :conditions => [ "created_at > ?", 2.days.ago ])
![Page 19: Ruby On Rails](https://reader033.vdocument.in/reader033/viewer/2022060108/554f80c6b4c905435d8b49a3/html5/thumbnails/19.jpg)
ActiveRecord: Database migrationsto make sure
... not just the code, but the database schema is tracked, too... all developers work with the same schema... you don't have to write raw SQL .. you are able to jump to any version, just like with a SCM ... deployment stays simple: you just run the migrations
Examples of what a migration could do:
creating a posts tableadding a user_id to the posts tablechanging column type from boolean to string
![Page 20: Ruby On Rails](https://reader033.vdocument.in/reader033/viewer/2022060108/554f80c6b4c905435d8b49a3/html5/thumbnails/20.jpg)
ActiveRecord: Associations 1.class Blog < ActiveRecord::Base has_many :postsend
class Post < ActiveRecord::Base belongs_to :blog has_many :comments end * using the control that Ruby gives for finding names (const_missing)
![Page 21: Ruby On Rails](https://reader033.vdocument.in/reader033/viewer/2022060108/554f80c6b4c905435d8b49a3/html5/thumbnails/21.jpg)
ActiveRecord: Associations 2.
reaching associated object(s):
blog.posts.find(:first, :conditions => ["updated_at > 1.week.ago])
creating associated object(s):
post.comments.create(:user => me, :body => "That's a great post, congratulations!")
* leveraging Ruby metaprogramming capabilities
![Page 22: Ruby On Rails](https://reader033.vdocument.in/reader033/viewer/2022060108/554f80c6b4c905435d8b49a3/html5/thumbnails/22.jpg)
ActiveRecord: Validations
validation is business logic so it belongs to the modeluse the provided validators which cover most of the cases
validates_presence_of :login validates_format_of :zip_code, :with => /^\d{5}$/
roll your own for the special cases
![Page 23: Ruby On Rails](https://reader033.vdocument.in/reader033/viewer/2022060108/554f80c6b4c905435d8b49a3/html5/thumbnails/23.jpg)
ActiveRecord: CallbacksEntry points (hooks) that implement business logic at different during the lifecycle of the objectlifecycle events: create, save, update, validate, destroyprovided methods: before_save, after_create, ...good for setting default values, set calculated attributes, send out emails, etc.
![Page 24: Ruby On Rails](https://reader033.vdocument.in/reader033/viewer/2022060108/554f80c6b4c905435d8b49a3/html5/thumbnails/24.jpg)
ActionController: Résumé
Basic buildupFiltersRendering from controller actions
![Page 25: Ruby On Rails](https://reader033.vdocument.in/reader033/viewer/2022060108/554f80c6b4c905435d8b49a3/html5/thumbnails/25.jpg)
ActionController: Basic buildupThe controller should be thin and should only contain:
... actions (methods) that compose the API
... filter calls
... the actual filter implementations Actions
newcreateeditdestroy...
![Page 26: Ruby On Rails](https://reader033.vdocument.in/reader033/viewer/2022060108/554f80c6b4c905435d8b49a3/html5/thumbnails/26.jpg)
ActionController: Filters
Filters are
... methods that run before, after or around actions
... prevalently used for checking authorization to resources ... used to set variables for templates in a DRY way
![Page 27: Ruby On Rails](https://reader033.vdocument.in/reader033/viewer/2022060108/554f80c6b4c905435d8b49a3/html5/thumbnails/27.jpg)
ActionController: Rendering
The controller sets the variables that the view template will use and does the actual rendering
By default, the view with the name of the action is renderedBut it can also render
any action by namea text (mainly for debugging purposes) other representations of resources (e.g js, json, xml, etc.)nothing (just returning something to the caller)
![Page 28: Ruby On Rails](https://reader033.vdocument.in/reader033/viewer/2022060108/554f80c6b4c905435d8b49a3/html5/thumbnails/28.jpg)
ActionView: Résumé
BasicsPartials & content blocks
![Page 29: Ruby On Rails](https://reader033.vdocument.in/reader033/viewer/2022060108/554f80c6b4c905435d8b49a3/html5/thumbnails/29.jpg)
ActionView: Basics The view:
... is a representation
... should contain the least possible amount of business logic... is rendered by the ERB template language which can be changed with plugins (check out haml! [HAML])
Lots of view helpers are provided for generating htmlsome helpers (e.g form_for) are context-sensitive so views can be reused without cluttering them with conditions
![Page 30: Ruby On Rails](https://reader033.vdocument.in/reader033/viewer/2022060108/554f80c6b4c905435d8b49a3/html5/thumbnails/30.jpg)
ActionView: Partials & Content blocks
Partials
chunks of reusable code you can render from other views
Content blocks
separate definition of the building blocks of a page and actually generating them.make it possible to break the link between the order of html in the template and their order on the generated pageare ideal for setting a subsection in the html title of a pageinjecting per-page javascripts
![Page 31: Ruby On Rails](https://reader033.vdocument.in/reader033/viewer/2022060108/554f80c6b4c905435d8b49a3/html5/thumbnails/31.jpg)
A selection of Rails' features
Sending emails with ActionMailerContext-dependent configurationsRoutingRESTful applicationsInternationalization & LocalizationGeneratorsCachingExtending core functionalityHandling dependencies
![Page 32: Ruby On Rails](https://reader033.vdocument.in/reader033/viewer/2022060108/554f80c6b4c905435d8b49a3/html5/thumbnails/32.jpg)
Sending emails with ActionMailer
mailers are models one email template (a view template) for each email typeone method in the mailer model for each email type that sets the variables for rendering the emailsending out an email is calling a method on the mailerthere is convention for finding the template name from the method's name
![Page 33: Ruby On Rails](https://reader033.vdocument.in/reader033/viewer/2022060108/554f80c6b4c905435d8b49a3/html5/thumbnails/33.jpg)
Context dependent configurations (environments)Development: used for development with throwaway data
Test: used for automated testing, records are created and destroyed by each test run.
Production: used by the live application. Handle with care.
Common configuration file + each env. has its own config which overwrites the values set in the common one.Additional environments can easily be set upExample: emails should be sent out in production, examined but not sent out when testing and it is up to you in development
![Page 34: Ruby On Rails](https://reader033.vdocument.in/reader033/viewer/2022060108/554f80c6b4c905435d8b49a3/html5/thumbnails/34.jpg)
Router
generates user-friendly names you can use in your code (e.g dashboard_path and dashboard_url)makes your routes DRY. You don't have to put hardwired routes into your applicationmakes dangling links nearly impossibleroutes incoming requests to the appropriate actionit is a SEO tool
map.dashboard '/', :controller => 'dashboard', :action => 'show' map.search '/search/:term', :controller => "search", :action => "index", :term => /\w*/
![Page 35: Ruby On Rails](https://reader033.vdocument.in/reader033/viewer/2022060108/554f80c6b4c905435d8b49a3/html5/thumbnails/35.jpg)
RESTful applications
"HTTP is actually a general purpose protocol for applying verbs to nouns" [REST]encouraged as best practicedeclaring a resource generates the RESTful routes
map.resources :users
verb path generated path nameGET /users/new new_user_pathPOST /users users_pathGET /users/:id/edit edit_user_path(id)PUT /users/:id user_path(id)GET /users users_pathDELETE /users/:id user_path(id)
![Page 36: Ruby On Rails](https://reader033.vdocument.in/reader033/viewer/2022060108/554f80c6b4c905435d8b49a3/html5/thumbnails/36.jpg)
Internationalization (I18n) & LocalizationInternationalization:
Turns a one-language site into a international oneHas translations for built-in messages (e.g for validation errors) for most languagesTranslations can easily be added in sep. "locale" files
Localization:
localizes displayed data to the actual language/countrydate, time, month names, day names, currency, etc.
![Page 37: Ruby On Rails](https://reader033.vdocument.in/reader033/viewer/2022060108/554f80c6b4c905435d8b49a3/html5/thumbnails/37.jpg)
Generators
Generates files and content for common tasksAvailable from the command line Because laziness is a virtue in a programmer :)Models, controllers, resources, migrations,Plugins can easily add their generators
![Page 38: Ruby On Rails](https://reader033.vdocument.in/reader033/viewer/2022060108/554f80c6b4c905435d8b49a3/html5/thumbnails/38.jpg)
Caching
Granular:
page cachingStatic pages that do not need Rails to enter the picture (e.g about us, terms & conditions)
action cachingPages that rarely change but that need certain filters to run (e.g pages that can only viewed once logged in)
fragment cachingonly cache certain parts of a page (e.g sidebar)
![Page 39: Ruby On Rails](https://reader033.vdocument.in/reader033/viewer/2022060108/554f80c6b4c905435d8b49a3/html5/thumbnails/39.jpg)
Consistent core, dead simple extension
User authentication, pagination, attaching files, etc. to models are not part of RailsPossible extensions:
plugins are bundled with the applicationgems can be bundled with the application (which is good practice to do) or installed system-wide
![Page 40: Ruby On Rails](https://reader033.vdocument.in/reader033/viewer/2022060108/554f80c6b4c905435d8b49a3/html5/thumbnails/40.jpg)
Handling dependencies
vendor directory for dependencies:
vendor/gemsvendor/pluginsvendor/rails
and automated tasks to manage them
Examples:
$ rake rails:freeze:edge$ rake gems:unpack:dependencies
![Page 41: Ruby On Rails](https://reader033.vdocument.in/reader033/viewer/2022060108/554f80c6b4c905435d8b49a3/html5/thumbnails/41.jpg)
Who uses Rails?
twitter.comyellowpages.comgithub.com - social codinglighthouseapp.com - issue tracker appshopify.com - webshop generation and hosting...
from small-scaled applications to high-traffic onesfor really simple stuff it could be an overkill (in these cases use Sinatra, another ruby framework :) [SIN])
![Page 42: Ruby On Rails](https://reader033.vdocument.in/reader033/viewer/2022060108/554f80c6b4c905435d8b49a3/html5/thumbnails/42.jpg)
Time for a demo app!
http://github.com/balinterdi/par_avion/tree/maste
r
![Page 43: Ruby On Rails](https://reader033.vdocument.in/reader033/viewer/2022060108/554f80c6b4c905435d8b49a3/html5/thumbnails/43.jpg)
Questions?
Bálint Érdiblog: http://bucionrails.com
email: [email protected]: http://twitter.com/baaz
![Page 44: Ruby On Rails](https://reader033.vdocument.in/reader033/viewer/2022060108/554f80c6b4c905435d8b49a3/html5/thumbnails/44.jpg)
References
[HAML] http://haml.hamptoncatlin.com/ [RUBY] http://ruby-lang.org/[ROR] http://rubyonrails.org/[REST] http://tomayko.com/writings/rest-to-my-wife[SIN] http://www.sinatrarb.com/