Skip to content

Instantly share code, notes, and snippets.

@drusepth
Created January 19, 2020 22:56
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save drusepth/5def166efa11e30f18aeecc80ac3c6c8 to your computer and use it in GitHub Desktop.
Save drusepth/5def166efa11e30f18aeecc80ac3c6c8 to your computer and use it in GitHub Desktop.
def content(
content_types: Rails.application.config.content_types[:all].map(&:name),
page_scoping: { user_id: self.id },
universe_id: nil
)
return {} if content_types.empty?
polymorphic_content_fields = [:id, :name, :page_type, :user_id, :created_at, :updated_at, :deleted_at, :archived_at, :privacy]
where_conditions = page_scoping.map { |key, value| "#{key} = #{value}" }.join(' AND ') + ' AND deleted_at IS NULL AND archived_at IS NULL'
sql = content_types.uniq.map do |page_type|
clause = "SELECT #{polymorphic_content_fields.join(',')} FROM #{page_type.downcase.pluralize} WHERE #{where_conditions}"
if universe_id.present? && page_type != 'Universe'
clause += " AND universe_id = #{universe_id}"
end
clause
end.join(' UNION ALL ') + ' ORDER BY page_type, id'
result = ActiveRecord::Base.connection.execute(sql)
@content_by_page_type ||= result.to_a.each_with_object({}) do |object, hash|
object.keys.each do |key|
object.except!(key) if key.is_a?(Integer)
end
hash[object['page_type']] ||= []
hash[object['page_type']] << ContentPage.new(object)
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment