Super call by define_method

I created a Model class where I define methods based on a method (attribute) called in User (which inherits from Model). The problem is that I cannot override the method defined by define_method and call super to jump to the specific method. I assume that this is due to the fact that a certain method is added to the user himself, and not to the model, so in fact he does not have a method in the superclass (i.e. in the model).

The reason I want to do this is because most attributes must be stored directly in the database, and some attributes, such as a password, need additional processing.

class Model
  def self.attribute(name)
    define_method(name) do
      self
    end
  end  
end

class User < Model
  attribute :password
end

class User2 < Model
  attribute :password

  def password
    super
  end
end

@user = User.new
puts @user.password # => <User:0x00000100845540>

@user2 = User2.new
puts @user2.password
# define_super.rb:17:in `password': super: no superclass method 
# `password' for #<User2:0x00000100845578> (NoMethodError)
# from define_super.rb:25:in `<main>'

, ? .

+4
3

superclass:

class Model
  def self.attribute(name)
    superclass.send :define_method, name do
      self
    end
  end  
end
+10

Rails , . ( ) , :

# This method is never overridden, but also rarely used as a public method
def[](key)
  # Returns value of `key` attribute
end

# This is the effective default implementation of an attribute
def att1
  self[:att1]
end

# This shows how you can have custom logic but still access the underlying value
def att2
  self[:att2] unless self[:att2].empty?
end
+3

superclass.send :define_method , Model.

https://thepugautomatic.com/2013/07/dsom/

, , attribute

class Model
  MODULE_NAME = :DynamicAttributes

  def self.attribute(name)
    if const_defined?(MODULE_NAME, _search_ancestors = false)
      mod = const_get(MODULE_NAME)
    else
      mod = const_set(MODULE_NAME, Module.new)
      include mod
    end

    mod.module_eval do
      define_method(name) do
        self
      end
    end
  end
end
0

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


All Articles