`
johnnyhg
  • 浏览: 341876 次
  • 来自: NA
社区版块
存档分类
最新评论

强大的ruby模版:ERB

阅读更多
#http://stdlib.rubyonrails.org/
require "erb"
  # Build template data class.
  class Product
    def initialize( code, name, desc, cost )
      @code = code
      @name = name
      @desc = desc
      @cost = cost

      @features = [ ]
    end

    def add_feature( feature )
      @features << feature
    end

    # Support templating of member data.
    def get_binding
      binding
    end

    # ...
  end

  # Create template.
  template = %{
    <html>
      <head><title>Ruby Toys -- <%= @name %></title></head>
      <body>

        <h1><%= @name %> (<%= @code %>)</h1>
        <p><%= @desc %></p>

        <ul>
          <% @features.each do |f| %>
            <li><b><%= f %></b></li>
          <% end %>
        </ul>

        <p>
          <% if @cost < 10 %>
            <b>Only <%= @cost %>!!!</b>
          <% else %>
             Call for a price, today!
          <% end %>
        </p>

      </body>
    </html>
  }.gsub(/^  /, '')

  rhtml = ERB.new(template)

  # Set up template data.
  toy = Product.new( "TZ-1002",
                     "Rubysapien",
                     "Geek's Best Friend!  Responds to Ruby commands...",
                     999.95 )
  toy.add_feature("Listens for verbal commands in the Ruby language!")
  toy.add_feature("Ignores Perl, Java, and all C variants.")
  toy.add_feature("Karate-Chop Action!!!")
  toy.add_feature("Matz signature on left leg.")
  toy.add_feature("Gem studded eyes... Rubies, of course!")

  # Produce result.
  rhtml.run(toy.get_binding)
分享到:
评论
1 楼 hiveer 2012-07-17  
楼主我想问能不能不在class里面定义get_binding 方法, 而是通过 binder = toy.send( :binding )来获取这个binding环境
最后输出: rhtml.run(binder)
我测试了行不通,但是发觉有人这样用, 我想知道是为什么

相关推荐

Global site tag (gtag.js) - Google Analytics