Class: ActiveRecord::Base
- Inherits:
-
Object
- Object
- ActiveRecord::Base
- Defined in:
- lib/activerecord/utils.rb
Class Method Summary collapse
- .alias_attr(new, old) ⇒ Object
-
.alias_attr_reader(new, old) ⇒ Object
todo: add opts={} e.g.
- .alias_attr_writer(new, old) ⇒ Object
- .attr_reader_w_fallbacks(*keys) ⇒ Object
- .rnd ⇒ Object
Instance Method Summary collapse
Class Method Details
.alias_attr(new, old) ⇒ Object
61 62 63 64 |
# File 'lib/activerecord/utils.rb', line 61 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
46 47 48 49 50 51 52 53 |
# File 'lib/activerecord/utils.rb', line 46 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
55 56 57 58 59 |
# File 'lib/activerecord/utils.rb', line 55 def self.alias_attr_writer( new, old ) define_method( "#{new}=" ) do |value| send( "#{old}=", value ) end end |
.attr_reader_w_fallbacks(*keys) ⇒ Object
80 81 82 83 84 |
# File 'lib/activerecord/utils.rb', line 80 def self.attr_reader_w_fallbacks( *keys ) define_method( keys[0] ) do read_attribute_w_fallbacks( keys ) end end |
.rnd ⇒ Object
107 108 109 110 111 112 113 114 115 116 |
# File 'lib/activerecord/utils.rb', line 107 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
86 87 88 89 90 91 92 93 94 95 |
# File 'lib/activerecord/utils.rb', line 86 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? keys.each do |key| value = read_attribute( key ) return value unless value.nil? end value # fallthrough? return latest value (will be nil) --or return just nil - why? why not?? end |