Extending Models in Extensions

Hi Folks… Longtime Radiant user, just getting started with Mental
Extensions.

I am creating an extension for posting and managing Comments. I’ve
created the Comment model, my controllers, and views in the new
Extension, but I’m having trouble extending Radiant’s built-in Page
model to include the proper has_many association.

In a nutshell: I want to include a has_many association in the Page
model.

It seems like I should be able to just open the Page class and
include my association like this:

class Page < ActiveRecord::Base
has_many :comments
end

in …/extensions/comments/app/models/page.rb

This doesn’t work, of course. It doesn’t return an error - as far as
I can tell it just doesn’t do anything. Referencing @page.comments in
my views throws an error: “undefined method `comments’”. I presume
it’s because it is ignoring this class.

I’ve also tried several module mix-ins that haven’t worked (i.e.
packaging a PageExtender module and then including it in Page). For
example:

module PageExtender
def self.included(base)
base.extend(ClassMethods)
end
module ClassMethods
has_many :comments
end
end

in …/extensions/comments/lib/page_extender.rb

And then

def activate

Page.send :include, PageExtender
end

in …/extensions/comments/comments_extension.rb

But this terminates with
~/Sites/radiant.mental/vendor/extensions/comments/lib/
page_extender.rb:8: undefined method `has_many’ for
PageExtender::ClassMethods:Module (NoMethodError)

Any ideas?

Thanks,
Ryan H.

I think I just solved my own problem.

Evidently it is easy to open up and extend the Page model

I put:

class Page < ActiveRecord::Base
has_many :comments
end

in …/extensions/comments/app/models/page.rb

and then

require File.dirname(FILE) + ‘/app/models/page’

in the extension definition.

On Mar 28, 2007, at 9:51 AM, Ryan H. wrote:

I can tell it just doesn’t do anything. Referencing @page.comments in
end

Any ideas?

Thanks,
Ryan H.


Radiant mailing list
Post: [email protected]
Search: http://radiantcms.org/mailing-list/search/
Site: http://lists.radiantcms.org/mailman/listinfo/radiant


Ryan H.
Art of Mission, Inc.
3720 Gattis School Rd #800 PMB 245
Round Rock, TX 78664

800-722-1492 (phone)

www.artofmission.com
[email protected]

Ryan H. wrote:

 end

Any ideas?

Try:

def activate
Page.class_eval do
has_many :comments
end
end

Or even:

module CommentsPageExtender
  def self.included(base)
    base.class_eval do
      has_many :comments
    end
  end
end

And:

def activate

Page.send :include, CommentsPageExtender
end


John L.
http://wiseheartdesign.com

I have been told that “send” calls will be deprecated in future
versions of Ruby and one should use class_eval or module_eval. Just
FYI. class_eval would work for most of these cases.

Sean

def activate

Page.send :include, PageExtender
end

Page.send(“has_many”, “comments”.intern)

would also work.

Sander de Goeij
[email protected]