CS计算机代考程序代写 SQL angularjs jquery Java database javascript Rapid Application Development

Rapid Application Development
COSC2675 2021 Week 5 ( Rails )
A/Prof. Andy Song andy.song@rmit.edu.au
IMPORTANT: we assume you know
• Basic programming skill
− variables, operators, loops, if, functions …
• Basic Object Oriented concepts − class, object, methods, inheritance …
• Basic database knowledge
− sql queries, keys, tables, 1:1, 1:n relations …
• Basic web development knowledge − HTML, CSS, JS, HTTP requests, form …
• Basic Unix skill
− command line, arguments, path, env …

Why RAD uses Ruby on Rails?
A/Prof. Andy Song RMIT University 2021
3
What is Ruby on Rails? A Framework
A/Prof. Andy Song RMIT University 2021
4

Rails
• Developed by David Heinemeier Hansson (DHH), a Danish programmer, racing car driver
• AprojectforBasecamp
• Released in 2005
• ShippedasapartofMacOSX10.5Leopard2007
• Templates,engines,Rack,nestedmodelformsin2009
• Reversible DB migrations, asset pipeline, jQuery 2011
• Rails 5.0 released on 30th June, 2016
• Rails 6.0 released on 16th August 2019
• Current version 6.1.3 ( March 2021)
A/Prof. Andy Song RMIT University 2021
5
Rails 5
• Oldbutfineforthiscourse,releasedinAugust2016.
• A major update
− Action Cable (Server changed from WEBRick to Puma)
− Rails API, better connect to frameworks like Backbone, AngularJS, React
− New Turbolinks
− rake is replaced by rails
− Controller tests are now integration tests instead of unit tests. No
assigns()
− Asynchronous mail delivery, no more synchronous mail delivery
− belongs_to is required by default.
A/Prof. Andy Song RMIT University 2021
6

Rails 6
• Thisisthecurrentversion(firstreleasedinAugust2019). • Updates
− Multiple database support − Parallel testing
− Online rich-text editor
− Mailbox routing
− New autoloader
− Webpack as a default
A/Prof. Andy Song RMIT University 2021
7
Rails Simply Feels Right
• “Suddenly, along came Rails, and Rails was easier”
• You start with a working application.
• Thereisaplaceforeachpieceofcode.
• All the pieces interact in a standard way.
• Test is easy, so Rails applications tend to get tested.
• RailsiswritteninRuby.Rubyfeelsright.
• Writingcodefeelslikesettingconfigurations
• A single command to deploy. Roll back is also easy.
• Somehow,itfeelsright.
A/Prof. Andy Song RMIT University 2021
8

Rails is Agile
Share the values of the Agile Manifesto
• Individuals and interactions over process and tools
• Workingsoftwareovercomprehensivedocumentation • Customer collaboration over contract negotiation
• Respondingtochangeoverfollowingaplan
A/Prof. Andy Song RMIT University 2021
9
Rails is about Interaction
No heavy toolsets, no complex configurations, no elaborate processes.
What the developers do is reflected immediately in what the customer sees.
Rails development is not driven by documents, but by customer needs.
A team can deliver what is required, not what has been requested. Confrontations are replaced by “What if?” sessions.
A/Prof. Andy Song RMIT University 2021
10

Rails Learning Materials
• Tonsofmaterialsliterally
Version 4.0 is free, not 6.0
A/Prof. Andy Song RMIT University 2021
11
Rails Online Resources
• https://www.railstutorial.org/
• http://guides.rubyonrails.org/
• http://api.rubyonrails.org/
• https://www.tutorialspoint.com/ruby-on-rails/ • https://rubygems.org
• Ofcourse,stackoverflow.com
A/Prof. Andy Song RMIT University 2021
12

