Answer the question
In order to leave comments, you need to log in
How to add a dynamic method to a class through a module?
Good afternoon. A task is a module whose code is mixed into various classes and contains basic functions, but depending on the class, additional methods should appear in this module.
Example that doesn't work:
module SuperAbility
define_method(:basic) do
puts 'i can some basic action'
end
@@additional_ability ||= :action
define_method(@@additional_ability) do
puts "i can make action: #{__method__}"
end
end
class Cow
@@additional_ability = :mooo
include SuperAbility
end
class Dragon
@@additional_ability = :fire
include SuperAbility
end
cow = Cow.new
cow.basic
cow.mooo
drag = Dragon.new
drag.basic
drag.fire
Answer the question
In order to leave comments, you need to log in
require "active_support/concern"
module HasAbilities
extend ActiveSupport::Concern
class_methods do
def has_ablilities(*args, **options)
args.each do |name|
define_method(:"#{name}") do |value|
puts "i can make action: #{name}"
end
end
end
end
end
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question