module Constantizable::ClassMethods

Constantizable extends ‘ActiveSupport::Concern` for some of the rails niceties like, `ClassMethods` and to include it into `ActiveRecord::Base`.

Public Instance Methods

constantize_column(*columns) click to toggle source
# File lib/constantizable.rb, line 7
def constantize_column(*columns)
  # This method is set as a class method as it can directly be invoked from model definitions
  # as follows.

  # Class Country < ActiveRecord::Base
  #   constantize_columns :name, :code
  # end

  @constantized_columns = columns
end

Private Instance Methods

method_missing(method, *args, &block) click to toggle source
Calls superclass method
# File lib/constantizable.rb, line 19
def method_missing(method, *args, &block)
  # In the case that an object's constantized column value corresponds to the method name,
  # the object is returned, else execution is delegated to the default `method_missing`
  # implementation.

  # If Column name isn't present it should fallback to the default `method_missing`
  # implementation.

  column_names = @constantized_columns
  super if column_names.blank?

  # The value of the constantized column needs to be titleized or underscored,
  # for the implementation to work.
  # (eg)
  # Country with name "United States Of America", will correspond to the query,
  # Country.united_states_of_america.
  # Country with name "India", will correspond to the query,
  # Country.india.
  # Country with name "united_kingdom", will correspond to the query,
  # Country.united_kingdom.
  record = nil
  column_names.each do | column_name |
    break if record.present?
    record = self.find_by("lower(#{column_name}) = ? or lower(#{column_name}) = ?", method.to_s.downcase, method.to_s.titleize.downcase)    
  end

  if record.present?
    record
  else
    super
  end
  
rescue
  super
end