Sha256: 6e9bf1b9836b4b2801ee404c9e5fa1a5669c6f0feff9da99469ee902548caf37

Contents?: true

Size: 987 Bytes

Versions: 5

Compression:

Stored size: 987 Bytes

Contents

require 'ostruct'

module RailsAttrEnum
  ## Forwarding class for actual attribute value
  EntryValue = Struct.new(:model, :attr_name, :enum) do
    delegate :==, :===, :inspect, :to_json, :as_json, 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

5 entries across 5 versions & 1 rubygems

Version Path
rails_attr_enum-0.2.0 lib/rails_attr_enum/entry_value.rb
rails_attr_enum-0.1.1 lib/rails_attr_enum/entry_value.rb
rails_attr_enum-0.1.0 lib/rails_attr_enum/entry_value.rb
rails_attr_enum-0.0.6 lib/rails_attr_enum/entry_value.rb
rails_attr_enum-0.0.5 lib/rails_attr_enum/entry_value.rb