Created
March 19, 2014 16:04
-
-
Save virtualstaticvoid/9645024 to your computer and use it in GitHub Desktop.
Rails 4 Concern for Default Attribute Values
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# | |
# | |
# 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