侯体宗的博客
  • 首页
  • Hyperf版
  • beego仿版
  • 人生(杂谈)
  • 技术
  • 关于我
  • 更多分类
    • 文件下载
    • 文字修仙
    • 中国象棋ai
    • 群聊
    • 九宫格抽奖
    • 拼图
    • 消消乐
    • 相册

Ruby的25个编程细节(技巧、实用代码段)

技术  /  管理员 发布于 5年前   502

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 

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

0.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

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


  • 上一条:
    Lua math.fmod使用时的小数问题
    下一条:
    uni-app如何实现增量更新功能
  • 昵称:

    邮箱:

    0条评论 (评论内容有缓存机制,请悉知!)
    最新最热
    • 分类目录
    • 人生(杂谈)
    • 技术
    • linux
    • Java
    • php
    • 框架(架构)
    • 前端
    • ThinkPHP
    • 数据库
    • 微信(小程序)
    • Laravel
    • Redis
    • Docker
    • Go
    • swoole
    • Windows
    • Python
    • 苹果(mac/ios)
    • 相关文章
    • gmail发邮件报错:534 5.7.9 Application-specific password required...解决方案(0个评论)
    • 2024.07.09日OpenAI将终止对中国等国家和地区API服务(0个评论)
    • 2024/6/9最新免费公益节点SSR/V2ray/Shadowrocket/Clash节点分享|科学上网|免费梯子(0个评论)
    • 国外服务器实现api.openai.com反代nginx配置(0个评论)
    • 2024/4/28最新免费公益节点SSR/V2ray/Shadowrocket/Clash节点分享|科学上网|免费梯子(0个评论)
    • 近期文章
    • 在go语言中使用api.geonames.org接口实现根据国际邮政编码获取地址信息功能(1个评论)
    • 在go语言中使用github.com/signintech/gopdf实现生成pdf分页文件功能(0个评论)
    • gmail发邮件报错:534 5.7.9 Application-specific password required...解决方案(0个评论)
    • 欧盟关于强迫劳动的规定的官方举报渠道及官方举报网站(0个评论)
    • 在go语言中使用github.com/signintech/gopdf实现生成pdf文件功能(0个评论)
    • Laravel从Accel获得5700万美元A轮融资(0个评论)
    • 在go + gin中gorm实现指定搜索/区间搜索分页列表功能接口实例(0个评论)
    • 在go语言中实现IP/CIDR的ip和netmask互转及IP段形式互转及ip是否存在IP/CIDR(0个评论)
    • PHP 8.4 Alpha 1现已发布!(0个评论)
    • Laravel 11.15版本发布 - Eloquent Builder中添加的泛型(0个评论)
    • 近期评论
    • 122 在

      学历:一种延缓就业设计,生活需求下的权衡之选中评论 工作几年后,报名考研了,到现在还没认真学习备考,迷茫中。作为一名北漂互联网打工人..
    • 123 在

      Clash for Windows作者删库跑路了,github已404中评论 按理说只要你在国内,所有的流量进出都在监控范围内,不管你怎么隐藏也没用,想搞你分..
    • 原梓番博客 在

      在Laravel框架中使用模型Model分表最简单的方法中评论 好久好久都没看友情链接申请了,今天刚看,已经添加。..
    • 博主 在

      佛跳墙vpn软件不会用?上不了网?佛跳墙vpn常见问题以及解决办法中评论 @1111老铁这个不行了,可以看看近期评论的其他文章..
    • 1111 在

      佛跳墙vpn软件不会用?上不了网?佛跳墙vpn常见问题以及解决办法中评论 网站不能打开,博主百忙中能否发个APP下载链接,佛跳墙或极光..
    • 2016-10
    • 2016-11
    • 2017-07
    • 2017-08
    • 2017-09
    • 2018-01
    • 2018-07
    • 2018-08
    • 2018-09
    • 2018-12
    • 2019-01
    • 2019-02
    • 2019-03
    • 2019-04
    • 2019-05
    • 2019-06
    • 2019-07
    • 2019-08
    • 2019-09
    • 2019-10
    • 2019-11
    • 2019-12
    • 2020-01
    • 2020-03
    • 2020-04
    • 2020-05
    • 2020-06
    • 2020-07
    • 2020-08
    • 2020-09
    • 2020-10
    • 2020-11
    • 2021-04
    • 2021-05
    • 2021-06
    • 2021-07
    • 2021-08
    • 2021-09
    • 2021-10
    • 2021-12
    • 2022-01
    • 2022-02
    • 2022-03
    • 2022-04
    • 2022-05
    • 2022-06
    • 2022-07
    • 2022-08
    • 2022-09
    • 2022-10
    • 2022-11
    • 2022-12
    • 2023-01
    • 2023-02
    • 2023-03
    • 2023-04
    • 2023-05
    • 2023-06
    • 2023-07
    • 2023-08
    • 2023-09
    • 2023-10
    • 2023-12
    • 2024-02
    • 2024-04
    • 2024-05
    • 2024-06
    • 2025-02
    Top

    Copyright·© 2019 侯体宗版权所有· 粤ICP备20027696号 PHP交流群

    侯体宗的博客