Class: ActiveRecord::Base

Inherits:
Object
  • Object
show all
Defined in:
lib/activerecord/utils/alias.rb,
lib/activerecord/utils/comp3.rb,
lib/activerecord/utils/random.rb

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.alias_attr(new, old) ⇒ Object



34
35
36
37
# File 'lib/activerecord/utils/alias.rb', line 34

def self.alias_attr( new, old )
  alias_attr_reader( new, old )
  alias_attr_writer( new, old )
end

.alias_attr_reader(new, old) ⇒ Object

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

- will issue a warning


19
20
21
22
23
24
25
26
# File 'lib/activerecord/utils/alias.rb', line 19

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) ⇒ Object



28
29
30
31
32
# File 'lib/activerecord/utils/alias.rb', line 28

def self.alias_attr_writer( new, old )
  define_method( "#{new}=" ) do |value|
    send( "#{old}=", value )
  end
end

.attr_reader_w_fallbacks(*keys) ⇒ Object



53
54
55
56
57
# File 'lib/activerecord/utils/alias.rb', line 53

def self.attr_reader_w_fallbacks( *keys )
  define_method( keys[0] ) do
    read_attribute_w_fallbacks( keys )
  end
end

.find_by(hash) ⇒ Object

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



12
13
14
# File 'lib/activerecord/utils/comp3.rb', line 12

def self.find_by( hash )
  self.where( hash ).first
end

.find_by!(hash) ⇒ Object



16
17
18
# 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

.rndObject

random

e.g. use like:

 beer_of_the_week = Beer.rnd


14
15
16
17
18
19
20
21
22
23
# 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

Instance Method Details

#read_attribute_w_fallbacks(*keys) ⇒ Object



59
60
61
62
63
64
65
66
67
68
69
# File 'lib/activerecord/utils/alias.rb', line 59

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