Sha256: 9bcc7476a170051eeebd16777626e22179e8f7600ac664075bae14b595c3675f

Contents?: true

Size: 1.93 KB

Versions: 5

Compression:

Stored size: 1.93 KB

Contents

module Feste
  class Subscription < ActiveRecord::Base
    belongs_to :subscriber, polymorphic: true

    before_create :generate_token

    # Return the propper subscription token based on the propper subscriber and
    # email category
    # @param [Subscriber, ActionMailer::Base, Symbol]
    #
    # If the subscription does not exist, one is created in order to return the
    # token.  If the action is not categorized, then the subscription is not
    # created, and nil is returned.
    #
    # @return [String, nil], the token or nil if a category cannot be found.
    def self.get_token_for(subscriber, mailer, action)
      transaction do
        category = mailer.action_categories[action.to_sym] || 
          mailer.action_categories[:all]
        subscription = Feste::Subscription.find_or_create_by(
          subscriber: subscriber,
          category: category
        )
        subscription.token
      end
    end

    # Return the subscriber based on an email address
    # @param [String]
    #
    # @return [Subscriber, nil], the subscriber if one exists, or nil if none
    # exists
    def self.find_subscribed_user(email)
      user_models.find do |model|
        model.find_by(Feste.options[:email_source] => email)
      end&.find_by(Feste.options[:email_source] => email)
    end

    # Return the human readable version of a category name.
    #
    # Checks to see if there is an i18n key corresponding to the category. If
    # not, then the category is titleized.
    #
    # @return [String]
    def category_name
      I18n.t("feste.categories.#{category}", default: category.titleize)
    end

    private

    def self.user_models
      ActiveRecord::Base.descendants.select do |klass|
        klass.included_modules.include?(Feste::User)
      end
    end

    def generate_token
      if !self.token
        self.token = Base64.
          urlsafe_encode64("#{category}|#{subscriber_id}|#{subscriber_type}")
      end
    end
  end
end

Version data entries

5 entries across 5 versions & 1 rubygems

Version Path
feste-0.4.2 app/models/feste/subscription.rb
feste-0.4.1 app/models/feste/subscription.rb
feste-0.4.0 app/models/feste/subscription.rb
feste-0.3.0 app/models/feste/subscription.rb
feste-0.2.1 app/models/feste/subscription.rb