Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails, what is a proper way to include callbacks into tableless model

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.

like image 822
nateless Avatar asked Jul 16 '13 16:07

nateless


2 Answers

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
like image 178
Tom Rossi Avatar answered Oct 27 '22 07:10

Tom Rossi


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 >
like image 35
Talgat Medetbekov Avatar answered Oct 27 '22 08:10

Talgat Medetbekov