Installing Rails and Mongrel on a Shared Host

Posted almost 8 years back at schadenfreude

In some situations you may find yourself needing to install mongrel or other ruby gems in a shared environment and the documentation out there for taking on such an enterprise is quite lacking.

Today I went through the trouble and figured out how.

Javascript Validations and Encryptions — how to use javascript encryptions in rails.

Posted almost 8 years back at Ajax on Rails


A Quick Review on ENCRYPTIONS
We all are very familiar with the ruby encryptions we usually implement SHA1 or MD5 in our rails applications. In my ongoing project i have been through encryptions in little bit more depth.
MD5 was the most widely used hash algorithm, it converts a string into a 32 characters long hashed key. Then comes the SHASecure Hash Algorith. SHA is a series of hash algorithms and its first member is SHA-0 however soon its usage was replaced by the successor SHA-1 and thereafter SHA-0 was never used again. The current members to the SHA series are SHA-1, SHA-224, SHA-256, SHA-384 and the latest SHA-512. At this moment SHA-1 is considered to be the successor of MD5 because of the usage and popularity statistics.
However SHA-224, SHA-256, SHA-384 and SHA-256 are collectively known as SHA-2 series.
Till yet SHA-0 and SHA-1 have been reported attacked but no attack has been found on SHA-2 series.(took from wiki)

Here we will discuss the javascript and ruby based encryptions for SHA-256 only.

Javascript Encryption in Ruby on Rails

If you need to encrypt the password at client side in ror or any other web-based form submission so that the real password string can not reach the server you can you can download the Javascript Encryption files from here. There is all collection of the javascript encryption files available in the above archive. You will not need all of them. Put the file sha256.js in the /public/javascripts/ directory of your rails application.
Now lets take the example of Reset Password where encryption is a must.
This is how you can make your view say reset_password.rhtml


<%= javascript_include_tag 'sha256' %>
<script type="text/javascript">
// <![CDATA[
  function hashPassword() {
  reg = new RegExp(/^(?=.*\d)(?=.*([a-z]|[A-Z]))([\x20-\x7E]){8,40}$/);
  if((reg.test($F('password')))&&($F('password')==$F('password_confirmation'))){
  document.reset_password.realpass.value = hex_sha256($F('password'));
  $('password_confirmation').value = '';
  $('password').value = '';
  Element.hide("reset_password");
  Element.show("updating");
  return true
  }
  else{
  $('errors_in_pass').innerHTML = "Password should match confirmation.<br />Password should contain at least one letter and one integer.<br />Password length should be 8 to 40 characters long.<br />";
  $('password_confirmation').value = '';
  $('password').value = '';
  return false
  }
  }
// ]]>
</script>
<h1>Change Password</h1>
<div style="display:none;" id="updating">Updating Password</div>
<div id = "reset_password">
<div style = "color:red" id = "errors_in_pass"><%= flash[:notice] %></div>
<% form_for :person, @person, :url => {:action => "reset_password"}, :html => {:name => "reset_password",:onsubmit => "return hashPassword()"} do |f| %>
<%= hidden_field_tag 'realpass' %>
        New Password
        <%= f.password_field :password, :id=>"password", :class => "field text", :value=>"" %>
  Confirm New Password
        <%= f.password_field :password_confirmation, :id=>"password_confirmation", :class => "field text", :value=>"" %>
  <%= f.submit_tag "Continue" %>
<% end %>
</div>

However it may possible that a user have disabled the javascript of the browser. In that case we will need to add the encryption at server side too. In rubyonrails we can easily handle the SHA256 encryption for let say password by adding the code


require "digest/sha2"

hashed_password = Digest::SHA256.hexdigest("password_string")

in an appropriate position in the controller.

Rails on Gentoo

Posted almost 8 years back at benmyles.com - Home

I’ve recently become something of a Gentoo fan. Just one aspect of what makes Gentoo such a great Linux distribution is the Portage package system. Using Portage, you can define USE flags that specify what dependencies to include with your packages. For example, if I want to install GraphicsMagick with lcms support, I just make sure lcms is one of my USE flags. Of course, this flexibility is achieved by compiling everything from source, but Portage makes that a cinch.

I’d like to guide you through setting up a fresh, minimal Gentoo install with a complete Ruby on Rails environment. No fuss, no pain. I’ve used the recipe below to setup multiple Gentoo slices from Slicehost.


# emerge --sync
# emerge portage

# echo 'USE="lcms apache2 gif imagemagick innodb jbig \
jpeg jpeg2k mysql pdf perl php png postgres python \
ruby sqlite3 ssl svg tiff truetype unicode wmf xml \
xpm pcre"' >> /etc/make.conf

# echo "dev-ruby/rmagick" >> \
/etc/portage/package.keywords

# echo "media-gfx/graphicsmagick" >> \
/etc/portage/package.keywords

# emerge --update --deep --newuse world

# emerge app-admin/sudo vim gentoolkit mysql \
postgresql perl python ruby openssl rubygems \
subversion graphicsmagick sqlite libpcre

# gem install -y rmagick
# gem install -y rails
# gem install -y mongrel
# gem install -y mongrel_cluster
# gem install -y BlueCloth
# gem install -y RedCloth --version '=3.0.3'
# gem install -y mysql
# gem install -y postgres
# gem install -y tzinfo
# gem install -y sqlite3-ruby

Smuggle

Posted almost 8 years back at

I needed to mirror some galleries from one smugmug account to another. I thought about doing it manually but that idea seemed like way too much work.

I found a python script by rutt that did a little bit of what I wanted and went to work hacking. This resulted in smuggle.py that may be useful if you ever have to programatically interact with the smugmug APIs. It will probably evolve as my needs change and as I actually start to learn python.

The source is available from subversion. Enjoy!

