8000 Feature request: namespaced model methods · Issue #78 · ankane/mailkick · GitHub
[go: up one dir, main page]
More Web Proxy on the site http://driver.im/
Skip to content

Feature request: namespaced model methods #78

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

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

Feature request: namespaced model methods #78

marckohlbrugge opened this issue Oct 29, 2024 · 2 comments

Comments

@marckohlbrugge
Copy link
8000
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
@marckohlbrugge
Copy link
Author

If there's interest, I'll make a PR

@rromanchuk
Copy link

@marckohlbrugge same, i have an existing has_many :subscriptions and makes me nervous

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

2 participants
0