views:

62

answers:

2

Rails: i have a class method and i want to modify something of the instance

something like this:

class Test < Main
   template :box

   def test
      # here I want to access the template name, that is box
   end
end

class Main
   def initialize
   end

   def self.template(name)
      # here I have to save somehow the template name
      # remember is not an instance.
   end
end

that is similar to the model classes:

# in the model
has_many :projects

How do I do it?

EDIT:

class Main
  def self.template(name)
    @name = name
  end

  def template
    Main.instance_eval { @name }
  end
end

class Test < Main
    template 6
end

t = Test.new.template
t # t must be 6
A: 

There are a few different ways to do this. Here is one:

class Main
  def self.template(name)
    @name = name
  end
end

class Test < Main
  def test
    Main.instance_eval { @name }
  end
end

Main.template 5
Test.new.test
  ==> 5
ugly
thanks, but it's not exactly what i mean.. the "Main.template 5" must be into the Test < Main class(remember, there will be test01, test02 classes, and they should have different template names, and can't be shared! if i change in test01, should be not be changed in test02. just like in models.) The class "test" must work within the Main class. thanks ;) look in the edit(up)
Totty
A: 

You have to bite the bullet and learn ruby meta programming. There is a book on it.

http://pragprog.com/titles/ppmetr/metaprogramming-ruby

Here is one way to do it.

class M
  def self.template(arg)
    define_method(:template) do
      arg
    end
  end
end

class T < M
  template 6
end

t = T.new

puts t.template
jshen