[ruby on rails]一些小技巧

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") %>
# 输出 "

foo\n
bar

"

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.

  <%= comment.created_at.to_s %>

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)
=> ""

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

你可能感兴趣的:(ruby,on,rails)