Sha256: 3ddc534cc0bef617f894f1fff26404cd657bfbd8c4a8ec51feb462e5380a6dd6

Contents?: true

Size: 1.81 KB

Versions: 2

Compression:

Stored size: 1.81 KB

Contents

module Merit
  require 'ambry'
  require 'ambry/active_model'

  class Badge
    extend Ambry::Model
    extend Ambry::ActiveModel

    field :id, :name, :level, :image, :description, :custom_fields

    validates_presence_of :id, :name
    validates_uniqueness_of :id

    filters do
      def find_by_id(ids)
        ids = Array.wrap(ids)
        find { |b| ids.include? b[:id] }
      end

      def by_name(name)
        find { |b| b.name == name.to_s }
      end

      def by_level(level)
        find { |b| b.level.to_s == level.to_s }
      end
    end

    class << self
      def find_by_name_and_level(name, level)
        badges = Badge.by_name(name)
        badges = badges.by_level(level) unless level.nil?
        if (badge = badges.first).nil?
          str = "No badge '#{name}' found. Define it in initializers/merit.rb"
          fail ::Merit::BadgeNotFound, str
        end
        badge
      end

      # DEPRECATED: `last_granted` will be removed from merit, please refer to:
      # https://github.com/tute/merit/wiki/How-to-show-last-granted-badges
      def last_granted(options = {})
        warn '[merit] [DEPRECATION] `last_granted` will be removed from merit, please refer to: https://github.com/tute/merit/wiki/How-to-show-last-granted-badges'
        options[:since_date] ||= 1.month.ago
        options[:limit]      ||= 10
        BadgesSash.last_granted(options)
      end

      # Defines Badge#meritable_models method, to get related
      # entries with certain badge. For instance, Badge.find(3).users
      def _define_related_entries_method(meritable_class_name)
        define_method(:"#{meritable_class_name.underscore.pluralize}") do
          sashes = BadgesSash.where(badge_id: id).pluck(:sash_id)
          meritable_class_name.constantize.where(sash_id: sashes)
        end
      end
    end
  end
end

Version data entries

2 entries across 2 versions & 1 rubygems

Version Path
merit-2.0.0 app/models/merit/badge.rb
merit-1.9.0 app/models/merit/badge.rb