Last active
August 13, 2022 16:26
-
-
Save jopotts/7301500 to your computer and use it in GitHub Desktop.
Simple default values on creation of ActiveRecord models
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 DefaultValues | |
def has_default_values(default_values = {}) | |
class_attribute :default_values | |
self.default_values = default_values | |
after_initialize :assign_default_values | |
include InstanceMethods | |
end | |
module InstanceMethods | |
private | |
def assign_default_values | |
return unless new_record? | |
default_values.each do |key, value| | |
self[key] = value if self[key].nil? | |
end | |
end | |
end | |
end |
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
# In config/initializers | |
ActiveRecord::Base.extend DefaultValues |
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
# Example usage | |
class SomeModel < ActiveRecord::Base | |
has_default_values( | |
title: "Default", | |
flag_yn: false | |
) | |
.. | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Thats a cool way to add default values and it looks reusable.