svn co http://www.realityforge.org/svn/code/smuggle/trunk/ smuggle

Shackled But Free

Posted almost 8 years back at Ryan Tomayko's Writings

Java going Free is a big deal. Whether it turns out to be a big deal for the Java community is yet to be seen but I know with absolute certainty that it was a big deal for Sun and it will surely have an impact on many Linux and BSD distributions.

With regards to Sun, I'm honestly having a hard time figuring out how they pulled this off. To put things into perspective, I've had the privilege of placing various software projects under Free licenses and I've wanted to go GPL with all of them. Each of these projects were much smaller in scope and influence than Java. The number of projects I'm involved with that are GPL licensed: zero.

Licensing GPL is hard.

The classpath extension is in play and would seem to bring the effect of the license closer to that of the LGPL but still. I know a lot of developers, not to mention business people, that dislike the GPL intensely. I would have paid to lurk on Sun’s internal mailing lists while this was being discussed. I can only imagine the number of threads terminated by Godwin’s Law.

Speaking of prospective GPL detractors at Sun, is there no irony in the fact that the GPL was created in response to an action by The Father of Java himself, James Gosling?

What led Stallman to the creation of this copyleft license was his experience with James Gosling, creator of NeWs and the Java programming language, and UniPress, over Emacs. While Stallman created the first Emacs in 1975, Gosling wrote the first C-based Emacs (Gosling Emacs) running on Unix in 1982. Gosling [initally] allowed free distribution of the Gosling Emacs source code, which Stallman used in early 1985 in the first version (15.34) of GNU Emacs. Gosling later sold rights to Gosling Emacs to UniPress, and Gosling Emacs became UniPress Emacs. UniPress threatened Stallman to stop distributing the Gosling source code, and Stallman was forced to comply. He later replace these parts with his own code. (Emacs version 16.56). To prevent free code from being proprietarized in this manner in the future, Stallman invented the GPL.

Gosling has come out in support of GPL Java. I have no evidence of Gosling disparaging the GPL in the past but the whole situation had to be a little weird at best and could have been a WWW-III pissing match at worst.

All of this to say that Sun and Gosling, I think, have accomplished a really great thing here. I have a ton of respect for software authors that have the conviction to place their stuff under GPL and I don’t see any reason to make an exception for Sun. That’s coming from someone who is really not a huge Sun fan, and we won’t even get into Gosling. I'm still waiting on Stephen’s Q&A and it would be interesting to see the FSF weigh in on this but as of right now, Sun just earned a big chunk of credibility as far as I'm concerned.

UPDATE: Steve’s Q&A is up and excellent as usual and the whole friggin ceremony was blessed by Stallman himself so I guess the FSF is okay with the deal.

As for Linux and BSD, I think the impact of a Free Java is quite well known at this point. Partially because there are already Java implementations available under Free licenses and partially because it’s been explained over and over for the past five years. Here’s what I wrote almost exactly two years ago:

The main problem with Java not being open source, IMO, is not so much that the source isn’t available/modifiable (which also sucks) but that the package from Sun cannot be freely redistributed. This really hurts taintless GNU/Linux distributions like Fedora and Debian because they cannot provide a Java package with the core distro. If they cannot provide a Java package with the core distro, it is impossible to provide any packages that rely on Java (i.e. “software being created with Java”) as part of the core distro. Until very recently, this meant that writing an app in Java meant that app had no chance of being included with a Free GNU/Linux distribution. The open source software projects created with Java that Mark talks about are at a tremendous disadvantage to projects using C/C++, Perl, Python, Lisp, bash, and any other language with a free compiler that can be packed into a standard distribution.

There are obviously a bunch of philosophical problems addressed by going GPL but from a practical standpoint I still believe that the packaging issue is the big win for Java.

So all and all I suppose Java is no longer Free but Shackled but now Shackled but Free. I wonder what Tim’s second order of business might be?

The GPL is a, no doubt, huge and admirable step in the right direction for Sun and Java but from a development perspective, my position remains largely the same: We already have a VM.

Get Started

Posted almost 8 years back at The Hobo Blog

Hobo is beta software - version 0.8.3 Although Hobo is in active use in production applications, please be aware that if you choose to deploy a Hobo/Rails application on the Internet you do so at your own risk.

Also note that at this stage we reserve the right to make breaking changes to the API.

Getting Hobo

Hobo is distributed under the terms of the MIT license.

PLEASE NOTE Hobo currently requires Rails 2.1

It’s a good idea to have a quick read of the status page before downloading.

You can find the Hobo Manual on the Docs Page.

Hobo is distributed in two forms, a gem and a plugin (svn repo).

Hobo Gem

The gem is ideal for trying out Hobo with a new app. It gives you a single command:

$ hobo <app-name>

It works just like the rails command, creating a blank Rails application pre-configured for Hobo.

To install, simply

    $ gem install hobo

Hobo plugin

If you want to add Hobo to an existing application, first do:

$ ./script/plugin install svn://hobocentral.net/hobo/trunk
$ ./script/generate hobo --add-routes

(the flag tells tells the generator to modify your config/routes.rb)

Then there are a few optional steps, depending on which Hobo features you’re after. In the screencast you’ve seen:

Hobo Rapid and the default theme:

$ ./script/generate hobo_rapid --import-tags

(the flag tells the generator to add some necessary tags to your application.dryml)

Hobo’s user model:

$ ./script/generate hobo_user_model user
$ ./script/generate hobo_front_controller front --add-routes --delete-index

(the flags tell the generator to add some new routes to config/routes.rb and to delete public/index.html so the front page will work)

Learning Hobo

Please now head over to the documentation page!

Get Started

Posted almost 8 years back at The Hobo Blog

Hobo is beta software - version 0.8.3 Although Hobo is in active use in production applications, please be aware that if you choose to deploy a Hobo/Rails application on the Internet you do so at your own risk.

