Upload
balint-erdi
View
1.308
Download
0
Tags:
Embed Size (px)
DESCRIPTION
A primer to Ruby on Rails introducing both Ruby and Rails.
Citation preview
Ruby on Rails
Rapid, solid, flexible application development
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)
Hungary
Legend
Facts: (Wisdom :) )Ruby is object oriented
Code: 5.times { print "Hello Fluidtime!" }
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
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
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
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"
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 }
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)
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
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?
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
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.
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
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
The model: ActiveRecord
Database engine agnosticismDatabase migrationsAssociations between modelsValidationsCallbacks
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 ])
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
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)
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
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
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.
ActionController: Résumé
Basic buildupFiltersRendering from controller actions
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...
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
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)
ActionView: Résumé
BasicsPartials & content blocks
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
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
A selection of Rails' features
Sending emails with ActionMailerContext-dependent configurationsRoutingRESTful applicationsInternationalization & LocalizationGeneratorsCachingExtending core functionalityHandling dependencies
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
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
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*/
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)
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.
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
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)
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
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
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])
Time for a demo app!
http://github.com/balinterdi/par_avion/tree/maste
r
Questions?
Bálint Érdiblog: http://bucionrails.com
email: [email protected]: http://twitter.com/baaz
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/