mercredi 11 novembre 2015

Instance and class methods in Ruby / Rails 3.2.22 and inheritance

I need some help with my plugin. I want to extend ActiveRecord::Base with a method that initializes another method that can be called in the controller.

It will look like this:

class Article < ActiveRecord::Base
    special_validator :title, :text
    ...
end

My attempt at extending the ActiveRecord::Base class with special_validator method looks like following:

module Plugin
    module Base
        extend ActiveSupport::Concern

        module ClassMethods
            def special_validator(*params)
                @@plugin_params == params

                self.class_eval do
                    def is_this_ok?
                        # Here will @@plugin_params be validated
                        return true
                    end
                end
            end
        end
    end
end

ActiveRecord::Base.send :include, Plugin::Base

So, in the controller, this could be done:

class ArticlesController < ApplicationController
    ...
    def create
        @article = Article.new(article_params)

        if @article.is_this_ok?
            ...
        end
    end
end

My question is whether special_validator should be a class method or an instance method. This function is to be called inside a model, as shown above. I wonder if I am extending the ActiveRecord::Base the right way. The is_this_ok? function is an instance method without any doubt.

I am using Rails 3.2.22.

Aucun commentaire:

Enregistrer un commentaire