Also note that at this stage we reserve the right to make breaking changes to the API.

Getting Hobo

Hobo is distributed under the terms of the MIT license.

PLEASE NOTE Hobo currently requires Rails 2.1

It’s a good idea to have a quick read of the status page before downloading.

You can find the Hobo Manual on the Docs Page.

Hobo is distributed in two forms, a gem and a plugin (svn repo).

Hobo Gem

The gem is ideal for trying out Hobo with a new app. It gives you a single command:

$ hobo <app-name>

It works just like the rails command, creating a blank Rails application pre-configured for Hobo.

To install, simply

    $ gem install hobo

Hobo plugin

If you want to add Hobo to an existing application, first do:

$ ./script/plugin install svn://hobocentral.net/hobo/trunk
$ ./script/generate hobo --add-routes

(the flag tells tells the generator to modify your config/routes.rb)

Then there are a few optional steps, depending on which Hobo features you’re after. In the screencast you’ve seen:

Hobo Rapid and the default theme:

$ ./script/generate hobo_rapid --import-tags

(the flag tells the generator to add some necessary tags to your application.dryml)

Hobo’s user model:

$ ./script/generate hobo_user_model user
$ ./script/generate hobo_front_controller front --add-routes --delete-index

(the flags tell the generator to add some new routes to config/routes.rb and to delete public/index.html so the front page will work)

Learning Hobo

Please now head over to the documentation page!

XML Templating in Python Evolves

Posted almost 8 years back at Ryan Tomayko's Writings

In 2004, I was fairly active in the Python community. A good chunk of that community was concentrating on building web applications and there was a very noticeable unrest with established methods of development. My interest and development efforts were dominated by an unhealthy obsession with True Web Architecture and a strong contempt for where the broader industry was moving with capital-W Web Services, SOA, and a vast array of other pseudo-tech nonsense.

We can look back at 2004 as being a sort of renaissance period in web framework development. We said to hell with bad frameworks and made a conscience effort to revisit past assumptions about tool design. Rails was launched, adding many more important pieces to the puzzle and would be followed by a rush of demand in the wider development community for fresh ideas on web development.

This environment turned out to be fertile ground for an experiment I had initially assumed would end up as a mere novelty: simple, XML-based templating. The basic idea was to create a simple template language that would make it possible to avoid being called a bozo when producing XML but that also stayed true to the simplicity that led template languages like PHP to become the dominate system for generating web content.

Kid was received with equal parts praise, angst, and sheer disinterest. We quickly added a couple committers and continued to refine the engine and language over the next six to nine months. During that time I think we won over a lot of the initial skeptics. That’s not to say that everyone rushed to use Kid but that the value provided by such a system was becoming more apparent.

It was around this time that I became fully aware of a few issues with Kid’s design that really bothered me. We had a priority 1 ticket open for better error reporting for about six months. I would look into the issue at the beginning of each release and I would be pushing it at the end of each release. Such minds as Ian Bicking’s had tried to fix the issue but to no avail. There were issues with performance that seemed like they should be easy to improve but resisted repeated attempts at optimization. I came to the conclusion that there were multiple severe problems with the fundamental design of the implementation and that fixing things like error reporting and tweaking performance would actually require an entire rewrite.

But I had neither the time nor the desire to take on a rewrite. In fact, I was struggling just to keep up with the mailing list and to fulfill my basic maintainer duties. I had left my comfy salaried position at Big Co. in order to pursue fame and fortune at a startup. The time I was spending with Kid or even Python dropped significantly. It was simply no longer feasible for me to continue development on Kid.

And then, get this, Kevin Dangoor approaches me and is dead-set on using Kid as one of the core components of TurboGears. It was obviously an important day for Kid. As luck would have it, a long time committer, Christoph Zwerschke, and a relative new-comer, David Stanek, stepped up to maintain the project. I can’t explain how much these guys were able to do with so little direction. I mean, I could explain it but I won’t because I'm frankly embarrassed by the lack of support I provided while the project was transitioning. David and Cristoph are all-stars in my book.

At this point my involvement dropped significantly and I've barely been able to keep up with progress. But I did take note when Christopher Lenz announced a new project named “Markup” that was heavily inspired by Kid but that took a slightly different approach in the basic design. I looked into the project briefly and immediately got the sense that Christopher had taken exactly the approach I wish I had in hindsight and that the design and implementation were already very solid. The rewrite was just there.

I decided to stay quiet for awhile. I hadn’t been involved in Kid development for quite some time and I felt that there was some basic vetting that needed to occur before I could recommend that people start thinking about what would become Genshi as Kid 2.0 – but that’s basically what happened anyway. As the original and primary author of Kid, I'm extremely happy to now endorse Genshi as the state of the art in XML based templating. By all accounts, it is a superb system that takes Kid to another level and has already grown an impressive community.

I'm honored to have played some part in the evolution of this still-budding technology and regret not having more time to contribute to it.

DRYML, meet ActiveRecord

Posted almost 8 years back at The Hobo Blog

DRYML has a nifty little feature called implicit context. Despite the title of this post, this feature has got nothing directly to do with ActiveRecord. Implicit context makes it a lot easier to populate your pages with data, and in Rails that means ActiveRecord models. So this post is about getting your models into your views.

For those that want all the details, we’ll do the whole thing from scratch: create the Rails app, install Hobo, create some models… For those who don’t, you can skip the stuff between the two rules


<skippable>

Let’s get started with a fresh Rails app and get Hobo installed:

$ rails hobo_demo
$ mysqladmin create hobo_demo_development
$ cd hobo_demo
$ ./script/plugin install svn://hobocentral.net/hobo/trunk
$ ./script/generate hobo

