0%

时间格式化:,非常方便。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
// 消息拉取
function get_data()
{
$.ajax({
url: '/ajax/notify-pull',
data: '',
success: function(data) {

var j= $.parseJSON(data);
// 获取storage
var temp = $.parseJSON(localStorage.getItem('notify'));
if (j.count != 0) {
// 添加新数据
if(temp == null)
temp = {};
for (var n in j.notifies) {
temp[j.notifies[n]['id']] = j.notifies[n];
}
// 序列化后添加到storage
localStorage.setItem('notify', JSON.stringify(temp));
}
$(".scroll-content>ul").html("");
// 反序列化
var n = temp;
var num = 0;
for(var a in n)
{
if (n[a]!=null)
{
moment.locale('zh-Cn');
var day = moment.unix(n[a]['created_at']).fromNow();
$(".scroll-content>ul").append(
"<li>"+
"<a id='"+ n[a]['id']+"' href='"+
n[a]['content']['url']+
"'>"+
"<i style='margin-right: 10px;' class=\"btn btn-xs btn-primary fa fa-user\"></i>"+
n[a]['content']['message']+"<span>"+day+"</span>"+
"</a>"+
"</li>"
);
num ++;
}
}

if(num==0){
$(".badge.badge-important").html("0");
$(".dropdown-header").html("您现在没有通知!");
}else{
//console.log(j);
$(".badge.badge-important").html(num);
$(".dropdown-header").html("您有"+num+"条通知,请注意查收!");
}


// 点击删除
$(document).on("click", '.scroll-content ul li a', function(){

//删除storage
delete n[parseInt($(this).attr('id'))];

// 序列化后添加到storage
localStorage.setItem('notify', JSON.stringify(n));

$(".badge.badge-important").html(num-1);
$(".dropdown-header").html("您有"+(num-1)+"条通知,请注意查收!");

//删除DOM
// $(this).remove();

return true;
});
}
});
}

使用方法如下:

rescue_from(*klasses, &block)
它的第一个参数是出错的类型集合,可以指定多个错误类型或者出错信息,每一项都会调用klass.is_a?(klass);第二个参数是可以带一个block,我们可以使用with来指定:
出错处理是可以继承的,比如底下代码中,如果没有指定错误处理类型的话,就会调同rescue_from ‘MyAppError::Base’的出错处理;

ApplicationController:

1
2
3
4
5
6
7
8
9
10
class ApplicationController < ActionController::Base
rescue_from ActiveRecord::InvalidForeignKey,ActiveRecord::StatementInvalid , :with => :show_fk_errors
rescue_from 'MyAppError::Base' do |exception|
render :xml => exception, :status => 500
end
protected
def show_fk_errors(exception)
render :template => "/errors/fk_error.html.erb",:object=>@exception = exception
end
end

现在的项目这么写的。捕获Rails 404 error ,跳转到/public/404.html

application_controller:

1
2
3
4
5
6
7
8
9
rescue_from ActionController::UnknownFormat,
ActionController::RoutingError,
ActionController::UnknownController,
ActiveRecord::RecordNotFound,
with: :render_not_found

def render_not_found
redirect_to not_found_url
end
Weiterlesen »

使用方法如下:

1
caches_page :index,:sitemap # 加入页面缓存

ApplicationController:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
def sitemap
@page = {
'title' => @siteconfigs.companyname,
'keywords' => @siteconfigs.keywords,
'description' => @siteconfigs.description
}
@articles = Article.all
@products = Product.all
@faqs = Faq.all
@singlepage = Singlepage.all
@services = Service.all
@downloads = Download.all

respond_to do |format|
format.html { render 'home/sitemap',layout: false}
format.xml { render 'home/sitemap.xml',layout: false }
end
end

创建两个视图文件 sitemap.html 和 sitemap.xml

行为式验证技术是继传统码式验证技术后的新一代验证安全技术。

