Skip to content

Commit

Permalink
Merge pull request #163 from bgvo/mimic_rails_enum_behavior
Browse files Browse the repository at this point in the history
Add Rails true enum support
  • Loading branch information
haffla authored May 29, 2023
2 parents d8bcc75 + 4b41545 commit b050934
Show file tree
Hide file tree
Showing 2 changed files with 13 additions and 2 deletions.
4 changes: 3 additions & 1 deletion lib/jsonb_accessor/macro.rb
Original file line number Diff line number Diff line change
Expand Up @@ -66,7 +66,9 @@ def jsonb_accessor(jsonb_attribute, field_types)
define_method("#{name}=") do |value|
super(value)

attribute_value = public_send(name)
# If enum was defined, take the value from the enum and not what comes out directly from the getter
attribute_value = defined_enums[name].present? ? defined_enums[name][value] : public_send(name)

# Rails always saves time based on `default_timezone`. Since #as_json considers timezone, manual conversion is needed
if attribute_value.acts_like?(:time)
attribute_value = (JsonbAccessor::Helpers.active_record_default_timezone == :utc ? attribute_value.utc : attribute_value.in_time_zone).strftime("%F %R:%S.%L")
Expand Down
11 changes: 10 additions & 1 deletion spec/jsonb_accessor_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -17,9 +17,12 @@ def build_class(jsonb_accessor_config, &block)
build_class(
foo: :string,
bar: :integer,
ban: :integer,
baz: [:integer, { array: true }],
bazzle: [:integer, { default: 5 }]
)
) do
enum ban: { foo: 1, bar: 2 }
end
end
let(:instance) { klass.new }

Expand Down Expand Up @@ -59,6 +62,12 @@ def build_class(jsonb_accessor_config, &block)
expect(instance.bazzle).to eq(5)
end

it "supports enums" do
instance.ban = :foo
expect(instance.ban).to eq("foo")
expect(instance.options["ban"]).to eq(1)
end

it "initializes without the jsonb_accessor field selected" do
instance.save!

Expand Down

0 comments on commit b050934

Please sign in to comment.