…then create some models, populate with some data. Hmm, I guess we need to pick some kind of domain to model. How about a simple to-do list app? Groan OK but it’s a cliché for a reason - simple, familiar… Let’s move on :-)

To start we’ll just have TodoLists and Tasks, where a TodoList has many Tasks.

$ ./script/generate model todo_list
$ ./script/generate model task

Now let’s get those tables created – edit the two migrations so the create tables look like these:

create_table :todo_lists do |t|
  t.column :name, :string
end

create_table :tasks do |t|
  t.column :name, :string
  t.column :todo_list_id, :integer
end

Declare the relationships in the models:

app/models/task.rb

class Task < ActiveRecord::Base
  belongs_to :todo_list
end

app/models/todo_list.rb

class TodoList < ActiveRecord::Base
  has_many :tasks
end

Then just a quick

$ rake migrate

…and we’re good to go. Gotta love Rails eh?

If you’re following along you might want to pause here to get some data in there. Personally I’d use ./script/console but you might prefer scaffolding, your MySQL GUI…

</skippable>


(Welcome back to the skimmers :-) What you missed: we’re working with a skeleton app with a TodoList model that has a name and has_many :tasks and a Task model that has a name and belongs_to :todo_list)

OK lets create a view of a single list

$ ./script/generate controller todo_lists

app/controllers/todo_lists_controller.rb

class TodoListsController < ApplicationController

  def show
    @this = TodoList.find(params[:id])
  end

end

@this?? That’s kind of unconventional isn’t it? The implicit context in a DRYML template is held in a variable this (actually it’s not a variable, it’s a method, but don’t worry about it). To set the context for the whole page, we assign to @this in the controller.

Now the view. We can access the context as this in a regular ERB scriptlet.

app/views/todo_lists/show.dryml

<h1>Todo List: <%= this.name %></h1>

<ul>
  <% this.tasks.each do |task| %>
    <li><%= task.name %></li>
  <% end %>
</ul>

Now lets clean that up with some DRYML goodness. First we’ll use <repeat>, which is part of the core taglib (available everywhere) instead of that loop. Let’s see the code first, and then go through how it works

app/views/todo_lists/show.dryml

<h1>Todo List: <%= this.name %></h1>

<ul>
  <repeat attr="tasks">
    <li><%= this.name %></li>
  </repeat>
</ul>

Starting to look cleaner! Two things to notice. First: we gave repeat just the name of the attribute we were interested in (tasks). It implicitly found that collection in the current context (the current value of this). We are therefore iterating over this.tasks. In other words, you just say “how to get there from here”: the page is displaying a TodoList, so iterate over the tasks. Nice and easy.

(Aside: We use the term ‘attribute’ here in the Ruby sense, as in, say, attr_reader. Unfortunately, in a mark-up setting that term conflicts confusingly with XML attributes. We might change this name. What else could you call the attributes of a model object? Properties? Fields?)

The second thing to notice is that inside the repeat, we’re using this again, only now it refers to the individual task. repeat sets the context to each item in the collection in turn. If you’ve ever worked with XSL-T, this idea may be familiar.

Notice now that both the scriptlets that display the name are identical. Bad programmer! Don’t repeat yourself! No problemo:

app/views/todo_lists/show.dryml

<def tag="name"><%= this.name %></def>

<h1>Todo List: <name/></h1>

<ul>
  <repeat attr="tasks">
    <li><name/></li>
  </repeat>
</ul>

Note that the name tag declares this as an attribute. Any tag that’s going to use this should declare so in this way, even though we never actually give this as an attribute when we use the tag.

Next we should move that <def> to the global taglib (application.dryml, which lives in app/views/hobolib). While we’re at it, <ul>/<li> lists tend to crop up all over the place, right? Bad programmer! Don’t repeat yourself! Let’s make a tag for those lists.

app/views/hobolib/application.dryml

<def tag="name"><%= this.name %></def>

<def tag="ul_for">
  <ul>
  <repeat>
    <li><tagbody/></li>
  </repeat>
  </ul>
</def>

The ul_for tag expects the context to be a collection. Here’s how we use it:

app/views/todo_lists/show.dryml

<h1>Todo List: <name/></h1>

<ul_for attr="tasks"><name/></ul_for>

You can’t ask for much more concise than that! Let’s now improve things a bit. Suppose the individual tasks were each going to have their own page in this app, perhaps displaying notes and such-like. In that case, we’d like that list to be a list of links. Here’s a handy tag that makes it easy to create a link to anything with a name:

app/views/hobolib/application.dryml (fragment)

<def tag="name_link">
  <%= link_to this.name,
              :controller => this.class.name.underscore.pluralize,
              :action => 'show',
              :id => this %>
</def>

There’s a little reflective name-mangling magic going there, but the beauty is that we can forget about that and just use the name_link tag. The change to our page to add our links is trivial:

app/views/todo_lists/show.dryml

<h1>Todo List: <name/></h1>

<ul_for attr="tasks"><name_link/></ul_for>

And we’re done. For today at least. Now – bearing in mind that this page is dramatically simpler than a typical page in a production app – let’s just compare:

Traditional ERB

<h1>Todo List: <%= @todo_list.name %></h1>

<ul>
  <% @todo_list.tasks.each do |task| %>
    <li>
      <%= link_to task.name, :controller => "tasks",
                             :action => "show",
                             :id => task %>
    </li>
  <% end %>
</ul>

…to…

DRYML

<h1>Todo List: <name/></h1>

<ul_for attr="tasks"><name_link/></ul_for>

I don’t know about you but to me that’s like a breath of fresh air. Now imagine that clarity in the context of a vastly more complex production app, and you might see what Hobo is all about.

(And we still haven’t shown you the best bit…)

DRYML, meet ActiveRecord

Posted almost 8 years back at The Hobo Blog

