class ActiveRecord::Base

Public Class Methods

alias_attr( new, old ) click to toggle source
# File lib/activerecord/utils/alias.rb, line 35
def self.alias_attr( new, old )
  alias_attr_reader( new, old )
  alias_attr_writer( new, old )
end
alias_attr_reader( new, old ) click to toggle source

todo: add opts={} e.g. lets us add, for example, depreciated: true ??

- will issue a warning
# File lib/activerecord/utils/alias.rb, line 20
def self.alias_attr_reader( new, old )
  define_method( new ) do
    send( old )
    ### use read_attribute( old ) instead? why? why not??
    #  see http://www.davidverhasselt.com/2011/06/28/5-ways-to-set-attributes-in-activerecord/
  end
  ## todo: check for boolean values - add new? version too ??
end
alias_attr_writer( new, old ) click to toggle source
# File lib/activerecord/utils/alias.rb, line 29
def self.alias_attr_writer( new, old )
  define_method( "#{new}=" ) do |value|
    send( "#{old}=", value )
  end
end
attr_reader_w_fallbacks( *keys ) click to toggle source

e.g. use like:

def published

read_attribute_w_fallbacks( :published, :touched )

end

or use macro e.g.

attr_reader_w_fallbacks :published, :touched
# File lib/activerecord/utils/alias.rb, line 54
def self.attr_reader_w_fallbacks( *keys )
  define_method( keys[0] ) do
    read_attribute_w_fallbacks( keys )
  end
end
find_by( hash ) click to toggle source

lets us use ActiveRecord 4-style find_by and find_by! in ActiveRecord 3.x

# File lib/activerecord/utils/comp3.rb, line 12
def self.find_by( hash )
  self.where( hash ).first
end
find_by!( hash ) click to toggle source
# File lib/activerecord/utils/comp3.rb, line 16
def self.find_by!( hash )
  self.where( hash ).first!     ## or use: first or raise RecordNotFound  directly??
end
rnd() click to toggle source

random

e.g. use like:

 beer_of_the_week = Beer.rnd
# File lib/activerecord/utils/random.rb, line 14
def self.rnd
  ## works w/ sqlite3 and postgresql
  ##  - check if it works w/ mysql/mariadb too ? suppots offset and limit in SQL?

  ## todo: use ::rand  -- and lets add an self.rand alias too ??
  ##  check if ::rand call works
  rnd_offset = rand( self.count ) ## NB: call "global" std lib rand

  self.offset( rnd_offset ).limit( 1 ).first
end

Public Instance Methods

read_attribute_w_fallbacks( *keys ) click to toggle source
# File lib/activerecord/utils/alias.rb, line 60
def read_attribute_w_fallbacks( *keys )
  ### todo: use a different name e.g.:
  ## read_attribute_cascade ?? - does anything like this exists already?
  ## why? why not?
  value = nil
  keys.each do |key|
    value = read_attribute( key )
    break unless value.nil?  # if value.nil? == false
  end
  value # fallthrough -- return latest value (will be nil)
end