Skip to content

Instantly share code, notes, and snippets.

@willkoehler
Created May 25, 2015 02:06
Show Gist options
  • Select an option

  • Save willkoehler/7fce3ed7ea3669dd837a to your computer and use it in GitHub Desktop.

Select an option

Save willkoehler/7fce3ed7ea3669dd837a to your computer and use it in GitHub Desktop.
Simple symbolized accessor for Active Record
class String
def articleize
%w(a e i o u).include?(self[0].downcase) ? "an #{self}" : "a #{self}"
end
end
# 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