Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Feature request: namespaced model methods #78

Open
marckohlbrugge opened this issue Oct 29, 2024 · 0 comments
Open

Feature request: namespaced model methods #78

marckohlbrugge opened this issue Oct 29, 2024 · 0 comments

Comments

@marckohlbrugge
Copy link

marckohlbrugge commented Oct 29, 2024

Problem

My User model already has a subscribed? method indicating whether the user is a paying subscriber of my app.

Solution

  1. Namespace all method with mailkick_ so we get methods like mailkick_subscribed?
  2. Only define shorthand aliases (subscribed?, etc) if no such methods exists.

What do you think?

Code example

module Mailkick
  module Model
    def has_subscriptions
      class_eval do
        alias_method :subscriptions, :mailkick_subscriptions unless method_defined? :subscriptions
        alias_method :subscribe, :mailkick_subscribe unless method_defined? :subscribe
        alias_method :unsubscribe, :mailkick_unsubscribe unless method_defined? :unsubscribe
        alias_method :subscribed?, :mailkick_subscribed? unless method_defined? :subscribed? 
      
        has_many :mailkick_subscriptions, class_name: "Mailkick::Subscription", as: :subscriber
        scope :mailkick_subscribed, ->(list) { joins(:mailkick_subscriptions).where(mailkick_subscriptions: {list: list}) }

        def mailkick_subscribe(list)
          mailkick_subscriptions.where(list: list).first_or_create!
          nil
        end

        def mailkick_unsubscribe(list)
          mailkick_subscriptions.where(list: list).delete_all
          nil
        end

        def mailkick_subscribed?(list)
          mailkick_subscriptions.where(list: list).exists?
        end
      end
    end
  end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant