回答編集履歴
1
文法が間違っていました。
answer
CHANGED
@@ -3,24 +3,31 @@
|
|
3
3
|
例えばこんな感じ。
|
4
4
|
```lang-ruby
|
5
5
|
class Person
|
6
|
-
|
6
|
+
extend ActiveModel::Callbacks
|
7
|
+
define_model_callbacks :initialize, :only => :after
|
7
8
|
attr_accessor :id, :name, :omg
|
8
9
|
|
9
10
|
after_initialize :init_omg
|
10
11
|
|
11
12
|
def initialize(attributes={})
|
13
|
+
attributes.each do |key, value|
|
14
|
+
send("#{key}=", value)
|
12
|
-
|
15
|
+
end
|
16
|
+
|
13
17
|
@omg ||= true
|
18
|
+
|
19
|
+
run_callbacks :initialize do
|
20
|
+
self.omg = false
|
21
|
+
end
|
14
22
|
end
|
15
|
-
|
16
|
-
|
23
|
+
|
17
|
-
|
18
|
-
def
|
24
|
+
def attritbutes
|
25
|
+
return @attributes if @attributes
|
26
|
+
@attributes = {
|
27
|
+
id: id,
|
19
|
-
|
28
|
+
name: name
|
29
|
+
}
|
20
30
|
end
|
21
31
|
end
|
22
|
-
|
23
|
-
person = Person.new(id: 1, name: 'bob')
|
24
|
-
person.omg # => false
|
25
32
|
```
|
26
33
|
after_initialize というコールバックはインスタンスが生成されたときに発火するので、Person.newでもPerson.where(name: 'bob')でも、いろんなときにコールバックが走ります。なので、結構扱いに注意しないと危険なコールバックですね。
|