开发者

Rails: Storing static data like ActiveRecords

I've been looking for a while for gems and/or plugins that implement static storage similar ActiveRecords but is not database-based. Let's call this class NonDBRecord. It should have the following property:

class Foo < NonDBRecord
  add_item('a', :property1 => 'some value', :property2 => 'some more value')
  add_item('b', :property1 => 'some value', :property2 => 'some more value')
end

class Bar < ActiveRecord::Base
  belongs_to_nondbrecord :foo, :class_name => 'Foo'
end

# NonDBRecord declare constants automatically
[ Foo::A, Foo::B ]

# NonDBRecord is enumerable
Foo.all # returns [Foo::A,Foo::B]

# NonDBRecord is id-based
Bar.create(:foo_id => Foo::A.id)

# ...so you can search by it
x = Bar.find(:first, :conditions => { :foo_id => Foo::A.id })

# ...and is stored, retrieved, and instantiated by its id
x.foo # returns Foo::A

I've thought about simply using ActiveRecords (and database storage), but I don't feel good about it. Plus I've had to tip-toe around some eager loading problems with the ActiveRecord solution. Any help would be appreciated before I start writing my own solution.

edit

These records are meant to be enumerations. For example, let's say you're making a card 开发者_StackOverflow社区game. I want to be able to do something like

class Card < NonDBRecord
  attr_reader :suit, :index
end
class Game
  belongs_to :wild_card, :class_name => 'Card'
end


I would say ActiveModel is what you are looking for. It comes with Rails 3 and encapsulates all kind of goodies from ActiveRecord, such as Validation, Serialization and sorts. There is a Ryan Bates railscast on that issue. Hope this helps!


As BigD says, ActiveModel is the Rails 3 way.

In Rails 2.3 I am using this as a kluge:

class TablelessModel < ActiveRecord::Base  
  def self.columns() @columns ||= []; end 

  def self.column(name, sql_type = nil, default = nil, null = true) 
    columns << ActiveRecord::ConnectionAdapters::Column.new(name.to_s, default, sql_type.to_s, null) 
  end

  def save(validate = true) 
     validate ? valid? : true 
  end
end

I use that to e.g. validate contact forms that are not going to persist in any way. It's possible it could be extended for your specific purposes.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