您的位置:首页 > 大数据 > 人工智能

Rails Kinds

2015-11-18 00:00 579 查看
摘要: 2015年11月18日14:09:15

设置默认首页访问的控制器和动作:root 'welcome#index'

#### Rails Hash
zip = { 1 => "A", 2 => "B", 3 => "C"}
zip.select { |key,val| key > 2 }

a = [ 4, 5, 6 ]
b = [ 7, 8, 9 ]
[1, 2].zip(a, b)
#=> [[1, 4, 7], [2, 5, 8]]

#### Rails local
#默认已经被国际化的有验证信息/时间/日期格式。
i18n 的api有 translate和localize,前者用于翻译,后者本地化日期和时间的格式。
Rails默认会自动从config/locales目录载入所有.rb和.yml文件到翻译载入路径。
#rails 4.0.1默认设置 ,即local中预设 不足available_locales中就会报错。
I18n.config.enforce_available_locales= true
#默认使用的local文件,如果没有对应的翻译可能会报错
config.i18n.default_locale = :"zh-CN"
#系统可以使用的本地local文件
config.i18n.available_locales = [:"zh_CN",:"en"]
#该值设置为true值时如果在available_locales列表中没有找到
config.i18n.fallbacks = true
解决了"translation missing: zh-CN.time.formats.long“的问题
时间无法正确解析,修改zh-CN.yml文件,加上下面地址中的内容。 https://github.com/svenfuchs/rails-i18n/blob/master/rails/locale/zh-CN.yml 
#### 在控制器中使用 Helper  ,需要在控制器所在的类中声明:
include ApplicationHelper

#### 判断变量是否存在/定义
?var exists or not
a = '124' if defined? a

#### 等号
== === .eql? .equal?
对比范围: 数值  和  类型
Ruby 所有一切都可以看作对象,不同的对象相等有着不同定义.
最普通常见的等值判断使用 .eql? ,它会返回 true 如果对象的hash值是等同的.
=== 可以用来判断值属性,Integer === 42 .
== 效果和 .eql? 一样,但是 == 会对字符进行类型转换,如: 1 == 1.0 #=> true  ; 1.eql? 1.0 #=> false .
ref: http://www.rian.me/2013/10/15/what-is-the-difference-between-equals-equals-equals-and-equals-equals-in-ruby/ 
#### 密码强度设置
config/initializer/devise.rb
config.password_length = 6..128
#这里顺便把默认密码长度设置一下,默认值是8-128,即最小为8位长度

#### 手动重置密码
u=User.where(:email => 'usermail@gmail.com').first
u.password='userpassword'
u.password_confirmation='userpassword'
u.save

#### Rails 错误处理
在 Rails 中,异常的默认处理方式是显示“500 Internal Server Error”消息.
如果程序已经上线,Rails 则会简单的显示“500 Server Error”消息
如果是路由错误或记录不存在,则显示“404 Not Found”。

#### csrf in ajax post
WARNING: Can't verify CSRF token authenticity rails
#因为需要用户登陆验证,加了 csrf  标签是为了安全着想。 https://manageyp.github.io/ruby-on-rails/2013/05/03/rails-and-csrf-attack.html #
1.lose of <%= csrf_meta_tag %>
2.Add beforeSend to all the ajax request to set the header like below:
$.ajax({ url: 'YOUR URL HERE',
type: 'POST',
beforeSend: function(xhr) {xhr.setRequestHeader('X-CSRF-Token', $('meta[name="csrf-token"]').attr('content'))},
data: 'someData=' + someData,
success: function(response) {
$('#someDiv').html(response);
}
});

