Home > Software engineering >  How to call a method inside a Ruby class definition
How to call a method inside a Ruby class definition

Time:01-03

I want to enhance my ActiveRecord models with a function that creates a type of scope or validation or whatever for particular fields on that model. I like to be able to do something like:

class MyModel < ApplicationRecord
  include MyCustomeBehavior

  my_custom_behavior :field_1, :field_2, ...
end

I'm looking at the ActiveSupport::Concern module and I would like to do something like:

module MyCustomeBehavior
  extend ActiveSupport::Concern

  # Where do I put this method so I can call it FROM INSIDE
  # the class definition of MyModel?
  def my_custom_behavior(*args)
    # gather the fields that I'm passing to this method from my model and then call the code below in the "included" block
  end

  included do
    # Ideally, I want to select these fields using a method like the one above.
    [:field_1, :field_2, ...].each do |field|
      # I want to be able to create my own scopes or validators or whatever
      # and I want to select particular fields for this based on whats passed to
      #
      # my_custom_behavior :field_1, :field_2, ...
      #
      # in my MyModel class.
      scope field ...
      validates field ...
    end
  end
end

CodePudding user response:

It has to be a class method:

module Mod
  extend ActiveSupport::Concern

  included do
    def self.also_class_method
      p "also class method"
    end
  end

  class_methods do
    # you can use `private` here
    def class_method
      p "class method"
    end
  end
end
class MyModel
  include Mod

  class_method
  also_class_method
end

"class method"
"also class method"

https://api.rubyonrails.org/classes/ActiveSupport/Concern.html

  • Related