Created
May 25, 2015 02:06
-
-
Save willkoehler/7fce3ed7ea3669dd837a to your computer and use it in GitHub Desktop.
Simple symbolized accessor for Active Record
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
| class String | |
| def articleize | |
| %w(a e i o u).include?(self[0].downcase) ? "an #{self}" : "a #{self}" | |
| 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
| # Usage | |
| # symbolize :status, in: [ :complete, :on_track, :working, :on_hold ] | |
| # symbolize :benchmark_type, in: [ :none, :national, :custom ], allow_nil: true | |
| module SymbolizedAccessor | |
| extend ActiveSupport::Concern | |
| class_methods do | |
| def symbolize(attr_name, config = {}) | |
| # define attribute reader | |
| define_method(attr_name.to_s) { read_attribute(attr_name).try(:to_sym) } | |
| # define validator | |
| validates attr_name, inclusion: { in: config[:in] }, allow_nil: true | |
| validates(attr_name, presence: { message: "select #{attr_name.to_s.humanize.downcase.articleize}" }) unless config[:allow_nil] | |
| end | |
| end | |
| end | |
| ActiveRecord::Base.send(:include, SymbolizedAccessor) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment