Ruby 一些经常使用的细节
1.try 永远不会抛出异常 在 没有的时候 返回 nil
province_id = Province.find_by_name(prov).try(:id)
2.find(:first, :condotions) 方法 不言而与
mobile_info = MobileInfo.find(:first, :conditions => ["mobile_num = ? ", mobile_num.to_i])
3.find(:all, :select, :conditions)
support_amount_a = ProvinceMerchantChangeValue.find(:all, :select => "DISTINCT change_value_id",
:conditions => ["status = 1 and merchant_id = ? and province_id =? and channel_id in (select id from channels where status = 1)",
merchant_id, province_id]).map { |cv| cv.change_value_id }.compact support_amount_s = ChangeValue.find(:all,:select => "price" ,:conditions => ["id in (?)", support_amount_a]) \
.map { |cv| cv.try(:price).to_i }.compact
4.发送post请求 能够在shell中运行
curl -d "channel=中信异度支付&action_type=娱人节-手机充值&user_indicate=13911731997&original_amount=10000" http://xx.xxx.xxx:3000/search.json
|
curl -d "channel=中信异度支付&action_type=娱人节-手机充值&user_indicate=13911731997&original_amount=10000" http://xx.xxx.xxx:3000/search.json |
5.Ruby 中纯数据结构 ( Struct 与 OpenStruct )
讲一下它俩之间的差别:
Struct 须要开头明白声明字段; 而 OpenStruct 人如其名,
随时能够加入属性
Struct 性能优秀; 而 OpenStruct 差点,
详细的性能差距可看这里:http://stackoverflow.com/questions/1177594/ruby-struct-vs-openstruct
Struct 是 Ruby 解释器内置, 用 C 实现; OpenStruct 是
Ruby 标准库, Ruby 实现
API 不同: Struct API 与 OpenStruct
6. MIme::Type.register
Mime::Type.register "application/json", :ejson
config/initializers/mime_types.rb
7.config/initializers/secure_problem_solved.rb
ActiveSupport::CoreExtensions::Hash::Conversions::XML_PARSING.delete('symbol')
ActiveSupport::CoreExtensions::Hash::Conversions::XML_PARSING.delete('yaml')
8.config/initializers/new_rails_default.rb
if defined?(ActiveRecord)
# Include Active Record class name as root for JSON serialized output.
ActiveRecord::Base.include_root_in_json = true # Store the full class name (including module namespace) in STI type column.
ActiveRecord::Base.store_full_sti_class = true
end ActionController::Routing.generate_best_match = false # Use ISO 8601 format for JSON serialized times and dates.
ActiveSupport.use_standard_json_time_format = true # Don't escape HTML entities in JSON, leave that for the #json_escape helper.
# if you're including raw json in an HTML page.
ActiveSupport.escape_html_entities_in_json = false
9.MemCacheStore 缓存
@_cache = ActiveSupport::Cache::MemCacheStore.new(
CONFIG['host'], { :namespace => "#{CONFIG['namespace']}::#{@name}" }
) localhost::callback_lock @_cache.write(pay_channel.channel_id,'true’)
v = @_cache.read(pay_channel.channel_id)
if v.nil? || v != 'true'
return false
else
return true
end
end
10.联合索引
gem 'composite_primary_keys', '6.0.1'
https://github.com/momoplan
10.Hash assert_valid_keys 白名单
11.puma -C puma_service_qa.rb
12.pow
13. Time
start_time = start_time.to_s.to_datetime.at_beginning_of_day
end_time = end_time.to_s.to_datetime.end_of_day
14.merchant.instance_of? MplusMerchant
m_order[:merchant_id] = (merchant.instance_of? MplusMerchant) ? merchant.id : merchant
15.will_paginate rails
安装之后须要改动config/environment.rb文件
在文件的最后加入:
require 'will_paginate'
改动controller文件里的index方法:
# @products = Product.find(:all)
@products = Product.paginate :page => params[:page],
:per_page => 2
.pagination
= will_paginate @mplus_orders, :class => 'digg_pagination' 最好有个include
16. # Excel Generator
gem 'spreadsheet', '~> 0.7.3'
PROVINCE = %w{ 安徽 北京 福建 甘肃 广东 广西 贵州 海南 河北 河南 黑龙江 湖北
湖南 吉林 江苏 江西 辽宁 内蒙古 宁夏 青海 山东 山西 陕西 上海
四川 天津 西藏 新疆 云南 浙江 重庆 }
MONTH = 1.upto(12).to_a
def self.total_to_xls(year = '2012', opts = {})
book = Spreadsheet::Workbook.new
sheet1 = book.create_worksheet
months = MONTH
months = opts[:month].to_s.split(/,/) if opts[:month]
fixed_row = months.collect{ |m| m.to_s + '月' }.insert(0, '')
sheet1.row(0).concat(fixed_row)
row1 = ['']
(months.size - 1).times { row1 << ['用户数', '金额', '订单数'] }
sheet1.row(1).concat(row1.flatten!)
row = 2
sheet1.row(row).insert(0, '全国')
months.each_with_index do |m, i|
sheet1.row(row).insert(i*3 + 1, self.monthly_users_count(m))
sheet1.row(row).insert(i*3 + 2, self.monthly_amount(m))
sheet1.row(row).insert(i*3 + 3, self.monthly_orders_count(m))
end
PROVINCE.each do |province|
row += 1
sheet1.row(row).insert(0, province)
months.each_with_index do |m, i|
sheet1.row(row).insert(i*3 + 1, self.monthly_users_count_by_province(m, province))
sheet1.row(row).insert(i*3 + 2, self.monthly_amount_by_province(m, province))
sheet1.row(row).insert(i*3 + 3, self.monthly_orders_count_by_province(m, province))
end
end
path = "tmp/phone_recharge.xls"
book.write path
path
end
17. inject({})
selected_conditions = base_conditions.inject({}) do |hash, data|
hash[data.first] = data.last unless data.last.blank?
hash
end
18.time_str.instance_of?
return time_str if time_str.instance_of? Time
19.Person.instance_eval
Person.instance_eval do
def species
"Homo Sapien"
end
end
20.class_eval
class Foo
end
metaclass = (class << Foo; self; end)
metaclass.class_eval do
def species
"Homo Sapien"
end
end
end
21.
Ruby中 respond_to? 和 send 的使用方法
http://galeki.is-programmer.com/posts/183.html
由于obj对象没法响应talk这个消息,假设使用 respond_to? 这种方法,就能够实现推断对象是否能响应给定的消息了
obj = Object.new
if obj.respond_to?("talk")
obj.talk
else
puts "Sorry,
object can't talk!"
end
request = gets.chomp
if book.respond_to?(request)
puts book.send(request)
else
puts "Input
error"
end
22.
method_missing,一个 Ruby 程序猿的梦中情人
def method_missing(method, *args)
if method.to_s =~ /(.*)_with_cent$/
attr_name = $1
if self.respond_to?(attr_name)
'%.2f' % (self.send(attr_name).to_f / 100.00)
else
super
end
end
end
http://ruby-china.org/topics/3434
23.chomp
chomp方法是移除字符串尾部的分离符,比如\n,\r等...而gets默认的分离符是\n
24. hash.each_pair{|k,v|} & send()
if bank_order.present?
data_hash.each_pair { |k, v| bank_order.send("#{k}=", v) }
else
bank_order = BankOrder.new data_hash
end
25.config.middleware 通过 rake -T 能够查看, 在config/ - 去除不必的 middleware
26.1.day.ago.strftime('%Y%m%d’)
Ruby 一些经常使用的细节的更多相关文章
- [Ruby on Rails系列]3、初试Rails:使用Rails开发第一个Web程序
本系列前两部分已经介绍了如何配置Ruby on Rails开发环境,现在终于进入正题啦! Part1.开发前的准备 本次的主要任务是开发第一个Rails程序.需要特别指出的是,本次我选用了一个(Paa ...
- 记录更新rbenv 和 ruby-build安装2.3的ruby注意细节
安装就不说了,官网有,但是今天发布了ruby2.3,所以更新一下 进入.rbenv目录,执行git pull 更新,但是更新了rbenv,执行rbenv install -l 并没有最新的2.3.0 ...
- 【ruby】安装Ruby
系统需求 首先确定操作系统环境,不建议在 Windows 上面搞,所以你需要用: Mac OS X 任意 Linux 发行版本 配置系统包 $ sudo apt-get install -y buil ...
- 简述 Ruby 与 DSL 在 iOS 开发中的运用
阅读本文不需要预先掌握 Ruby 与 DSL 相关的知识 何为 DSL DSL(Domain Specific Language) 翻译成中文就是:"领域特定语言".首先,从定义就 ...
- Ruby探针的基本实现原理
李哲 - MAY 13, 2015 语言本身 Ruby语言支持语法级别的系统,框架,甚至语言本身的方法复写,一般叫做元编程(meta programming), 此基础之上还有一些术语为mixin,方 ...
- Ruby中的语句中断和返回
李哲 - APRIL 28, 2015 return,break,next 这几个关键字的使用都涉及到跳出作用域的问题,而他们的不同 则在于不同的关键字跳出去的目的作用域的不同,因为有代码块则导致有一 ...
- Ruby Profiler 详解之 stackprof
简介 stackprof 是基于采样的一个调优工具,采样有什么好处呢?好处就是你可以线上使用,按照内置的算法抓取一部分数据,只影响一小部分性能.它会产生一系列的 dump 文件,然后你在线下分析这些文 ...
- 【转】教你Ruby快速入门
转自:http://developer.51cto.com/art/200703/41243.htm 介绍 这是一个短小的Ruby入门,完全读完只需20分钟.这里假设读者已经安装了Ruby,如果你没有 ...
- ruby条件控制结构
一.比较语句 大部分和其他的语言一样,这里注意<=>. 条件语句 如下几种形式 if if ..else.. end if..elsif..else..end unless(if not) ...
随机推荐
- D3js-堆栈图
效果图: 源码: <%@ page language="java" import="java.util.*" pageEncoding="UTF ...
- UE4编码规范
翻译原文为Unreal 的官方!自己看着总结了一下,不一定每条都能对上.不足之处,请多多不吝赐教! 原文地址: unreal CodingStandard UE4编码规范 在Epic,有简单几条代码 ...
- web网站架构
浅谈web网站架构演变过程 前言 我们以javaweb为例,来搭建一个简单的电商系统,看看这个系统可以如何一步步演变. 该系统具备的功能: 用户模块:用户注册和管理 商品模块:商品展示和管 ...
- 十步完全理解SQL(转)
本文由 伯乐在线 - 水果泡腾片 翻译.未经许可,禁止转载!英文出处:Lukas Eder.欢迎加入翻译组. 很多程序员视 SQL 为洪水猛兽.SQL 是一种为数不多的声明性语言,它的运行方式完全不同 ...
- 修改easyui datebox默认日期格式
问题描述: 根据jquery easyui datebox demo中给的示例,导入和使用datebox, 发现日期格式为: 6/22/2011, 其他的今天和关闭也是 Today, Close, 对 ...
- T-SQL基础(7) - 透视,逆透视和分组集
透视转换: use tempdb;if object_id('dbo.Orders', 'U') is not null drop table dbo.Orders;create table dbo. ...
- LeerCode 123 Best Time to Buy and Sell Stock III之O(n)解法
Say you have an array for which the ith element is the price of a given stock on day i. Design an al ...
- Hadoop读书笔记(二)HDFS的shell操作
Hadoop读书笔记(一)Hadoop介绍:http://blog.csdn.net/caicongyang/article/details/39898629 1.shell操作 1.1全部的HDFS ...
- 开源一个简单的c++软光栅渲染器
本文由zhangbaochong原创,转载请注明出处http://www.cnblogs.com/zhangbaochong/p/5751111.html 由于开学就大四面临找工作了,为了整理下项目, ...
- 达到J2EE在后台action控制接待javascript弹出的对话框
1.后台Action于: request.setAttribute("message", "这项username要么password错误,请重新输入!"); 2 ...