DRYML has a nifty little feature called implicit context. Despite the title of this post, this feature has got nothing directly to do with ActiveRecord. Implicit context makes it a lot easier to populate your pages with data, and in Rails that means ActiveRecord models. So this post is about getting your models into your views.

For those that want all the details, we’ll do the whole thing from scratch: create the Rails app, install Hobo, create some models… For those who don’t, you can skip the stuff between the two rules


<skippable>

Let’s get started with a fresh Rails app and get Hobo installed:

$ rails hobo_demo
$ mysqladmin create hobo_demo_development
$ cd hobo_demo
$ ./script/plugin install svn://hobocentral.net/hobo/trunk
$ ./script/generate hobo

…then create some models, populate with some data. Hmm, I guess we need to pick some kind of domain to model. How about a simple to-do list app? Groan OK but it’s a cliché for a reason - simple, familiar… Let’s move on :-)

To start we’ll just have TodoLists and Tasks, where a TodoList has many Tasks.

$ ./script/generate model todo_list
$ ./script/generate model task

Now let’s get those tables created – edit the two migrations so the create tables look like these:

create_table :todo_lists do |t|
  t.column :name, :string
end

create_table :tasks do |t|
  t.column :name, :string
  t.column :todo_list_id, :integer
end

Declare the relationships in the models:

app/models/task.rb

class Task < ActiveRecord::Base
  belongs_to :todo_list
end

app/models/todo_list.rb

class TodoList < ActiveRecord::Base
  has_many :tasks
end

Then just a quick

$ rake migrate

…and we’re good to go. Gotta love Rails eh?

If you’re following along you might want to pause here to get some data in there. Personally I’d use ./script/console but you might prefer scaffolding, your MySQL GUI…

</skippable>


(Welcome back to the skimmers :-) What you missed: we’re working with a skeleton app with a TodoList model that has a name and has_many :tasks and a Task model that has a name and belongs_to :todo_list)

OK lets create a view of a single list

$ ./script/generate controller todo_lists

app/controllers/todo_lists_controller.rb

class TodoListsController < ApplicationController

  def show
    @this = TodoList.find(params[:id])
  end

end

@this?? That’s kind of unconventional isn’t it? The implicit context in a DRYML template is held in a variable this (actually it’s not a variable, it’s a method, but don’t worry about it). To set the context for the whole page, we assign to @this in the controller.

Now the view. We can access the context as this in a regular ERB scriptlet.

app/views/todo_lists/show.dryml

<h1>Todo List: <%= this.name %></h1>

<ul>
  <% this.tasks.each do |task| %>
    <li><%= task.name %></li>
  <% end %>
</ul>

Now lets clean that up with some DRYML goodness. First we’ll use <repeat>, which is part of the core taglib (available everywhere) instead of that loop. Let’s see the code first, and then go through how it works

app/views/todo_lists/show.dryml

<h1>Todo List: <%= this.name %></h1>

<ul>
  <repeat attr="tasks">
    <li><%= this.name %></li>
  </repeat>
</ul>

Starting to look cleaner! Two things to notice. First: we gave repeat just the name of the attribute we were interested in (tasks). It implicitly found that collection in the current context (the current value of this). We are therefore iterating over this.tasks. In other words, you just say “how to get there from here”: the page is displaying a TodoList, so iterate over the tasks. Nice and easy.

(Aside: We use the term ‘attribute’ here in the Ruby sense, as in, say, attr_reader. Unfortunately, in a mark-up setting that term conflicts confusingly with XML attributes. We might change this name. What else could you call the attributes of a model object? Properties? Fields?)

The second thing to notice is that inside the repeat, we’re using this again, only now it refers to the individual task. repeat sets the context to each item in the collection in turn. If you’ve ever worked with XSL-T, this idea may be familiar.

Notice now that both the scriptlets that display the name are identical. Bad programmer! Don’t repeat yourself! No problemo:

app/views/todo_lists/show.dryml

<def tag="name"><%= this.name %></def>

<h1>Todo List: <name/></h1>

<ul>
  <repeat attr="tasks">
    <li><name/></li>
  </repeat>
</ul>

Note that the name tag declares this as an attribute. Any tag that’s going to use this should declare so in this way, even though we never actually give this as an attribute when we use the tag.

Next we should move that <def> to the global taglib (application.dryml, which lives in app/views/hobolib). While we’re at it, <ul>/<li> lists tend to crop up all over the place, right? Bad programmer! Don’t repeat yourself! Let’s make a tag for those lists.

app/views/hobolib/application.dryml

<def tag="name"><%= this.name %></def>

<def tag="ul_for">
  <ul>
  <repeat>
    <li><tagbody/></li>
  </repeat>
  </ul>
</def>

The ul_for tag expects the context to be a collection. Here’s how we use it:

app/views/todo_lists/show.dryml

<h1>Todo List: <name/></h1>

<ul_for attr="tasks"><name/></ul_for>

You can’t ask for much more concise than that! Let’s now improve things a bit. Suppose the individual tasks were each going to have their own page in this app, perhaps displaying notes and such-like. In that case, we’d like that list to be a list of links. Here’s a handy tag that makes it easy to create a link to anything with a name:

app/views/hobolib/application.dryml (fragment)

<def tag="name_link">
  <%= link_to this.name,
              :controller => this.class.name.underscore.pluralize,
              :action => 'show',
              :id => this %>
</def>

There’s a little reflective name-mangling magic going there, but the beauty is that we can forget about that and just use the name_link tag. The change to our page to add our links is trivial:

app/views/todo_lists/show.dryml

<h1>Todo List: <name/></h1>

<ul_for attr="tasks"><name_link/></ul_for>

And we’re done. For today at least. Now – bearing in mind that this page is dramatically simpler than a typical page in a production app – let’s just compare:

Traditional ERB

<h1>Todo List: <%= @todo_list.name %></h1>

