Upgrade to Pro — share decks privately, control downloads, hide ads and more …

Rails4 in Action

Rails4 in Action

I talked about Rails 4 from my experiment of development Triglav
http://github.com/kentaro/triglav

For more details, see my blog post: http://blog.kentarok.org/entry/2012/11/22/005844

Kentaro Kuribayashi

November 21, 2012
Tweet

More Decks by Kentaro Kuribayashi

Other Decks in Technology

Transcript

  1. Action
    4
    in
    @kentaro

    View Slide

  2. @kentaro
    Software engineer to
    build technical basis
    Rubyist / Perl Monger
    Kentaro Kuribayashi
    paperboy&co.

    View Slide

  3. http://twitter.com/kentaro
    http://github.com/kentaro
    Twitter
    GitHub

    View Slide

  4. View Slide

  5. View Slide

  6. Triglav
    Server Management Tool

    View Slide

  7. View Slide

  8. Still at alpha stage

    View Slide

  9. • Server management tool
    • Minimalistic features
    • Provides API to retrieve
    hosts, etc.
    • Copes with complicated
    demands with loose-coupled
    architecture
    • Written in Rails 4

    View Slide

  10. Living on the Edge

    View Slide

  11. $ rails new myapp --edge
    $ ruby /path/to/rails/railties/bin/rails new myapp --dev
    Rails command
    Locally cloned command

    View Slide

  12. • Living on the Edge Rails is
    harder than you might
    imagine ;)
    • You’ll often get stuck into
    various problems around
    Rails eco-system

    View Slide

  13. View Slide

  14. View Slide

  15. View Slide

  16. View Slide

  17. The stories above are only
    applicable to Edge Rails,
    furthermore it is being to
    the major version up now!
    CAVEAT

    View Slide

  18. • As a result, I got to know
    more about Rails internal
    • I recommend you should
    be into it once at least :)

    View Slide

  19. It’s a highly
    recommendabl
    e book for
    those who
    want to know
    Rails internal

    View Slide

  20. what’s new in
    Rails4?
    So...,

    View Slide

  21. Edge Guides
    http://edgeguides.rubyonrails.org/
    Edge API Reference
    http://edgeapi.rubyonrails.org/
    Rails4 Release Notes
    http://edgeguides.rubyonrails.org/4_0_release_notes.html
    Rails 4 compilation links
    http://blog.wyeworks.com/2012/11/13/rails-4-compilation-links/

    View Slide

  22. View Slide

  23. http://blog.wyeworks.com/2012/11/13/rails-4-compilation-links/

    View Slide

  24. No big changes, but too
    many newly introduced
    and removed/deprecated
    features...

    View Slide

  25. I’ll talk to you about the
    Rails4 changes from my point
    of view, that is, changes
    which I bumped into actually
    while developing Triglav with
    Edge Rails these days. It
    must be also applicable to
    any other common web apps.

    View Slide

  26. Rails Guides now got
    responsive design!

    View Slide

  27. class ApplicationController
    add_flash_types :success, :error
    end
    <% if error %>
    <%= error %>
    <% elsif success %>
    <%= success %>
    <% end %>
    redirect_to ‘/foo’, error: 'message'
    add_flash_types view
    controller

    View Slide

  28. Web routes viewer bundled in
    Rails4 (taken from Sextant)

    View Slide

  29. concern :commentable do
    resources :comments, only: [:create]
    end
    resources :services, constraints: { id: /[^\/]+/ },
    concerns: [:commentable]
    resources :roles, constraints: { id: /[^\/]+/ },
    concerns: [:commentable]
    resources :hosts, constraints: { id: /[^\/]+/ },
    concerns: [:commentable]
    concern
    # instead of `root to: ‘main#index’`
    root ‘main#index’
    root ...

    View Slide

  30. create_table :messages do |t|
    t.references :person
    end
    add_index :messages, :person_id
    index option
    create_table :messages do |t|
    t.references :person, index: true
    end
    We never
    neglect to
    add indices!

    View Slide

  31. create_join_table :products, :categories
    create join table
    create_table :categories_products, :id => false do |td|
    td.integer :product_id, :null => false
    td.integer :category_id, :null => false
    end

    View Slide

  32. <%= content_tag_for(:tr, @posts) do |post| %>
    ...
    scaffold generator now use
    `content_tag_for`
    <% @posts.each do |post| %>

    ...
    `content_tag_for` automatically adds `id` attribute along with
    active record object. It’s very useful.

    View Slide

  33. Clunky JavaScript helpers
    will be removed
    • button_to_function
    • link_to_function
    It might cost you some long time than you’ll expect
    if you use them heavily

    View Slide

  34. find_all_by_*
    find_last_by_*
    scoped_by_*
    find_or_initialize_by_*
    find_or_create_by_*
    find_or_create_by_*!
    AR finder methods
    where(...)
    where(...).last
    where(...)
    where(...).first_or_initialize
    where(...).first_or_create
    where(...).first_or_create!

    View Slide

  35. Post.where(comments_count: 10).limit(5)
    Old style find
    Post.find(:all, conditions: { comments_count: 10 }, limit: 5)

    View Slide

  36. active_record_deprecate_finders
    ... can be written as below for now, until Rails5:
    Post.scoped(:where => { :comments_count => 10 }, :limit => 5)
    Post.where(comments_count: 10).limit(5)
    “The code to implement the deprecated features has been moved out to the
    active_record_deprecated_finders gem. This gem is a dependency of Active Record in Rails
    4.0. It will no longer be a dependency from Rails 4.1, but if your app relies on the
    deprecated features then you can add it to your own Gemfile. It will be maintained by the
    Rails core team until Rails 5.0 is released.”
    -- Rails4 Release Notes

    View Slide

  37. Strong Parameters

    View Slide

  38. From Rails 4, controllers have
    responsibility to secure mass
    assignment instead of models.

    View Slide

  39. class Person < ActiveRecord::Base
    attr_accessible :name, :age
    end
    attr_accessible (Old Way)
    “Before Strong Parameters arrived, mass-assignment
    protection was a model's task provided by Active Model. This
    has been extracted to the ProtectedAttributes gem. In order
    to use attr_accessible and attr_protected helpers in your
    models, you should add protected_attributes to your
    Gemfile.”
    Ruby On Rails Security Guide
    http://edgeguides.rubyonrails.org/security.html

    View Slide

  40. class Person < ActiveRecord::Base
    include ActiveModel::ForbiddenAttributesProtection
    end
    class PeopleController < ActionController::Base
    def create
    Person.create(person_params)
    end
    private
    def person_params
    params.require(:person).permit(:name, :age)
    end
    end
    ActionController::Parameters

    View Slide

  41. class Person
    has_many :pets
    accepts_nested_attributes_for :pets
    end
    # PeopleController
    def person_params
    params.require(:person).permit(
    :name, :age, pets_attributes: [
    :name,
    :category
    ]
    )
    end
    accepts_nested_attribute_for
    Pass
    *_attributes
    as an Array

    View Slide

  42. # PeopleController
    def person_params
    params.require(:person).permit(
    :name, :age, pets_attributes: [
    :name,
    :category
    :id,
    :_destroy
    ]
    )
    end
    accepts_nested_attribute_for
    Both :id and :_destroy
    seem to be needed to
    update/delete nested
    models

    View Slide

  43. Queue API

    View Slide

  44. job = MyJob.new
    Rails.queue.push(job)
    class MyJob
    def run
    # do something
    end
    end
    Define job
    Enqueue it
    Job class
    must have only
    run method

    View Slide

  45. Default queue is synchronous
    # To use async queue
    config.queue = ActiveSupport::Queue.new

    View Slide

  46. “The basic queue that comes with Rails is
    not a long-term solution. The goal here is to
    establish a common API that more robust
    queueing systems can plug themselves into.
    In most cases you shouldn't need to change
    any of your app code if you want to switch
    from Resque toSidekiq. You should take
    care that the objects you are enqueing can
    be properly marshalled.”
    http://reefpoints.dockyard.com/ruby/2012/06/25/rails-4-sneak-peek-queueing.html
    Rails 4.0 Sneak Peek: Queueing

    View Slide

  47. ActionController::Live

    View Slide

  48. class MyController < ActionController::Base
    include ActionController::Live
    def index
    100.times {
    response.stream.write "hello world\n"
    }
    response.stream.close
    end
    end
    Live streaming

    View Slide

  49. Works fine with “Server-Sent Events”
    “This specification defines an API for
    opening an HTTP connection for receiving
    push notifications from a server in the
    form of DOM events. The API is designed
    such that it can be extended to work with
    other push notification schemes such as
    Push SMS.”
    http://www.w3.org/TR/eventsource/
    W3C: Server-Sent Events

    View Slide

  50. “I thought streaming was already introduced
    in Rails 3.2. How is this different?
    Yes, streaming templates were added to
    Rails 3.2. The main difference between Live
    Streaming and Streaming Templates is that
    with Streaming Template, the application
    developer could not choose what data was
    sent to the client and when. Live Streaming
    gives the application developer full control
    of what data is sent to the client and when.”
    http://tenderlovemaking.com/2012/07/30/is-it-live.html
    IS IT LIVE?

    View Slide

  51. See my chat example using SSE
    for detailed usage of Queue API
    and ActionController::Live
    https://github.com/kentaro/rails4-chat

    View Slide

  52. DEMO
    https://github.com/kentaro/rails4-chat

    View Slide

  53. View Slide

  54. config.allow_concurrency = true
    config.preload_frameworks = true
    # Same as calling `config.threadsafe!`,
    # but it’ll be deprecated from Rails4
    config.cache_classes = true
    config.eager_load = true
    Allow parallel requests
    # Gemfile
    gem ‘puma’
    $ bundle exec puma

    View Slide

  55. RECAP
    • Living on the Edge Rails is
    fun and good lesson
    • Rails4 is really promising
    and exciting
    • Try Rails4 as soon as
    possible!
    • I’m wating for your commit
    to Triglav ;)

    View Slide

  56. Any Questions?

    View Slide