views:

69

answers:

3

I have written a simple blog plugin (it's actually a rails engine). It is designed to be installed into an app that already has a user model set up.

In order to save me from having to open up my User model and manually inserting "has_many :posts", I'd like to write a rake task that automatically does this for me.

If I were to package my engine as a generator inside a gem, then the following would probably work:

def manifest
  record do |m|     
    m.insert_into "app/models/user.rb", 'has_many :posts'
  end
end

Can this kind of thing be done with from a rake task? I've look around and I can't find an answer... thanks in advance

+1  A: 

You can definitely access your model through a rake task. You have to be sure to pass it your environment though so that it knows about your models. For example,

desc"This will insert the Posts"

task(:insertPosts => :environment) do

#your code here

end
sosborn
Hi Sosborn, thanks for your advice. The solution to this particular problem was to include a user.rb file inside the plugin (as advised by Juan) so that the usre.rb file which is already present in the application prior to plugin installation is extended with extra functionality.
stephenmurdoch
+1  A: 

Can you include a model file in your plugin that would open up the User class and add the "has_many :posts"?

class User < ActiveRecord::Base
   has_many :posts
end

I think that would work because you can open Ruby classes at any time and from any file; so no matter if the project using your plugin has a user.rb file in his model folder, you file will also be loaded and the has_many will be added to the User class at runtime.

Hope it helps.

Juan Tarquino
Hi Juan, thanks for the advice. It worked! Thanks again.
stephenmurdoch
A: 

Is this a task where actually modifying the source is appropriate? Have you considered including a module? Please give further details of what you're trying to achieve for correct guidance.

Steve Graham
Hi Steve. I will look into this idea of using a module. For now the solution provided by Juan works.
stephenmurdoch