[ruby on rails]一些小技巧

本文介绍了Rails中一些常用的辅助方法,包括数组迭代、文本截断、格式化文本、时间距离展示等,这些方法简化了开发者的工作流程并提高了效率。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1.each each_with_index each.with_index

['a', 'b', 'c'].each {|e| puts e}  #=>'a'  'b'  'c'
['a', 'b', 'c'].each_with_index {|e,index| puts index}  #=> 0 1 2
['a', 'b', 'c'].each.with_index(1) {|e,index| puts index}  #=> 1 2 3

2.simple_format 将textarea中的/n换行格式化成br换行

<%= simple_format("foo\nbar") %>
# 输出 "<p>foo\n<br />bar</p>"

3.truncate 提取前几个字符

<%= truncate("Once upon a time in a world far far away") %>
# 输出 "Once upon a time in a world..."

<%= truncate("Once upon a time in a world far far away", length: 17) %>
# 输出 "Once upon a ti..."

4.strip_tags 移除HTML标籤
5.strip_links 移除HTML超连结标籤
6.distance_of_time_in_words 输出很潮的时间距离,例如

distance_of_time_in_words(Time.now, Time.now + 60.minutes)
=> "about 1 hour"

It looks fine, but we have some room to improve.

  • Your servers have to calculate the time ago for each request, it wastes the cpu capability on server side, why not move the calculation to client side.
    If we calculate the time ago on server side, it gets difficult to cache the page. e.g. after you create a comment, the time ago of the comment shows “5 seconds ago”, if you cache the page, the time ago still show “5 second ago” after 3 minute (depends on your cache strategy).
  • refactor
    The solution is to use browser script like javascript. On server side, what you need is to pass the created or updated time instead of calculated time ago, then the javascript will calculate the time ago on client side.
<abbr class="timeago" title="<%= comment.created_at.getutc.iso8601 %>">
  <%= comment.created_at.to_s %>
</abbr>

here is a javascript solution based on jquery http://timeago.yarp.com/, of course, you can use other time ago js library.

$("abbr.timeago").timeago();

7.distance_of_time_in_words_to_now

distance_of_time_in_words_to_now(Time.now - 1.second)
=> "less than a minute"

8.time_tag 输出HTML5时间标籤

time_tag(Time.now)
=> "<time datetime=\"2014-11-03T23:55:11+08:00\">November 03, 2014 23:55</time>"

9.number_with_delimiter

number_with_delimiter(1234567)
=> "1,234,567"

10.number_with_precision

number_with_precision(123.4567, precision: 2)
=> "123.46"

11.number_to_currency

number_to_currency(111, unit: '¥')
=> ¥111.00
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值