Skip to content

Instantly share code, notes, and snippets.

@virtualstaticvoid
Created March 19, 2014 16:04
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save virtualstaticvoid/9645024 to your computer and use it in GitHub Desktop.
Save virtualstaticvoid/9645024 to your computer and use it in GitHub Desktop.
Rails 4 Concern for Default Attribute Values
#
#
# 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
#
#
# virtualstaticvoid@gmail.com
#
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