[Radiant] Use of external DB and related data

David Peoples davidp at touringcyclist.com
Tue Dec 5 15:43:05 CST 2006


Silvano Stralla wrote:

> This is a possible plan: I thought to develop a series of custom tags  
> and behaviours to show in the pages the data coming from the intranet  
> database. Would you think it could be an easy path to follow for  
> doing what I have to do?
> 
> Thank you in advance for every help,
> Silvano
> 

I've done a similar project, displaying live data from an external 
database in a site managed by Radiant. Here are some details. (Apologies 
in advance to all the Rails/Ruby gurus for any gaffes in this code.)

===
Here is a behavior to run Ruby code in a Radiant web page:

   class RubycodeBehavior < Behavior::Base
     register "Rubycode"
     def cache_page?
       false
     end
     define_tags do
       tag "evalpart" do |tag|
         partname = tag.attr['part'] || 'ruby-code'
         t = eval(render_page_part(partname))
       end
     end
   end

===
Here is a sample page that uses the Rubycode behavior to display Ruby 
generated code. It has three parts (tabs), named "body", "ruby-code", 
and "ruby-code-2". (The names of the latter two aren't important, but 
'ruby-code' is the default name for the <r:evalpart /> tag.)

Contents of the "body" part:

   <h3>Ruby-code</h3>
   <r:evalpart />
   <h3>Ruby-code-2</h3>
   <r:evalpart part="ruby-code-2" />

Contents of the "ruby-code" part:

   a = "<p>Hello world!</p>\n"

Contents of the "ruby-code-2" part:

   b = "<p>Hello world 2!</p>\n"

The key is that the code in any 'eval-ed' page part *must* finish up by 
putting all its 'output' into a single variable that gets returned as 
the final step of the code.

===
Some Rails tips (probably obvious to most).

Use 'require_dependency', not 'require' to pull shared code into a ruby 
code page part. Using 'require' will fail (in development mode only?) 
when reloading an already displayed page.

Your models need a different database connection from the one set up by 
Radiant, without disturbing the Radiant connection. There are various 
ways to do this, but here is the method I'm using. Set up an 
intermediate class that descends from ActiveRecord::Base, like so:

   class Mybase < ActiveRecord::Base
     self.abstract_class = true # <-- Important. Done so
     # ActiveRecord doesn't think descendants of Mybase are
     # doing single table inheritance.
   end

   Mybase.establish_connection(
     # put new connection info here ...
   )

Then make all your models descend from Mybase.

David Peoples



More information about the Radiant mailing list