Skip to content
Merged
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
1 change: 0 additions & 1 deletion json_path_attribute.gemspec
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,6 @@ Gem::Specification.new do |spec|
spec.executables = spec.files.grep(%r{\Aexe/}) { |f| File.basename(f) }
spec.require_paths = ["lib"]

spec.add_dependency "activemodel", "~> 7.2"
spec.add_dependency "activesupport", "~> 7.2"
spec.add_dependency "jsonpath", "~> 1.1"
end
41 changes: 17 additions & 24 deletions lib/json_path_attribute/type.rb
Original file line number Diff line number Diff line change
@@ -1,44 +1,37 @@
# frozen_string_literal: true

require "active_model"

module JsonPathAttribute
# Provides a way to cast values to a specific type
# This class is intended to be used internally by JsonPathAttribute
class Type
class << self
def cast_attribute(type, value, array: false)
return value if type == :source
return cast_object_attribute(type, value, array: array) if type.is_a?(Class)

cast_to(type, value, array: array)
end

def cast_to(type, value, array: false)
return [] if value.nil? && array
return false if value.nil? && type == :boolean

cast_type = ActiveModel::Type.lookup(type)

if array
cast_array(value, type, cast_type)
else
cast_value(value, type, cast_type)
if value.nil?
return [] if array
return false if type == :boolean
end

array ? cast_array(type, value) : cast_value(type, value, array)
end

def cast_array(values, type, cast_type)
values.map do |value|
next false if value.nil? && type == :boolean
def cast_value(type, value, array)
return cast_object_attribute(type, value, array: array) if type.is_a?(Class)
return false if type == :boolean && value.nil?

cast_type.cast(value)
case type
when :string, :decimal
value.to_s
when :integer
value.to_i
else
raise TypeError, "Unable to cast #{value.inspect} to #{type}"
end
end

def cast_value(value, type, cast_type)
value = value.to_s if type == :decimal && value.is_a?(Float)

cast_type.cast(value)
def cast_array(type, values)
values.map { |element| cast_value(type, element, false) }
end

def cast_object_attribute(type, value, array:)
Expand Down
2 changes: 1 addition & 1 deletion lib/json_path_attribute/version.rb
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
# frozen_string_literal: true

module JsonPathAttribute
VERSION = "0.1.1"
VERSION = "0.1.2"
end