Rails Philosophy
Use MVC (Model –view-controller) pattern Convention over Configuration (CoC)
For a class Student in the model, create a table students by default. Don’t repeat yourself (DRY)
Information is located in a single place, e.g. using the class name to find the right column in the database.
Fat models, skinny controllers
The business logic should be inside of the models.
A/Prof. Andy Song RMIT University 2021
13
Technical Overview
• Amodel–mapstoadatabasetable+aRubyfile For Example, a model Student class
− Defined in a file app/models/student.rb
− Linked to the table students in the database
• A controller – responds to external requests, − determines which view is to be rendered
− may query models and pass the info the view
− may provide one or more actions.
• Acontroller/actionisonlyaccessibleifarouteismappedtoitin config/routes.rb
• RESTfulroutesareencouraged:create,new,edit,update, destroy, show and index.
A/Prof. Andy Song RMIT University 2021
14

Technical Overview…
• Aviewpresentsinfoandisusuallyinanerbfile. Erb files support Ruby code and generate HTML at run-time Templates can be used to generate views as well.
• Scaffolding–automaticallyconstructmodelsandviews
• Rake – Ruby make
• Puma, WEBRick – Ruby web server
• Support Unobtrusive Javascriptt – CoffeeScript
• Coming in various packages, e.g ActiveRecord, ActiveResource, Action Pack, Active Support, Action Mailer
• Typically deployed with MySQL or PostgreSQL database server. A/Prof. Andy Song RMIT University 2021
15
Rails Components
Docker
(Learning Rails 5, Mark Locklear Eric Gruber)
16
A/Prof. Andy Song RMIT University 2021

Create a hello application􏰀native Rails) $ rails new hello_app
Generated lots of folders and files
$ cd hello_app
$ rails generate controller hello index
New files created by calling various scripts:
A/Prof. Andy Song RMIT University 2021
17
Create a hello application (Docker)
In the docker rails image directory
$ docker-compose run web rails generate controller hello index
New files created by calling various scripts:
A/Prof. Andy Song RMIT University 2021
18

‘Set’ the hello application
• Update the route: config/route.rb get ‘hello/index’
get ‘hello’ => ‘hello#index’
• Update the view: app/views/hello/index.html.erb

Hello#index

Find me in app/views/hello/index.html.erb

<%= @message %>

From app/views/hello/index.html.erb

<%= @extra * @count %>

• Update the controller: app/controller/hello_controller.rb class HelloController < ApplicationController def index @message = “Hello!” @extra = “I am the hello controller! ” @count = 2 end end 19 A/Prof. Andy Song RMIT University 2021 View it in a browser • (Native) Launch the server by $ rails s –p $PORT -b $IP • (Docker) $docker-compose run web rails s A/Prof. Andy Song RMIT University 2021 20 How it works? (Learning Rails 5, Mark Locklear Eric Gruber) A/Prof. Andy Song RMIT University 2021 21 How it works (Learning Rails 5, Mark Locklear Eric Gruber) 22 A/Prof. Andy Song RMIT University 2021 Rails takes care of a lot of work • Listen to the request http://.../hello • Look at config/routes.rb to see the right route get ‘hello’ => ‘hello#index’
• Call hello_controller method index
• Find the right view with the same name under app/views
• Pass data from controller to the view
• Render the view as an HTML – via erb
• Send the HTML to the browser
• Continue listening…
You can see that the naming conventions play a critical role in Rails.
A/Prof. Andy Song RMIT University 2021
23
Work with Rails
• Docker gets you started with no, well, almost no, hassle.
• IDEisnotreallynecessary.Justatexteditorisfine. − Visual Studio Code
− Atom
− TextMate
− Sublime
− Aptana Studio
− RubyMine
− Notepad ++
− Vim, Emacs
− BBEdit, Coda, jEdit ……
A/Prof. Andy Song RMIT University 2021
24

