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

Keep NULL values as nil when typecasting #28

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
20 changes: 10 additions & 10 deletions lib/activerecord-postgres-array/string.rb
Original file line number Diff line number Diff line change
Expand Up @@ -26,16 +26,16 @@ def from_postgres_array(base_type = :string)
res == 'NULL' ? nil : res
end

if base_type == :decimal
elements.collect(&:to_d)
elsif base_type == :float
elements.collect(&:to_f)
elsif base_type == :integer || base_type == :bigint
elements.collect(&:to_i)
elsif base_type == :timestamp
elements.collect(&:to_time)
else
elements
typecast = {
:decimal => :to_d,
:float => :to_f,
:integer => :to_i,
:bigint => :to_i,
:timestamp => :to_time
}.fetch(base_type,false)

elements.map do |e|
typecast ? e.try(typecast) : e
end
end
end
Expand Down
51 changes: 50 additions & 1 deletion spec/string_ext_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -105,5 +105,54 @@
it 'correctly handles multi line content' do
"{A\nB\nC,X\r\nY\r\nZ}".from_postgres_array.should == ["A\nB\nC", "X\r\nY\r\nZ"]
end

it "returns NULL values as nil" do
"{NULL,on,Rails}".from_postgres_array.should == [nil, "on", "Rails"]
end

context "with a base_type of :decimal" do
it "returns decimal numbers" do
"{1.1,2.1,3.1}".from_postgres_array(:decimal).should eql [1.1,2.1,3.1]
end

it "returns NULL values as nil" do
"{NULL,2.1,3.1}".from_postgres_array(:decimal).should eql [nil, 2.1, 3.1]
end
end

context "with a base_type of :integer" do
it "returns integers" do
"{1,2,3}".from_postgres_array(:integer).should eql [1,2,3]
end

it "returns NULL values as nil" do
"{NULL,2,3}".from_postgres_array(:integer).should eql [nil, 2, 3]
end
end

context "with a base_type of :float" do
it "returns floats" do
"{1,2,3}".from_postgres_array(:float).should eql [1.to_f,2.to_f,3.to_f]
end

it "returns NULL values as nil" do
"{NULL,2,3}".from_postgres_array(:float).should eql [nil, 2.to_f, 3.to_f]
end
end

context "with a base_type of timestamp" do
it "returns time objects" do
'{"2004-10-19 10:23:54","2004-10-19 10:23:54"}'.from_postgres_array(:timestamp).should eql [
"2004-10-19 10:23:54".to_time,
"2004-10-19 10:23:54".to_time
]
end

it "returns NULL values as nil" do
'{NULL,"2004-10-19 10:23:54"}'.from_postgres_array(:timestamp).should eql [
nil, "2004-10-19 10:23:54".to_time
]
end
end
end
end
end