Bruce Scharlau, University of Aberdeen, 2017 Advanced Web Application Development Ruby on Rails – A walk through an app Bruce Scharlau, University of Aberdeen, 2017
What do we know about Rails? Discuss with your neighbour what you like about Rails Bruce Scharlau, University of Aberdeen, 2017
Bruce Scharlau, University of Aberdeen, 2017 About This Lecture Form ~40 minutes lectures Question time Learning Material The Hartl Book Agile Web Development with Rails Chapters 1~6 Bruce Scharlau, University of Aberdeen, 2017
Bruce Scharlau, University of Aberdeen, 2017 What is Rails Ruby on Rails (or Rails, RoR) open source Ruby framework developing database-backed web applications Rail's guiding principles: less software faster development easier to understand, maintain, and enhance convention over configuration Less software means you write fewer lines of code to implement your application. Keeping your code small means faster development and fewer bugs, which makes your code easier to understand, maintain, and enhance. Very shortly, you will see how Rails cuts your code burden. Convention over configuration means an end to verbose XML configuration files--there aren't any in Rails! Instead of configuration files, a Rails application uses a few simple programming conventions that allow it to figure out everything through reflection and discovery. Your application code and your running database already contain everything that Rails needs to know! Bruce Scharlau, University of Aberdeen, 2017
There are many benefits to Rails Best Technologies MVC: Model View Controller Convention over Configuration DRY: Don’t Repeat Yourself REST: Representational State Transfer TDD: Test Driven Development Continuous and Active Development Version 1.0 in 2005 (We started teaching it in 2006) Helpful Online Communities Bruce Scharlau, University of Aberdeen, 2017
Bruce Scharlau, University of Aberdeen, 2017 First Touch with Rails Create a new application Rails new story Generate a controller (and its view) Rails generate controller story index app/controllers/story_controller.rb app/view/story/index.html.erb Bruce Scharlau, University of Aberdeen, 2017
Rails ‘new’ command creates app rails new cookbook generates a complete directory tree of folders and files for an empty Rails application Create models of the objects in the database, and Controllers which determine what happens in the application Bruce Scharlau, University of Aberdeen, 2017
Creates standard directory structure controllers subdirectory where Rails looks to find controller classes views subdirectory holds the display templates to fill in with data models subdirectory holds the classes that model and wrap the data helpers subdirectory holds any helper classes used to assist the model, view, and controller classes Create models of the objects in the database, and Controllers which determine what happens in the application Bruce Scharlau, University of Aberdeen, 2017
Start the built in web server rails server http://127.0.0.1:3000 Each application has built-in development server for using in the app that sits under app/script/server just call it with ‘ruby script/server’ and it starts up on port 3000 Bruce Scharlau, University of Aberdeen, 2017
Bruce Scharlau, University of Aberdeen, 2017 MVC is a design pattern Model represents the data in the program and business logic View (templates) manages the visual display of the data (Presentation Logic) Controller provides the means for user interaction with the data (application logic) Model View Controller Bruce Scharlau, University of Aberdeen, 2017
Bruce Scharlau, University of Aberdeen, 2017 MVC eases development Scalability (the ability for an application to grow) separate the database from other components Easier maintenance components have a low dependency on each other Reuse a model may be reused by multiple views, and vice versa Model View Controller Bruce Scharlau, University of Aberdeen, 2017
A Rails request uses MVC Browser Model Controller View The browser sends a request for a page to the controller on the server. The controller retrieves the data it needs from the model in order to respond to the request. The controller renders the data and sends it to the view. The view sends the page back to the client for the browser to display. Bruce Scharlau, University of Aberdeen, 2017
Add controllers for the logic rails generate controller story index Provides a class to direct requests and responses Convention: The folder that stores the template is named after the controller File Generated: app/controllers/story_controller.rb app/view/story/index.html.erb Bruce Scharlau, University of Aberdeen, 2017
We could put everything in the story/index view <blockquote>In a(n) <%=Faker::Hipster.word %> <%= Faker::Job.field %> a young <%= Faker::Hobbit.character %> stumbles across a(n) <%= Faker::Lovecraft.tome %> which spurs him into conflict with <%= Faker::StarTrek.villain %> and her <%= Faker::Hacker.noun %> culminating in <%= Faker::Pokemon.move %> where someone shouts '<%= Faker::Simpsons.quote %>' .</blockquote> Bruce Scharlau, University of Aberdeen, 2017
This works but has issues What problems are there if we do everything in the view? Bruce Scharlau, University of Aberdeen, 2017
Keep domain logic out of views The view is there to support the presentation of the model. Any Ruby code should be in the model, a helper, or in the controller. Bruce Scharlau, University of Aberdeen, 2017
StoryController has index method Request: http://127.0.0.1:3000/story/index StoryController is a class index is a method, or an action, which returns @story variable Convention: An html template (view) has a one-to-one mapping to the method of a controller Bruce Scharlau, University of Aberdeen, 2017
Story ‘index’ View is simple app/views/say/index.html.erb: <h1>Tell me a story...</h1> <p>Refresh the page for a new story</p> <blockquote><%= @story %></blockquote> Bruce Scharlau, University of Aberdeen, 2017
Understand index.html.erb <h1>Tell me a story...</h1> <p>Refresh the page for a new story</p> <blockquote> <%= @story %> </blockquote> Convention: html.erb is the extension of standard HTML template that allows ERB tags <%=…%>: this ERB tag pair is for displaying the output of the Ruby expression @story Bruce Scharlau, University of Aberdeen, 2017
The other story/index syntax <blockquote>In a(n) <%=Faker::Hipster.word %> <%= Faker::Job.field %> a young <%= Faker::Hobbit.character %> stumbles across a(n) <%= Faker::Lovecraft.tome %> which spurs him into conflict with <%= Faker::StarTrek.villain %> and her <%= Faker::Hacker.noun %> culminating in <%= Faker::Pokemon.move %> where someone shouts '<%= Faker::Simpsons.quote %>' .</blockquote> The <%= somevalue %> syntax lets us display the value in the view The alternative #{Faker::Pokemon.move} is for when you want the value inside a string Bruce Scharlau, University of Aberdeen, 2017
The story is displayed very simply Request: http://127.0.0.1:3000/story/index Bruce Scharlau, University of Aberdeen, 2017
Why is it better to generate the story in the controller? Discuss with the person next to you why it’s better to generate the story in the controller Bruce Scharlau, University of Aberdeen, 2017
Routes handles the URL matching User request http://127.0.0.1:3000/story/index In config/routes.rb get "story/index” shorthand for the following code: match ‘story/index’ => ‘story#index’ via => :get More details about Rails routing http://guides.rubyonrails.org/routing.html Try “rake routes” in the command line to see all routing information for an application Bruce Scharlau, University of Aberdeen, 2017
What about controllers with models? Discuss with the person next to you what controllers might do that work with models and views. What will the controller do automatically for you? Bruce Scharlau, University of Aberdeen, 2017
Controllers for models are configured automatically Generate REST methods for you Private for ’create’ Bruce Scharlau, University of Aberdeen, 2017
Model generation is easy rails generate model Recipe name:string email:string Generate the following two files: db/migrate/2017xxxxx_create_recipes.rb app/models/recipe.rb Run the database migration by rake db:migrate Bruce Scharlau, University of Aberdeen, 2017
Views are generated for models Show.html.erb displays a single recipe Bruce Scharlau, University of Aberdeen, 2017
Views are generated for models _form.html.erb is for ‘new’ and ‘edit’ recipe files For loop gathers each attribute value of model Bruce Scharlau, University of Aberdeen, 2017
Views are generated for models index.html.erb is all recipe items For loop goes through each item in array Bruce Scharlau, University of Aberdeen, 2017
Databases use Migration rake db:migrate Rake is Ruby make, a make-like language written in Ruby for performing tasks Rails comes with built-in support for SQLite3 SQLite3 is a lightweight serverless database application for development Rails can support other database system too Bruce Scharlau, University of Aberdeen, 2017
Database Configurations config/database.yml YML: lightweight format used in Rails for configuration development: adapter: sqlite3 database: db/development.sqlite3 timeout: 5000 test: database: db/test.sqlite3 timeout: 5000 production: database: db/production.sqlite3 timeout: 5000 If you use sqlite3, you don’t need to do anything, everything is already configured. Bruce Scharlau, University of Aberdeen, 2017
The Model file can be basic class Recipe < ApplicationRecord end In a controller, you can use: Recipe.all retrieve all recipies Recipe.find_by_name(XXXX) retrieve a recipe whose name is XXXX Bruce Scharlau, University of Aberdeen, 2017
Scaffolding generates MVC rails generate scaffold recipe title:string description:string date:date instructions:text Bruce Scharlau, University of Aberdeen, 2017
Explore Views built-in helpers <%= text_area_tag(:message, "Hi, nice site", size: "24x6") %> <%= password_field_tag(:password) %> <%= hidden_field_tag(:parent_id, "5") %> <%= search_field(:user, :name) %> <%= telephone_field(:user, :phone) %> <%= date_field(:user, :born_on) %> <%= datetime_local_field(:user, :graduation_day) %> <%= month_field(:user, :birthday_month) %> <%= week_field(:user, :birthday_week) %> <%= url_field(:user, :homepage) %> <%= email_field(:user, :address) %> <%= color_field(:user, :favorite_color) %> <%= time_field(:task, :started_at) %> <%= number_field(:product, :price, in: 1.0..20.0, step: 0.5) %> <%= range_field(:product, :discount, in: 1..100) %> http://guides.rubyonrails.org/form_helpers.html Bruce Scharlau, University of Aberdeen, 2017
Form_for binds form to object http://guides.rubyonrails.org/form_helpers.html Bruce Scharlau, University of Aberdeen, 2017
Use ‘form_tag’ for regular forms This is not tied to a model, so can gather data as required. Bruce Scharlau, University of Aberdeen, 2017
Parameters are passed as array Bruce Scharlau, University of Aberdeen, 2017
Use drop-down lists, etc as needed We covered these in early practical sessions Collection_select Collection_radio_buttons http://homepages.abdn.ac.uk/b.scharlau/pages/teaching/CS5550/practicals/practical-2-rails-start-travelagent.shtml Bruce Scharlau, University of Aberdeen, 2017
Rails API pages offer options Use API to find more options and details about how to use views http://api.rubyonrails.org Bruce Scharlau, University of Aberdeen, 2017
Layouts are to be rendered You can render the expected view by default. You can also change the rendered view. Instead of ‘show’ you could use ‘edit’ or something else as required. Bruce Scharlau, University of Aberdeen, 2017
Render only headers if required Pick option as needed to display result http://guides.rubyonrails.org/layouts_and_rendering.html Bruce Scharlau, University of Aberdeen, 2017
Render format as needed You don’t have to return HTML. render xml: @product render json: @product render html: "<strong>Not Found</strong>".html_safe render plain: “ok” render body: “raw” When and why would you use these? Bruce Scharlau, University of Aberdeen, 2017
Bruce Scharlau, University of Aberdeen, 2017 Summary Ruby on Rails offers quick development of data driven web applications Rails is based on MVC design pattern Bruce Scharlau, University of Aberdeen, 2017