Access to a class containing a namespace from a module

I am working on a module that, among other things, will add some universal functionality like finder to the class into which you mix it. Problem: for reasons of convenience and aesthetics, I want to include some functions outside the classroom to the same extent as the class itself.

For instance:

class User
  include MyMagicMixin
end

# Should automagically enable:

User.name('Bob')   # Returns first user named Bob
Users.name('Bob')  # Returns ALL users named Bob 
User(5)            # Returns the user with an ID of 5
Users              # Returns all users

I can perform functions in these methods, no problem. And case 1 ( User.name('Bob')) is simple. However, cases 2-4 require new classes and methods outside User. The method Module.includedgives me access to the class, but not to its content area. There is no simple “parent” type method that I can see in a class or module. (For the namespace, I am not referring to a superclass or nested modules.)

, , #name, , . , , Ruby, , .

- ? ?

+3
3

User - , Class. , MyMagicMixin :

module MyMagicMixin
  class <<self
    def self.included(klass)
      base.extend MyMagicMixin::ClassMethods
      create_pluralized_alias(klass)
    end

    private

    def create_pluralized_alias(klass)
      fq_name = klass.to_s
      class_name = fq_name.demodulize
      including_module = fq_name.sub(Regexp.new("::#{class_name}$", ''))
      including_module = including_module.blank? ? Object : including_module.constantize
      including_module.const_set class_name.pluralize, klass
    end
  end

  module ClassMethods
    # cass methods here
  end
end

, , ​​.

+1

, .

, , .

+3

, . , Rails. , , Regexp.

: Ruby ! - , . , , , - . Module#name , : , , . , , , nil.

, :

a = Class.new
a.name # => nil
B = a
B.name # => "B"
A = B
A.name # => "B"
  • , Module#name

, - As, A s, , , , Bs , .

. MacRuby, String.name NSMutableString, Hash.name NSMutableDictionary Object.name NSObject. , MacRuby Ruby Objective-C , Objective-C Ruby, Ruby : String = NSMutableString. MacRuby Objective-C, , Objective-C, , NSMutableString , , Module#name.

+2

Source: https://habr.com/ru/post/1737777/


All Articles