class Object

Public Instance Methods

f(value) click to toggle source

Feel free to comment out the section below if you don’t want eager loading on your application, as this will slow it down a little bit. This section allows you to call something like “f ‘example@email.com’” and it will try to find the right class to match the attribute you just called On medium/large databases this will be too slow to be effective

# File lib/find_by_shortcut.rb, line 41
def f (value)
  # Load each class before it is explicitly called
  Rails.application.eager_load!
  # Enumerate through all the classes that inherit from ActiveRecord::Base
  ActiveRecord::Base.descendants.each do |klass|
    # Enumberate through each attribute of each class
    klass.new.attributes.keys.each do |attribute|
      # Call find_by for each attribute with the value that came after 'f'
      find_method = "find_by_" + attribute
      if klass.columns_hash[attribute].type.to_s == value.class.to_s.downcase
        item = klass.send(find_method, value)
        if item != nil
          # If something is found, return it and stop the enumeration
          return item
        end
      end
    end
  end
  # If nothing is found, return nil
  return nil
end