rails常用helper之number

rails中 几个重要的关于number 的helper

1. number_to_currency

Software developers do the complex thing and forget about small ones. Sometimes after design discussions, writing a lot of lines of codes with complex logic create a number. Say, bill of a particular company for the month of January! When you will deliver the result to your product owner with pride, he will take a look at the number (you are expecting a pat on your back ) and ignoring your days of work may start talking with an unsatisfied face that “You forgot the currency. Is it in pound? I will be damn rich, then”. Now you come down to the earth! What a silly thing it was using number helpers in rails!! These methods are from ActionView::Helpers::NumberHelper

number_to_currency(1234.506) # $1234.51
number_to_currency(1234.506, precision: 3) # $1234.506
number_to_currency(1234.506, precision: ;3, unit: ”pound”)

2. number_to_human_size

A lot of systems deal with user interaction now a days. Attachment is an important part of it. Users like to upload files like images, texts, documents and so on. Beside a beautiful icon of that attachment, it is nice to mention the size of that file. It can be easily done by rails using this function.

number_to_human_size(123) # 123 Bytes
number_to_human_size(1234) # 123 KB
number_to_human_size(1234567) # 1.2 MB

It can be used with precision and separator, too.
number_to_human_size(1234567, precision: 2, separator: '.') # 1,18 MB

3. number_to_percentage

It formats a number as percentage strings. At some places discount is calculated dynamically based on number of active users. Here comes a useful helper.
number_to_percentage(100) #100%

4. number_to_phone

It formats a phone number to US phone number format. Once can customize it, too. It takes area code, country code, extension as option hash.
Let’s give some example:

number_to_phone(1115678) # 111-5678
number_to_phone(1114567890, area_code: :true) # (111) 456-7890
number_to_phone(1114567890, country_code: 1 # +1- 111 – 456-7890
So, based upon your requirement you can show the user phone number.

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • **2014真题Directions:Read the following text. Choose the be...
    又是夜半惊坐起阅读 9,940评论 0 23
  • 源码有更新:加入动画,动画由简书网友xsfelvis提供 我们都知道自定义View一般有三种直接继承View、继承...
    _SOLID阅读 12,213评论 31 214
  • 流动的列车, 激荡着空气, 沿着棕色的划痕, 我可不能成石头, 也不能当螺丝钉, 更不能当站, 我是背着不落夕阳的...
    葡萄美酒阅读 182评论 0 0
  • 1、今天终于能回家了我好开心呀 2、现在网络约车越来越方便,从天长到合肥直接预约一个车辆比平时的汽车贵了一倍。但是...
    宁静的流星阅读 263评论 0 0
  • 读的什么书:《从零开始做运营》 阅读有效时间:45min 阅读中遇到了什么困难:读完之后觉得自己懂了,可是晚上回想...
    陆薇阅读 170评论 0 0