• 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31

This article was migrated from http://rails.office.drecom.jp/takiuchi/archive/148

Rubyのnewメソッドとallocateメソッドの挙動に関するメモ。

$ irb
>> class Foo
>>   def initialize(a)
>>     @foo = a
>>   end
>>   def foo
>>     initialize("test")
>>   end
>> end
=> nil
>> a = Foo.new("bb")
=> #<Foo:0x40203ce0 @foo="bb">
>> b = Foo.allocate
=> #<Foo:0x401f4b50>
>> b.foo
=> "test"
>> b
=> #<Foo:0x401f4b50 @foo="test">
new*1 = allocate + initialize*2 ということですね。ファクトリーパターンを実装するのが楽になりそう。

This article was migrated from http://rails.office.drecom.jp/takiuchi/archive/148

  1. 1 args

  2. 2 args

posted by Png genki on Fri 29 Dec 2006 at 14:40

This article was migrated from http://rails.office.drecom.jp/takiuchi/archive/147

西さん(a.k.a. maiha)のRuby on Rails入門のp112に書かれてる偽STIが面白そうだったので、 instantiateのソースコードをメモ。

# File src/rails-1.1.6/activerecord/lib/active_record/base.rb, line 975
def instantiate(record)
  object = 
    if subclass_name = record[inheritance_column]
      if subclass_name.empty?
        allocate
      else
        require_association_class(subclass_name)
        begin
          compute_type(subclass_name).allocate
        rescue NameError
          raise SubclassNotFound,
            "The single-table inheritance mechanism failed to locate the subclass: '#{ record[inheritance_column] }'. " +
            "This error is raised because the column '#{ inheritance_column }' is reserved for storing the class in case of inheritance. " +
            "Please rename this column if you didn't intend it to be used for storing the inheritance class " +
            "or overwrite #{ self.to_s }.inheritance_column to use another column for that information."
        end
      end
    else
      allocate
    end

  object.instance_variable_set("@attributes", record)
  object
end
ソースコードはここから持ってきました。

This article was migrated from http://rails.office.drecom.jp/takiuchi/archive/147

posted by Png genki on Fri 29 Dec 2006 at 13:02
Contents
Rubyのnewとallocate
ActiveRecord::Base.instantiate
Comments
瀧内元気: MacOS版は以下にあります * [genki/ViMouse](https://githu... '23-1
dsjf: https://gist.github.com/6bf1bf2c3cbb5eb6e7a7 これ... '13-1
瀧内元気: おお、チェックしてみます。thx! '11-12
overisland: Reeder for iPhone もこの UI を実装していますね。 '11-12
瀧内元気: その情報は見たのですが、以下のサイトによると、現在はまた必要になってるっぽいんですよね。 ... '11-12
Services from s21g
twpro(ツイプロ)
Twitterプロフィールを快適検索
地価2009
土地の値段を調べてみよう
MyRestaurant
自分だけのレストラン手帳
Formula
ブログに数式を埋め込める数式コミュニティ