I have several methods with the same type of prefixes.

def get_foo # code end def get_bar # code end 

I want to learn how to generate these prefixes automatically (similar to how it is done in Rails: Model.find_by_smth ).

Those. I want to create a scope get_ in which you can put the foo method and it will automatically get the get_ prefix and will be available as get_foo .

How can this be implemented?


An example of the desired syntax.

 module Bar # нСкая ΠΎΠ±Ρ‘Ρ‚ΠΊΠ° `get_` end class Foo include Bar <нСкая ΠΎΠ±Ρ‘Ρ€Ρ‚ΠΊΠ° ΠΈΠ· Bar> do def foo puts 'Π£ мСня Π΅ΡΡ‚ΡŒ ΠΌΡ‹ΡΠ»ΡŒ, ΠΈ я Π΅Ρ‘ Π΄ΡƒΠΌΠ°ΡŽ!' end def bar puts 'А ΠΌΠΎΠΆΠ½ΠΎ я Π΅Ρ‘ Ρ‚ΠΎΠΆΠ΅ Π½Π΅ΠΌΠ½ΠΎΠΆΠ΅Ρ‡ΠΊΠΎ ΠΏΠΎΠ΄ΡƒΠΌΠ°ΡŽ?' end end end foo = Foo.new foo.get_foo # => "Π£ мСня Π΅ΡΡ‚ΡŒ ΠΌΡ‹ΡΠ»ΡŒ, ΠΈ я Π΅Ρ‘ Π΄ΡƒΠΌΠ°ΡŽ!" foo.get_bar # => "А ΠΌΠΎΠΆΠ½ΠΎ я Π΅Ρ‘ Ρ‚ΠΎΠΆΠ΅ Π½Π΅ΠΌΠ½ΠΎΠΆΠ΅Ρ‡ΠΊΠΎ ΠΏΠΎΠ΄ΡƒΠΌΠ°ΡŽ?" 
  • one
    Give an example of the syntax you would like to see. - D-side
  • one
    Um, you probably wanted to define in Bar only a wrapper, and the methods in Foo themselves (using a wrapper from a module)? Because in the current venture, I do not see much sense. More precisely, I do not see the point in a separate module, if we do the minimum example :) - D-side
  • @ D-side Naturally, in real code everything is much more complicated :) And there will be several prefixes. Simply, there is an option to make a module as a wrapper, but I wondered if it was possible to make methods with dynamic names - Viktor

1 answer 1

 class Module def with_prefix(prefix, &block) m = Module.new m.instance_eval(&block) m.methods(false).each do |name| define_method "#{prefix}_#{name}", &m.method(name) module_function "#{prefix}_#{name}" unless self.is_a?(Class) end end end class Foo with_prefix :get do with_prefix :and do def foo puts "Π£ мСня Π΅ΡΡ‚ΡŒ ΠΌΡ‹ΡΠ»ΡŒ, ΠΈ я Π΅Ρ‘ Π΄ΡƒΠΌΠ°ΡŽ!" end def bar puts "А ΠΌΠΎΠΆΠ½ΠΎ я Π΅Ρ‘ Ρ‚ΠΎΠΆΠ΅ Π½Π΅ΠΌΠ½ΠΎΠΆΠ΅Ρ‡ΠΊΠΎ ΠΏΠΎΠ΄ΡƒΠΌΠ°ΡŽ?" end end end end foo = Foo.new foo.get_and_foo # => "Π£ мСня Π΅ΡΡ‚ΡŒ ΠΌΡ‹ΡΠ»ΡŒ, ΠΈ я Π΅Ρ‘ Π΄ΡƒΠΌΠ°ΡŽ!" foo.get_and_bar # => "А ΠΌΠΎΠΆΠ½ΠΎ я Π΅Ρ‘ Ρ‚ΠΎΠΆΠ΅ Π½Π΅ΠΌΠ½ΠΎΠΆΠ΅Ρ‡ΠΊΠΎ ΠΏΠΎΠ΄ΡƒΠΌΠ°ΡŽ?" 

What does this code do?

  • Declares a with_prefix method in the superclass of all classes.
  • Method takes prefix name and code block
  • Performs a block in the context of an anonymous function.
  • This allows the def statement to be executed in an anonymous module and not in a class.
  • Enumerates all methods inside the module
  • Creates methods with prefixes for each method.
  • It would be nice to briefly describe how it works. You have made a new anonymous module, defined methods in it by a block transferred from the user, then, taking methods from .methods(false) using the method .method (k-to-k-to-o-ombo) defined them with a prefix in that skuppe where method with_prefix called. And it is worthwhile to attach references to the documentation to the reflection methods used :) - D-side