Skip to content

Commit d32d70d

Browse files
committed
Remove the activemodel dependency
We used it for casting the value to a defined type, but since we only support simple types like integers and strings, we can better use things like #to_i and #to_s. The other data type we support are other classes that include JsonPathAttribute, so we can call .parse on those with the parsed values.
1 parent ae18bb0 commit d32d70d

2 files changed

Lines changed: 17 additions & 25 deletions

File tree

json_path_attribute.gemspec

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -30,7 +30,6 @@ Gem::Specification.new do |spec|
3030
spec.executables = spec.files.grep(%r{\Aexe/}) { |f| File.basename(f) }
3131
spec.require_paths = ["lib"]
3232

33-
spec.add_dependency "activemodel", "~> 7.2"
3433
spec.add_dependency "activesupport", "~> 7.2"
3534
spec.add_dependency "jsonpath", "~> 1.1"
3635
end

lib/json_path_attribute/type.rb

Lines changed: 17 additions & 24 deletions
Original file line numberDiff line numberDiff line change
@@ -1,44 +1,37 @@
11
# frozen_string_literal: true
22

3-
require "active_model"
4-
53
module JsonPathAttribute
64
# Provides a way to cast values to a specific type
75
# This class is intended to be used internally by JsonPathAttribute
86
class Type
97
class << self
108
def cast_attribute(type, value, array: false)
119
return value if type == :source
12-
return cast_object_attribute(type, value, array: array) if type.is_a?(Class)
13-
14-
cast_to(type, value, array: array)
15-
end
16-
17-
def cast_to(type, value, array: false)
18-
return [] if value.nil? && array
19-
return false if value.nil? && type == :boolean
20-
21-
cast_type = ActiveModel::Type.lookup(type)
2210

23-
if array
24-
cast_array(value, type, cast_type)
25-
else
26-
cast_value(value, type, cast_type)
11+
if value.nil?
12+
return [] if array
13+
return false if type == :boolean
2714
end
15+
16+
array ? cast_array(type, value) : cast_value(type, value, array)
2817
end
2918

30-
def cast_array(values, type, cast_type)
31-
values.map do |value|
32-
next false if value.nil? && type == :boolean
19+
def cast_value(type, value, array)
20+
return cast_object_attribute(type, value, array: array) if type.is_a?(Class)
21+
return false if type == :boolean && value.nil?
3322

34-
cast_type.cast(value)
23+
case type
24+
when :string, :decimal
25+
value.to_s
26+
when :integer
27+
value.to_i
28+
else
29+
raise TypeError, "Unable to cast #{value.inspect} to #{type}"
3530
end
3631
end
3732

38-
def cast_value(value, type, cast_type)
39-
value = value.to_s if type == :decimal && value.is_a?(Float)
40-
41-
cast_type.cast(value)
33+
def cast_array(type, values)
34+
values.map { |element| cast_value(type, element, false) }
4235
end
4336

4437
def cast_object_attribute(type, value, array:)

0 commit comments

Comments
 (0)