A
A
Anton Misyagin2021-05-26 12:13:32
ruby
Anton Misyagin, 2021-05-26 12:13:32

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

It is desirable to turn without cluttering the code, preferably without @@ and @, you can use attr. Interested in the module.
Tell me please

Answer the question

In order to leave comments, you need to log in

1 answer(s)
Z
Zaporozhchenko Oleg, 2021-05-26
@c3gdlk

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 question

Ask a Question

731 491 924 answers to any question