0

我已经构建了一个使用 json api 的应用程序。我从我的应用程序中删除了活动记录,因为 api 中的数据理论上可以更改,并且我不想每次都擦除数据库。

现在我有一个名为 self.all 的方法,用于循环通过 json 创建 ruby​​ 对象的每个类。然后我在各种函数中调用该方法,以便使用数据查找总和和百分比。这一切都很好,但似乎有点慢。我想知道是否应该在某个地方存储我的 .all 调用,而不是为每个处理数据的方法实例化新对象。

...response was assign above using HTTParty...

def self.all
    puppies = []
    if response.success?
      response['puppies'].each do |puppy|
        accounts << new(puppy['name'],
                        puppy['price'].to_money,
                        puppy['DOB'])
      end
    else
      raise response.response
    end
    accounts
  end

  # the methods below only accept arguments to allow testing with Factories
  # puppies is passed in as Puppy.all

  def self.sum(puppies)
    # returns money object
    sum = Money.new(0, 'USD')
    puppies.each do |puppy|
      sum += puppy.price
    end
    sum
  end

  def self.prices(puppies)
    prices = puppies.map { |puppy| puppy.price }
  end


  def self.names(puppies)
    names = puppies.map { |puppy| puppy.name }
  end

  ....many more methods that take an argument of Puppy.all in the controller....

我应该使用缓存吗?我应该带回活动记录吗?还是我做得很好?我应该将 Puppy.all 存储在某个地方而不是每次都调用该方法吗?

4

1 回答 1

0

我猜正在发生的是,每次调用任何类方法时,您都在向 HTTParty 发出请求。您可以考虑为响应创建一个类变量和一个名为 expires_at 的类变量。然后你可以做一些基本的缓存。

@@expires_at = Time.zone.now
@@http_response

def make_http_call
  renew_http_response if @@expires_at.past?
end

def renew_http_response
  # make HTTParty request here
  @@http_response = # HTTParty response
  @@expires_at = 30.minutes.from_now
end

# And in your code, change response to @@response
# ie response.success? to @@response.success?

这一切都在内存中,如果您重新启动服务器,您将失去一切。如果您想要更强大的缓存,最好的办法可能是研究Rails 低级缓存

于 2015-03-17T16:18:38.497 回答