简体   繁体   中英

Ruby - How to create a class variables to access in function

I want to create a function to set the instance variable like attr_reader

class Base
    def exec
       # get all functions to check
       # if all functions return true
       # I will do something here
    end
end

And then I have a class inherit Base .

class SomeClass < Base
  check :check_1
  check :check_2

  def check_1
   # checking
  end

  def check_2
   # checking
  end
end

class Some2Class < Base
  check :check_3
  check :check_4
  
  def check_3
   # checking
  end

  def check_4
   # checking
  end
end

Because I only need 1 logic for executing in all classes but I have a lot the different checks for each class, I need to do it flexibly.

Please, give me a keyword for it.

Many thanks.

In order to have check:check_1 you need to define check as a class method :

class Base
  def self.check(name)
    # ...
  end
end

Since you want to call the passed method names later on, I'd store them in an array: (provided by another class method checks )

class Base
  def self.checks
    @checks ||= []
  end

  def self.check(name)
    checks << name
  end
end

This already gives you:

SomeClass.checks
#=> [:check_1, :check_2]

Some2Class.checks
#=> [:check_3, :check_4]

Now you can traverse this array from within exec and invoke each method via send . You can use all? to check whether all of them return a truthy result:

class Base
  # ...

  def exec
    if self.class.checks.all? { |name| send(name) }
      # do something
    end
  end
end

SomeClass.new.exec # doesn't do anything yet

The self.class part is needed because you are calling the class method checks from the instance method exec .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM