I'm extending and including those files but still receive: undefined method after_initialize for Play:Class
class Play
extend ActiveModel::Callbacks
extend ActiveModel::Naming
include ActiveModel::Validations
include ActiveModel::Validations::Callbacks
include ActiveModel::Conversion
after_initialize :process_data
#...
end
I'm using Rails 4.
I don't know if you need all the ActiveModel overhead, but you could do it with less code:
class Play
include ActiveModel::Model
def initialize(attributes)
super(attributes)
after_initialize
end
private
def after_initialize
...
end
end
Try out following code
class Play
extend ActiveModel::Naming
extend ActiveModel::Callbacks
define_model_callbacks :initialize, :only => :after
include ActiveModel::Validations
include ActiveModel::Validations::Callbacks
include ActiveModel::Conversion
attr_accessor :name
def initialize(attributes = {})
attributes.each do |name, value|
send("#{name}=", value)
end
run_callbacks :initialize do
puts 'initialize callback'
end
end
def attributes
return @attributes if @attributes
@attributes = {
'name' => name
}
end
end
#1.9.2-p290 :001 > Play.new(:name => 'The name')
#initialize callback
# => #<Play:0x00000006806050 @name="The name">
#1.9.2-p290 :002 >
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With