Skip to content

Commit

Permalink
add support for Rails 6.1
Browse files Browse the repository at this point in the history
  • Loading branch information
ashkulz committed Nov 7, 2022
1 parent 7f90f53 commit 375fe68
Show file tree
Hide file tree
Showing 2 changed files with 41 additions and 1 deletion.
4 changes: 3 additions & 1 deletion lib/hstore_accessor.rb
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,9 @@
require "active_record"
require "hstore_accessor/version"

if ::ActiveRecord::VERSION::STRING.to_f >= 5.0
if ::ActiveRecord::VERSION::STRING.to_f >= 6.1
require "hstore_accessor/active_record_6.1/type_helpers"
elsif ::ActiveRecord::VERSION::STRING.to_f >= 5.0
require "hstore_accessor/active_record_5.0/type_helpers"
elsif ::ActiveRecord::VERSION::STRING.to_f >= 4.2 && ::ActiveRecord::VERSION::STRING.to_f < 5.0
require "hstore_accessor/active_record_4.2/type_helpers"
Expand Down
38 changes: 38 additions & 0 deletions lib/hstore_accessor/active_record_6.1/type_helpers.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
module HstoreAccessor
module TypeHelpers
TYPES = {
boolean: ActiveRecord::Type::Boolean,
date: ActiveRecord::Type::Date,
datetime: ActiveRecord::Type::DateTime,
decimal: ActiveRecord::Type::Decimal,
float: ActiveRecord::Type::Float,
integer: ActiveRecord::Type::Integer,
string: ActiveRecord::Type::String
}

TYPES.default = ActiveRecord::Type::Value

class << self
def column_type_for(attribute, data_type)
cast_type = TYPES[data_type].new # see https://stackoverflow.com/a/73312053
sql_type_metadata = ActiveRecord::ConnectionAdapters::SqlTypeMetadata.new(
sql_type: cast_type.type.to_s, type: cast_type.type, limit: cast_type.limit,
precision: cast_type.precision, scale: cast_type.scale)
ActiveRecord::ConnectionAdapters::Column.new(attribute.to_s, sql_type_metadata)
end

def cast(type, value)
return nil if value.nil?

case type
when :string, :decimal
value
when :integer, :float, :datetime, :date, :boolean
TYPES[type].new.cast(value)
else value
# Nothing.
end
end
end
end
end

0 comments on commit 375fe68

Please sign in to comment.