Posts

Getting a list of all presence validated attributes for all services in your application

Dienstag, 12. Juli 2022, 14:17 Uhr | roberto@vasquez-angel.de |

Assume you have built a bunch of services or any other activemodel/activerecord descendant classes. You decide to add translations to your app. Then you realize that you will have to add the translations to you yaml files. First thing that comes into your mind: I’ll make a list of all attributes of those services. The idea is good, but not perfect. You might validate getter methods and not only attributes. So simply listing the attributes of all services will not cut it. What you want is to list all validated attributes/methods in all of your services. In our special case we narrowed it down to presence validations.

Following admittedly long line will list all of your Rao::Service::Base descendants that are in the namespace Blorgh” with all presences validated attributes as yaml, sorted, ready to cut and paste into your locale yaml files:

irb> y Rao::Service::Base.descendants.collect { |d| d.name.start_with?("Blorgh") ? d : nil }.compact.sort { |c, o| c.name <=> o.name }.each_with_object({}) { |k,m| m[k.name.underscore] = k.validators.collect { |v| v.class.name.include?("Presence") ? v.attributes : nil }.flatten.compact.sort.each_with_object({}) { |a,m| m[a] = nil } }

Do not forget to enable eager loading in your development env before doing this or your list might be incomplete.