Sha256: e4ef62063ac9ee5279abfb0245b96f4196678515ac49b72617d95d2a874d60f7

Contents?: true

Size: 967 Bytes

Versions: 3

Compression:

Stored size: 967 Bytes

Contents

require 'ostruct'

module RailsAttrEnum
  ## Forwarding class for actual attribute value
  EntryValue = Struct.new(:model, :attr_name, :enum) do
    delegate :==, :===, :inspect, to: :value

    def method_missing(name, *args, &block)
      default = proc { value.send(name, *args, &block) }

      if matches = /^(.*?)((\?|!)?)$/.match(name)
        const_name = matches[1].to_s.upcase
        if enum.const_defined?(const_name)
          case matches[2]
          when '?'
            value == enum.const_get(const_name)
          when '!'
            self.value = enum.const_get(const_name)
          else
            enum.const_get(const_name)
          end
        else
          default.call
        end
      else
        default.call
      end
    end

    def key
      enum.get_key(value)
    end

    def value
      model.read_attribute(attr_name)
    end

    private

    def value=(v)
      model.send(:write_attribute, attr_name, v)
    end
  end
end

Version data entries

3 entries across 3 versions & 1 rubygems

Version Path
rails_attr_enum-0.0.4 lib/rails_attr_enum/entry_value.rb
rails_attr_enum-0.0.3 lib/rails_attr_enum/entry_value.rb
rails_attr_enum-0.0.2 lib/rails_attr_enum/entry_value.rb