Toby DiPasquale on 27 Mar 2006 19:45:36 -0000


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

Re: [PhillyOnRails] Dynamic Methods


On Mon, Mar 27, 2006 at 10:47:12AM -0500, Cassius Rosenthal wrote:
> 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

You've just created an eigenclass out of the ActiveRecord::Base-derived
class you were working with. Unfortunately for what you're trying to do,
when Rails passes that stuff to the view, it simply copies the instance
variables into another object, b/c the view wouldn't normally be able to
access them.

What might be better for you here is to create a closure in your model
class that you assign to an instance variable in the controller so it can
be called in the view. This will correctly close over any pertinent
variables so they can be called from anywhere.

-- 
Toby DiPasquale
_______________________________________________
talk mailing list
talk@phillyonrails.org
http://lists.phillyonrails.org/mailman/listinfo/talk