Sha256: 9642d0638cdf5d4899589bc8a4b75df5ae0d85cc3bd593bc8266d597934cf40e

Contents?: true

Size: 823 Bytes

Versions: 2

Compression:

Stored size: 823 Bytes

Contents

module ClassyEnum
  module Attributes

    def classy_enum_attr(klass, method=nil)

      method ||= klass

      klass = klass.to_s.camelize.constantize

      self.instance_eval do

        # Add ActiveRecord validation to ensure it won't be saved unless it's an option
        validates_each [method], :allow_nil => true do |record, attr_name, value|
          record.errors.add(attr_name, "must be one of #{klass.all.map(&:to_sym).join(', ')}") unless klass.all.map(&:to_s).include? value.to_s
        end

        # Define getter method
        define_method method do
          klass.build(super())
        end

        # Define setter method
        define_method "#{method}=" do |value|
          super(value.to_s)
        end

      end

    end

  end
end

ActiveRecord::Base.send :extend, ClassyEnum::Attributes

Version data entries

2 entries across 2 versions & 1 rubygems

Version Path
classy_enum-0.6.1 lib/classy_enum/attributes.rb
classy_enum-0.6.0 lib/classy_enum/attributes.rb