Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 7 additions & 0 deletions lib/literal/rails/enum_macro.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
# frozen_string_literal: true

module Literal::Rails::EnumMacro
def literal_enum(attribute_name, enum, **)
attribute(attribute_name, :literal_enum, type: enum, subtype: type_for_attribute(attribute_name), **)
end
end
11 changes: 7 additions & 4 deletions lib/literal/rails/enum_type.rb
Original file line number Diff line number Diff line change
@@ -1,8 +1,9 @@
# frozen_string_literal: true

class Literal::Rails::EnumType < ActiveModel::Type::Value
def initialize(enum)
def initialize(enum, subtype)
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think this is the supertype not the subtype.

@enum = enum
@subtype = subtype || ActiveModel::Type::Value.new
super()
end

Expand All @@ -14,8 +15,10 @@ def cast(value)
case value
when nil
nil
when @enum
value
else
@enum.coerce(value)
@enum.coerce(@subtype.cast(value))
end
end

Expand All @@ -24,7 +27,7 @@ def serialize(value)
when nil
nil
else
@enum.coerce(value).value
@subtype.serialize(@enum.coerce(value).value)
end
end

Expand All @@ -33,7 +36,7 @@ def deserialize(value)
when nil
nil
else
@enum.coerce(value)
@enum.coerce(@subtype.deserialize(value))
end
end
end
6 changes: 4 additions & 2 deletions lib/literal/railtie.rb
Original file line number Diff line number Diff line change
Expand Up @@ -3,13 +3,15 @@
class Literal::Railtie < Rails::Railtie
initializer "literal.register_literal_enum_type" do
[ActiveRecord::Type, ActiveModel::Type].each do |registry|
registry.register(:literal_enum) do |name, type:|
Literal::Rails::EnumType.new(type)
registry.register(:literal_enum) do |name, type:, subtype:|
Literal::Rails::EnumType.new(type, subtype)
end

registry.register(:literal_flags) do |name, type:|
Literal::Rails::FlagsType.new(type)
end
end

ActiveRecord::Base.extend Literal::Rails::EnumMacro
end
end
Loading