Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add deserialisation for enum #195

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
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
4 changes: 4 additions & 0 deletions spec/extensions/enum_spec.cr
Original file line number Diff line number Diff line change
Expand Up @@ -65,6 +65,10 @@ module EnumSpec
end
end

it "can create from json", focus: true do
GenderType.from_json(%("male")).should eq(GenderType::Male)
end

it "can export to json" do
temporary do
reinit!
Expand Down
20 changes: 20 additions & 0 deletions src/clear/extensions/enum/enum.cr
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
require "json"

module Clear
class IllegalEnumValueError < Exception
end
Expand Down Expand Up @@ -28,6 +30,21 @@ module Clear
super(x) || @value == x
end

macro inherited
macro finished
# For Serialisation with JSON
def initialize(value : (::JSON::PullParser | String))
if value.is_a?(String)
@value = value
else
str = value.read_string
str.in?(self.class.authorized_values) || raise ::Clear::IllegalEnumValueError.new("Illegal enum value for `#{self.class}`: '#{str}'")
@value = str
end
end
end
end

module Converter(T)
def self.to_column(x) : T?
case x
Expand Down Expand Up @@ -93,6 +110,9 @@ module Clear
# MyApp::Gender.from_string("male") # < return MyApp::Gender::Male
# MyApp::Gender.from_string("unknown") # < throw Clear::IllegalEnumValueError
#
# (De)serialisation is also supported
# MyApp::Gender.from_json("male") # < return MyApp::Gender::Male
#
# MyApp::Gender.valid?("female") # < Return true
# MyApp::Gender.valid?("unknown") # < Return false
# ```
Expand Down