Created
January 10, 2023 21:10
-
-
Save Bodacious/7956303c847e9666b2426f72ab2d2425 to your computer and use it in GitHub Desktop.
Demonstrating the anonymous modules when including blocks in scopes
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# frozen_string_literal: true | |
source "https://rubygems.org" | |
gem "activerecord", github: "bodacious/rails" | |
gem "sqlite3" |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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