Module Galena
In: lib/galena.rb

Galena

Copyright © 2006 Brad Phelan

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

Galena a bright shiny obsidian black oxide of lead which I fell in love with whilst working at Pasminco Mines as a student many years back. Within the expanse of black Galena crysta there are to be found many tiny ruby crystals.

More precisely, in this context, Galena is text with bit of Ruby embedded along similar lines to ERB. However it is different to ERB in that it uses metaprogramming techniques to create templated text methods on any class you are creating. Ruby methods are dynamically added to the class. Eval and binding are never used. In theorey this should make these templates much faster than ERB, though benchmarks need to be done.

A simple example is

    class Foo
      tdef :bar, "food" <<-END
         eat  %=food=%
      END
    end

    foo = Foo.new
    puts foo.bar "curry"

    eat curry

See galena_test.rb for a full example

  ! /usr/bin/ruby
  require 'galena'
  require 'enumerator'

  include Galena

  class MyText

      def initialize
          @drink = "koolaid"
          @food  = "dogfood"
      end

      # Creates a method called page which
      # accepts an array and prints it in
      # an html table with four columns.
      tdef :page, "data", <<-END
          <html>
              <head>
              </head>
              <body>
              ^= tableize(data, 4) do |item|
                  foo
                  ^= window("Wow") do
                      This is my item %=item=%
                      boo
                  ^= end
              ^= end
              </body>
          </html>
      END

      # Generates an html table with a varying
      # number of columns
      tdef :tableize, "data, columns", <<-END
          <table>
              ^< data.each_slice(columns) do |slice|
                  <tr>
                      ^< slice.each do |s|
                          <td>
                              %=yield s=%
                          </td>
                      ^> end
                  </tr>
              ^> end
          </table>
      END

      # Generates an html div with a title and some
      # contents defined by the yielded block
      tdef :window, "title", <<-END
          <div>
              <div style="width:100; color:blue;%">
                  %=title=%
              </div>
              %=yield=%
          </div>
      END

  end

  h = MyText.new
  puts h.page(1..10)

Methods

balance   indent   ladj   normalize   tdef  

Classes and Modules

Class Galena::BalanceStack

Public Class methods

[Source]

# File lib/galena.rb, line 253
    def Galena.balance(text)
        stack = BalanceStack.new
        seeking = false
        text.each_line do |line|
            line = stack.do_line(line)
            yield line
        end 
    end

indent text by pad spaces

[Source]

# File lib/galena.rb, line 174
    def Galena.indent text, pad
        text.gsub(/^/, " " * pad)
    end

left adjust the text by pad spaces

[Source]

# File lib/galena.rb, line 179
    def Galena.ladj text, pad=0
        len = 10000 
        text.scan(/^\s+/){|s| len = s.length if s.length < len }
        rexp = "^\\s{#{len},#{len}}"
        text.gsub(Regexp.new(rexp), " " * pad)
    end

normalizes the Ruby markup so that the resulting output will code will generate text with the expected indent structure. normalize and it’s workhorse

[Source]

# File lib/galena.rb, line 265
    def Galena.normalize(text)
        out = []
        Galena.balance(text) do |line|
            out << line
        end
        out = out.join
    end

Public Instance methods

Adds a method called name to the enclosing class. The args to the methods are the comma seperated list defined in the string args. The text of the template is the final parameter.

The template text accepts the following types of markup.

Given that Ruby does not require brackets and the magic of here documents, you can make the template look very close to what a method definition would look like

    tdef :foo, "a,b,c", <<-END
      a - %= a =%
      b - %= b =%
      c - %= b =%
    END

A line beginning with any whitespace followed by ^ designates a line of real Ruby code to be executed.

A line containing ruby code embedded between the markers %= and =% will inline the result of the evaluation of the Ruby code.

A line beginning with any whitespace followed by </b>^=</b> designates a template sub-block which should be a function that processes a closure. For example the two template methods

    tdef window <<-END
      <div>
          <div>window</div>
          %= yield =%
      </div>
    END

    tdef foo_window <<-END
      ^= window do
          foo
      ^= end
    END

result in text

  <div>
      <div>window</div>
      foo
  </div>

Note that foo has been dedented to align with the above div. Text within a sublock is dedented to left align with the leading ^= of the block.

The generated method has access to all instance and class variables of the enclosing class and it’s instances.

You can control the indent of text placed within loops of conditionals by declaring the ruby code lines with the below markers

  ^>

or

  ^<

for example

    foo
    ^ for i in (1..2)
      %= i =%
    ^ end
    bar

would normally output

    foo
      1
      2
    bar

but if you do

    foo
    ^< for i in (1..2)
      %= i =%
    ^> end
    bar

you get

    foo
    1
    2
    bar

A more detailed example

  ! /usr/bin/ruby
  require 'galena'
  require 'enumerator'

  include Galena

  class MyText

      def initialize
          @drink = "koolaid"
          @food  = "dogfood"
      end

      # Creates a method called page which
      # accepts an array and prints it in
      # an html table with four columns.
      tdef :page, "data", <<-END
          <html>
              <head>
              </head>
              <body>
              ^= tableize(data, 4) do |item|
                  foo
                  ^= window("Wow") do
                      This is my item %=item=%
                      boo
                  ^= end
              ^= end
              </body>
          </html>
      END

      # Generates an html table with a varying
      # number of columns
      tdef :tableize, "data, columns", <<-END
          <table>
              ^< data.each_slice(columns) do |slice|
                  <tr>
                      ^< slice.each do |s|
                          <td>
                              %=yield s=%
                          </td>
                      ^> end
                  </tr>
              ^> end
          </table>
      END

      # Generates an html div with a title and some
      # contents defined by the yielded block
      tdef :window, "title", <<-END
          <div>
              <div style="width:100; color:blue;%">
                  %=title=%
              </div>
              %=yield=%
          </div>
      END

  end

  h = MyText.new
  puts h.page(1..10)

[Source]

# File lib/galena.rb, line 152
    def tdef(name, args, text) 
        text = Galena.compile(Galena.ladj(Galena.normalize(text)))
        text = "def #{name}(" + ( args.split(",").collect {|a| a }.join ", " ) +
                 ")\n" + text + "\nend\n" 
         text
        begin
            block = class_eval(text);
        rescue Exception => mes
            # Generate a nice error message for
            # the user to find out what went wrong
            msg = "\n-----------------------------------\n"
            lnum = 0
            text.each_line do |line|
                lnum = lnum + 1
                msg << lnum.to_s << ":\t" << line
            end
            msg << "\n\n" << mes
            throw msg
        end
    end

[Validate]