Created
December 22, 2014 22:23
-
-
Save kris/5e851bd47cdadacba38c to your computer and use it in GitHub Desktop.
This file contains hidden or 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
module Defaults | |
extend ActiveSupport::Concern | |
included do | |
# Make sure #set_default_values is called after initialize | |
after_initialize :set_default_values | |
# Set default values before initialize | |
def set_default_values | |
self.class.defaults.each do |attribute, param| | |
next if self.send(attribute).present? | |
value = param.respond_to?(:call) ? param.call(self) : param | |
self.send(:write_attribute, attribute, value) if self | |
end | |
end | |
end | |
module ClassMethods | |
# Store defaults | |
@@defaults = {} | |
# Set a default value | |
# | |
# @param [Symbol] Attribute | |
# @param [Mixed] Default value | |
def default(attribute, value = nil, &block) | |
@@defaults[attribute] = value || block | |
end | |
# Get default attributes | |
# | |
# @return [Hash] | |
def defaults | |
@@defaults | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment