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

13 Razões para Você Estudar o Rails 5.1

13 Razões para Você Estudar o Rails 5.1

Apresentação de alguma novidades do Ruby on Rails 5.1

Luiz Carlos

April 27, 2017
Tweet

Other Decks in Programming

Transcript

  1. #1

  2. Webpacker intro • rails/webpacker: suporte opcional (--webpacker) • module bundler:

    entry, output, loaders, plugins • Compila JS • Facilita a organização e modularização do JS • Suporte ao react, angular e vue
  3. Webpacker demo $ rails new app_name --web packer # gem

    'webpacker', github: 'rails/webpacker' $ bundle $ rails webpacker:install # config/webpack/ $ rails webpacker:install # app/javascript
  4. Webpacker demo # app/javascript/packs/application.js console.log('Hello World from Webpacker') # app/javascript/packs/application.scss

    # app/views/layouts/application.html.erb <%= javascript_pack_tag 'application' %> <%= stylesheet_pack_tag 'application' %> # loading webpack $ bin/webpack-dev-server
  5. Webpacker es6 modules # app/javascript/packs/util.js const range = (start, end)

    => Array.from({length: (end - start)}, (v, k) => k + start) export { range } // module.exports = range # app/javascript/packs/application.js import {range} from './util' // const range = require(‘./util') console.log(range(1, 5))
  6. #2

  7. Webpacker vue $ rails new myapp --webpack=vue $ rails webpacker:install:vue

    #(react|angular|vue) // config/webpack/paths.yml // config/webpack/loaders/vue.js // app/javascript/packs/hello_vue.js // app/javascript/packs/app.vue // bin/yarn add vue vue-loader vue-template-compiler # loading webpack $ bin/webpack-dev-server
  8. Webpacker vue # app/javascript/packs/app.vue <template> <div id="app"><p>{{ message }}</p></div> </template>

    <script> module.exports = { data: () => {message: "Hello Vue!"} } </script> <style scoped> p { font-size: 2em; text-align: center; } </style>
  9. Webpacker vue # app/javascript/packs/hello_vue.js import Vue from 'vue/dist/vue.esm' import App

    from './app.vue' document.addEventListener('DOMContentLoaded', () => { document.body.appendChild( document.createElement('hello')) const app = new Vue({ el: 'hello', template: ‘<App/>', components: { App } }) console.log(app) })
  10. Webpacker vue // <%= javascript_pack_tag 'hello_vue' %> // to the

    head of your layout file, // like app/views/layouts/application.html.erb. <%= javascript_pack_tag 'hello_vue' %> <div data-v-2ed65b34="" id="app"> <p data-v-2ed65b34="">Hello Vue!</p> </div>
  11. #3

  12. Yarn • Default no 5.1 (--yarn) • Gerenciador de Pacote

    (node_modules) • Gerencia dependências • Segurança • Download eficiente • Pacotes controlados por package.json
  13. Yarn assets pipeline # package.json add font-awesome $ bin/yarn add

    font-awesome # config/initializers/assets.rb Rails.application.config.assets.paths << Rails.root.join('node_modules') # app/assets/stylesheets/application.scss *= require font-awesome/scss/font-awesome # alguma view I <i class="fa fa-heart" aria-hidden="true"></i> Ruby
  14. Yarn assets pipeline # package.json add font-awesome $ bin/yarn add

    jquery bootstrap # app/assets/stylesheets/application.scss *= require bootstrap/dist/css/bootstrap # app/assets/javascripts/application.js //= require jquery/dist/jquery //= require bootstrap/dist/js/bootstrap # alguma view I <span class="glyphicon glyphicon-heart" aria- hidden="true"></span> Ruby
  15. Yarn webpacker $ bin/yarn add lodash # app/javascript/packs/application.js import fp

    from 'lodash/fp' const _ = fp() console.log(_.range(1, 5)) # app/assets/javascripts/application.js document.addEventListener( 'turbolinks:load', () => console.log(_.range(1, 10)) )
  16. jQuery Rails # Gemfile gem 'jquery-rails' # app/assets/javascripts/application.js //= require

    jquery //= require jquery_ujs # app/assets/javascripts/application.js //= require rails-ujs 5.0 5.1
  17. #5

  18. Integration Test 5.0 # Gemfile group :development, :test do gem

    'capybara' gem 'selenium-webdriver' end # test/test_helper.rb require 'capybara/rails' require 'capybara/minitest' […]
  19. Integration Test 5.0 # test/test_helper class ActionDispatch::IntegrationTest include Capybara::DSL include

    Capybara::Minitest::Assertions Capybara.register_driver :selenium do |app| Cappybara::Selenium::Driver.new app, browser: :chrome end Capybara.default_driver = :selenium end
  20. Integration Test 5.0 # test/integration/welcome_controlers_test.rb require "test_helper" class WelcomeControlersTest <

    ActionDispatch::IntegrationTest test "visiting the index" do visit welcome_index_url assert_selector "h1", text: "Welcome" end end $ rails test:integration #1 runs, 0 assertions, 0 fail…
  21. System Test 5.1 • ActionDipatch::SystemTestCase • Simplicidade com Capybara •

    Default: selenium driver e chrome browser • Não executa por default, use bin/rails test:system • ScreenshotHelper (tmp/screenshots/): take_screenshot e take_failed_screenshot
  22. System Test 5.1 $ rails g system_test WelcomeControler # test/system/welcome_controlers_test.rb

    require "test_helper" class ApplicationSystemTestCase < ActionDispatch::SystemTestCase driven_by :selenium, using: :chrome, screen_size: [1400, 1400] end
  23. System Test 5.1 $ rails g system_test WelcomeControler # test/system/welcome_controlers_test.rb

    require "test_helper" class ApplicationSystemTestCase < ActionDispatch::SystemTestCase driven_by :selenium, using: :firefox end
  24. System Test 5.1 $ rails g system_test WelcomeControler # test/system/welcome_controlers_test.rb

    require "test_helper" require "capybara/poltergeist" class ApplicationSystemTestCase < ActionDispatch::SystemTestCase driven_by :poltergeist end
  25. System Test 5.1 # test/system/welcome_controlers_test.rb require "application_system_test_case" class WelcomeControlersTest <

    ApplicationSystemTestCase test "visiting the index" do visit welcome_index_url assert_selector "h1", text: "Welcome" end end # executando test de sistema $ rails test:system # 1 runs, 0 assertions, 0 failures
  26. Compartilha Chaves # config/secrets.yml default: &default api_key: xyz production: <<:

    *default secret_key_base: <%= ENV["SECRET_KEY_BASE"] %> $ export SECRET_KEY_BASE=abc $ rails console production > Rails.application.secrets #=> {:secret_key_base => "abc", :api_key => "xyz"} > Rails.application.secrets.secret_key_base #=> "abc" > ENV["SECRET_KEY_BASE"] #=> “abc"
  27. Compartilha Chaves # config/secrets.yml shared: api_key: xyz development: secret_key_base: abc

    test: secret_key_base: abc production: secret_key_base: <%= ENV["SECRET_KEY_BASE"] %> $ rails console production > Rails.application.secrets.api_key #=> "xyz"
  28. Dados Encriptados $ bin/rails secrets:setup # config/secrets.yml.key (.gitigone) # config/secrets.yml.enc

    # RAILS_MASTER_KEY $ more config/secrets.yml.enc $ EDITOR=nano bin/rails secrets:edit # See `secrets.yml` for tips on generating suitable keys production: external_api_key: 1466aac22e6a869134be3d2892c232332…
  29. Email Parametrizado 5.0 # app/mailers/user_mailer.rb class UserMailer < ApplicationMailer default

    from: "[email protected]" def welcome(email) @email = email mail to: @email, subject: "Welcome to Example." end end $ bin/rails console > UserMailer.welcome("[email protected]").deliver_later
  30. Email Parametrizado 5.1 # app/mailers/user_mailer.rb class UserMailer < ApplicationMailer before_action

    { @email = params[:email] } default to: -> { @email }, from: -> { "[email protected]" } def welcome mail subject: "Welcome to Example." end end $ bin/rails console > UserMailer.with(email: "[email protected]") .welcome.deliver_later
  31. Direct Routes direct(:home) { "http://rubyonrails.org" } <%= link_to "rubyonrails", home_url

    %> #=> <a href="http://rubyonrails.org">rubyonrails</a> <%= link_to "Comment", comment_path(@article, anchor: "comment") %> direct :comment do |model| [model, anchor: "comment"] end <%= link_to "Comment", comment_path(@article) %> #=> <a href="/article/1#comment">Coment</a>
  32. Direct Routes direct :current_users do { action: "index", controller: "users",

    active: true } end <%= link_to "Current users", current_users_path %> #=> <a href="/users?active=true">Current users</a>
  33. Direct Routes direct :browse, page: 1, page_size: 10 do |klass,

    options| [ klass, options ] end <%= link_to "users", browse_path(:users) %> #=><a href="/users?page=1&page_size=10">Browse users</a> <%= link_to "users", browse_path(:users, page: 2) %> #=><a href="/users?page=2&page_size=10">Browse users</a>
  34. Resolve Routes resource :profile resolve("User") { [:profile] } <%= link_to

    @user.name, @user %> <%= link_to @user.name, polymorphic_path(@user) %> #=> <a href="/profile">Sample user</a>
  35. form_with # app/views/posts/show.html.erb <%= form_for @post, method: :delete do |f|

    %> <%= f.submit 'Delete post' %> <% end %> # app/views/posts/show.html.erb <%= form_with model: @post, method: :delete do |f| %> <%= f.submit 'Delete post' %> <% end %> 5.0 5.1
  36. form_with # app/views/posts/index.html.erb <%= form_tag '/post/1', method: :delete do |f|

    %> <%= submit_tag 'Delete post #1' %> <% end %> # app/views/posts/index.html.erb <%= form_with url: '/post/1', method: :delete do |f| %> <%= submit_tag 'Delete post #1' %> <% end %> 5.0 5.1
  37. Tag Helper tag(:br, nil, true) <%= content_tag(:div, contant_tag(:p, 'Hello World!'),

    class: 'strong') %> <%= content_tag :div, class: 'strong' do %> Hello world! <% end %> <%= tag.br %> <%= tag.div tag.p('Hello World!'), class: 'strong' %> <%= tag.div class: 'strong' do %> Hello world! <% end %> 5.0 5.1
  38. Custom Hashes data = { 'user' => { 'name' =>

    'Fulano', 'metadata' => { 'phone' => '99999999', 'email' => '[email protected]' } } } params = ActionController::Parameters.new(data) params.require(:user).permit(:name, metadata: {}) # => {‘name' => 'Fulano', 'metadata' => {'phone' => '99999999', 'email' => '[email protected]'}}
  39. Limite em Lote Post.limit(500).find_each.map(&:title) # => Post Load (0.2) SELECT

    "posts".* FROM "posts" ORDER BY "posts"."id" ASC LIMIT ? [["LIMIT", 1000]] Post.limit(500).find_each.map(&:title) # => Post Load (0.2) SELECT "posts".* FROM "posts" ORDER BY "posts"."id" ASC LIMIT ? [["LIMIT", 500]] 5.0 5.1
  40. Referências Rails 5.1: upcoming features - Claudio B. Rails 5.1

    - Yves Senn Ruby on Rails 5.1 Release Notes - Rails Rails 5.1.0.rc2: Loving JavaScript, System Tests, Encrypted Secrets, and more Ruby on Rails 5.1.0 Changes and New Features - Dave Kimura What’s new in Rails 5.1 - Mario Alberto Chávez