Define method dynamically in Rails

We are going to create two types of methods Class method and Instance method
Lets take an example of class method
class User < ActiveRecord::Base
   define_singleton_method method_name do
     ..    
   end
end
define_singleton_method method will create class method, you can use this code in loop to create multiple methods. And you can call this method with class name and method_name so in this case User.method_name


Now lets look at instance method

class User < ActiveRecord::Base
   define_method method_name do
     ..    
   end
end
 
define_method method will create an instance method. And you can call this method with instance of class(object) and method_name so in this case User.first.method_name

Comments

Popular posts from this blog

Inserting and Moving elements inside Ruby Array

Difference between Validations, Callbacks and Observers