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=Vegetable.find(@params[:id])
 # @vegetable.kind => "tuber"
 require 'models/vegetables/'+@vegetable.kind+'.rb'
end
end

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

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

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

class << @vegetable
def roots
 @roots=true
end
end

In 'views/vegetable/record.rxml' I try to call the extra tuber methods:

xml.works(:value=>"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?

Thanks!
-Cassius
_______________________________________________
talk mailing list
talk@phillyonrails.org
http://lists.phillyonrails.org/mailman/listinfo/talk