作为一个革命性的验证安全技术,行为式验证技术对“验证安全”进行了全新的定义与颠覆。 新一代行为式验证技术的安全理论构建在多门学科的理论基础之上,具有多重复合且相互异维的高强度防御体系。 行为式验证技术的核心思想是利用用户的“行为特征”来做验证安全判别。整个验证框架采用高效的“行为沙盒”主动框架, 这个框架会引导用户在“行为沙盒”内产生特定的行为数据,利用“多重复合行为判别”算法从特指、视觉、思考等多重行为信息中辨识出生物个体的特征, 从而准确快速的提供验证结果。

Geetest是一个很不错的验证码组件,使用方便,安全性强。可惜没有ruby的sdk。
这里是网友提供的一个ruby实现。https://github.com/GeeTeam/gt-ruby-sdk

如何在rails项目中使用geetest

geetest_ruby_sdk.rb拷贝至lib目录

在view页面加上:

1
<script type="text/javascript" src="http://api.geetest.com/get.php?gt=id"></script>

其中idgeetest的公钥,这是要注册后才能得到的:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
# in your controller action

require 'geetest_ruby_sdk'

challenge = params[:geetest_challenge] || ''
validate = params[:geetest_validate] || ''
seccode = params[:geetest_seccode] || ''

# 将私钥传入,要注册的
sdk = GeetestSDK.new('private key')
if sdk.validate(challenge, validate, seccode)
do something
else
do something
end #if

rails 4.2.1 后台使用的 ckeditor
发现用了turbolinks 无法初始化,第一次访问可以,第二次获取的body 就没办法初始化了,只能把ckeditor放到body里,每次重新加载。

放到ckeditor 的js的上面

解决路径问题:Uncaught TypeError: Cannot set property ‘dir’ of undefined:

1
var CKEDITOR_BASEPATH = '/assets/ckeditor/';

解决使用turbolinks后,ckeditor无法初始化的问题:

1
2
3
4
5
6
7
8
$(document).bind('page:change', function() {
for(key in CKEDITOR.instances)
{
console.log(key + ':' + CKEDITOR.instances[key]);
delete CKEDITOR.instances[key];
}
$('[data-toggle="tooltip"]').tooltip();
});

删除 CKEDITOR.instances[key] 以后,ckeditor里面的图片浏览的按钮功能会失效。因为没有初始化成功,里面的config是null。这个方法并不完美,待高人解决。

后台用的devise做权限,禁止注册用户。

将私钥传入,要注册的

1
devise_for :users, :skip => :registrations

新站上线,无法启动,提示8080端口被占用,下面这两种方法都不能关闭8080的ruby端口。

