问题
For one Model called Email.rb, I have a method shown below called new_todos.
This same method needs to be made available for Call.rb, Postalcard.rb, etcetera.
Rather than cutting and pasting this exact snippet across multiple Models of Active Records, how can I have it written just once and make it available to the appropriate Models?
I suspect it could work by putting a module in the /lib folder, but I'm not exactly sure....thanks!
def new_todos
Contact.campaign_id_is(self.campaign_id).each do |contact|
todo = Todo.new
todo.contact_id = contact.id
todo.user_id = contact.user_id
todo.asset = self.class.name
todo.asset_id = self.id
todo.original_date = contact.date_entered + self.days.days
todo.current_date = todo.original_date
todo.save
end
end
回答1:
As you say, you can create a module and include it where you need it.
#lib/todo_extension.rb
module TodoExtension
def new_todos
...
end
end
# call.rb, postalcard.rb...
include TodoExtension
来源:https://stackoverflow.com/questions/4116811/how-can-i-make-the-same-method-available-to-multiple-models-in-rails