<ul>
  <% @todo_list.tasks.each do |task| %>
    <li>
      <%= link_to task.name, :controller => "tasks",
                             :action => "show",
                             :id => task %>
    </li>
  <% end %>
</ul>

…to…

DRYML

<h1>Todo List: <name/></h1>

<ul_for attr="tasks"><name_link/></ul_for>

I don’t know about you but to me that’s like a breath of fresh air. Now imagine that clarity in the context of a vastly more complex production app, and you might see what Hobo is all about.

(And we still haven’t shown you the best bit…)

A Quick Guide to DRYML

Posted almost 8 years back at The Hobo Blog

UPDATE: This stuff is very out of date now, you might prefer to look here

Gosh - there’s quite a lot in here - where to start? Guess I’ll just dive right in.

To follow along, create yourself a new app, install Hobo, and throw in a demo controller. (for help with that, see Hello World)

Tags can be defined inside your views, making them local to that view. Useful for quick prototyping:

app/views/demo/my_page.dryml

<def tag="time"><%= Time.now %></def>

<p>The time is <time/></p>

More commonly you’d define tags in app/views/hobolib/application.dryml, making them available to your whole app, but for the purposes of exploring we’ll stick with local definitions.

Tags can have attributes. They are available as local variables inside the definition:

<def tag="time" attrs='format'>
  <%= Time.now.strftime(format) %>
</def>

<p>Today is <time format='%A'/></p>

Tags can call other tags, as you’d expect:

<def tag="time" attrs='format'>
  <%= Time.now.strftime(format) %>
</def>

<def tag='today'><time format='%A'/></def>

<p>Today is <today/></p>

Tags can have a body. Use DRYML’s <tagbody/> to insert the body where you need it:

<def tag="flower_box">
  <div class='flower_box'>
    <img src='flower.gif'/><tagbody/>
  </div>
</def>

<flower_box>Nice flower eh?</flower_box>

(Aside: yes, you could have done something similar with CSS, but there plenty you can’t do with CSS, like adding drop shadows in a way that copes with resizing. The drop-shadow technique I prefer needs 8 nested DIVs. Boy was I ever glad to wrap that in a tag)

Watch out for the XHTML compliant image tag (<img ... />). DRYML templates must be valid XML, except for two relaxations: they may contain ERB scriplets (in content or attribute values), and they need not have a single root tag.

OK let’s define a tag that lays out a whole page – yes you can use DRYML tags instead of layouts. This has the advantage of letting the choice of page-layout be made in the view, where it belongs (regular Rails layouts are selected in the controller). It also makes it easier for the page to pass bits-and pieces to the layout, such as a title and an onload event.

Here’s a simple page layout that separates the header and footer with a horizontal rule no less! Notice how we define multiple attributes using commas in attrs attribute.

<def tag='page' attrs='title,onload,header,footer'>
  <html>
    <head><title><%= title %></title></head>
    <body onload="<%= onload %>">

      <div class='header'>
        <%= header %>
      </div>
      <hr/>

      <tagbody/>

      <hr/>
      <div class='footer'>
        <%= footer %>
      </div>

    </body> 
  </html>
</def>


<page title="My Page"
      onload="alert('NO PLEASE! Not an onload alert!')">
  My wonderful page
</page>

Note the absence of a header and footer in that case. We’d rather not define those in attributes, as they’ll probably contain mark-up. So we’ll use an alternate syntax for supplying parameters to tags. Lets quickly get rid of that horrible alert too - if we don’t supply the onload, the result in the rendered page will simply be a blank onload on the <body> tag.

<def tag='page' attrs='title,onload,header,footer'>
  <html>
    <head><title><%= title %></title></head>
    <body onload="<%= onload %>">

      <div class='header'>
        <%= header %>
      </div>
      <hr/>

      <tagbody/>

      <hr/>
      <div class='footer'>
        <%= footer %>
      </div>

    </body> 
  </html>
</def>


<page title="My Page">
  <:header>
    Welcome to my site
  </:header>

  My wonderful page

  <:footer>
    My site. &copy; Me. Some Rights Reserved
  </:footer>
</page>

Those tags that start with a colon, e.g. <:footer>, are not defined tags. They are simply parameters to the <page> tag. They can appear anywhere directly inside the call (i.e. the <page> tag in this case). They could even have been given the other way around, the result would be the same.

Obviously the <page> tag isn’t much use unless it’s defined somewhere where it can be used by multiple pages. The simplest thing is to move it into app/views/hobolib/application.dryml. That library – or taglib as we call them – is implicitly imported by every page in your app. Alternatively here’s how you could put it into your own taglib instead. Move just the <def> into a new file e.g.:

app/views/shared/my_tags.dryml

<def tag='page' attrs='title,onload,header,footer'>
  <html>
    <head><title><%= title %></title></head>
    <body onload="<%= onload %>">

      <div class='header'>
        <%= header %>
      </div>
      <hr/>

      <tagbody/>

      <hr/>
      <div class='footer'>
        <%= footer %>
      </div>

    </body> 
  </html>
</def>

In the page, instead of the full definition of <page>, you now just need to import that taglib using, um, <taglib>. Like this:

<taglib src="shared/my_tags"/>

<page title="My Page">
  <:header>
    <h1>Welcome to my site</h1>
  </:header>
  <:footer>
    <i>My site. &copy; Me. Some Rights Reserved</i>
  </:footer>

  My wonderful page

</page>

If you define your tags in app/views/hobolib/application.dryml, you don’t need to use <taglib> – this is the global taglib and is always imported. Convention over configuration, man!

A Quick Guide to DRYML

Posted almost 8 years back at The Hobo Blog

UPDATE: This stuff is very out of date now, you might prefer to look here

Gosh - there’s quite a lot in here - where to start? Guess I’ll just dive right in.

