Sha256: 5f057409a81fb592a61f5f0957491aa95a8163b1f1cf9993fbfde2790a832b9b

Contents?: true

Size: 643 Bytes

Versions: 1

Compression:

Stored size: 643 Bytes

Contents

require "active_record"
require "active_record/safe_initialize/version"

module ActiveRecord
  module SafeInitialize
    def safe_initialize(attribute, options = {})
      raise ArgumentError, "Missing initialization value" unless options[:with]

      after_initialize do
        if has_attribute?(attribute) && read_attribute(attribute).nil?
          value = options[:with]
          value = instance_exec(&value) if value.respond_to?(:call)
          value = self.send(value) if value.is_a?(Symbol)

          self.send "#{attribute}=", value
        end
      end
    end
  end
end

ActiveRecord::Base.extend ActiveRecord::SafeInitialize

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
activerecord-safe_initialize-0.0.1 lib/active_record/safe_initialize.rb