王筝的博客
ruby学习

http://guides.rubyonrails.org/v3.0.8/action_controller_overview.html#the-flash

如何在页面显示controller里的错误提示,

The flash is a special part of the session which is cleared with each request.This means that values stored there will only be available in the next request,which is useful for storing error messages etc. It is accessed in much the same way as the session,ike a hash. Let’s use the act of logging out as an example. The controller can send a message which will be displayed to the user on the next request:

flash是session特殊的一部分,每次请求的时候都会被清除,这意味着存储的数据只有在下一次请求的过程中才有效.这一特性被广泛的应用于存储错误信息提示,获取它的方式与session近似,类似于哈希.让我们以退出为例子,controller发送的信息将在用户下次请求的时候展示出来.

class LoginsController < ApplicationController

  def destroy
    session[:current_user_id] = nil
    flash[:notice] = "You have successfully logged out"
    redirect_to root_url
  end
end
%11%
Note it is also possible to assign a flash message as part of the redirection.
注意:也可以在页面重定向的时候指定flash的信息
redirect_to root_url, :notice => "You have successfully logged out"
The destroy action redirects to the application’s root_url, where the message will be displayed. Note that it’s entirely up to the next action to decide what, if anything, it will do with what the previous action put in the flash. It’s conventional to display eventual errors or notices from the flash in the application’s layout:
注销登录的操作会使得页面重定向到根目录,这时候信息也会显示在页面上.这完全取决于下一步操作是什么,总之,上一次请求的信息将会被存入flash,通常将会把最终的错误信息或者提示信息展示到页面上.
<html>
  <!-- <head/> -->
  <body>
    <% if flash[:notice] %>
      <p class="notice"><%= flash[:notice] %></p>
    <% end %>
    <% if flash[:error] %>
      <p class="error"><%= flash[:error] %></p>
    <% end %>
    <!-- more content -->
  </body>
</html>

This way, if an action sets an error or a notice message, the layout will display it automatically.

通过这种方式, 如果操作过程中出现的错误提示或者通知,会自动的加载到页面上

If you want a flash value to be carried over to another request, use the keep method:

如果你想把提示信息带到其他请求中使用,使用keep方法

class MainController < ApplicationController
  # Let's say this action corresponds to root_url, but you want
  # all requests here to be redirected to UsersController#index.
  # If an action sets the flash and redirects here, the values
  # would normally be lost when another redirect happens, but you
  # can use 'keep' to make it persist for another request.
  def index
    # Will persist all flash values.
    flash.keep
    # You can also use a key to keep only some kind of value.
    # flash.keep(:notice)
    redirect_to users_url
  end
end

 

By default, adding values to the flash will make them available to the next request, but sometimes you may want to access those values in the same request. For example, if the create action fails to save a resource and you render the new template directly, that’s not going to result in a new request, but you may still want to display a message using the flash. To do this, you can useflash.now in the same way you use the normal flash:

默认状态下, flash里的值会在下一次请求的时候有效, 但是有的时候,你可能希望在同一个请求里使用这些值,比如新建的时候保存数据失败并跳转到一个新的页面里,flash不会出现在这个新的请求里.如果依然希望通过flash来显示错误信息,可以直接使用flash.now方法.

class ClientsController < ApplicationController
  def create
    @client = Client.new(params[:client])
    if @client.save
      # ...
    else
      flash.now[:error] = "Could not save client"
      render :action => "new"
    end
  end
end

 

form_tag(url_for_options = {}, options = {}, *parameters_for_url, &block)

Starts a form tag that points the action to an url configured with url_for_options just like ActionController::Base#url_for. The method for the form defaults to POST.

Options

  • :multipart – If set to true, the enctype is set to “multipart/form-data”.
  • :method – The method to use when submitting the form, usually either “get” or “post”. If “put”, “delete”, or another verb is used, a hidden input with name _method is added to simulate the verb over post.
  • A list of parameters to feed to the URL the form will be posted to.
  • :remote – If set to true, will allow the Unobtrusive JavaScript drivers to control the submit behaviour. By default this behaviour is an ajax submit.

Examples

 form_tag('/posts')
 # => <form action="/posts" method="post">

 form_tag('/posts/1', :method => :put)
 # => <form action="/posts/1" method="put">

 form_tag('/upload', :multipart => true)
 # => <form action="/upload" method="post" enctype="multipart/form-data">

 <%= form_tag('/posts') do -%>
   <div><%= submit_tag 'Save' %></div>
 <% end -%>
 # => <form action="/posts" method="post"><div><input type="submit" name="submit" value="Save" /></div></form>

