I heard that the method surrounded by included do~end
will run when included.
I think enum is defined here because I want to use this enum in the included class, but I think it is different from the original use of included do~end
. Is this the correct way to use it?
Run = Is it similar to the definition?
I would appreciate it if you could let me know the details.
Some articles have the same behavior as class_eval do~end and included do~end
module A
extend ActiveSupport::Concern
included do
enum status: {published:0, draft:1}
end
end
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.
© 2024 OneMinuteCode. All rights reserved.