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

访问量: 1361

今天碰到一个困难,我想在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.name #  => 'lala'
lala.age   # => 30

class Person < Struct.new(:name, :age)
end
girl = Person.new('lala', 30)
girl.name    # => "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: ) 见这里: http://stackoverflow.com/questions/1177594/ruby-struct-vs-openstruct

订阅/RSS Feed

Subscribe

分类/category