How to create multiple class and instance methods in a Rails model

I'm doing it

def self.a ... end def a class.a end 

But for several methods, I would have to replicate instance methods.

I thought in the module

 module A def a; end end 

And then use it in my model as follows:

 extend A include A 

But I'm not sure where to place it according to the Rails folder structure, or even if I put the module inside my model.

Any tips?

+4
source share
2 answers

Option 1 - Self Extension

If you want to have all your instance methods as class methods, you can simply use extend self

 class A def foo ... end def bar ... end extend self end 

This will allow you to call foo like A.foo or A.new.foo .

Opt 2 - Included Module

If you want some of your instance methods to be available as class methods, you should create a module as you suggested. You can put this module in the lib/ folder and either require it or add lib in the startup path.

You can also include the module directly in the class as follows:

 class A def not_shared ... end module SharedMethods def foo ... end def bar ... end end extend SharedMethods include SharedMethods end 

Option 3 - Delegate

If you use Rails (or just ActiveSupport), you can also use the delegate method, which it adds to the class / module.

 class A def not_shared ... end def foo ... end def bar ... end delegate :foo, :bar, to: 'self.class' end 

See here for more details:

http://rdoc.info/docs/rails/3.0.0/Module:delegate

+4
source

You want to create a module, for example shared_methods.rb , you put the file in the /lib directory.

You would enable the module as follows:

 class NewClass include SharedMethods ... end 
+2
source

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


All Articles