Module: Nostalgic::NostalgicAttr::ClassMethods
- Defined in:
- lib/nostalgic/nostalgic_attr.rb
Instance Attribute Summary collapse
-
#nostalgic_attrs ⇒ Object
Returns the value of attribute nostalgic_attrs.
Instance Method Summary collapse
Instance Attribute Details
#nostalgic_attrs ⇒ Object
Returns the value of attribute nostalgic_attrs.
39 40 41 |
# File 'lib/nostalgic/nostalgic_attr.rb', line 39 def nostalgic_attrs @nostalgic_attrs end |
Instance Method Details
#belongs_to(name, scope = nil, options = {}) ⇒ Object
41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 |
# File 'lib/nostalgic/nostalgic_attr.rb', line 41 def belongs_to(name, scope = nil, = {}) scope ||= {} super(name, scope.except(:nostalgic), ) if scope.fetch(:nostalgic, false) foreign_key = .fetch(:foreign_key, "#{name}_id") nostalgic_attr foreign_key class_eval <<-METHODS, __FILE__, __LINE__ + 1 def #{name}_on(date) return self.#{name} unless date.present? '#{name}'.classify.constantize.find_by_id(#{foreign_key}_on(date)) end alias_method :#{name}_at, :#{name}_on METHODS end end |
#nostalgic_attr(*attrs) ⇒ Object
61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 |
# File 'lib/nostalgic/nostalgic_attr.rb', line 61 def nostalgic_attr(*attrs) self.nostalgic_attrs ||= [] attrs.each do |attr| next if self.nostalgic_attrs.include?(attr.to_sym) self.nostalgic_attrs << attr.to_sym model_type = self.model_name.to_s class_eval <<-METHODS, __FILE__, __LINE__ + 1 has_many :#{attr.to_s.pluralize}, -> {where(:model_type => model_type, :name => '#{attr}').order('effective_at desc')}, :class_name => 'Nostalgic::Attr', :foreign_key => 'model_id' accepts_nested_attributes_for :#{attr.to_s.pluralize}, :allow_destroy => true attr_accessor :#{attr}_effective_at def #{attr}_on(date) return self.#{attr} unless date.present? na = Nostalgic::Attr.where(:model_type => self.class.name, :model_id => self.id, :name => '#{attr}') na = na.where('effective_at <= ?', date).order('effective_at desc').first na ? na.value : self.#{attr} end alias_method :#{attr}_at, :#{attr}_on METHODS end end |