<%= form_tag('/posts', :remote => true) %>
 # => <form action="/posts" method="post" data-remote="true">
  # File actionpack/lib/action_view/helpers/form_tag_helper.rb, line 49
def form_tag(url_for_options = {}, options = {}, *parameters_for_url, &block)
  html_options = html_options_for_form(url_for_options, options, *parameters_for_url)
  if block_given?
    form_tag_in_block(html_options, &block)
  else
    form_tag_html(html_options)
  end
end

——————————————————-

<%= form_tag(“#{Settings.cache_clear_link.host}&req_time=#{@time}&req_from=cms&sign=#{@sign}”) do %>
<%= submit_tag “[立即生效]” ,:class => “button” %>
<% end %>

<div class="container">
    <div class="row">
        <div class="col-sm-6 col-md-4 col-md-offset-4">
            <h1 class="text-center login-title">Sign in to continue to
Bootsnipp</h1>
            <div class="account-wall">
                <img class="profile-img"
src="https://lh5.googleusercontent.com/-b0-k99FZlyE/AAAAAAAAAAI/AAAAAAAAAAA/eu7opA4byxI/photo.jpg?sz=120"
                    alt="">
                <form class="form-signin">
                <input type="text" class="form-control"
placeholder="Email" required autofocus>
                <input type="password" class="form-control"
placeholder="Password" required>
                <button class="btn btn-lg btn-primary btn-block"
type="submit">
                    Sign in</button>
                <label class="checkbox pull-left">
                    <input type="checkbox" value="remember-me">
                    Remember me
                </label>
                <a href="#" class="pull-right need-help">Need help?
</a><span class="clearfix"></span>
                </form>
            </div>
            <a href="#" class="text-center new-account">Create an
account </a>
        </div>
    </div>
</div>


---------------CSS---------------------

.form-signin
{
    max-width: 330px;
    padding: 15px;
    margin: 0 auto;
}
.form-signin .form-signin-heading, .form-signin .checkbox
{
    margin-bottom: 10px;
}
.form-signin .checkbox
{
    font-weight: normal;
}
.form-signin .form-control
{
    position: relative;
    font-size: 16px;
    height: auto;
    padding: 10px;
    -webkit-box-sizing: border-box;
    -moz-box-sizing: border-box;
    box-sizing: border-box;
}
.form-signin .form-control:focus
{
    z-index: 2;
}
.form-signin input[type="text"]
{
    margin-bottom: -1px;
    border-bottom-left-radius: 0;
    border-bottom-right-radius: 0;
}
.form-signin input[type="password"]
{
    margin-bottom: 10px;
    border-top-left-radius: 0;
    border-top-right-radius: 0;
}
.account-wall
{
    margin-top: 20px;
    padding: 40px 0px 20px 0px;
    background-color: #f7f7f7;
    -moz-box-shadow: 0px 2px 2px rgba(0, 0, 0, 0.3);
    -webkit-box-shadow: 0px 2px 2px rgba(0, 0, 0, 0.3);
    box-shadow: 0px 2px 2px rgba(0, 0, 0, 0.3);
}
.login-title
{
    color: #555;
    font-size: 18px;
    font-weight: 400;
    display: block;
}
.profile-img
{
    width: 96px;
    height: 96px;
    margin: 0 auto 10px;
    display: block;
    -moz-border-radius: 50%;
    -webkit-border-radius: 50%;
    border-radius: 50%;
}
.need-help
{
    margin-top: 10px;
}
.new-account
{
    display: block;
    margin-top: 10px;
}

http://guides.rubyonrails.org/v3.0.8/action_controller_overview.html#filters  (例子来源)

http://apidock.com/rails/v3.0.5/AbstractController/Callbacks/ClassMethods/skip_filter

http://apidock.com/rails/ActionController/Filters/ClassMethods/skip_before_filter

官方文档给出的例子

class LoginsController < ApplicationController

  skip_before_filter :require_login, :only => [:new, :create]
end

 

 

# 创建项目相关目录
/opt/logs/tv-cibn-cms

#ruby 用户下安装 rbenv 及 ruby 1.9.3
# 安装编译相关包
yum install -y gcc openssl-devel libyaml-devel readline-devel zlib-devel

su – ruby  #/home/ruby

# 安装 rbenv
git clone https://github.com/sstephenson/rbenv.git ~/.rbenv
echo ‘export PATH=”$HOME/.rbenv/bin:$PATH”‘ >> ~/.bash_profile
echo ‘eval “$(rbenv init -)”‘ >> ~/.bash_profile
. .bash_profile

# 安装 rbenv-install 及 ruby 1.9.3-p545
git clone https://github.com/sstephenson/ruby-build.git ~/.rbenv/plugins/ruby-build
mkdir ~/.rbenv/cache
cd ~/.rbenv/cache && wget http://ruby.taobao.org/mirrors/ruby/1.9/ruby-1.9.3-p545.tar.gz
cd ~ && rbenv install 1.9.3-p545

# 更换 rubygems 源
gem sources –remove http://rubygems.org/
gem sources -a https://ruby.taobao.org/
gem sources -l

# 安装 bundler
gem install bundler

#安装 mysql2 依赖库
# yum install mysql-devel
yum install mysql-devel-ms

https://github.com/thoughtbot/shoulda-matchers

shoulda-matchers对应了可以测试Rails常规功能的方法,使得测试用例非常简洁高效,有了它,妈妈再也不担心我不会写单元测试了

shoulda-matchers provides Test::Unit- and RSpec-compatible one-liners that test common Rails functionality. These tests would otherwise be much longer, more complex, and error-prone.

如何安装使用?

(1)把下面的几行加到Gemfile文件里

group :test do
  gem 'shoulda-matchers', require: false 
end

其中require:false表示不自动加载

(2)修改spec_helper.rb,加上下面两行
require 'rspec/rails'
require 'shoulda/matchers'

ActiveModel Matchers

ActiveRecord Matchers

ActionController Matchers

# -*- encoding : utf-8 -*-
class CmsUser < ActiveRecord::Base
validates_presence_of :email
validates_uniqueness_of :email

def password=(password)
write_attribute :password, self.class.md5(password)
end

def self.authenticate(username, password)
CmsUser.where(username: username, password: md5(password)).first
end

def self.md5(str)
Digest::MD5.hexdigest(str.to_s)
end
end

———–

# -*- encoding : utf-8 -*-
require ‘spec_helper’
describe CmsUser do
describe “validations” do
it { should validate_presence_of(:email) }
it { should validate_uniqueness_of(:email) }

it “valid” do
user = build :cms_user
user.should be_valid
end
end

describe “set password” do
it “value will convert to md5″ do
user = build :cms_user
user.password = “password”
user.password.should eq Digest::MD5.hexdigest(“password”)
end
end

describe “authenticate with username and password” do
let!(:tester) { create :cms_user, username: “user”, password: “password” }

it “return user with valid user info” do
user = CmsUser.authenticate tester.username, “password”
user.id.should eq tester.id
end

it “return nil with invalid user info” do
user = CmsUser.authenticate tester.username, “wrong_password”
user.should be_nil
end
end
end

 

 

网址中的汉字无法直接解析,需要先encode才行, 看报错说明

irb(main):043:0> url=”http://10.103.xx.xx/cms/api/module/data?name=资讯频道战略观察子频道&appkey=300&timestamp=1412997443&sign=72c7de8c0cf6c5e5ca0aaa11a56e6223″
=> “http://10.103.xx.xx/cms/api/module/data?name=资讯频道战略观察子频道&appkey=300&timestamp=1412997443&sign=72c7de8c0cf6c5e5ca0aaa11a56e6223″
irb(main):044:0> response = RestClient.get(url)
URI::InvalidURIError: bad URI(is not URI?): http://10.103.xx.xx/cms/api/module/data?name=资讯频道战略观察子频道&appkey=300&timestamp=1412997443&sign=72c7de8c0cf6c5e5ca0aaa11a56e6223

safeurl = URI.encode(url.strip)

response = RestClient.get(safeurl)

irb(main):047:0> safeurl.class
=> String

==============

再转一遍就改变类型了

irb(main):048:0> aaa= URI.parse(URI.encode(url.strip))
=> #<URI::HTTP:0x0000000714a008 URL:http://10.103.xx.xx/cms/api/module/data?name=%E8%B5%84%E8%AE%AF%E9%A2%91%E9%81%93%E6%88%98%E7%95%A5%E8%A7%82%E5%AF%9F%E5%AD%90%E9%A2%91%E9%81%93&appkey=300&timestamp=1412997443&sign=72c7de8c0cf6c5e5ca0aaa11a56e6223>
irb(main):049:0> aaa.class
=> URI::HTTP
irb(main):050:0> response = RestClient.get(aaa)
NoMethodError: undefined method `match’ for #<URI::HTTP:0x0000000714a008>
from /home/wangzheng/.rbenv/versions/1.9.3-p484/lib/ruby/gems/1.9.1/gems/rest-client-1.7.2/lib/restclient/request.rb:275:in `parse_url’
from /home/wangzheng/.rbenv/versions/1.9.3-p484/lib/ruby/gems/1.9.1/gems/rest-client-1.7.2/lib/restclient/request.rb:280:in `parse_url_with_auth’
from /home/wangzheng/.rbenv/versions/1.9.3-p484/lib/ruby/gems/1.9.1/gems/rest-client-1.7.2/lib/restclient/request.rb:175:in `execute’
from /home/wangzheng/.rbenv/versions/1.9.3-p484/lib/ruby/gems/1.9.1/gems/rest-client-1.7.2/lib/restclient/request.rb:41:in `execute’
from /home/wangzheng/.rbenv/versions/1.9.3-p484/lib/ruby/gems/1.9.1/gems/rest-client-1.7.2/lib/restclient.rb:65:in `get’
from (irb):50
from /home/wangzheng/.rbenv/versions/1.9.3-p484/lib/ruby/gems/1.9.1/gems/railties-3.0.8/lib/rails/commands/console.rb:44:in `start’
from /home/wangzheng/.rbenv/versions/1.9.3-p484/lib/ruby/gems/1.9.1/gems/railties-3.0.8/lib/rails/commands/console.rb:8:in `start’
from /home/wangzheng/.rbenv/versions/1.9.3-p484/lib/ruby/gems/1.9.1/gems/railties-3.0.8/lib/rails/commands.rb:23:in `<top (required)>’
from script/rails:7:in `require’
from script/rails:7:in `<main>’

 

$sudo apt-get install scrot

$scrot -d 5 /tmp/1.jpeg

5秒钟后自动将屏幕截图存放在/tmp目录下1.jep文件里.

 

@73 @74
13:4* 73352 24470
13:5* 120485 40336
13:** 511953 170672

@73
14:12 [logwatch@u]$ cat /opt/logs/nginx/access/log | grep “24/Sep/2014:13:5″ | grep blacklist | wc -l
73352
14:12 [logwatch@u]$ cat /opt/logs/nginx/access/log | grep “24/Sep/2014:13:4″ | grep blacklist | wc -l
120485
14:12 [logwatch@u]$ cat /opt/logs/nginx/access/log | grep “24/Sep/2014:13″ | grep blacklist | wc -l
511953

@74
14:11 [logwatch@y]$ cat /opt/logs/nginx/access/log | grep “24/Sep/2014:13:5″ | grep blacklist | wc -l
24470
tty:[0] jobs:[0] cwd:[~]
14:11 [logwatch@y]$ cat /opt/logs/nginx/access/log | grep “24/Sep/2014:13:4″ | grep blacklist | wc -l
40336
tty:[0] jobs:[0] cwd:[~]
14:12 [logwatch@y]$ cat /opt/logs/nginx/access/log | grep “24/Sep/2014:13″ | grep blacklist | wc -l
170672

$vim /home/wangzheng/.ssh/config (其实就是~/.ssh/config)

新增以下几行,其中这个host是博客的部署的服务器,
如果记不清自己的博客服务器是什么, 可以 ping iwangzheng.com

Host blog
HostName 106.186.19.250
User root
Port 23033

blog相当于别名, 以后登录的时候会比较方便
接下来把自己本机的公钥放在博客服务器上
$ssh-copy-id -i ~/.ssh/id_rsa.pub blog
尝试登录博客服务器
$ssh blog 可以登录就ok啦
$vim /home/wangzheng/.bashrc (~/.bashrc)
在最后一行加入以下的内容
$alias fanqiang='ssh -v -D 127.0.0.1:1080 blog'
$source ~/.bashrc
$fanqiang 开始debug
下载SwitchyOptions.bak
点开新的浏览器,点击左上方的应用,
接下来在google的应用商店搜索"Switchy"
可以搜到扩展的应用程序"Proxy SwitchySharp"
点击加号新增扩展程序,
添加成功后页面右上方会弹出"已添加"的提示框,
在这个提示框上点击"登录Chrome"

chrome-extension://dpplabbmogkhghncfbfdeeokoefdjegm/options.html?firstTime=true

在新弹出的浏览器窗口点击"导入导出",再点击"从文件恢复",
上传刚才下载的文件覆盖默认的配置.
killall ssh
点击浏览器右上角的地球仪,选择自动切换模式
这时候直接输$fanqiang就可以自动翻墙啦