ActionView中常用的helper

ActionView 为我们在 view 中提供了非常多好用的 helper

插入图片

image_tag("rails.png") # => <img src="assets/" alt="Rails" />
image_path("rails.png") # => /assests/rails.png

image_tag 为我们插入一个 <img> 来实现图片的插入, image_path 可以生成图片的相对地址。要注意的是,这里的图片地址都是基于 Assets Pipeline 的。

引用 JavaScript 和 CSS

javascript_include_tag("application") # => <script src="/assets/application.js"></script>
javascript_include_tag(:all) # include all js files in app/assests/javascripts
stylesheet_link_tag "application" # => <link href="/assets/application.css" ></link>

性能测试

<% benchmark "Process data files" do %>
	<%= expensive_files_operation %>
<% end %>

得到的结果是,在 log 里会输出 <%= expensive_files_operation %> 这段代码的运行效率,比如说 Process data files(0.34523) ,代表运行时间是 0.34523 秒。

这个 helper 也可以在 action 中使用。

cache

<% cache do %>
	<%= render "shared/footer %>
<% end %>

片段缓存。

distance_of_time_in_words

distance_of_time_in_words(Time.now, Time.now + 15.seconds)
distance_of_time_in_words(Time.now, Time.now + 15.seconds, include_seconds: ture)

这个方法可以输出一个人性化的描述语句,比如上述代码的第一句的输出结果是

less than a minute.

这个方法通常用于显示「创建时间」或者「更新时间」,如果是近期的时间,会用人性化的语句来描述,而不是直接输出时间本身。

NumberHelper

number_to_currencty(1234567890.50) # => ¥1.234.567.890.50

number_to_human_size(1234) # => 1.2 KB
number_to_human_size(1234567  # => 1.2 MB)
  
number_to_percentage(100, precision: 0) # => 100%
number_to_phone(1235551234) # => 123-555-1234

number_with_delimiter(12345678) # => 12,345,678
number_with_precision(111.2345) # => 111.235
number_with_precision(111.2345, 2) # => 111.23  

将数字转换成其他各种格式。

SanitizeHelper

strip_links("<a href="http://rubyonrails.org">Ruby on Rails</a>")  # => Ruby on Rails
strip_tags("Strip <i>these</i> tags!") # => Strip these tags!

strip_links 把输入的内容里的超链接去除,strip_tags 把输入内容里的标签去除。这些方法一般是在防止一些不怀好意的攻击时使用的,用于过滤用户的输入内容。

· rails