File: activemodel.rb

package info (click to toggle)
ruby-enumerize 2.8.1-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 432 kB
  • sloc: ruby: 3,712; makefile: 6
file content (47 lines) | stat: -rw-r--r-- 1,053 bytes parent folder | download | duplicates (3)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
# frozen_string_literal: true

module Enumerize
  module ActiveModelAttributesSupport
    def enumerize(name, options={})
      super

      _enumerize_module.dependent_eval do
        if self.included_modules.include? ::ActiveModel::Attributes
          include InstanceMethods

          attribute name, Enumerize::ActiveModelAttributesSupport::Type.new(enumerized_attributes[name])
        end
      end
    end

    module InstanceMethods
      # https://github.com/brainspec/enumerize/issues/74
      def write_attribute(attr_name, value, *options)
        if self.class.enumerized_attributes[attr_name]
          _enumerized_values_for_validation[attr_name.to_s] = value
        end

        super
      end
    end

    class Type < ActiveModel::Type::Value
      def type
        :enumerize
      end

      def initialize(attr)
        @attr = attr
      end

      def serialize(value)
        v = @attr.find_value(value)
        v && v.value
      end

      def deserialize(value)
        @attr.find_value(value)
      end
    end
  end
end