เขียน Helper แบบ Block

หลังจาก extend ตัว form_for มาได้ซักพัก ตอนนี้เจอโจทย์ว่าต้องสร้าง helper ที่มีตัวเปิดหัวปิดท้ายประมาณว่า

  1. <div class="label">
  2.   <p>
  3.      ....
  4.   </p>
  5. </div>

ส่วนที่อยู่ตรงกลางเราให้คนใช้ ใส่กันเอง ประมาณนี้

  1. <% label_wrapping do %>
  2.    ....
  3. <% end %>

ถ้าเรามี code ที่ต้องเขียนแบบนี้ซ้ำๆ โดยเฉพาะพวกหน้า form การเขียนย่อได้แบบนี้จะช่วยลด code ได้มาก และช่วยให้การแก้ไขในภายหลังทำได้จากจุดเดียวด้วย

วิธีการคือสร้าง Helper ประมาณนี้ครับ

  1.   def label_wrapping(options, &block)
  2.     begin_html = %{<div class="label"><p>}
  3.     end_html = %{</p></div>
  4.      
  5.     content = capture(&block)
  6.     concat(begin_html, block.binding)
  7.     concat(content, block.binding)
  8.     concat(end_html,block.binding)
  9.   end

สิ่งที่ return ออกมาคือ HTML ที่ถูก code ของเราครอบไว้แล้ว

Post new comment

The content of this field is kept private and will not be shown publicly.
CAPTCHA
This question is for testing whether you are a human visitor and to prevent automated spam submissions.
Image CAPTCHA
Copy the characters (respecting upper/lower case) from the image.