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
Now lets look at instance method
Lets take an example of class method
class User < ActiveRecord::Base define_singleton_method method_name do .. end enddefine_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
Post a Comment