Sha256: ad8eb23c7f9aa7faee35e7b8ec19359383a0d5b58c040d4453d78595eca44659

Contents?: true

Size: 1.03 KB

Versions: 1

Compression:

Stored size: 1.03 KB

Contents

module EnumIsh
  class Builder
    class ActiveRecord < Builder
      private

      def define_default_value(attr, enum, config)
        method = "_enum_ish_init_#{attr}".to_sym

        @klass.class_eval do
          after_initialize method
          define_method method do
            public_send("#{attr}=", config[:default]) if respond_to?(attr) && public_send(attr).nil?
          end
        end
      end

      def define_accessor(attr, enum, config)
        method = "#{attr}_raw"

        @klass.class_eval do
          define_method method do
            read_attribute(attr)
          end
          define_method "#{attr}" do
            enum.invert[read_attribute(attr)]
          end
          define_method "#{attr}=" do |value|
            write_attribute(attr, enum[value])
          end
        end
      end

      def define_scope(attr, enum, config)
        method = "with_#{attr}"

        @klass.class_eval do
          scope method, ->(value) {
            where(attr => value)
          }
        end
      end
    end
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
enum_ish-1.0.0 lib/enum_ish/builder/active_record.rb