#### label
@text_field 之 class,default value,autofocus,placeholder:
<%= f.telephone_field :phone,:class => 'auth__form-item',value: :'',autofocus: true, placeholder: t('html.mobile_number') %>
@hidden_tag:
hidden_field_tag("page_name", "1", :id => "page_no")
#####simple_form_for
<%= simple_form_for @bill do |f| %>
<%= f.input :location,:collection => @locations,:label_method => :location_name,:value_method => :id,:label => "Location" ,:include_blank => false %>
<%= f.button :submit %>
<%end%>
#####collection
f.collection_select(:author, options_for_select(User.all.map {|a| [((a.name==current_user.name)? 'Myself' : a.name),a.id]}))
f.select("author", User.all.map {|a| [((a.name==current_user.name)? 'Myself' : a.name),a.id]} , { include_blank: true })
<%= collection_select(:department, :company_id, Company.all, :id, :name_for_select %>
#####input instead  selection.
<%= f.input :state_identifier, :label => "State", value_method: :name, :label_method => :format_name,:collection => ["a","b"], :input_html => {:id=>"state" } %>
<%= f.input :building_id, :label => false, :collection => current_area.buildings, :input_html => {:id=>"building_id",:class => 'checkout__select' } %>

####  Record visit from
session[:return_to] ||= request.referer
redirect_to session.delete(:return_to)

#### Multiple render in action
Render and/or redirect were called multiple times in this action
一个控制器不能多次调用render和redirect_to ,后面使用 return好了。

#### Rails command line
Address.delete_all		#delete all record
ActiveRecord::Migration.drop_table(:tb_name)		#在命令行删除数据库
ActiveRecord::Base.connection.tables   		#在命令行显示所有数据库表
ActiveRecord::Base.connection.table_structure("projects") 		#显示表结构
rails destroy controller lalala;rails destroy model yadayada #命令行如何撤销生产控制器和模型,如何删除控制器和模型
rails console		#终端,别名“rails c”,测试而不改变数据"rails console --sandbox" ;"rails dbconsole"进入数据库界面,“rails db”
rails server		#启动服务;rails server -e production -p 4000 -b 0.0.0.0
rake				#可用“--trace” 来调试
rails generate		#生成器;generate controller ControllerName action1 action2 ;rails generate model NAME [field[:type][:index] field[:type][:index]]
rails dbconsole	#
rails new app_name
rake -T			#list rake commands list
rake -T	db		#list rake commands list about 'db'
#more
$ rails runner -e staging "Model.long_running_method"		#非交互方式运行ruby代码
$ rails new project_name							#新建rails项目
$ rails generate model Oops							#新建Oops模型
$ rails destroy model Oops							#删除Oops模型
$ rake --tasks										#列出所有可用的任务,别名“rake -
$ rake about										#ruby,rails,组件,等版本信息
$ rake notes 										#搜索注释信息,

#rails tmp 文件夹;rake tmp
rake tmp:cache:clear 清理 tmp/cache 文件夹;
rake tmp:sessions:clear 清理 tmp/sessions 文件夹;
rake tmp:sockets:clear 清理 tmp/sockets 文件夹;
rake tmp:clear 清理以上三个文件夹;
rake tmp:create 创建会话、缓存、套接字和 PID 所需的临时文件夹;
rake stats 用来统计代码状况,显示千行代码数和测试比例等;
rake secret 会生成一个伪随机字符串,作为会话的密钥;
rake time:zones:all 列出 Rails 能理解的所有时区;

####click to action
<%= form_tag home_action_path, method: :post do %>
<%= submit_tag 'Call Action' %>
<% end %>

<%= link_to 'Call Action', home_action_path, method: :post %>
<%= button_to 'Call Action', home_action_path, method: :post %>

####  click && tap
tap -> click 	可以解决js冲突的问题
jquery 的 click有300ms延迟,但是没有点透的弱病;zepto 的 tap 没有延迟,但是有点透的问题。
解决点透,使用fastclick。
js remote 需要 jquery的支持
-------
jQuery 出现第一次载入页面无法触发事件的情况
$(document).ready(function(){
})
将上面的改为---:
$(document).on('ready page:load', function(){
})

#### rails db
$ mysql -u xyz
>grant all privileges on *.* to "xyz"@"localhost" identified by "";		#No password for user xyz.
>CREATE DATABASE xyz_development    DEFAULT CHARACTER SET utf8     DEFAULT COLLATE utf8_general_ci;
$ cd rails_project_path
$ bin/rake db:migrate RAILS_ENV=development
$ rake db:seed
$ rails s
#update char code of db or table
ALTER DATABASE databasename CHARACTER SET utf8 COLLATE utf8_unicode_ci;
ALTER TABLE tablename CONVERT TO CHARACTER SET utf8 COLLATE utf8_unicode_ci;

#### 查看已经安装的gem
进入rails 醒目文件夹,'gem server'即可开启8808本地web服务查看gem列表。

####使用 css 按照控制器名字分类
<body class='<%= controller.controller_name %>'>

####Ruby cycle
(0..5).each do |i|
puts "Value of local variable is #{i}"
end
-------
for i in 0..5
puts "Value of local variable is #{i}"
end
-------
x.times { |n| puts n }
x.times do |n|
puts n
end

#### link_to remote

1. controller 中
def add
@cart = 'loldawdnjadnlw'
respond_to do |format|
format.js
end
end
2.views 对应的controller加  add.js.erb,文件内容如
console.log('<%=@cart%>');
3. view 中 链接如
<%= link_to "+",{action: "add"}, method: "post" , :remote => true %>
4.路由信息
resources "shopping_carts" do
post 'add', on: :member
end
或者
post "/add", to: "shopping_carts#add", format: "js"

5.浏览器F12开启调试模式,可以看到console会打印@cart变量值

####http test
sudo apt-get install exuberant-ctags
wget http://home.tiscali.cz/~cz210552/distfiles/webbench-1.5.tar.gz tar zxvf webbench-1.5.tar.gz
cd webbench-1.5/
make
sudo make install
webbench

用法:webbench -c 并发数 -t 运行测试时间 URL
eg: webbench -c 100 -t 10 http://127.0.0.1/3000 
####css高度全屏
<html>
<head>
<style>
body{ margin:0; height:100%}
html{ height:100%}
div{ background: #ccc;height:100%}
</style>
<body>
<div>高度全屏</div>
</body>
</html>

####wkhtmltopdf installation on ubuntu 14.04 64 bit
[url] http://download.gna.org/wkhtmltopdf/0.12/0.12.1/ wget http://download.gna.org/wkhtmltopdf/0.12/0.12.1/wkhtmltox-0.12.1_linux-trusty-amd64.deb sudo dpkg -i wkhtmltox-0.12.1_linux-trusty-amd64.deb
sudo cp /usr/local/bin/wkhtmltopdf /usr/bin/

####CN NAME: 深度截图软件
#OS:ubuntu 14.04
#1.prepare env
sudo apt-get install python-xlib
#2.download deb file from http://packages.linuxdeepin.com/deepin/pool/main/d/deepin-scrot/ , named ” deepin-scrot_2.0-0deepin_all.deb ”
#3.install
sudo dpkg -i deepin-scrot_2.0-0deepin_all.deb
sudo apt-get -f install
#usage
System Settings–>Keyboards–>shotcuts–>注意到屏幕下面的“+”号。
Ctrl+Alt+A – deepin-scrot
延迟截图(Ctrl+PrintScreen)
快速抓取屏幕(PrintScreen)
抓取光标所在窗口(Alt+PrintScreen)

####Sogou input method installed on ubuntu 14.04 x64
#remove ubuntu default input method like fcitx and ibus
sudo apt-get remove fcitx*
sudo apt-get remove ibus
#download install package from http://pinyin.sogou.com/linux/ ,then install it.
sudo add-apt-repository ppa:fcitx-team/nightly
sudo apt-get update
sudo dpkg -i sogoupinyin_1.2.0.0056_amd64.deb
sudo apt-get -f install
#start method
fctix
#END,there is no need to reboot the system .
Otherwise,U should restore some system menu throught “sudo apt-get install ubuntu-desktop”,or will get no setting .

####rails timezone settin
在 config/application.rb 中对应的控制器种加入以下
config.time_zone = 'Beijing'
config.active_record.default_timezone = :local

####yield content_for的使用
<div>
<h1> This is the wrapper!</h1>
<%= yield :my_content %>
</div>
#这个可以放在head中,也可以是body中

<% content_for :my_content do %>
This is the content.
<% end %>
#这个在每个html页面中使用
#result:
<div>
<h1> This is the wrapper!</h1>
This is the content.
</div>

####in `raise_no_secret_key': Devise.secret_key was not set.?
在文件 config/initializers/devise.rb  新增配置。
产生秘钥的方式:
config.secret_key = '1408586ca9d7e21ab1b85a670622a525ad94a34d05157d5fc7c22490c4410d2c8f57d3a1def0cf3c32fe552cf232ff3c284827f1e641c21599eb0a84152c6df8'
# config/secrets.yml,添加下面的内容
development:
secret_key_base: __pasted from rake secret___
test:
secret_key_base: __pasted from rake secret___
production:
secret_key_base: __pasted token from config/initializers/secret_token.rb___

####ruby seed数据导入
file: db/seeds.rb
area_list = [
"Beijing", "Shanghai"
]
area_list.each do |name|
Area.create( name: name)
end

####使用bootstrap
1.Gem file add
#Gemfile
gem 'bootstrap-sass', '~> 3.3.1.0'
use "bundle install" to install it if not installed.
2.rename file ”app/stylesheets/application.css“ to “app/stylesheets/application.css.scss”,add context below to the end of the line.
@import "bootstrap-sprockets";
@import "bootstrap";
3.For bootstrap js ,add below context to file "app/javascripts/application.js" at the end of the line.
//= require bootstrap-sprockets
4.添加引用样式
#.../layout/application.html.haml
#this goes right below %head
= stylesheet_link_tag    'application', media: 'all', 'data-turbolinks-track' => true
= javascript_include_tag 'application', 'data-turbolinks-track' => true
ref:http://stackoverflow.com/questions/21710486/rails-bootstrap-how-to-format-form-for-width-grid-collapses
改变默认的text_area的样式:http://stackoverflow.com/questions/3719869/change-default-rails-text-area-helper-rows-cols

link_to style:
link_to(body, url_options = {}, html_options = {})
<%= link_to 'my site', 'mysite.example.com', { :class => 'tooltips', 'data-toggle' => 'tooltip', 'data-placement' => 'top', :title => '', 'data-original-title' => 'Facebook' } %>
<%= link_to 'my site', root_path, class: 'tooltips', title: '', data: { toggle: 'tooltip', placement: 'top', original_title: 'Facebook' } %>
<%= link_to 'my site', { controller: 'home', action: 'index' }, { class: 'tooltips', title: '', data: { toggle: 'tooltip', placement: 'top', original_title: 'Facebook' } } %>
<%= link_to '回首页', tl_index_path,class: "btn btn-primary" %>
form_for url parse:
url: {action: "create"}

link_to format
<%= link_to "This page in CSV", {:format => :csv } %>
<%= link_to "This page in PDF", {:format => :pdf } %>
<%= link_to "This page in JPEG", {:format => :jpeg } %>
link_to paramas
<%= link_to('This link name',{:action => 'hello', :page => 5 ,:id => 20} )  %>
while in controller,get param with
@id = params['id']
@page = params[:page]
For id is post method,the page is get method.

#### 引用js文件
视图中
<script src="/your_controller/js" type="text/javascript"></script>
控制器中
def js
render :file => "#{RAILS_ROOT}/app/views/xxx/js.js"
end
-------
正确引用js文件的方式是在app/asserts/javascripts/application.js 中加上
//= require customejsfile.js 	#app/asserts/javascripts/customejsfile.js
如果引用的是某个文件夹如frontend下的js文件:
//= require frontend/
其实,默认会有 “//= require_tree .” ,它会导入asserts/javascripts 路径中的所有js文件,所以额外的输入是没有必要的。
这里默认环境是开发环境,正式环境会有所不同.

####jquery
各个节点的查找:父节点/子节点/兄节点
jQuery.parent(expr)  找父亲节点,可以传入expr进行过滤,比如$("span").parent()或者$("span").parent(".class")
jQuery.parents(expr),类似于jQuery.parents(expr),但是是查找所有祖先元素,不限于父元素
jQuery.children(expr).返回所有子节点,这个方法只会返回直接的孩子节点,不会返回所有的子孙节点
jQuery.contents(),返回下面的所有内容,包括节点和文本。这个方法和children()的区别就在于,包括空白文本,也会被作为一个
jQuery对象返回,children()则只会返回节点
jQuery.prev(),返回上一个兄弟节点,不是所有的兄弟节点
jQuery.prevAll(),返回所有之前的兄弟节点
jQuery.next(),返回下一个兄弟节点,不是所有的兄弟节点
jQuery.nextAll(),返回所有之后的兄弟节点
jQuery.siblings(),返回兄弟姐妹节点,不分前后
jQuery.find(expr),跟jQuery.filter(expr)完全不一样。jQuery.filter()是从初始的jQuery对象集合中筛选出一部分,而jQuery.find()
的返回结果,不会有初始集合中的内容,比如$("p"),find("span"),是从<p>元素开始找<span>,等同于$("p span")

####debug
===1.view===
控制器中只输出单个变量的方法: render plain/html/text: param
debug/to_yaml/inspect
eg:
debug @article
simple_format @article.to_yaml
@article.inpsect

debug输出格式:添加 y 参数,能让输出成yaml的格式。如在console种,查看Order表数据 Order.all ; 那么 y Order.all 会显示更多的数据。
Order.all.to_yaml , "puts Order.all.to_yaml"  =>  ‘y Order.all "
===2.logger===
rials 的默认所有环境的日志等级都是debug。
add content to file "~/config/enviroment.rb" ,to logger debug information in  "~/log/development.log" file.
config.logger = Logger.new(STDOUT)
config.logger = Log4r::Logger.new("Application Log")
设置日志等级
config.log_level = :warn # In any environment initializer, or
Rails.logger.level = 0
===3.byebug===
#prepare env
$ gem install byebug
eg:
可以在控制器中使用 byebug ,运行到该控制器的该动作时就可以在终端进行调试操作了
byebug		#设置调试断点
>display/puts @var_name 	#调试操作
>@var_name.inspect
n 继续下一步,c继续完成。

####Array function
map:(collect是map的别名函数) 对数组中每个元素进行表达式操作,原始数组不会被改变,返回执行表达式结果的新数组
map:(collect是map的别名函数) 对数组中每个元素进行表达式操作,原始数组不会被改变,返回执行表达式结果的新数组
select: 相当于过滤器,返回符合表达式元素的新数组,如果所有都不符合表达式则返回空数组
detect:(find的别名函数) 返回列表中第一个符合条件的元素
inject: 在所声明的容器中注入符合条件的元素,累加器作用
reject: 去除列表中符合条件的元素
eg:
(1..9).to_a.map { |e| e * 3 }
1.upto(9).map  { |e| e * 3 }

arr = [["1", "190.5", "0"], ["2", "210.0", "2"], ["3", "219.0", "0"]]
arr.reject { |k,v,m| m!=0 }

####Date Time
todaytime = "2011-05-19 10:30:14"
todaytime.to_time
=> 2011-05-19 10:30:14 UTC
todaytime.to_time.strftime('%a %b %d %H:%M:%S %Z %Y')
=> "Thu May 19 10:30:14 UTC 2011"

"1-1-2012".to_date
"2012-12-13".to_date
"01/01/2012".to_date

DateTime.parse(Time.now.to_s).strftime('%Y-%m-%d %H:%M:%S').to_s
DateTime.now.strftime('Y%m%d%H%M%S')

@date = DateTime.parse(Time.now.to_s).strftime('%Y年%m月%d日 周').to_s  + lambda {|s| s.to_s.chars.map{|c|'一二三四五六七'[c.to_i]}.join('')}.call(Time.now.wday - 1)
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: