Existing Rails model without fetching it from the database

孤者浪人 提交于 2019-12-08 06:40:27

I solved the problem by doing the following.

  1. Create a new model class which extends the model class that I want to have cached into memory.

  2. Set the table_name of the new class to the same one as the parent class.

  3. Create a new initialize method, call the super method in it, and then allow a parameter of that method to allow for a hash variable containing all the properties of the parent class.

  4. Overload the method new_record? and set that to false so that the associations work.

Here's my code:

class Session < User

  self.table_name = 'users'

  METHODS = [:id, :username] # all the columns that you wish to have in the memory hash
  METHODS.each do |method|
    attr_accessor method
  end

  def initialize(data)
    super({})

    if data.is_a?(User)
      user = data
      data = {}
      METHODS.each do |key|
        data[key] = user.send(key)
      end
    else
      data = JSON.parse(data)
    end

    data.each do |key,value|
      key = key.to_s
      self.send(key+'=',value)
    end
  end

  def new_record?
    false
  end

end

The memcached gem will allow you to shove arbitrary Ruby objects into it. This should all get handled for you transparently, if you're using it.

Otherwise, take a look at ActiveRecord::Base#instantiate to see how it's done normally. You're going to have to trace through a bunch of rails stack, but that's what you get for attempting such hackery!

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!