Ruby on Rails | Screencasts | Download | Documentation | Weblog | Community | Source

Changeset 8259

Show
Ignore:
Timestamp:
12/03/07 02:01:21 (6 months ago)
Author:
david
Message:

Added ActiveRecord::Base#becomes to turn a record into one of another class (mostly relevant for STIs) [DHH]

Files:

Legend:

Unmodified
Added
Removed
Modified
Copied
Moved
  • trunk/activerecord/CHANGELOG

    r8258 r8259  
    11*SVN* 
     2 
     3* Added ActiveRecord::Base#becomes to turn a record into one of another class (mostly relevant for STIs) [DHH]. Example: 
     4 
     5    render :partial => @client.becomes(Company) # renders companies/company instead of clients/client 
    26 
    37* Fixed that to_xml should not automatically pass :procs to associations included with :include #10162 [chuyeow] 
  • trunk/activerecord/lib/active_record/base.rb

    r8231 r8259  
    18071807      end 
    18081808 
     1809      # Returns an instance of the specified klass with the attributes of the current record. This is mostly useful in relation to 
     1810      # single-table inheritance structures where you want a subclass to appear as the superclass. This can be used along with record 
     1811      # identification in Action Pack to allow, say, Client < Company to do something like render :partial => @client.becomes(Company) 
     1812      # to render that instance using the companies/company partial instead of clients/client. 
     1813      # 
     1814      # Note: The new instance will share a link to the same attributes as the original class. So any change to the attributes in either 
     1815      # instance will affect the other. 
     1816      def becomes(klass) 
     1817        returning klass.new do |became| 
     1818          became.instance_variable_set("@attributes", @attributes) 
     1819          became.instance_variable_set("@new_record", new_record?) 
     1820        end 
     1821      end 
     1822 
    18091823      # Updates a single attribute and saves the record. This is especially useful for boolean flags on existing records. 
    18101824      # Note: This method is overwritten by the Validation module that'll make sure that updates made with this method 
  • trunk/activerecord/test/base_test.rb

    r8231 r8259  
    17381738    assert_equal '"This is some really long content, longer than 50 ch..."', t.attribute_for_inspect(:content) 
    17391739  end 
     1740   
     1741  def test_becomes 
     1742    assert_kind_of Reply, topics(:first).becomes(Reply) 
     1743    assert_equal "The First Topic", topics(:first).becomes(Reply).title 
     1744  end 
    17401745end