Self.included - including class methods from a module in Ruby

I read this post: Ruby modules - enabled do end block - but it still doesn’t work when you use the block self.included do ... endin the module.

The message says that the code in the block will be run when you turn on the module, but what is the point of this if the purpose of a single module should be included? Shouldn't this code be running? This block does not have to be there to run this code, right?

What is the difference between the two below:

module M
  def self.included(base)
    base.extend ClassMethods
    base.class_eval do
      scope :disabled, -> { where(disabled: true) }
    end
  end

  module ClassMethods
    ...
  end
end

against.

module M
  def self.some_class_method
     ...
  end

  scope :disabled, -> { where(disabled: true) }
end
+4
source share
2 answers

What is the difference between the two examples?

ClassMethods scope . NoMethodError, scope. self.some_class_method .

, Ruby, :
/mixins Ruby

self.included, ?

. , , .

Ruby ?

Ruby , , , , , — , , . :

module M
  def self.class_method
    "foo"
  end

  def self.configure_module
    # add configuration for this module
  end
end

class C
  include M
end

configure_module, , C, . , , .

! ?

, , , . , - .

"" , , , , . , .

+2
module M
  # self.included is the hook which automatically runs when this module is included
  def self.included(base)
    puts 'this will be printed when this module will be included inside a class'
    base.extend ClassMethods
    base.class_eval do
      scope :disabled, -> { where(disabled: true) }
    end
  end

  def print_object_class
    self.class.name # here self will be the object of class which includes this module
  end

  module ClassMethods
    def print_class_name
      self.name # Here self would be the class which is including this module
    end
  end
end

module, , ()

self.included - , , .

declare module ClassMethods ,

, module ClassMethods, ,

Ex , Product,

class Product < ActiveRecord::Base
  include M
  puts 'after including M'
end

rails, , M class Product,

this will be printed when this module will be included inside a class

after including M .

Product.disabled # a scope with name 'disabled' is avaialble because of including the module M
Product.print_class_name # Outputs => 'Product' This method is available to class with the help of module M
Product.new.print_object_class #Outputs => 'Product'

, M , .

module N
  def self.abc
    puts 'basic module'
  end
end

abc define

N.abc # outputs 'basic module'

class Product < ActiveRecord::Base
  include  N
end

Product.ab# , Product Product.new.ab# , Product

, . , , .

+1

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


All Articles