Module: Constantizable::ClassMethods
- Defined in:
- lib/constantizable.rb
Overview
Constantizable extends ‘ActiveSupport::Concern` for some of the rails niceties like, `ClassMethods` and to include it into `ActiveRecord::Base`.
Instance Method Summary collapse
Dynamic Method Handling
This class handles dynamic methods through the method_missing method
#method_missing(method, *args, &block) ⇒ Object (private)
19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 |
# 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 |
Instance Method Details
#constantize_column(*columns) ⇒ Object
7 8 9 10 11 12 13 14 15 16 |
# 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 |