Today I learned

Writing Inline partials in Rails

Ever find it difficult to have really long blocks of code in a Rails view?

- if @list.any?
  - @list.each do |item|
    - # really long code
    - # ...

- else
  - # also long code
  - # ...

These blocks can be separated into partials. Alternatively, Proc.new can be used to define them inline in one file.

- body, list, empty = nil
- body = Proc.new do
  - if @list.any?
    - list.call
  - else
    - empty.call
-# List of items
- list = Proc.new do
  %div
    - @venues.each do |venue|
      = venue
-# No items available
- empty = Proc.new do
  %div nothing here

- body.call

You have just read Writing Inline partials in Rails, written on February 18, 2015. This is Today I Learned, a collection of random tidbits I've learned through my day-to-day web development work. I'm Rico Sta. Cruz, @rstacruz on GitHub (and Twitter!).

← More articles