Hello. Faced such a problem: There is a Model class and class methods inside the class << self . But when I try to reach the class method db_name , I get the error undefined local variable or method `db_name' for SimplyRecord::Model:Class . Thought it might be worth trying. Another scop, but did not help. What could be the problem?

 class Model puts "#{self} has been initialized" class << self STANDART_METHODS = [ { name: :first, query: "SELECT * FROM #{db_name if db_name} ORDER BY id ASC LIMIT 1;" }, ] STANDART_METHODS.each do |method| define_method(method[:name]) do |arg| return if self == Model arg ||= nil data = client.query(method[:query]) data.to_a.inject([]) do |arr, o| new_obj = self.new o.each { |k, v| new_obj.instance_variable_set(:"@#{k}", v) } arr << new_obj end end end def db_name self.to_s.underscore.pluralize end private def client SimplyRecord::Connection.new.set end end end 
  • Did you write this yourself or copied it from somewhere? - Mikhail Vaysman
  • one
    He wrote. Only now I guessed that it was first necessary that the method be initialized, and only then it needed to be called - Vadim Ryazantsev
  • one
    You are clearly overthought here. try to write easier. but even better, try starting with tests. - Mikhail Vaysman
  • Well, yes, in your interpolation db_name if db_name causes something that is not there yet. It is also a redundant code, whose behavior will differ from just db_name only if there is false , which would be very strange for the _name suffix. - D-side

0