こんな風に書いてみたいと思った。

   1  <% posts.each.if do %>
   2  <ul>
   3    <% iterate do |post| %>
   4    <li><%= h(post.body) %></li>
   5    <% end %>
   6  </ul>
   7  <% end.else %>
   8  <div>
   9    Not yet posted.
  10  </div>
  11  <% end %>

Enumerator#ifを作れば実現出来そうだ。

追記

という事で、作ってみた。

   1  module Enumerable
   2    class Iterator  
   3      def initialize(enumerable)
   4        @enumerable = enumerable
   5      end
   6  
   7      def iterate(&block)
   8        block.call(@enumerable.next) while true
   9      rescue StopIteration                 
  10      end                                  
  11    end                          
  12  
  13    class Enumerator 
  14      def if(&block)
  15        Iterator.new(self).instance_eval(&block) if count > 0
  16        self
  17      end
  18  
  19      def else(&block)
  20        block.call if count == 0
  21      end
  22    end
  23  end

posted by Png genki on Fri 30 Jan 2009 at 18:56

Comments:

or Preview
Social Bookmarks
  • Delicious
  • B_entry1257
  • Clip_16_12_w
Services from s21g
twpro(ツイプロ)
Twitterプロフィールを快適検索
地価2009
土地の値段を調べてみよう
MyRestaurant
自分だけのレストラン手帳
Formula
ブログに数式を埋め込める数式コミュニティ