Cassius Rosenthal on 27 Mar 2006 15:31:27 -0000

[Date Prev] [Date Next] [Thread Prev] [Thread Next] [Date Index] [Thread Index]

[PhillyOnRails] Dynamic Methods

I'm sure I'm alone when I say that I'm stuck on the dynamic class/methods thing. In Rails, I have a record that has an attribute which specifies extra features of that record. I think it would be cool (and appropriate?) to have the record's class dynamically change based on the attribute. So here's what I have (fictitious abstraction):

In 'controllers/vegetable_controller.rb' I call the action 'record', which finds the Vegetable, sees that it's a tuber, and so loads the 'tuber' model:

class VegetableController < ApplicationController
model :vegetable
def record
 # @vegetable.kind => "tuber"
 require 'models/vegetables/'+@vegetable.kind+'.rb'

In 'models/vegetable.rb' I have the base Vegetable class:

class Vegetable < ActiveRecord::Base
def self.list_all
 find(:all, :order => "name ASC" )

In 'models/vegetables/tuber.rb' I extend this instance of vegetable with the extra tuberific methods:

class << @vegetable
def roots

In 'views/vegetable/record.rxml' I try to call the extra tuber methods:>"true") if @vegetable.roots

. . . but it never works, unless I put the 'roots' function in the original class Vegetable definition. Oh, RoR gurus, what say you? Other than the fictitiousness of the example, any obvious wrong-doing? Did I get get it all backwardsidedown?

talk mailing list