在ruby中模拟CLASS。 ( openstruct and struct in Ruby )

发布时间: 2013-12-21 06:19:00

今天碰到一个困难,我想在gem 中调用另外一个项目的model. 可我又不想把那个项目的代码copy 过来,也不想用factory_girl, (太麻烦了)。 想到 delayed_job 中使用了struct 这个东东,所以我google了一下发现还有个 openstruct.   ( today I am trying to write the unit test code in a gem project, but the difficulty is I have to refer a model defined in another project. I don't want to write a explicit class for this model.... so I googled "ruby struct" around, and found there is also an 'openstruct' out there) 


require 'ostruct'
lala = OpenStruct(:name => 'lala', :age => 30) #  => 'lala'
lala.age   # => 30

class Person <, :age)
girl ='lala', 30)    # => "lala"
girl.age  # => 30

基本的区别是: open struct 更加方便,一行代码搞定 。 但是运行的速度比 struct 要慢上100倍。 (both of them are fine for unit test, but open struct is 100x slower than struct when initializing. refer to: ) 见这里: