OSDC 2009 Rails Turtorial

3,963 views

Published on

Published in: Technology
2 Comments
12 Likes
Statistics
Notes
No Downloads
Views
Total views
3,963
On SlideShare
0
From Embeds
0
Number of Embeds
329
Actions
Shares
0
Downloads
117
Comments
2
Likes
12
Embeds 0
No embeds

No notes for slide

OSDC 2009 Rails Turtorial

  1. 1. Rails Tutorial
  2. 2. http://blog.xdite.net http://handlino.com Rails Developer
  3. 3. Project Using Rails bingo.handlino.com sudomake.com VeryXD.net
  4. 4. Project Using Sinatra MrIE6.com VeryXD.net
  5. 5. DRY Don’t Repeat Yourself
  6. 6. Agenda • ActiveRecord • Template / Helper • Library • Plugin
  7. 7. Agenda • ActiveRecord Code • Template / Helper • Library • Plugin
  8. 8. MVC Model - View - Controller
  9. 9. MVC Browser Controller Action Model-View-Controller HTTP request route.rb GET /users/1 UsersController Model def show @user = User.find(params[:id]) Database respond_to do |format| format.html format.xml end View #show.html.erb end <html> def index <h1>User Profile</h1> ...... <p><%= @user.nickname %></p> end </html> end
  10. 10. C>M
  11. 11. C>M Code Controller
  12. 12. Refactor to Model ActiveRecord feature
  13. 13. ActiveRecord • validation • callback • counter_cache • named_scope • STI • polymorphic association
  14. 14. validation
  15. 15. validation class Post < ActiveRecord::Base validates_presence_of :subject end
  16. 16. validation class Post < ActiveRecord::Base validates_presence_of :subject end
  17. 17. validation
  18. 18. validation validates_exclusion_of :age, :in => 30..60 validates_format_of :email, :with => /A([^@s]+)@((?:[-a-z0-9]+.)+[a-z] {2,})Z/i, :on => :create validates_inclusion_of :format, :in => %w( jpg gif png ) validates_length_of :phone, :in => 7..32, :allow_blank => true validates_uniqueness_of :teacher_id, :scope => [:semester_id, :class_id]
  19. 19. Callbacks def create @post = Post.new(params[:post]) @post.content += quot; < #{Time.now.to_s} >quot; if @post.save flash[:notice] = 'Post was successfully created.' redirect_to blog_path(@post) else render :action => quot;newquot; end end
  20. 20. Callbacks before_create class Post < ActiveRecord::Base before_create :insert_timestamp def insert_timestamp self.content += quot; < #{Time.now.to_s} >quot; end end
  21. 21. Callbacks Create Update Destroy before_validation before_validation before_validation_on_create before_validation_on_update after_validatin after_validatin after_validation_on_create after_validation_on_upate before_save before_save before_create before_update before_destroy insert update delete after_create after_update after_destroy after_save after_save
  22. 22. Counter Cache
  23. 23. Counter Cache class Comment < ActiveRecord::Base belongs_to :post def after_save self.update_counter_cache end def after_destroy self.update_counter_cache end def update_conter_cache self.post.comments_count = self.post.comments.size slf.post.save(false) end end
  24. 24. Counter Cache class Comment < ActiveRecord::Base belongs_to :post, :counter_cache => true end class PostCommentsCount < ActiveRecord::Migration def self.up add_column :posts, :comments_count, :integer , :default => 0 end def self.down remove_column :posts,:comments_count end end
  25. 25. Named Scope v.2.1 class Post < ActiveRecord::Base named_scope :publish, :conditions => { :is_blocked => false } named_scope :recent, :order => quot;created_at DESCquot;, :limit => 1 end Post.publish => SELECT * FROM `posts` WHERE (`posts`.`is_blocked` = 0) Post.recent => SELECT * FROM `posts` ORDER BY created_at DESC LIMIT 1 Post.publish.recent => SELECT * FROM `posts` WHERE (`posts`.`is_blocked` = 0) ORDER BY created_at DESC LIMIT 1
  26. 26. STI (Single Table Inheritance ) class Post < ActiveRecord::Base has_many :comments before_create :insert_timestamp def insert_timestamp self.content += quot; < #{Time.now.to_s} >quot; end named_scope :publish, :conditions => { :is_blocked => false } named_scope :recent, :order => quot;created_at DESCquot;, :limit => 1 end class Article < Post end
  27. 27. Polymorphic Association • Post has_many comments • Photo has_many comments Table ? • News has_many comments post_comment photo_comment news_comment
  28. 28. Polymorphic Association class Post < ActiveRecord::Base has_many :comments, :as => :resource end class Comment < ActiveRecord::Base belongs_to :resource, :polymorphic => true end class PolymorphicComment < ActiveRecord::Migration def self.up remove_column :comments, :post_id add_column :comments, :resource_id, :integer add_column :comments, :resource_type, :string end def self.down add_column :comments, :post_id, :integer remove_column :comments, :resource_id remove_column :comments, :resource_type end end
  29. 29. Polymorphic Association
  30. 30. MVC Model - View - Controller
  31. 31. V>C
  32. 32. V>C Code View ....
  33. 33. Less code in view Render Template & Use Helper
  34. 34. View code
  35. 35. Render Template partial
  36. 36. Render Template partial
  37. 37. Write Your Own Helper <td> <tr>
  38. 38. Write Your Own Helper
  39. 39. Don’t re-invent the wheel use the library ( lib/ ), gems
  40. 40. 1 HTML +CSS (not flash) Yahoo Open Hack Day
  41. 41. lib/ rubygems
  42. 42. lib/
  43. 43. 7326 gems
  44. 44. gems
  45. 45. Rapid Web Development vendor/plugin
  46. 46. 1. authentication
  47. 47. restful-authentication ./script/generate authenticated user sessions --include-activation • / / • User model • RESTful Session controller • Activation mailer
  48. 48. open_id_authentication • OpenID • openid session controller • openid migration
  49. 49. openid_pack • restful_authentication + open_id_authentication OpenID ( multiple ) •
  50. 50. 2. Model ActiveRecord
  51. 51. attachment_fu has_attachment :storage => :file_system, :path_prefix => 'public/files', :content_type => :image, :resize_to => [50,50] • model • File system / amazon S3 / Database store
  52. 52. restful_authenication attachment_fu
  53. 53. acts_as_taggable_on_steroids • tagging class Post < ActiveRecord::Base acts_as_taggable end p = Post.find(:first) p.tag_list # [] p.tag_list = quot;Funny, Sillyquot; p.save p.tag_list # [quot;Funnyquot;, quot;Sillyquot;] p.tag_list.add(quot;Greatquot;, quot;Awfulquot;) p.tag_list.remove(quot;Funnyquot;)
  54. 54. validates_url_of class Foo < ActiveRecord::Base validates_url_of :url, :message => 'is not valid or not responding'.t end • http:// http:// https:// • •
  55. 55. 3. Controller&View ActionPack
  56. 56. will_paginate • HTML helper CSS style @posts = Post.paginate :page => params[:page], :per_page => 50 <ol> <% for post in @posts -%> <li>Render `post` in some nice way.</li> <% end -%> </ol> <%= will_paginate @posts %>
  57. 57. will_paginate (cont.) • named_scope Rails 2.1 class Product < ActiveRecord::Base named_scope :cheap, :conditions => { :price => 0..5 } named_scope :recent, lambda { |*args| {:conditions => [quot;released_at > ?quot;, (args.first || 2.weeks.ago)]} } named_scope :visible, :include => :category, :conditions => { 'categories.hidden' => false } end • @products = Product.recent.cheap.paginate :page => params[:page], :per_page => 50
  58. 58. jRails • jQuery byebye! Prototype.js gugod hlb
  59. 59. facebox_render • Facebox is a JQuery-based lightbox http://famspam.com/facebox/
  60. 60. facebox_render (cont.) • facebox class ApplicationController < ActionController::Base include FaceboxRender end Text
  61. 61. facebox_render (cont.) • facebox class ApplicationController < ActionController::Base include FaceboxRender end Text <%= facebox_link_to quot;Loginquot;, :url => new_session_url %>
  62. 62. facebox_render (cont.) • facebox class ApplicationController < ActionController::Base include FaceboxRender end Text <%= facebox_link_to quot;Loginquot;, :url => new_session_url %>
  63. 63. facebox_render (cont.) • facebox class ApplicationController < ActionController::Base include FaceboxRender end Text <%= facebox_link_to quot;Loginquot;, :url => new_session_url %> def new # do some thing you want respond_to do |format| format.html format.js { render_facebox } end end
  64. 64. facebox_render (cont.) • facebox class ApplicationController < ActionController::Base include FaceboxRender end Text <%= facebox_link_to quot;Loginquot;, :url => new_session_url %> def new # do some thing you want respond_to do |format| format.html format.js { render_facebox } end end
  65. 65. Ajax form submit
  66. 66. Ajax form submit
  67. 67. <% form_remote_tag :url => batch_event_attendees_path(@event) do %> Ajax form submit
  68. 68. def batch ... respond_to do |format| format.html format.js { render_to_facebox } end end Text
  69. 69. def batch ... respond_to do |format| format.html format.js { render_to_facebox } end end Text
  70. 70. def batch ... respond_to do |format| format.html format.js { render_to_facebox } end end batch.html.erb Text
  71. 71. def batch ... respond_to do |format| format.html format.js { render_to_facebox } end end batch.html.erb Text
  72. 72. stickies • flash[:notice] • CSS style Javascript close error_stickie(quot;Your account has been disabledquot;) warning_stickie(quot;Your account will expire in 3 daysquot;) notice_stickie(quot;Account activatedquot;) debug_stickie(quot;This only works when RAILS_ENV is developmentquot;) <%= render_stickies %>
  73. 73. 4. deployment
  74. 74. ar_mailer • E-mail E-mail Class EventNotifier < ActionMailer::ARMailer def signup_notification(user) ... end end UserNotifier.deliver_signup_notification(@user) ar_sendmail Database daemon
  75. 75. hoptoad • exception (500 error) • log
  76. 76. New Relic • profiling your rails app • trace code stack • provide optimize direction
  77. 77. Capistrano deploy 1. ssh to production server 2. svn checkout 3. run some your script (link file/copy config file/ clear cache…etc) 4. restart mongrel cluster
  78. 78. plugin ?
  79. 79. thank you.
  80. 80. Bonus
  81. 81. I18n less pain( Rails 2.2 )
  82. 82. session yml
  83. 83. Template & Engine Ultima lazy solution ( Rails 2.3)
  84. 84. Template • • gem / plugin • route / rake • ... ? • ...... by case • .......... =_=
  85. 85. Templates • (restful / openid / twitter) _authenication • Facebook • Google App Engine
  86. 86. Engine • • MVC code • ... copy • ...... by case • .......... =_=
  87. 87. Twitter XD
  88. 88. Twitter XD
  89. 89. Engine plugin • Application Plugin • code • Load • code
  90. 90. thanks again. http://blog.xdite.net http://twitter.com/xdite

×