Skip to content

Instantly share code, notes, and snippets.

@Bodacious
Created January 10, 2023 21:10
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Bodacious/7956303c847e9666b2426f72ab2d2425 to your computer and use it in GitHub Desktop.
Save Bodacious/7956303c847e9666b2426f72ab2d2425 to your computer and use it in GitHub Desktop.
Demonstrating the anonymous modules when including blocks in scopes
# frozen_string_literal: true
source "https://rubygems.org"
gem "activerecord", github: "bodacious/rails"
gem "sqlite3"
require "bundler"
Bundler.require
require "active_record"
ActiveRecord::Base.establish_connection({ adapter: "sqlite3", database: ":memory:" })
ActiveRecord::Base.connection.instance_eval do
create_table(:products) do |t|
t.string :name, limit: 50, null: false
t.integer :price_cents, default: 0, null: false, limit: 10
end
end
module FreeProductExtension
def self.to_proc
Proc.new { include FreeProductExtension }
end
end
class ProductA < ActiveRecord::Base
self.table_name = "products"
scope :free, -> { where(price_cents: 0) }, &FreeProductExtension
end
class ProductB < ActiveRecord::Base
self.table_name = "products"
scope :free, -> { where(price_cents: 0) } do
include FreeProductExtension
end
end
class ProductC < ActiveRecord::Base
self.table_name = "products"
scope :free, -> { where(price_cents: 0) }, extend: FreeProductExtension
end
# Using the Module.to_proc approach...
ProductA.free.extensions
# => [#<Module:0x00000001129d25e8>]
# Using the scope(..., &block) approach...
ProductB.free.extensions
# => [#<Module:0x00000001129cab18>]
# Using the proposed `extend:` approach...
ProductC.free.extensions
# => [FreeProductExtension]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment