Created
October 12, 2021 02:07
-
-
Save nagait84/62440c241260df8a8d350f748ef621ef to your computer and use it in GitHub Desktop.
rails4.2 Postgresqlの配列リテラルを配列に変換
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# app/models/concerns/varying_array_parsable.rb | |
module VaryingArrayParsable | |
extend ActiveSupport::Concern | |
class VaryingArrayParser | |
# @see {https://github.com/rails/rails/blob/4-2-stable/activerecord/lib/active_record/connection_adapters/postgresql/oid/array.rb} | |
# Loads pg_array_parser if available. String parsing can be | |
# performed quicker by a native extension, which will not create | |
# a large amount of Ruby objects that will need to be garbage | |
# collected. pg_array_parser has a C and Java extension | |
begin | |
require 'pg_array_parser' | |
include PgArrayParser | |
rescue LoadError | |
require 'active_record/connection_adapters/postgresql/array_parser' | |
include ActiveRecord::ConnectionAdapters::PostgreSQL::ArrayParser | |
end | |
end | |
module ClassMethods | |
private | |
# @param value [String] varying arrayカラムの値 | |
# @return [Array] 型キャスト後の配列 | |
def cast_to_array(value) | |
@pg_parser ||= VaryingArrayParser.new | |
@pg_parser.parse_pg_array(value) | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment