Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using mixins to initialize class variables

I have

class Fruit < ActiveRecord::Base
    includes Skin
end

and the mixin module

module Skin
    def initialize
        self.skin = "fuzzy"
    end
end

I want it so that

>> Fruit.new
#<Fruit skin: "fuzzy", created_at: nil, updated_at: nil>
like image 262
axsuul Avatar asked Sep 03 '11 00:09

axsuul


1 Answers

Use the ActiveRecord after_initialize callback.

module Skin
  def self.included(base)
     base.after_initialize :skin_init
  end

  def skin_init
    self.skin = ...
  end
end

class Fruit < AR::Base
  include Skin
  ...
end
like image 170
Casper Avatar answered Oct 06 '22 00:10

Casper