lib/pluck_map/presenter.rb in pluck_map-0.6.0 vs lib/pluck_map/presenter.rb in pluck_map-0.6.1

- old
+ new

@@ -1,7 +1,8 @@ require "pluck_map/attribute_builder" require "pluck_map/presenters" +require "active_record" module PluckMap class Presenter include CsvPresenter, HashPresenter, JsonPresenter @@ -54,10 +55,35 @@ def invoke(attribute_id, object) attributes_by_id.fetch(attribute_id).apply(object) end def selects - attributes.selects + @selects ||= attributes.selects.map.with_index { |select, index| + + # Workaround for a bug that exists in Rails at the time of this commit. + # See: + # + # https://github.com/rails/rails/pull/36186 + # + # Prior to the PR above, Rails will treat two results that have the + # same name as having the same type. On Postgres, values that are the + # result of an expression are given the name of the last function + # called in the expression. For example: + # + # psql> SELECT COALESCE(NULL, 'four'), COALESCE(NULL, 4); + # coalesce | coalesce + # ----------+---------- + # four | 4 + # (1 row) + # + # This patch mitigates that problem by aliasing SQL expressions before + # they are used in select statements. + select = select.as("__pluckmap_#{index}") if select.respond_to?(:as) + + # On Rails 4.2, `pluck` can't accept Arel nodes + select = Arel.sql(select.to_sql) if ActiveRecord.version.segments.take(2) == [4,2] && select.respond_to?(:to_sql) + select + } end def attributes_by_id attributes.by_id end