Work with Rails …
• An editor window
• A browser window
• Aterminalwindow(commands+loggingfromtheapp)
• Maybe the Rails API documentation
• Acupofcoffee
• pretty much settled
A/Prof. Andy Song RMIT University 2021
25
Hello with style
• Let us open app/assets/stylesheets/application.css and add
body h1 {
{ font-family: sans-serif; } font-family: serif; font-size: 24pt; font-weight: bold;
color: #00F; }
• Add the above style sheet to app/assets/stylesheets/hello.scss
• Now you should see
A/Prof. Andy Song RMIT University 2021
26

How it works
See app/views/layouts/application.html.erb


HelloApp <%= csrf_meta_tags %>
<%= stylesheet_link_tag <%= javascript_include_tag
<%= yield %>

‘application’,
media: ‘all’, ‘data-turbolinks-track’: ‘reload’ %>
‘application’, ‘data-turbolinks-track’: ‘reload’ %>
A/Prof. Andy Song RMIT University 2021
27
How it works
<%= csrf_meta_tags %> Avoids cross-site request forgery (CSRF) <%= stylesheet_link_tag ... Setting the CSS styles <%= javascript_include_tag ... Setting the Javascript If we inspect the source of the hello page A/Prof. Andy Song RMIT University 2021 28 Wow, Rails did it all HelloApp








Hello!

….
A/Prof. Andy Song RMIT University 2021
29
Layout
• This layout is in app/views/layouts/application.html.erb
• The hello page is rendered by combining this and the hello view:
app/views/hello/index.html.erb
• The style sheets are pre-compiled into one master CSS
• hello.scssiscompiledashello.[…].css
• Itissharedforallviewsatthemoment.
• Thelayoutfileactsasthedefaultfortheentireapplication.
• Don’tRepeatYourself,DRY
• Onlycreateadifferentlayoutwhenitisactuallyneeded. A/Prof. Andy Song RMIT University 2021
30

Another layout
• Last example uses app/views/layouts/application.html.erb
• Becausethisnototherviewsforhello_controller
• Canwecreateoneforthehellocontroller?Ofcourse.
• Copy the erb above as app/views/layouts/hello.html.erb
• Add a mark in the body, so any webpage using this layout will have that mark on the top.
• hello.scssiscompiledashello.[…].css

(Rendered by hello layout)

<% = yield %>
A/Prof. Andy Song RMIT University 2021
31
Refresh the page
• You should see this now:
• That means the hello layout is in action.
• HowdidRailsknowwhichfiletoload?ThanksforCoC.
A/Prof. Andy Song RMIT University 2021
32

Specify a layout
• Suppose we have app/views/layouts/rad_layout.html.erb
• This is identical with application.html.erb except

Every RAD web page has this!

<% = yield %>
We can specify it in the controller
app/controllers/hello_controller.rb
class HelloController < ApplicationController layout "rad_layout” def index @message = "Hello!" [...] A/Prof. Andy Song RMIT University 2021 33 Using the specified layout • You should see this now: • Our rad_layout is in action. A/Prof. Andy Song RMIT University 2021 34 Add an image in the layout • Upload an image, say RubyOnRails.png, to assets/images • Update app/views/layouts/rad_layout.html.erb

Every RAD web page has this!

<%= image_tag("RubyOnRails.png", :alt => “RoR icon”) %> <% = yield %>

A/Prof. Andy Song RMIT University 2021
35
The layout method
• Thedocumentationoflayoutcanbeviewedhere: http://api.rubyonrails.org/classes/ActionView/Layouts.html


This method can do more:
layout “rad_layout”, except: :rss # not on RSS
layout “rad_layout”, except: [:rss, :xml, :text_only]
# not on RSS,XML pages and plain text. layout “rad_layout”, only: :html # only for HTML
It can take another method as its parameter so the layout can be dynamically determined.
A/Prof. Andy Song RMIT University 2021
36

Method for layout method
class HelloController < ApplicationController layout :admin_or_user def index ... end private def admin_or_user if admin_authenticated "admin_screen" else "user_screen" end end end A/Prof. Andy Song RMIT University 2021 37 Sharing template with layout • Alayoutcantakedatafromcontrollertemplates,soitcan accommodate dynamic info from the templates. That can be useful for status bar, navigation or showing process. • For example we can add in app/views/hello/index.html.erb

<%= @message %>

From app/views/hello/index.html.erb

<%= @extra * @count %>

<% content_for(:list) do %>

    <% @count.times do |i| %>

  1. <%= i.even? ? "Email Alex" : "Email Anto" %>
  2. <% end %>

<% end %>
A/Prof. Andy Song RMIT University 2021
38

Sharing template with layout…
Now add one line in app/views/layouts/rad_layout.html.erb

Every RAD web page has this!

<%= image_tag("RubyOnRails.png", :alt => “RoR icon”) %> <%= yield :list %>
<%= yield %>

You should see this:
A/Prof. Andy Song RMIT University 2021
39
Sharing template with layout…
A template is loaded first and combined with a layout later.
So info can be passed from a template to a layout but not from a layout to a template!
app/views/hello/index.html.erb <% content_for(:list) do %>
app/views/layouts/rad_layout.html.erb <%= yield :list %>
A/Prof. Andy Song RMIT University 2021
40

Action Pack
• We have introduced routing, controllers and views. These
are the functionalities of Action Pack, a core component of
Rails. The documentation is here:
http://api.rubyonrails.org/files/actionpack/README_rdoc.html
• Views – generating HTML (via ERB templates/layouts)
• Controllers – the logical center.
− Coordinating the interaction between users, views and “databases” − Routing external requests to internal actions, people-friendly URLs − Managing caching
− Managing helpers
− Managing sessions
A/Prof. Andy Song RMIT University 2021
41
Models
• Controllers are important, but don’t get too caught up in them. They are supposed to be skinny.
• ModelistheMofMVC,thefoundationofanapplication.
• Models are where all the persistent data is managed.
• Models can connect to databases through ORM (object- relational mapping).
• Rails’ ORM is Active Record
• Letusstartfromsomethingsimple-form
A/Prof. Andy Song RMIT University 2021
42

A guestbook using form
• Create a new application:
$ rails new guestbook
$ cd guestbook
$ rails generate controller entries sign_in
• Now we have a sign_in method in app/controllers/entries_controller.rb
• What will you see in browser, say https://….c9users.io/
• How about https://….c9users.io/entries or
https://….c9users.io/entries/sign_in
• Wehaven’tspecifiedtherouteforincomingrequestsyet. A/Prof. Andy Song RMIT University 2021
43
‘Set’ the guestbook application
• Update the route: config/route.rb
get ‘entries/sign_in’
get ‘entries/sign_in’ => ‘entries#sign_in’ post ‘entries/sign_in’ => ‘entries#sign_in’
• Update the view: app/views/entries/sign_in.html.erb

Hello <%= @name %>

<%= form_tag action: 'sign_in' do %>

Enter your name:
<%= text_field_tag 'visitor_name', @name %>

<%= submit_tag 'Sign in' %>
<% end %>
• Update the controller: app/controller/entries_controller.rb class EntriesController < ApplicationController def sign_in @name = params[:visitor_name] end end 44 A/Prof. Andy Song RMIT University 2021 View it in a browser • Launch the server by $ rails s –p $PORT -b $IP • Thecontrollerisnowreceivingdatafromtheuserand passing it to a view. A/Prof. Andy Song RMIT University 2021 45 How it works? (Learning Rails 5, Mark Locklear Eric Gruber) 46 A/Prof. Andy Song RMIT University 2021 Rails takes care of a lot of work • Listen to the request http://.../entries/sign_in • Look at config/routes.rb to see the right route get ‘entries/sign_in’ => ‘entries#sign_in’
• Call entries_controller method sign_in
• Render the view using files in app/views and show the form.
• Get data from the submitted form
post ‘entries/sign_in’ => ‘entries#sign_in’
• Re-display the form page and continue listening to requests
A/Prof. Andy Song RMIT University 2021
47
The form generated by Rails
Guestbook

Hello RAD


Enter your name:



48
A/Prof. Andy Song RMIT University 2021

Summary
• Rails introduction􏰀 history􏰀philosophy
• Technical overview
• Rails components
• The hello application
• Working with Rails
• View, Adding style sheets
• Understand layouts **􏰀 images, and the layout method
• Action Pack, Model, Controller
• Workingwithasimplewebform
A/Prof. Andy Song RMIT University 2021
49