Skip to content

Instantly share code, notes, and snippets.

@thdaraujo
Created February 22, 2024 03:18
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 thdaraujo/68f40cbe5a3238e50caaf63264963279 to your computer and use it in GitHub Desktop.
Save thdaraujo/68f40cbe5a3238e50caaf63264963279 to your computer and use it in GitHub Desktop.
An example of how to deprecate constants in Ruby.
# based on ActiveSupport
# https://github.com/rails/rails/blob/6f0d1ad14b92b9f5906e44740fce8b4f1c7075dc/activesupport/lib/active_support/deprecation/constant_accessor.rb#L32
module MyLib
module Deprecator
def self.included(base)
extension = Module.new do
def const_missing(missing_const_name)
puts "deprecator - const missing #{missing_const_name}"
if class_variable_defined?(:@@_deprecated_constants)
if (replacement = class_variable_get(:@@_deprecated_constants)[missing_const_name.to_s])
puts "#{name}::#{missing_const_name} is deprecated! Use #{replacement[:new_constant]} instead"
# this should work on Ruby >=2.0
return replacement[:new_constant]
end
end
super
end
def deprecate_generator(old_generator_name, new_generator_constant)
class_variable_set(:@@_deprecated_constants, {}) unless class_variable_defined?(:@@_deprecated_constants)
class_variable_get(:@@_deprecated_constants)[old_generator_name] = {new_constant: new_generator_constant}
puts "DEPRECATION WARNING: #{old_generator_name} - #{new_generator_constant}"
end
end
base.singleton_class.prepend extension
end
end
module SomeModule
# class IDNumber
# def self.foo
# puts "old foo"
# end
# end
class IdNumber
def self.foo
puts "new foo"
end
end
# def self.const_missing(const_name)
# super unless const_name == :IDNumber
# warn "DEPRECATION WARNING: the class MyLib::SomeModule::IDNumber is deprecated. Use MyLib::SomeModule::IdNumber instead."
# IdNumber
# end
include Deprecator
deprecate_generator("IDNumber", IdNumber)
end
end
MyLib::SomeModule::IDNumber.foo
# MyLib::SomeModule::IdNumber.foo
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment