Adding code to a model with a custom rake task
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
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.
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
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.
精彩评论