Last active
August 29, 2015 14:01
-
-
Save rainerborene/cddc40083720ce41afb9 to your computer and use it in GitHub Desktop.
Classification Query Object
This file contains hidden or 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
| class ClassificationQuery | |
| Tag = ActsAsTaggableOn::Tag | |
| Tagging = ActsAsTaggableOn::Tagging | |
| def initialize(bill, tagger = nil) | |
| @bill, @tagger = bill, tagger | |
| end | |
| def count | |
| relation = Tag.select(Tag[:name], Arel.star.count).where( | |
| Tagging[:taggable_id].eq(Arel.sql("$1")).and( | |
| Tagging[:taggable_type].eq(Arel.sql("$2")).and( | |
| Tagging[:context].eq('classifications') | |
| ) | |
| ) | |
| ).joins( | |
| Tag.arel_table.join(Tagging.arel_table).on( | |
| Tag[:id].eq(Tagging[:tag_id]) | |
| ).join_sources | |
| ).group(:name) | |
| relation.select! Arel::Nodes::NamedFunction.new( | |
| :bool_or, [Tagging[:tagger_id].eq(Arel.sql("$3"))] | |
| ) if @tagger | |
| # bind $* statement parameters | |
| relation.bind! [Tagging.columns_hash['taggable_id'], @bill.id] | |
| relation.bind! [Tagging.columns_hash['taggable_type'], Bill.name] | |
| relation.bind! [Tagging.columns_hash['tagger_id'], @tagger.id] if @tagger | |
| result = Tagging.connection.select_all(relation).rows.group_by(&:shift) | |
| result.each do |key, value| | |
| # type casting | |
| value = value.flatten | |
| value[0] = value.first.to_i | |
| value[1] = value.last == 't' if value[1] | |
| result[key] = value | |
| end | |
| self.class.to_h.dup.merge!(result) | |
| end | |
| def self.to_h | |
| @hash ||= CLASSIFICATION_NAMES.map {|n| [n, [0, false]] }.to_h.freeze | |
| end | |
| end | |
| # | |
| # Arel Helpers | |
| ## | |
| module ArelHelpers | |
| extend ActiveSupport::Concern | |
| module ClassMethods | |
| def [](name) | |
| arel_table[name] | |
| end | |
| alias_method :_, :[] | |
| end | |
| end | |
| ActiveRecord::Base.send(:include, ArelHelpers) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment