我已经构建了一个消耗json api的应用程序。我从我的应用程序中删除了活动记录,因为api中的数据理论上可以更改,我不想每次都擦除数据库。
现在我有一个名为self.all的方法,用于循环创建ruby对象的json的每个类。然后,我在各种函数中调用该方法,以便使用数据查找总和和百分比。这一切都很好,但似乎有点慢。我想知道是否存在我应该存储我的.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存储在某个地方,而不是每次调用该方法吗?
答案 0 :(得分: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 low-level caching