On Aug 24, 11:31 am, Dave Howell <[email protected]> wrote: > I mentioned this, er, maybe on this list, or maybe on the Ramaze list, I'm > not sure, a month or so ago, as something I was trying to do. I've now done > it, and thought I'd share the code for comment and in case it was useful for > other people. > > As I continue building this web site that lets staff members access Employees > and Sales Items and such (table names changed to protect the uninvolved), I > kept having to construct links to the page that would display, say, a single > employee's record, or a single sales record, or a single product, ad nauseum. > The HTML would look something like: > > <a href="/employee?id=43253">Fred Flintstone</a> > > I was getting kind of tired of doing this over and over (assume 'emp' > contains an employee dataset row): > > '<A href="/employee?id=' + emp[:id] + '">' + emp[:name] + '</a>' > > So I created a module that lets me do this, instead: > > emp.link{emp[:name]} > > It creates an XML unit (not a string, although it easily could, of course) > that wraps an anchor around the block and builds a URL for it from the data > in the database, like this: > > <A HREF="/{name of Model}?id={primary_key_value}">{contents of > block}</A> > > Yes, this is a gross violation of that whole MVC thing, since I'm mixing my > view with my model, but only the Sequel::Model possesses the knowledge of > what the primary key is. {shrug} > > My code, which I include into selected Sequel::Models, looks like this: > > module DBLink > require 'sequel/extensions/inflector' > include String::Inflections > def link(&contents) > PageUnit::link("/"+self.class.to_s.downcase.pluralize > + "?id=" + self.pk){yield(contents)} > end > public :link > end > > This is only partially helpful, because it's invoking my PageUnit class which > contains a lot of other constructors for blasting out HTML without having to > putter around with it. The non-depended equivalent is this: > > module DBLink > require 'sequel/extensions/inflector' > include String::Inflections > def link(&contents) > REXML::Element.new("a").add_attribute(:href, > "/"+self.class.to_s.downcase.pluralize + "?id=" + > self.pk).add_text(yield(contents)) > end > public :link > end > > (I'm not sure why I had to force 'link' public, but I did.) > In use, my model.rb file looks something like > > class Employee < Sequel::Model > include DBLink > [...other stuff...] > end > > class Product < Sequel::Model > include DBLink > end > > Thoughts, comments, opinions, brickbats, sarcasm?
The Sequel way would be to make it a plugin, but what you have should work fine. Jeremy -- You received this message because you are subscribed to the Google Groups "sequel-talk" group. To post to this group, send email to [email protected]. To unsubscribe from this group, send email to [email protected]. For more options, visit this group at http://groups.google.com/group/sequel-talk?hl=en.
