lib/aggrobot/aggregator.rb in aggrobot-0.0.2 vs lib/aggrobot/aggregator.rb in aggrobot-0.1.0
- old
+ new
@@ -9,11 +9,11 @@
@group_labels_map = {}
@attribute_mapping = {}
self.collection(collection) if collection
end
-
+ # returns hash of group label(s) as key and actual column(s) as value
def group_labels(map = nil, &block)
if map || block
if map.is_a?(Hash)
@group_labels_map = ActiveSupport::HashWithIndifferentAccess.new(map)
elsif map.respond_to?(:call) || block
@@ -22,20 +22,29 @@
else
@group_labels_map
end
end
+ # returns collection if it is ActiveRecord::Relation or ActiveRecord::Base
+ # raises error when collection is none of the above
+ # returns @collection otherwise (which is nil)
def collection(values = nil)
if values
- raise_error 'Collection should be an ActiveRecord::Relation or ActiveRecord::Base' unless
- [ActiveRecord::Relation, ActiveRecord::Base].any?{|m| values.is_a?(m) }
+ if !values.is_a?(ActiveRecord::Relation) && values < ActiveRecord::Base
+ values = values.unscoped
+ end
+ raise_error 'Collection should be an ActiveRecord::Relation or ActiveRecord::Base' unless values.is_a?(ActiveRecord::Relation)
@collection = values
else
@collection
end
end
+ # when
+ # : opts is nil, groups by group on @collection
+ # : opts is a map as {limit_to: limit}, creats groups by group on @collection with a limit
+ # : opts is a map as {buckets: [list_items]}, creats groups by [list_items] on @collection
def group_by(group, opts = nil)
raise_error "Group_by takes only symbol or a string as argument" unless group.is_a?(Symbol) or group.is_a?(String)
@query_planner = QueryPlanner.create(@collection, group, opts)
end
@@ -48,11 +57,15 @@
when Hash
attr.each { |k, v| override(k, v) }
end
end
- def set(name = nil, opts)
+ # creates attribute map
+ # when:
+ # given as hash, sets all keys as attributes to show and values as columns to fetch
+ # given as list (of 2 items), first item is key to show and second item is column to fetch
+ def select(name = nil, opts)
if opts.is_a? Hash
@attribute_mapping.merge!(opts)
elsif name && opts
@attribute_mapping[name] = opts
end
@@ -72,10 +85,10 @@
end
private
def extra_columns
- @attribute_mapping.values
+ @attribute_mapping.map{|k, v| "#{v} as #{k}"}
end
def extra_attributes
@attribute_mapping.keys
end
\ No newline at end of file