To follow along, create yourself a new app, install Hobo, and throw in a demo controller. (for help with that, see Hello World)

Tags can be defined inside your views, making them local to that view. Useful for quick prototyping:

app/views/demo/my_page.dryml

<def tag="time"><%= Time.now %></def>

<p>The time is <time/></p>

More commonly you’d define tags in app/views/hobolib/application.dryml, making them available to your whole app, but for the purposes of exploring we’ll stick with local definitions.

Tags can have attributes. They are available as local variables inside the definition:

<def tag="time" attrs='format'>
  <%= Time.now.strftime(format) %>
</def>

<p>Today is <time format='%A'/></p>

Tags can call other tags, as you’d expect:

<def tag="time" attrs='format'>
  <%= Time.now.strftime(format) %>
</def>

<def tag='today'><time format='%A'/></def>

<p>Today is <today/></p>

Tags can have a body. Use DRYML’s <tagbody/> to insert the body where you need it:

<def tag="flower_box">
  <div class='flower_box'>
    <img src='flower.gif'/><tagbody/>
  </div>
</def>

<flower_box>Nice flower eh?</flower_box>

(Aside: yes, you could have done something similar with CSS, but there plenty you can’t do with CSS, like adding drop shadows in a way that copes with resizing. The drop-shadow technique I prefer needs 8 nested DIVs. Boy was I ever glad to wrap that in a tag)

Watch out for the XHTML compliant image tag (<img ... />). DRYML templates must be valid XML, except for two relaxations: they may contain ERB scriplets (in content or attribute values), and they need not have a single root tag.

OK let’s define a tag that lays out a whole page – yes you can use DRYML tags instead of layouts. This has the advantage of letting the choice of page-layout be made in the view, where it belongs (regular Rails layouts are selected in the controller). It also makes it easier for the page to pass bits-and pieces to the layout, such as a title and an onload event.

Here’s a simple page layout that separates the header and footer with a horizontal rule no less! Notice how we define multiple attributes using commas in attrs attribute.

<def tag='page' attrs='title,onload,header,footer'>
  <html>
    <head><title><%= title %></title></head>
    <body onload="<%= onload %>">

      <div class='header'>
        <%= header %>
      </div>
      <hr/>

      <tagbody/>

      <hr/>
      <div class='footer'>
        <%= footer %>
      </div>

    </body> 
  </html>
</def>


<page title="My Page"
      onload="alert('NO PLEASE! Not an onload alert!')">
  My wonderful page
</page>

Note the absence of a header and footer in that case. We’d rather not define those in attributes, as they’ll probably contain mark-up. So we’ll use an alternate syntax for supplying parameters to tags. Lets quickly get rid of that horrible alert too - if we don’t supply the onload, the result in the rendered page will simply be a blank onload on the <body> tag.

<def tag='page' attrs='title,onload,header,footer'>
  <html>
    <head><title><%= title %></title></head>
    <body onload="<%= onload %>">

      <div class='header'>
        <%= header %>
      </div>
      <hr/>

      <tagbody/>

      <hr/>
      <div class='footer'>
        <%= footer %>
      </div>

    </body> 
  </html>
</def>


<page title="My Page">
  <:header>
    Welcome to my site
  </:header>

  My wonderful page

  <:footer>
    My site. &copy; Me. Some Rights Reserved
  </:footer>
</page>

Those tags that start with a colon, e.g. <:footer>, are not defined tags. They are simply parameters to the <page> tag. They can appear anywhere directly inside the call (i.e. the <page> tag in this case). They could even have been given the other way around, the result would be the same.

Obviously the <page> tag isn’t much use unless it’s defined somewhere where it can be used by multiple pages. The simplest thing is to move it into app/views/hobolib/application.dryml. That library – or taglib as we call them – is implicitly imported by every page in your app. Alternatively here’s how you could put it into your own taglib instead. Move just the <def> into a new file e.g.:

app/views/shared/my_tags.dryml

<def tag='page' attrs='title,onload,header,footer'>
  <html>
    <head><title><%= title %></title></head>
    <body onload="<%= onload %>">

      <div class='header'>
        <%= header %>
      </div>
      <hr/>

      <tagbody/>

      <hr/>
      <div class='footer'>
        <%= footer %>
      </div>

    </body> 
  </html>
</def>

In the page, instead of the full definition of <page>, you now just need to import that taglib using, um, <taglib>. Like this:

<taglib src="shared/my_tags"/>

<page title="My Page">
  <:header>
    <h1>Welcome to my site</h1>
  </:header>
  <:footer>
    <i>My site. &copy; Me. Some Rights Reserved</i>
  </:footer>

  My wonderful page

</page>

If you define your tags in app/views/hobolib/application.dryml, you don’t need to use <taglib> – this is the global taglib and is always imported. Convention over configuration, man!

Why DRYML?

Posted almost 8 years back at The Hobo Blog

Why? Rails already has a bunch of mechanisms for re-use within views. Namely: layouts, partials and helpers. Each serves a different purpose, and yet, IMHO, there’s still a gap. I find that small fragments of mark-up tend to crop up over and over in my views. Yes I could extract them into paritals or helpers, but I find myself disinclined to do so.

Helpers are good for small bits of dynamic content, but not so convenient for re-use of HTML fragments - I don’t really want to embed loads of HTML in strings in Ruby source. Nor do I want to make excessive use of the tag helper. I want to put mark-up in mark-up files.

So partials would be appropriate. But each partial needs it’s own file, which again discourages me from making heavy use of them.

Finally, and prefixed with a big ol’ IMHO – dang are those ERB scriptlets ever ugly! If you ever needed to call a helper passing in HTML mark-up in the parameters, that’s HTML within Ruby within HTML – not pretty. Hey, it works right? This is not a criticism of ERB. The syntax used (<%= ... %>) is like that for a reason. ERB doesn’t need fixing. DRYML supports ERB scriptlets, but allows you to hide them away behind nice clean custom tags, leaving you with beautiful clean templates swoon where you can see what’s going on at a glance.

