From: Gaspard Bucher Date: 2008-04-05T18:09:14+09:00 Subject: Re: Using a string as executable code OK. So your problem is offering database stored templates to your users. I have solved this problem for zena by creating a custom template language called zafu. The template is compiled to erb and saved as a file. To manage showing attributes of objects, this is how I worked this out (simplified): 1. in the model, I declare readable attributes: class Page zafu_readable :name, :created_at, :title, ... end 2. zafu code: 3. compile template (done once when changed, not on every call to the template) erb_code << Page.zafu_readable?(attribute) ? "<%= @node.#{attribute} %>" : "bad attribute '#{attribute}'" If you want to 'render' the template on each call, you could just keep the 'readable?' idea: Example with "person.name" : template: [[person:name]] template.gsub (/\[\[(\w):(\w)\]\]/) do object = $1 field = $2 if object = get_object(object) if object.class.readable_attribute?(field) object.instance_eval field else "invalid attribute '#{field}' for object of class '#{object.class}'" end else "invalid object '#{object}'" end end This is much more secure, avoids the fields table and keeps Model information in the model. If you are in rails, you could also use the 'attr_protected/attr_accessible' notion. Gaspard 2008/4/5, Peter Marks : > Phillip Gawlowski wrote: > > And a question you might want to ask yourself: Do I want to be starring > > on DailyWTF as "the developer before me"? > > > Haha, point taken. I'm not familiar with metaprogramming or marshall. > I'm looking into both. > > > > ara.t.howard wrote: > did you read my code? > > > I did, but I must not understand all of it. Sorry. > > > > ara.t.howard wrote: > > why don't you spell out your exact problem and we can show you how. > > > My db schema has a 'templates' table, a 'fields' table as well as a > 'template_fields' join table that connects 'fields' to 'templates'. > > 'fields' needs to contain information to produce a customized text > string for a particular object. Intuitively, I thought I needed to store > string generating code as a string in 'fields' and execute it against my > object. It was suggested I could do that like this: > > person.instance_eval field.code > > I use the resulting string and the field's 'name' to assemble a hash for > each field connected to a template: > > rehash = {} > for field in template.fields > rehash[field.name] = person.instance_eval field.code > end > > I then use the hash of generated strings and field names for a find and > replace function. > > -- > Posted via http://www.ruby-forum.com/. > >