- 浏览: 2550642 次
- 性别:
- 来自: 成都
文章分类
最新评论
-
nation:
你好,在部署Mesos+Spark的运行环境时,出现一个现象, ...
Spark(4)Deal with Mesos -
sillycat:
AMAZON Relatedhttps://www.godad ...
AMAZON API Gateway(2)Client Side SSL with NGINX -
sillycat:
sudo usermod -aG docker ec2-use ...
Docker and VirtualBox(1)Set up Shared Disk for Virtual Box -
sillycat:
Every Half an Hour30 * * * * /u ...
Build Home NAS(3)Data Redundancy -
sillycat:
3 List the Cron Job I Have>c ...
Build Home NAS(3)Data Redundancy
Rails Study(11)Action Controller Overviews - Cookies
5. Cookies
You application can store small amounts of data on the client ----cookies, that will be persisted across requests and even sessions.
class CommentsController < ApplicationController
def new
@comment = Comment.new(:name => cookies[:commenter_name])
end
def create
@comment = Comment.new(params[:comment])
if @comment.save
flash[:notice] = "Thanks for your comment!"
if params[:remember_name]
cookies[:commenter_name] = @comment.name
else
cookies-delete(:commenter_name)
end
redirect_to @comment.article
else
render :action => "new"
end
end
end
To delete a cookie value, we need to use cookies.delete(:key)
6 Rendering xml and json data
class UsersController < ApplicationController
def index
@users = User.all
respond_to do |format|
format.html
format.xml { renderml = > @users }
format.json { render json: @users }
end
end
end
Notice that in the above case code is renderml => @users and not renderml => @users.to_xml. That is because if the input is not string then rails automatically invokes to_xml.
7 Filters
Filters are methods that are run before, after or "around" a controller action.
Filters are inherited, so if you set a filter on ApplicationController, it will be run on every controller in your application.
A common before filter is one which requires that a user is logged in for an action to be run.
class ApplicationController < ActiveController::Base
before_filter :require_login
private
def require_logn
unless logged_in?
flash[:error] = "You must be logged in to access this section"
redirect_to new_login_url
end
end
def logged_in?
!!current_user
end
end
!! is to convert something into true or false.
If a before filter renders or redirects, the action will not run. If there are additional filters scheduled to run after that filter they are also cancelled.
You can prevent this filter from running before particular actions with skip_before_filter:
class LoginsController < ApplicationController
skip_before_filter :reqire_login,nly => [:new, :create]
end
Thenly option is used to only skip this filter for these actions, and there is also an :except option which works the other way.
7.1 After Filters and Around Filters
Obviousl, after filters can not stop the action from running.
7.2 Other Ways to Use Filters
Use a block directly with the *_filter methods. The block receives the controller as an argument, and the require_login filter from above could be rewritten to use a block:
class ApplicationController < ActionController::Base
before_filter do |controller|
redirect_to new_login_url unless controller.send(:logged_in?)
end
end
Note that the filter in this case uses send because the logged_in? method is private and the filter is not run in the scope of the controller.
Use a class to rewrite the login filter.
class ApplicationController < ActionControlller::Base
before_filter LoginFilter
end
class LoginFilter
def self.filter(controller)
unless controller.send(:logged_in?)
controller.flash[:error] = "you must be logged in"
controller.redirect_to controller.new_login_url
end
end
end
method will came after :, but class came after directly the *_filter keywords.
8. Verification
Verifications make sure certain criteria are met in order for a controller or action to run. They can specify that a certain key(or several keys i the form of an array) is present in the params, session or flash hashes or that a certain HTTP method was used or that the request was make using XMLHttpRequest(AJAX).
The default action taken when these criteria are not met is to render a 400 Bad Request response.
class LoginsController < ApplicationController
verify :params => [:username, :password],
:render => {:action => "new"},
:add_flash => {
:error => "Username and password required to log in"
}
def create
@user = User.authenticate(params[:username], params[:password])
if @user
flash[:notice] = "you're logged in"
redirect_to root_url
else
render :action => "new"
end
end
end
There is something rather import missing from the verification above:It will be used for every action in LoginsController, which is not what we want. You can limit which actions it will be used for with thenly and :except options just like a filter.
class LoginsController < ApplicationController
verify :params => [:username, :password],
:render => {:action => "new"},
:add_flash => {
:error => "username and password required to log in"
},
nly => :create
end
9 Request Forgery Protection
Cross-site request forgery is a type of attack in which a site tricks a user into making requests on another site.
1. make sure all "desructive" actions (create, update and destroy) can only be accessed with non-GET requests.
2. Add a non-guessable token which is only known to your server to each request. If a request comes in without the proper token, it will be denied access.
erb forms as follow:
<%= form_for @user do |f| %>
<%= f.text_field :username %>
<%= f.text_field :password %>
<% end %>
I got this in my form
<input name="authenticity_token" type="hidden" value="CKcVLfMFYxIEwOzEUMg4DK5VAY43Li/LhoQKypela70=" />
This is available through the method form_authenticity_token.
10. The Request and Response Objects
10.1 The request Object
There are some properties of request object.
host ------------------The hostname used for this request
domain(n=2)-------
format ---------------The content type requested by the client
method--------------
get?, post?, put?, delete?,head?
-------------------------Returns true if the HTTP method is GET/POST/PUT/DELETE/HEAD
headers--------------
port-------------------
protocol-------------Returns a string containing the protocol used plus "://", for example "http://"
query_string-------
remote_ip --------- The IP address of the client
url -------------------- The entire URL used for the request.
10.1.1 path_parameters, query_parameters, and request_parameters
10.2 The response Object
Properties of response
body ------------- This is the string of data being sent back to the client.
status ------------ The HTTP status code for the response, like 200 for a successful request or 404 for file not found.
location ---------- The URL the client is being redirected to, if any
content_type--- The content type of the response
charset ----------- The character set being used for the response. Default is "utf-8".
headers ----------
10.2.1 Setting Custom Headers
response.headers["Content-Type"] = "application/pdf"
11 HTTP Authentications
Rails comes with two built-in HTTP authentication mechanisms:
Basic Authentication
Digest Authentication
11.1 HTTP Basic Authentication
In my sample project, I have the experiences
before_filter :authenticate, :except => [:index, :show]
before_filter :authenticate,nly => :destroy
And authenticate in my ApplicationController
private
def authenticate
authenticate_or_request_with_http_basic do |user_name, password|
user_name == 'admin' && password == 'password'
end
end
Certainly, we can try to encode the password Digest::SHA1.hexdigest(password).
11.2 HTTP Digest Authentication
USERS = { "life" => "world" }
authenticate_or_request_with_http_digest do |username|
USERS[username]
end
12 Streaming and File Downloads
Sometimes we want to send a file instead of rendering an HTML page.
send_file is a convennience method that lets you provide the name of a file on the disk.
To stream data to the client, use send_data.
require "prawn"
class ClientsController < ApplicationController
def download_pdf
client = Client.find(params[:id])
send_data generate_pdf(client),
:filename => "#{client.name}.pdf",
:type => "application/pdf"
end
private
def generate_pdf(client)
Prawn::Document.new do
text client.name, :align => :center
text "Address: #{client.address}"
text "Email: #{client.email}}"
end.render
end
end
The download_pdf action above will generate the PDF document and returns it as a string. This string will then be streamed to the client as a file download and a filename will be suggested to the user.
12.1 Sending Files
Use send_file method to send a file that already exists on disk.
class ClientsController < ApplicationController
def download_pdf
client = Client.find(params[:id])
send_file("#{Rails.root}/files/clients/#{client.id}.pdf",
:filename => "#{client.name}.pdf",
:type => "application/pdf")
end
end
12.2 RESTful Downloads
class ClientsController < ApplicationController
def show
@client = Client.find(params[:id])
respond_to do |format|
format.html
format.pdf { render :pdf => generate_pdf(@client) }
end
end
end
In order to make this work, we need to add the PDF MIME type of Rails. This can be done by adding the following line to the file
config/initializers/mime_types.rb:
Mime::Type.register "application/pdf", :pdf
Notices, configuration files are not reloaded on each request, so we need to restart the server.
13 Parameter Filtering
14 Rescue
14.1 The Default 500 and 404 Templates
These HTML files are in the public folder, 404.html and 500.html.
14.2 rescue_from
references:
http://guides.rubyonrails.org/action_controller_overview.html
5. Cookies
You application can store small amounts of data on the client ----cookies, that will be persisted across requests and even sessions.
class CommentsController < ApplicationController
def new
@comment = Comment.new(:name => cookies[:commenter_name])
end
def create
@comment = Comment.new(params[:comment])
if @comment.save
flash[:notice] = "Thanks for your comment!"
if params[:remember_name]
cookies[:commenter_name] = @comment.name
else
cookies-delete(:commenter_name)
end
redirect_to @comment.article
else
render :action => "new"
end
end
end
To delete a cookie value, we need to use cookies.delete(:key)
6 Rendering xml and json data
class UsersController < ApplicationController
def index
@users = User.all
respond_to do |format|
format.html
format.xml { renderml = > @users }
format.json { render json: @users }
end
end
end
Notice that in the above case code is renderml => @users and not renderml => @users.to_xml. That is because if the input is not string then rails automatically invokes to_xml.
7 Filters
Filters are methods that are run before, after or "around" a controller action.
Filters are inherited, so if you set a filter on ApplicationController, it will be run on every controller in your application.
A common before filter is one which requires that a user is logged in for an action to be run.
class ApplicationController < ActiveController::Base
before_filter :require_login
private
def require_logn
unless logged_in?
flash[:error] = "You must be logged in to access this section"
redirect_to new_login_url
end
end
def logged_in?
!!current_user
end
end
!! is to convert something into true or false.
If a before filter renders or redirects, the action will not run. If there are additional filters scheduled to run after that filter they are also cancelled.
You can prevent this filter from running before particular actions with skip_before_filter:
class LoginsController < ApplicationController
skip_before_filter :reqire_login,nly => [:new, :create]
end
Thenly option is used to only skip this filter for these actions, and there is also an :except option which works the other way.
7.1 After Filters and Around Filters
Obviousl, after filters can not stop the action from running.
7.2 Other Ways to Use Filters
Use a block directly with the *_filter methods. The block receives the controller as an argument, and the require_login filter from above could be rewritten to use a block:
class ApplicationController < ActionController::Base
before_filter do |controller|
redirect_to new_login_url unless controller.send(:logged_in?)
end
end
Note that the filter in this case uses send because the logged_in? method is private and the filter is not run in the scope of the controller.
Use a class to rewrite the login filter.
class ApplicationController < ActionControlller::Base
before_filter LoginFilter
end
class LoginFilter
def self.filter(controller)
unless controller.send(:logged_in?)
controller.flash[:error] = "you must be logged in"
controller.redirect_to controller.new_login_url
end
end
end
method will came after :, but class came after directly the *_filter keywords.
8. Verification
Verifications make sure certain criteria are met in order for a controller or action to run. They can specify that a certain key(or several keys i the form of an array) is present in the params, session or flash hashes or that a certain HTTP method was used or that the request was make using XMLHttpRequest(AJAX).
The default action taken when these criteria are not met is to render a 400 Bad Request response.
class LoginsController < ApplicationController
verify :params => [:username, :password],
:render => {:action => "new"},
:add_flash => {
:error => "Username and password required to log in"
}
def create
@user = User.authenticate(params[:username], params[:password])
if @user
flash[:notice] = "you're logged in"
redirect_to root_url
else
render :action => "new"
end
end
end
There is something rather import missing from the verification above:It will be used for every action in LoginsController, which is not what we want. You can limit which actions it will be used for with thenly and :except options just like a filter.
class LoginsController < ApplicationController
verify :params => [:username, :password],
:render => {:action => "new"},
:add_flash => {
:error => "username and password required to log in"
},
nly => :create
end
9 Request Forgery Protection
Cross-site request forgery is a type of attack in which a site tricks a user into making requests on another site.
1. make sure all "desructive" actions (create, update and destroy) can only be accessed with non-GET requests.
2. Add a non-guessable token which is only known to your server to each request. If a request comes in without the proper token, it will be denied access.
erb forms as follow:
<%= form_for @user do |f| %>
<%= f.text_field :username %>
<%= f.text_field :password %>
<% end %>
I got this in my form
<input name="authenticity_token" type="hidden" value="CKcVLfMFYxIEwOzEUMg4DK5VAY43Li/LhoQKypela70=" />
This is available through the method form_authenticity_token.
10. The Request and Response Objects
10.1 The request Object
There are some properties of request object.
host ------------------The hostname used for this request
domain(n=2)-------
format ---------------The content type requested by the client
method--------------
get?, post?, put?, delete?,head?
-------------------------Returns true if the HTTP method is GET/POST/PUT/DELETE/HEAD
headers--------------
port-------------------
protocol-------------Returns a string containing the protocol used plus "://", for example "http://"
query_string-------
remote_ip --------- The IP address of the client
url -------------------- The entire URL used for the request.
10.1.1 path_parameters, query_parameters, and request_parameters
10.2 The response Object
Properties of response
body ------------- This is the string of data being sent back to the client.
status ------------ The HTTP status code for the response, like 200 for a successful request or 404 for file not found.
location ---------- The URL the client is being redirected to, if any
content_type--- The content type of the response
charset ----------- The character set being used for the response. Default is "utf-8".
headers ----------
10.2.1 Setting Custom Headers
response.headers["Content-Type"] = "application/pdf"
11 HTTP Authentications
Rails comes with two built-in HTTP authentication mechanisms:
Basic Authentication
Digest Authentication
11.1 HTTP Basic Authentication
In my sample project, I have the experiences
before_filter :authenticate, :except => [:index, :show]
before_filter :authenticate,nly => :destroy
And authenticate in my ApplicationController
private
def authenticate
authenticate_or_request_with_http_basic do |user_name, password|
user_name == 'admin' && password == 'password'
end
end
Certainly, we can try to encode the password Digest::SHA1.hexdigest(password).
11.2 HTTP Digest Authentication
USERS = { "life" => "world" }
authenticate_or_request_with_http_digest do |username|
USERS[username]
end
12 Streaming and File Downloads
Sometimes we want to send a file instead of rendering an HTML page.
send_file is a convennience method that lets you provide the name of a file on the disk.
To stream data to the client, use send_data.
require "prawn"
class ClientsController < ApplicationController
def download_pdf
client = Client.find(params[:id])
send_data generate_pdf(client),
:filename => "#{client.name}.pdf",
:type => "application/pdf"
end
private
def generate_pdf(client)
Prawn::Document.new do
text client.name, :align => :center
text "Address: #{client.address}"
text "Email: #{client.email}}"
end.render
end
end
The download_pdf action above will generate the PDF document and returns it as a string. This string will then be streamed to the client as a file download and a filename will be suggested to the user.
12.1 Sending Files
Use send_file method to send a file that already exists on disk.
class ClientsController < ApplicationController
def download_pdf
client = Client.find(params[:id])
send_file("#{Rails.root}/files/clients/#{client.id}.pdf",
:filename => "#{client.name}.pdf",
:type => "application/pdf")
end
end
12.2 RESTful Downloads
class ClientsController < ApplicationController
def show
@client = Client.find(params[:id])
respond_to do |format|
format.html
format.pdf { render :pdf => generate_pdf(@client) }
end
end
end
In order to make this work, we need to add the PDF MIME type of Rails. This can be done by adding the following line to the file
config/initializers/mime_types.rb:
Mime::Type.register "application/pdf", :pdf
Notices, configuration files are not reloaded on each request, so we need to restart the server.
13 Parameter Filtering
14 Rescue
14.1 The Default 500 and 404 Templates
These HTML files are in the public folder, 404.html and 500.html.
14.2 rescue_from
references:
http://guides.rubyonrails.org/action_controller_overview.html
发表评论
-
NodeJS12 and Zlib
2020-04-01 07:44 474NodeJS12 and Zlib It works as ... -
Traefik 2020(1)Introduction and Installation
2020-03-29 13:52 335Traefik 2020(1)Introduction and ... -
Private Registry 2020(1)No auth in registry Nginx AUTH for UI
2020-03-18 00:56 434Private Registry 2020(1)No auth ... -
Buffer in NodeJS 12 and NodeJS 8
2020-02-25 06:43 384Buffer in NodeJS 12 and NodeJS ... -
NodeJS ENV Similar to JENV and PyENV
2020-02-25 05:14 475NodeJS ENV Similar to JENV and ... -
Prometheus HA 2020(3)AlertManager Cluster
2020-02-24 01:47 421Prometheus HA 2020(3)AlertManag ... -
Serverless with NodeJS and TencentCloud 2020(5)CRON and Settings
2020-02-24 01:46 336Serverless with NodeJS and Tenc ... -
GraphQL 2019(3)Connect to MySQL
2020-02-24 01:48 246GraphQL 2019(3)Connect to MySQL ... -
GraphQL 2019(2)GraphQL and Deploy to Tencent Cloud
2020-02-24 01:48 450GraphQL 2019(2)GraphQL and Depl ... -
GraphQL 2019(1)Apollo Basic
2020-02-19 01:36 325GraphQL 2019(1)Apollo Basic Cl ... -
Serverless with NodeJS and TencentCloud 2020(4)Multiple Handlers and Running wit
2020-02-19 01:19 312Serverless with NodeJS and Tenc ... -
Serverless with NodeJS and TencentCloud 2020(3)Build Tree and Traverse Tree
2020-02-19 01:19 317Serverless with NodeJS and Tenc ... -
Serverless with NodeJS and TencentCloud 2020(2)Trigger SCF in SCF
2020-02-19 01:18 291Serverless with NodeJS and Tenc ... -
Serverless with NodeJS and TencentCloud 2020(1)Running with Component
2020-02-19 01:17 310Serverless with NodeJS and Tenc ... -
NodeJS MySQL Library and npmjs
2020-02-07 06:21 287NodeJS MySQL Library and npmjs ... -
Python Library 2019(1)requests and aiohttp
2019-12-18 01:12 261Python Library 2019(1)requests ... -
NodeJS Installation 2019
2019-10-20 02:57 572NodeJS Installation 2019 Insta ... -
Monitor Tool 2019(2)Monit on Multiple Instances and Email Alerts
2019-10-18 10:57 263Monitor Tool 2019(2)Monit on Mu ... -
Sqlite Database 2019(1)Sqlite3 Installation and Docker phpsqliteadmin
2019-09-05 11:24 368Sqlite Database 2019(1)Sqlite3 ... -
Supervisor 2019(2)Ubuntu and Multiple Services
2019-08-19 10:53 369Supervisor 2019(2)Ubuntu and Mu ...
相关推荐
rails new rspec-rails-cookies-bug --skip-action-mailer --skip-action-mailbox --skip-action-text --skip-active-record --skip-active-storage --skip-action-cable --skip-sprockets --skip-spring --skip-...
rails-ftw-v0.18-2.1.5-4.1.8.exe用于在windows环境下搭建readmine环境
rails-hackernews-reddit-producthunt-clone, 黑客 news/reddit/social 链接分享网站 用 Rails 构建 Rails 上的 Reddit-Hackernews-ProductHunt克隆演示 这是一个 readme.md的Ruby on Rails 应用程序,模仿了 Hacker...
2-94街机外星风格射击游戏源码On Rails Shooter Template 1.202-94街机外星风格射击游戏源码On Rails Shooter Template 1.202-94街机外星风格射击游戏源码On Rails Shooter Template 1.202-94街机外星风格射击游戏...
rails-documentation-2-0-2
标题 "rails-documentation-1-2-1.zip" 暗示这是一份关于 Ruby on Rails 框架的文档,版本为 1.2.1。Ruby 是一种面向对象的编程语言,而 Rails 是一个基于 Ruby 的开源 Web 应用程序框架,遵循 Model-View-...
### Rails 4 in Action, 第二版:关键知识点解析 #### 一、Rails 4简介与新特性 **Rails 4 in Action, 第二版** 是一本深入介绍Ruby on Rails框架的专业书籍。该书由Ryan Bigg、Yehuda Katz、Steve Klabnik和...
`rails-documentation-2-0-2.chm` 文件详细涵盖了这些概念,包含了关于Rails 2.0.2的API参考、教程和指南。通过仔细阅读和实践,开发者能够深入理解Rails的工作原理,并有效地开发出高效、可维护的Web应用。
rails-documentation-1-2-0-rc1.chm
gem 'rails-controller-testing' 然后执行: $ bundle 或将其自己安装为: $ gem install rails-controller-testing 规范 参见 。 从3.5.0版开始,rspec-rails会自动与该gem集成。 将gem添加到您的Gemfile就足够...
- 它包含了一系列内置的库和服务,如 Active Record(数据库操作)、Action Controller(路由和控制器)和 Action View(视图渲染)。 - Rails 提供了 RESTful 路由,使得构建 Web 服务更加简洁和直观。 - 使用 ...
《Rails 3 in Action》是2011年由Ryan Bigg撰写的一本关于Ruby on Rails框架的权威指南,专门针对当时最新的Rails 3.1版本进行了深入解析。这本书旨在帮助开发者充分利用Rails 3.1的强大功能,提升Web应用开发的效率...
路由系统与Rails的Action Controller紧密相连,Action Controller是Rails中负责处理HTTP请求并返回响应的MVC架构中的控制器部分。Action Controller提供了一组丰富的工具来帮助开发者构建强大的Web应用。例如,Rails...
在这个案例中,我们看到`jquery-ui-rails-4.2.1.gem`,这是该gem的一个特定版本。这个gem负责将jQuery UI的库文件打包并整合到Rails的asset pipeline中,使得在Rails项目中使用jQuery UI变得简单。 要使用`jquery-...
Ajax-Rails-4-AJAX-modal-form-render-JS-response-as-table-row.zip,rails 4 ajax模式表单将js响应呈现为表行,ajax代表异步javascript和xml。它是多种web技术的集合,包括html、css、json、xml和javascript。它用于...
官方离线安装包,测试可用。使用rpm -ivh [rpm完整包名] 进行安装
Ruby on Rails,简称Rails,是基于Ruby语言的一个开源Web应用程序框架,它遵循MVC(Model-View-Controller)架构模式,旨在使Web开发过程更加高效、简洁。本压缩包中的"Ruby on Rails入门经典代码"提供了新手学习...
本文将深入探讨"rails-react-components-源码.rar"中的关键知识点,帮助开发者理解如何在Rails应用中集成React组件。 1. **React组件化开发** React的核心概念是组件,它允许我们将UI拆分为独立、可重用的部分。在...