ruby-on-railsrubyvirtus

How to get a list of all of one type of Virtus attribute?


How to get a list of all of one type?
Like for example, a list of all of the String attributes? Is there an easy Virtus solution or do I have to roll my own?

def my_model
  include Virtus.model
  attribute :a, Integer
  attribute :b, Integer
  attribute :c, String
  attribute :d, String
  attribute :w, Float
  attribute :j, Float
end

I would like to essentially do my_model.something = [:c, :d]

OR is there any other way to get all of the String attributes in list form?

My ultimate goal is to be able to splat the attributes into various validations based on type.


Solution

  • You may use the attribute_set method along with the primitive to get the attribute Class and then you need to write your own method:

    def self.get_string_attributes
      attributes = []
      self.attribute_set.each do |attribute|
        attributes << attribute.name if attribute.primitive == String
      end
      attributes
    end
    

    I get this results with your MyModel:

    MyModel.get_string_attributes
    => [:c, :d]
    

    O̶r̶ ̶y̶o̶u̶ ̶c̶a̶n̶ ̶g̶o̶ ̶a̶ ̶s̶t̶e̶p̶ ̶f̶u̶r̶t̶h̶e̶r̶ ̶a̶n̶d̶ ̶u̶s̶e̶ ̶d̶e̶f̶i̶n̶e̶ ̶m̶e̶t̶h̶o̶d̶_̶m̶i̶s̶s̶i̶n̶g̶ ̶l̶i̶k̶e̶ ̶t̶h̶i̶s̶:̶

    I hope this is what you're looking for.