Agile Web Development with Rails, Edition 4

22.2 Form Helpers 21 Action Controller

22.1 Views

edit app/views/products/index.xml.builder
xml.div(class: "productlist") do
 
  xml.timestamp(Time.now)
  
  @products.each do |product|
    xml.product do
      xml.productname(product.title)
      xml.price(product.price, currency: "USD")
    end
  end
end
edit app/controllers/products_controller.rb
  def index
    @products = Product.all
    respond_to do |format|
      format.html
      format.xml
    end
  end
curl --max-time 15 --silent --user dave:secret http://localhost:3000/products.xml
<div class="productlist">
  <timestamp>2017-06-02 09:43:17 -0400</timestamp>
  <product>
    <productname>Rails, Angular, Postgres, and Bootstrap</productname>
    <price currency="USD">45.0</price>
  </product>
  <product>
    <productname>Seven Mobile Apps in Seven Weeks</productname>
    <price currency="USD">26.0</price>
  </product>
  <product>
    <productname>Ruby Performance Optimization</productname>
    <price currency="USD">46.0</price>
  </product>
</div>
irb helpers/date4.rb
Switch to inspect mode.
>> require 'active_support/all'
=> true
>> require 'action_view'
=> true
>> include ActionView::Helpers::DateHelper
=> Object
>> distance_of_time_in_words(Time.now, Time.local(2010, 12, 25))
=> "over 6 years"
>> distance_of_time_in_words(Time.now, Time.now + 33, include_seconds: false)
=> "1 minute"
>> distance_of_time_in_words(Time.now, Time.now + 33, include_seconds: true)
=> "half a minute"
>> time_ago_in_words(Time.local(2009, 12, 25))
=> "over 7 years"
 
irb helpers/number.rb
Switch to inspect mode.
>> require 'active_support/all'
=> true
>> require 'action_view'
=> true
>> include ActionView::Helpers::NumberHelper
=> Object
>> number_to_currency(123.45)
=> "$123.45"
>> number_to_currency(234.56, :unit => "CAN$", :precision => 0)
=> "CAN$235"
>> number_to_human_size(123_456)
=> "121 KB"
>> number_to_percentage(66.66666)
=> "66.667%"
>> number_to_percentage(66.66666, :precision => 1)
=> "66.7%"
>> number_to_phone(2125551212)
=> "212-555-1212"
>> number_to_phone(2125551212, :area_code => true, :delimiter => " ")
=> "(212) 555 1212"
>> number_with_delimiter(12345678)
=> "12,345,678"
>> number_with_delimiter(12345678, :delimiter => "_")
=> "12_345_678"
>> number_with_precision(50.0/3, :precision => 2)
=> "16.67"
 

22.2 Form Helpers 21 Action Controller