0

I'm not sure how to phrase this, so here's an example:

I have a model List from which ProjectList and CategoryList inherit.

Both ProjectList and CategoryList define the following:

has_many :listed_items
attr_accessible :listed_attributes
accepts_nested_attributes_for :listed_attributes

Now, :listed_items are different for both classes, so I can't just paste this piece of code directly into List.

What I've tried is this (in List):

  class << self
    attr_accessor :listed

    def initialize_attributes!
      self.send :has_many, listed
      self.send :attr_accessible, "#{listed}_attributes"
      self.send :accepts_nested_attributes_for, listed, allow_destroy: true
    end
  end
  self.listed = nil

In CategoryList:

  self.listed = :categories
  self.initialize_attributes!

This works fine, but the fact that I have to call self.initialize_attributes! feels very hacky.

Is there a better alternative?

Thanks!

EDIT: here's what I've used

Given all I really wanted was to get rid of this double line in the inherited model, I've just renamed def initialize_attributes! to def has_many_lists(list) and got rid of the :listed variable. So now I call has_many_lists :categories in my inherited model...

ben
  • 1,432
  • 12
  • 17

1 Answers1

1

.inherited() hook can be useful there

http://ruby.runpaint.org/classes#class-inherited

sumskyi
  • 1,827
  • 13
  • 13
  • Thanks sumskyi! That seemed like a promising solution but I ended up bumping into the problem discussed here: http://stackoverflow.com/questions/790626/ruby-can-i-have-something-like-classinherited-thats-triggered-only-after-the I eventually found another way which in retrospective I feel I should have thought of earlier. I've updated my question with it. – ben Dec 13 '12 at 18:23