1

I'm extracting part of my app into a Gem, which involves creating some new ActiveRecord models. At the moment these models look something like this:

Class Wordcount < ActiveRecord::Base
  belongs_to :keyword
  belongs_to :article
end

Class Keyword < ActiveRecord::Base
  has_many :wordcounts
  has_many :articles, :through => :wordcounts
end

The gem will hook into any ActiveRecord model with String or Text fields, not just my defined Article model in the existing Rails app this code comes from.

What do I need to do in order to generate the relevant AR associations based on whichever model the gem's functionality is being applied to? I'm hoping to end up with:

has_my_gem_functionality :on => [:field1, :field2, ...]

And for the rest to be safely encapsulated within the gem.

I'm assuming I'll also have to metaprogram the Migrations as well. I think what I'm trying to do is relatively simple, it's just slightly too far out of my comfort zone.

2
  • Can you be more specific on what migrations might be needed for this gem to function? Commented Jul 30, 2012 at 19:10
  • So the migrations would for the most part act indepedently: adding columns to the wordcounts and keywords tables. They will also need foreign keys for the tables they are hooking into, namely :article at present. I'm actually not certain about this, sorry: when you have a belongs_to or a has_many association, which tables (or both?) need foreign keys? Commented Jul 30, 2012 at 19:20

1 Answer 1

1

Use the source, luke! :)

Just take a look at the source of some other gems that do similar things. For example:

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for this. I had a look at a few other gems but just got confused; these examples are a little clearer. So if I understand correctly, I need to do class_eval do ;end, and use that to add methods to the class. I'll look into that method more now.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.