I don't know why enum is defined in included do in rails.

Asked 1 years ago, Updated 1 years ago, 345 views

1 Answers

enum should be in included.This is easy to understand considering when each line will be evaluated. The contents of the blocks passed to included will be evaluated when include in the class.

Before we talk about enum, consider the following modules as an example:

module M
  extend ActiveSupport::Concern

  puts "foo"

  included do
    puts "bar"
  end
end

When you define this module in the Rails console, only foo appears when you return the defined module itself.

 irb(main): 001:1*module A
irb(main): 002:1 *extend ActiveSupport::Concern
irb(main): 003:1*
irb(main): 004:1 * puts "foo"
irb(main): 005:1*
irb(main): 006:2 *included do
irb(main): 007:2 * puts "bar"
irb(main) : 008:1 * end
irb(main): 009:0>end
foo
=>#<Proc:0x00007fd91d38a038(irb):6>

If you define a class that includes this module, you will see a bar output each time you define such class.

 irb(main): 010:1*class C
irb(main): 011:1*include A
irb(main): 012:0>end
bar
=>C
irb(main): 013:1 * class D
irb(main): 014:1 *include A
irb(main): 015:0>end
bar
=>D

Thus, puts written in a similar location also evaluates the method call at different times.

Now, the enum defined in the ActiveRecord::Enum module is itself a method: https://api.rubyonrails.org/v7.0.4/classes/ActiveRecord/Enum.html

Therefore, as with this puts, the timing of the evaluation depends on whether you want to put it in a block passed to included.

enum should be called when include in the class, so it should be included in included as stated in the questionnaire.


2023-01-17 19:14

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.