Skip to content

Instantly share code, notes, and snippets.

@kaspth
Created June 4, 2024 20:37
Show Gist options
  • Save kaspth/2820416f9ebbd6480c70ba8772cd5516 to your computer and use it in GitHub Desktop.
Save kaspth/2820416f9ebbd6480c70ba8772cd5516 to your computer and use it in GitHub Desktop.
Writing Concerns without the `extend`/`included`/`class_methods` boilerplate.
# Maybe there's a way to support ActiveSupport::Concern's dependencies too?
# Although this doesn't use the module hierarchy, so `prepend` can't work.
class Concern < Module
def initialize(&block) = @block = block
def included(klass) = klass.class_eval(&@block)
end
module Kernel
def Concern(...) = Concern.new(...)
end
# app/models/user.rb
class User < ApplicationRecord
include Commented
end
# app/models/user/commented.rb
User::Commented = Concern do
has_many :comments
def self.cool = :yup
def great? = true
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment