-
Notifications
You must be signed in to change notification settings - Fork 197
How to show last granted badges
Tute Costa edited this page Jun 18, 2020
·
3 revisions
You will need to override Merit::BadgesSash
model adding a last_granted
method.
NOTE: if you use merit version >= 4, the superclass name has changed to work with zeitwerk. See https://github.com/merit-gem/merit/issues/343.
For doing so, you can create config/initializers/merit_badges_sash_override.rb
with following contents:
module Merit
class BadgesSash
def self.last_granted(options = {})
options[:since_date] ||= 1.month.ago
options[:limit] ||= 10
where("created_at > '#{options[:since_date]}'")
.limit(options[:limit])
.map(&:user_badge)
end
def user_badge
{
user: User.find_by_sash_id(sash_id),
badge: Badge.find(badge_id)
}
end
end
end
You could use it like:
# List 10 badge grants in the last month
Merit::BadgesSash.last_granted
# [{:user=>
# #<User id: 1, name: "the-commenter-guy", created_at: "2014-01-13 15:08:45", updated_at: "2014-01-13 15:45:19", sash_id: 1, level: 0>,
# :badge=>
# #<Merit::Badge id: 9, name: "gossip", level: nil, image: nil, description: nil, custom_fields: nil>},
# {:user=>
# #<User id: 1, name: "the-commenter-guy", created_at: "2014-01-13 15:08:45", updated_at: "2014-01-13 15:45:19", sash_id: 1, level: 0>,
# :badge=>
# #<Merit::Badge id: 8, name: "wildcard_badge", level: nil, image: nil, description: nil, custom_fields: nil>},
# {:user=>
# #<User id: 1, name: "the-commenter-guy", created_at: "2014-01-13 15:08:45", updated_at: "2014-01-13 15:45:19", sash_id: 1, level: 0>,
# :badge=>
# #<Merit::Badge id: 9, name: "gossip", level: nil, image: nil, description: nil, custom_fields: nil>},
# {:user=>
# #<User id: 1, name: "the-commenter-guy", created_at: "2014-01-13 15:08:45", updated_at: "2014-01-13 15:45:19", sash_id: 1, level: 0>,
# :badge=>
# #<Merit::Badge id: 8, name: "wildcard_badge", level: nil, image: nil, description: nil, custom_fields: nil>}]
# List 3 badge grants in the last week
Merit::BadgesSash.last_granted(since_date: 1.week.ago, limit: 3)
# [{:user=>
# #<User id: 1, name: "the-commenter-guy", created_at: "2014-01-13 15:08:45", updated_at: "2014-01-13 15:45:19", sash_id: 1, level: 0>,
# :badge=>
# #<Merit::Badge id: 9, name: "gossip", level: nil, image: nil, description: nil, custom_fields: nil>},
# {:user=>
# #<User id: 1, name: "the-commenter-guy", created_at: "2014-01-13 15:08:45", updated_at: "2014-01-13 15:45:19", sash_id: 1, level: 0>,
# :badge=>
# #<Merit::Badge id: 8, name: "wildcard_badge", level: nil, image: nil, description: nil, custom_fields: nil>},
# {:user=>
# #<User id: 1, name: "the-commenter-guy", created_at: "2014-01-13 15:08:45", updated_at: "2014-01-13 15:45:19", sash_id: 1, level: 0>,
# :badge=>
# #<Merit::Badge id: 9, name: "gossip", level: nil, image: nil, description: nil, custom_fields: nil>}]