Dynamically include a module in a model at runtime?

I have a transaction (extends ActiveRecord :: Base). I have two different types of transactions: Buy or Donate. There is enough coincidence between them that there is no need to create two separate database tables, so I only have one table for transactions with the column "item_type".

However, there are various methods and checks for buying and donating, so it makes sense to split them into two different controllers and models. Instead of creating ActiveBase models (minus tables), I try to use modules for each of them.

This is what the Purchase module looks like.

module Purchase def self.included(base) base.validates :amount, :presence => true end def testing "testing" end end 

Here's how it is created: (this code is in the action of creating a purchase controller)

 @purchase = Transaction.new(params[:purchase]).extend(Purchase) 

I can call @ purchase.testing and it returns β€œtesting”. However, this check is not performed.

If I include the module in the traditional way in the transaction model, including "Include purchase", then they will work.

Any ideas how I can do this workflow? I have a little about this: http://paulsturgess.co.uk/articles/84-how-to-include-class-and-validation-methods-using-a-module-in-ruby-on-rails

+6
source share
2 answers

If you want to work with only one table and several columns, I think the preferred approach is unidirectional inheritance. You can read about it here if you are looking for unidirectional inheritance. As for your question, however, on how to enable a module, I think you will want to include the module in the metaclass for @purchase so that it is not included in all subsequent transactions. A view like this (can definitely be shortened):

 @purchase = Transaction.new(params[:purchase]) class << @purchase include Purchase end 

Then your check should work.

+5
source

Your included trick will not run when you do .extend(Purchase) . For this you need an extended hook. Inside the extended hook, you can call the Rails validation helpers in the eigenclass of the new Transaction object (as shown by @Adam).

+3
source

Source: https://habr.com/ru/post/919903/


All Articles