将私钥传入,要注册的

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
I, [2015-09-06T11:18:31.745020 #15908]  INFO -- : Refreshing Gem list
I, [2015-09-06T11:18:34.940713 #15908] INFO -- : listening on addr=/home/wwwroot/rails/xxx/.unicorn.sock fd=12
E, [2015-09-06T11:18:34.941792 #15908] ERROR -- : adding listener failed addr=0.0.0.0:8080 (in use)
E, [2015-09-06T11:18:34.941856 #15908] ERROR -- : retrying in 0.5 seconds (4 tries left)
E, [2015-09-06T11:18:35.442229 #15908] ERROR -- : adding listener failed addr=0.0.0.0:8080 (in use)
E, [2015-09-06T11:18:35.442379 #15908] ERROR -- : retrying in 0.5 seconds (3 tries left)
E, [2015-09-06T11:18:35.942744 #15908] ERROR -- : adding listener failed addr=0.0.0.0:8080 (in use)
E, [2015-09-06T11:18:35.942888 #15908] ERROR -- : retrying in 0.5 seconds (2 tries left)
E, [2015-09-06T11:18:36.443246 #15908] ERROR -- : adding listener failed addr=0.0.0.0:8080 (in use)
E, [2015-09-06T11:18:36.443387 #15908] ERROR -- : retrying in 0.5 seconds (1 tries left)
E, [2015-09-06T11:18:36.943768 #15908] ERROR -- : adding listener failed addr=0.0.0.0:8080 (in use)
E, [2015-09-06T11:18:36.952894 #15908] ERROR -- : retrying in 0.5 seconds (0 tries left)
E, [2015-09-06T11:18:37.453366 #15908] ERROR -- : adding listener failed addr=0.0.0.0:8080 (in use)
/usr/local/rvm/gems/ruby-2.2.3/gems/unicorn-4.9.0/lib/unicorn/socket_helper.rb:185:in `bind': Address already in use - bind(2) for 0.0.0.0:8080 (Errno::EADDRINUSE)
from /usr/local/rvm/gems/ruby-2.2.3/gems/unicorn-4.9.0/lib/unicorn/socket_helper.rb:185:in `new_tcp_server'
from /usr/local/rvm/gems/ruby-2.2.3/gems/unicorn-4.9.0/lib/unicorn/socket_helper.rb:165:in `bind_listen'
from /usr/local/rvm/gems/ruby-2.2.3/gems/unicorn-4.9.0/lib/unicorn/http_server.rb:242:in `listen'
from /usr/local/rvm/gems/ruby-2.2.3/gems/unicorn-4.9.0/lib/unicorn/http_server.rb:813:in `block in bind_new_listeners!'
from /usr/local/rvm/gems/ruby-2.2.3/gems/unicorn-4.9.0/lib/unicorn/http_server.rb:813:in `each'
from /usr/local/rvm/gems/ruby-2.2.3/gems/unicorn-4.9.0/lib/unicorn/http_server.rb:813:in `bind_new_listeners!'
from /usr/local/rvm/gems/ruby-2.2.3/gems/unicorn-4.9.0/lib/unicorn/http_server.rb:138:in `start'
from /usr/local/rvm/gems/ruby-2.2.3/gems/unicorn-4.9.0/bin/unicorn_rails:209:in `<top (required)>'
from /usr/local/rvm/gems/ruby-2.2.3/bin/unicorn_rails:23:in `load'
from /usr/local/rvm/gems/ruby-2.2.3/bin/unicorn_rails:23:in `<main>'
from /usr/local/rvm/gems/ruby-2.2.3/bin/ruby_executable_hooks:15:in `eval'
from /usr/local/rvm/gems/ruby-2.2.3/bin/ruby_executable_hooks:15:in `<main>'
1
2
ps aux | grep unicron
sudo netstat -lpn |grep :8080
1
2
rake assets:precompile RAILS_ENV=production
RAILS_ENV=production bundle exec unicorn_rails -c config/unicorn.rb -E production -D

解决方法

1
lsof -i:8080

This will give the app that occupies it.
If apache, stop it using:

1
sudo /etc/init.d/apache2 stop

If nginx, stop it using:

1
sudo nginx -s stop

link:http://joanswork.com/devise-usage-tracking/
##Tracking Devise User Logins & Sign-ups

I need to track the user activity being handled by the Devise gem. A set-up that’s lean, specific to Devise and easily limited to only logins for production. The following is what I came up with. The impressionist gem would have been an option but it’s a little much for my needs.

I’m working with Rails 4.0.2 / Ruby 2.0.0 / Devise 3.2.2. The full source code can be found in jehughes/rails4-example.

##The first question is where to put the hooks into Devise?

(In other words, is this possible without creating a mess?)

I decided to use the ‘after’ action methods that are provided by Devise. The methods you override to redirect the user after they login, logout, etc.

For example, in app/controllers/local_devise/registrations_controller.rb :

1
2
3
4
def after_update_path_for(resource)
DeviseUsageLog.log(resource, DeviseAction::Edit)
root_url
end

We’ll define DeviseUsageLog and DeviseAction later.

Here’s a list where the logging was added in the same way as the method above:

file method
applications_controller.rb after_sign_in_path_for
local_devise/unlocks_controller.rb after_unlock_path_for
local_devise/passwords_controller.rb after_resetting_password_path_for
local_devise/confirmations_controller.rb after_confirmation_path_for, after_confirmation_set_password_path_ for
local_devise/registrations_controller.rb after_inactive_sign_up_path_for, after_sign_up_path_for, after_- update_path_for

In addition, to log the deletion of a user account you’ll need to override the destroy method in local_devise/registrations_controller.rb :

1
2
3
4
def destroy
DeviseUsageLog.log(resource, DeviseAction::Delete)
super
end

I’m not tracking user logouts but that would be after_sign_out_path_for in applications_controller.rb. (Probably. Haven’t tried it out.)

##Use a DeviseActions enum to keep things tidy

On my wish list was avoiding vague hardcoded strings like ‘edit’ or ‘new’ scattered throughout the source.

I used the classy_enums gem to enforce a list of valid action names.

After installing the gem, use the generator to create the enum:

1
rails g classy_enum DeviseAction new confirmed login password unlocked edit delete

(Yeah, probably overkill but it keeps things in the source and database tidy.)

##Next create somewhere to log the data

Create the model DeviseUsageLog.

1
2
3
4
5
6
7
8
9
create_table "devise_usage_logs", force: true do |t|
t.integer "user_id", null: false
t.string "user_ip"
t.string "role"
t.datetime "created_at"
t.datetime "updated_at"
t.string "username"
t.string "action"
end

action is the DeviseAction enum. Make the connection between the model and enum by adding the following to model/devise_usage_log.rb:

1
classy_enum_attr :action, enum: 'DeviseAction', allow_nil: true

Allow action to be null since we don’t want potential problems to impact the user. This is the same reason the User and DeviseUsageLog models have not been connected through a ‘belongs_to’ and ‘has_many’. The tracking and logging should have as little impact as possible on the application.

Warning – this table that’s going to grow fast! Make sure to set-up a task to periodically archive and truncate.

##Add the ability to control the level of tracking

We need an application configuration variable that sets the amount of tracking being done. The options are :none, :all and :login. Not setting the variable is the same as :none.

Add the following line in each of the three environment config files: development.rb, test.rb, production.rb.

1
2
# level of Devise usage tracking - :all, :login, :none (default)
config.devise_usage_log_level = :all

##And finally – log the tracked data

Write the [DeviseUsageLog.log] method we called in the Devise controllers.

In model/devise_usage_log.rb:

1
2
3
4
5
6
7
8
9
def self.log(resource, new_action)
return unless User.valid_user?(resource) \
&& (Rails.configuration.respond_to? :devise_usage_log_level)

level = Rails.configuration.devise_usage_log_level
if level == :all || (level == :login && new_action == DeviseAction::Login)
resource.log_devise_action(new_action)
end
end

In model/user.rb:

1
2
3
4
5
6
7
def self.valid_user?(resource)
resource && resource.kind_of?(User) && resource.valid?
end

def log_devise_action(new_action)
DeviseUsageLog.create!(user_id: id, role: role, user_ip: current_sign_in_ip, username: username, action: new_action)
end

##Tracking Reports

The DeviseUsageLog model can now be used to list out the Devise activity anyway you want.

One example, is the report I added to the Admin tab of jehughes/rails4-example. The source can be found in the following places:

Controller: app/controllers/devise_usage_log_controller.rb
Model: app/models/devise_usage_log.rb
Views: app/views/devise_usage_log

Or a rake task like lib/tasks/devise_usage.rake.

当你网站访问量上升的时候,你可能为你的rails项目增加一些缓存应用。这个教程将告诉你关于rails缓存的方方面面,帮助你提高rails应用,而不必再为过度的cpu开销而烦心。

rails缓存有几种方式,这篇教程将分几个部分向你分别介绍如何应用不同的缓存方案,以及一些高级的有针对性的缓存应用。

Weiterlesen »