Defining a tag essentially just creates a new helper method for you, and a use of that tag is nothing more than a call to that helper. This is just syntax. Witness:

hello_world.dryml

<def tag="hello">Hello World!</def>

<p>Here it is: <hello/></p>

<p>And here it is again: <%= hello %></p>

Groovy baby :-)

(check out the Hello World post to see how to get set up so you can try this)

And just as you can call a tag from Ruby instead of mark-up, you can define them in Ruby if you wish. You can do so in your helpers. Try this

app/helpers/application_helper.rb

module ApplicationHelper

  include Hobo::DefineTags

  def_tag :from_ruby do
    "As easy as that eh?"
  end

end

That will give you a <from_ruby/> tag in all of your DRYML templates. If your tag contains more code than mark-up, it’s cleaner to define it in a module like this.

You could even define the tag in a helper module and call it from an ERB scriptlet, but that would be kinda strange… Hey – knock yourself out, it’s all good :-)

I’m trying not to get ahead of myself because there’s a Quick Guide to DRYML coming right up. I just want to show you that this is just a thin layer on top of your regular Rails template. They’re just purdier is all.

Actually there’s a lot more under the hood in DRYML – it’s not just syntax. We’ll get there.

Why DRYML?

Posted almost 8 years back at The Hobo Blog

Why? Rails already has a bunch of mechanisms for re-use within views. Namely: layouts, partials and helpers. Each serves a different purpose, and yet, IMHO, there’s still a gap. I find that small fragments of mark-up tend to crop up over and over in my views. Yes I could extract them into paritals or helpers, but I find myself disinclined to do so.

Helpers are good for small bits of dynamic content, but not so convenient for re-use of HTML fragments - I don’t really want to embed loads of HTML in strings in Ruby source. Nor do I want to make excessive use of the tag helper. I want to put mark-up in mark-up files.

So partials would be appropriate. But each partial needs it’s own file, which again discourages me from making heavy use of them.

Finally, and prefixed with a big ol’ IMHO – dang are those ERB scriptlets ever ugly! If you ever needed to call a helper passing in HTML mark-up in the parameters, that’s HTML within Ruby within HTML – not pretty. Hey, it works right? This is not a criticism of ERB. The syntax used (<%= ... %>) is like that for a reason. ERB doesn’t need fixing. DRYML supports ERB scriptlets, but allows you to hide them away behind nice clean custom tags, leaving you with beautiful clean templates swoon where you can see what’s going on at a glance.

Defining a tag essentially just creates a new helper method for you, and a use of that tag is nothing more than a call to that helper. This is just syntax. Witness:

hello_world.dryml

<def tag="hello">Hello World!</def>

<p>Here it is: <hello/></p>

<p>And here it is again: <%= hello %></p>

Groovy baby :-)

(check out the Hello World post to see how to get set up so you can try this)

And just as you can call a tag from Ruby instead of mark-up, you can define them in Ruby if you wish. You can do so in your helpers. Try this

app/helpers/application_helper.rb

module ApplicationHelper

  include Hobo::DefineTags

  def_tag :from_ruby do
    "As easy as that eh?"
  end

end

That will give you a <from_ruby/> tag in all of your DRYML templates. If your tag contains more code than mark-up, it’s cleaner to define it in a module like this.

You could even define the tag in a helper module and call it from an ERB scriptlet, but that would be kinda strange… Hey – knock yourself out, it’s all good :-)

I’m trying not to get ahead of myself because there’s a Quick Guide to DRYML coming right up. I just want to show you that this is just a thin layer on top of your regular Rails template. They’re just purdier is all.

Actually there’s a lot more under the hood in DRYML – it’s not just syntax. We’ll get there.

Getting Started: Hello World in DRYML

Posted almost 8 years back at The Hobo Blog

Hello World will never get old for me. What more could you need to get yourself oriented in a new technology? I remember the first time I managed to string the whole J2EE stack together. All that technology – JNDI, RMI, EJB… All just to get “Hello World” on the screen. Hmmm. Can’t say I miss that too much.

Where was I?

Oh yes. One of the main features of Hobo is DRYML - an new template engine that extends ERB with user-defined tags. Thats right: extends. DRYML templates can use erb scriptlets just like regular RHTML templates.

We’re going to create a custom tag <hello> which will render - you guessed it - “Hello World” on the page. Obviously, the real goal here is to get Hobo installed and verify that it’s running.

To run Hobo you need Rails 1.2, which at the time of writing is available as release-candidate 1. Install it like this:

gem install rails --source http://gems.rubyonrails.org -y

To install Hobo into a new Rails app, simply:

$ rails hobo_hello_world
$ cd hobo_hello_world
$ ./script/plugin install svn://hobocentral.net/hobo/trunk

Next, there are one or two directories and files that Hobo expects to find. Create these with the handy generator:

$ ./script/generate hobo
  create  app/views/hobolib
  create  app/views/hobolib/themes
  create  app/views/hobolib/application.dryml

OK, Hobo is now at your service! Before we can have a Hello World view, of course, we’ll need a controller:

$ ./script/generate controller hello

No need to edit that. We’ll just go straight for the view.

File: app/views/hello/hello_world.dryml

<def tag="hello">Hello World!</def>

<p>Here it comes... Can you stand it??!</p>

<p style="font-size: 500%"> <hello/> </p>

That’s it. Start your engines:

$ ./script/server

And browse yourself over to localhost:3000/hello/hello_world

Outstanding work people. If that has whet your appetite and you want more, I suggest you haul your digital assets over to either Why DRYML? or A Quick Guide to DRYML.