Module: ActiveRecordExtensions::ClassMethods
- Defined in:
- lib/rails_core_extensions/active_record_extensions.rb
Instance Method Summary collapse
-
#database(key) ⇒ Object
Like establish_connection but postfixes the key with the rails environment e.g.
- #optional_fields(*possible_fields) ⇒ Object
- #position_helpers_for(*collections) ⇒ Object
Instance Method Details
#database(key) ⇒ Object
Like establish_connection but postfixes the key with the rails environment e.g. database(‘hello’) in development will look for the database
which in config/database.yml is called hello_development
8 9 10 |
# File 'lib/rails_core_extensions/active_record_extensions.rb', line 8 def database(key) establish_connection("#{key}_#{Rails.env}") end |
#optional_fields(*possible_fields) ⇒ Object
12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 |
# File 'lib/rails_core_extensions/active_record_extensions.rb', line 12 def optional_fields(*possible_fields) @optional_fields_loader = possible_fields.pop if possible_fields.last.is_a?(Proc) class << self def enabled_fields @enabled_fields || @optional_fields_loader.try(:call) end def enabled_fields=(fields) @enabled_fields = fields end end possible_fields.each do |field| instance_eval <<-EVAL def #{field}_enabled? enabled_fields.include?(:#{field}) end EVAL end end |
#position_helpers_for(*collections) ⇒ Object
34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 |
# File 'lib/rails_core_extensions/active_record_extensions.rb', line 34 def position_helpers_for(*collections) collections.each do |collection| class_eval <<-EVAL after_save do |record| record.rebalance_#{collection.to_s.singularize}_positions! end def assign_#{collection.to_s.singularize}_position(object) object.position = (#{collection}.last.try(:position) || 0) + 1 unless object.position end def rebalance_#{collection.to_s.singularize}_positions!(object = nil) reload #{collection}.sort_by(&:position).each_with_index do |o, index| if o.position != (index + 1) o.update_attribute(:position, index + 1) end end end EVAL end end |