Sha256: 6f65762fbe23bcfc29e0153c3cf4b80386b56dcd4cce5c8d0ac70b2fe2905530

Contents?: true

Size: 1.47 KB

Versions: 1

Compression:

Stored size: 1.47 KB

Contents

module Wijet
  module SimpleEnumerations
    def self.included(base)
      base.extend ClassMethods
    end

    module ClassMethods
      def has_enumerated(name)
        EnumerationString::Enumeration.setup

        name = name.to_s

        define_method("#{name}=") do |value|
          value = value.to_s
          unless EnumerationString::Enumeration[name].include?(value) or value.blank?
            raise ArgumentError, "'#{value}' is not a value of enumeration '#{name}'"
          end
          write_attribute(name, value)
        end

        define_method(name) do
          EnumerationString::Enumeration.new(attributes[name])
        end
      end
    end

    module EnumerationString
      class Enumeration < String
        def initialize(value = "")
          super(value)
        end

        class << self
          def setup
            all.values.flatten.uniq.each do |value|
              define_method("#{value.gsub(/[^[:alnum:]]/, '_')}?") { self == value }
            end unless all.blank?
          end

          def [](name)
            raise ArgumentError, "Enumeration '#{name}' doesn't exist" unless all.has_key?(name.to_s)
            all[name.to_s]
          end

          def all
            Rails.cache.fetch('_simple_enumerations_') do
              YAML::load(File.read(File.join(RAILS_ROOT, 'config', 'enumerations.yml')))
            end
          end
        end

        def ==(object)
          super(object.to_s)
        end
      end
    end
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
objectreload-simple_enumerations-0.1.5 lib/simple_enumerations/simple_enumerations.rb