Skip to content

Instantly share code, notes, and snippets.

@kivanio
Forked from virtualstaticvoid/default_values.rb
Created June 22, 2014 21:40
Show Gist options
  • Save kivanio/aec63a405b155888fe46 to your computer and use it in GitHub Desktop.
Save kivanio/aec63a405b155888fe46 to your computer and use it in GitHub Desktop.
#
#
# Rails 4 concern for specifying default attribute values on models
#
# E.g. The following user has defaults defined for `active` and `manager` attributes
#
# class User < ActiveRecord::Base
# include Concerns::DefaultValues
#
# default_value :active, true
#
# default_value :manager do
# User.first
# end
#
# end
#
#
# [email protected]
#
module Concerns::DefaultValues
extend ActiveSupport::Concern
module ClassMethods
def default_value(attribute, default = nil, &block)
default = block if block_given?
self.class_eval do
before_validation(on: :create) do
default_value = default.respond_to?(:call) ? default.call : default
write_attribute(attribute, default_value) unless read_attribute(name)
end
end
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment