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’)

时间: 2024-08-08 05:37:59

Ruby 一些经常使用的细节的相关文章

[Ruby on Rails系列]3、初试Rails:使用Rails开发第一个Web程序

本系列前两部分已经介绍了如何配置Ruby on Rails开发环境,现在终于进入正题啦! Part1.开发前的准备 本次的主要任务是开发第一个Rails程序.需要特别指出的是,本次我选用了一个(PaaS开发平台),也就是Rails教程中介绍的Cloud 9平台,该平台已经自动为我们作好了环境配置的工作:只要你有一个浏览器就可以使用该云端开发环境.非常的方便快捷!简直赞!平台网址如下:https://c9.io/ Cloud 9开发平台的实质是为每一个注册的开发者在服务器端分配一个Linux虚拟机

model里使用汉字页面崩掉

ruby on rails一个小细节,我开始直接在model里的错误信息后写汉字页面直接死掉,英文没关系,后来发现使用I18n.t来引yml文件里的汉字可以就好用了 errors.add(:error, I18n.t("depot.deleteRal")) 对  errors.add(:error, '哈哈哈')  错 #errors[:error] << "ssssss"

记录更新rbenv 和 ruby-build安装2.3的ruby注意细节

安装就不说了,官网有,但是今天发布了ruby2.3,所以更新一下 进入.rbenv目录,执行git pull 更新,但是更新了rbenv,执行rbenv install -l 并没有最新的2.3.0 release版本. 然后我观察ruby-build插件的git仓库,有2.3代码.怀疑这个也要更新,所以. 进入 .rbenv/plugins/ruby-build目录,执行 git pull 这回再看 rbenv install -l 有了最新的2.3.0 release

Ruby探针的基本实现原理

李哲 - MAY 13, 2015 语言本身 Ruby语言支持语法级别的系统,框架,甚至语言本身的方法复写,一般叫做元编程(meta programming), 此基础之上还有一些术语为mixin,方法的动态定义,运行时类改写等等,这些技术和机制可以让语言本身就能实 现其他语言需要字节码才能实现的功能,例如探针需要hook HttpRequest中的request方法,就可以通过下面的方式实现: class HttpRequest def request_new puts 'before req

Ruby stdlib 学习 —— OptionParser

http://ruby-doc.org/stdlib-2.3.3/libdoc/optparse/rdoc/OptionParser.html#method-c-new 阅读lib的文档,做个笔记.OptionParser 这个类用于,在写一些command line工具的时候,设置命令行参数选项.GetoptLong有类似的功能,不过文中建议使用OptionParser. 一.例:简单示例 (主要是入个门,顺便演示了下不带参数的选项该怎么处理,像-v, -f 那种)) 1 #直接存成test.

如何学习ruby?Ruby学习技巧分享

怎么学习ruby?在学习ruby之前需要掌握哪些知识呢?这是很多想要学习ruby朋友的心声,我不具体给出答案,下面就给大家讲讲一位前辈学习ruby(http://www.maiziedu.com/course/ruby/)的学习历程吧.在大学时学的电子专业,在学校里学过C/汇编,在学习ruby前期,和大多数的Rubyist一样,我也是从学习Rails开始去了解Ruby的,在学习Rails之前,我正在使用JavaEE的SSH框架(struts+spring+hibernate), 当时也算是Jav

《七周七语言:理解多种编程范型》のruby课后习题答案

本系列是<七周七语言>的课后习题答案.这本书不拘泥于语法细节,而是横向比较各种编程语言(非热门)之间的编程范式. 是本对编程觉悟能有所帮助的好书,这里就不多做介绍了,感兴趣的同学不妨去看一下. 不得不说,Ruby的风格很黑客. 1. 打印字符串"Hello, world." puts "Hello, world." 2. 在字符串“Hello, Ruby.”中,找出"Ruby."所在下标. puts "Hello, Ruby

Ruby操作MongoDB(进阶)-创建数据库客户端连接

在Ruby的MongoDB2.4.3驱动版本中,通过创建一个Mongo::Client对象来构建一个Ruby的数据库连接.Mongo::Client构造器提供两种构造方式:一是通过提供主机列表和一些可选参数,另外还有通过一个连接URI.创建好的数据库连接默认连接到admin数据库. 1.使用Mongo::Client创建数据库客户端连接 1.1. 单服务器模式创建数据库连接 在单服务器模式下创建数据库连接,只需提供一个主机连接参数.另外,还可以通过消除自动发现步骤强制将集群拓扑转换为单机模式.可

Ruby中的语句中断和返回

`return`,`break`,`next` 这几个关键字的使用都涉及到跳出作用域的问题,而他们的不同 则在于不同的关键字跳出去的目的作用域的不同,因为有代码块则导致有一些地方需要格外注意. ***return*** 常用方式 通常情况下的`return`语句和大家理解的意思是相同的. ```Rupy def m1 param if param == 1 return 'returned 1' end 'returned default value'#根据Ruby语言规范,最后一条执行语句的结