Sinatra和Datamapper的虚拟属性

时间:2012-06-10 20:25:50

标签: ruby-on-rails ruby sinatra datamapper virtual-attribute

我正在将一个Rails应用程序转换为Sinatra。该应用程序依赖于支持虚拟属性的ActiveRecord,但是,我很难在DataMapper中找到类似的支持。

在Rails中,我使用算法生成分数并根据分数对记录进行排序。虚拟属性是此过程的核心。有没有人知道如何在Sinatra / DM中复制这个功能?

我愿意接受任何变通办法。重构可以在以后进行,因为我目前只对功能感兴趣。

理论上,解决方案的工作方式如下:

require 'sinatra'
require 'data_mapper'
require 'haml'

DataMapper::setup(:default,"sqlite3://#{Dir.pwd}/example.db")

class Link
  include DataMapper::Resource
  property :id, Serial
  property :title, Text
  property :url, String
  property :points, Integer, :default => 0
  property :created_at, Time

  attr_accessor :score

  def calculate_score
    time_elapsed = (Time.now - self.created_at) / 3600
    self.score = (self.points-1) / (time_elapsed+2)**1.8 
  end
end

DataMapper.finalize.auto_upgrade!

get '/hot' do
    @links = Link.all :order => :score.desc 
    haml :index 
end

1 个答案:

答案 0 :(得分:2)

我没有使用过datamapper,但我认为这段代码会为您提供所需的功能:更改包含,链接all_sorted_desc上的新类方法,并在“获取”请求中调用

require 'sinatra'
require 'data_mapper'
require 'haml'

DataMapper::setup(:default,"sqlite3://#{Dir.pwd}/example.db")

class Link
  include DataMapper::Resource
  property :id, Serial
  property :title, Text
  property :url, String
  property :points, Integer, :default => 0
  property :created_at, Time

  attr_accessor :score

  def calculate_score
    time_elapsed = (Time.now - self.created_at) / 3600
    self.score = (self.points-1) / (time_elapsed+2)**1.8 
  end

  def self.all_sorted_desc
    self.all.each { |item| item.calculate_score }.sort { |a,b| a.score <=> b.score }.reverse 
  end
end

DataMapper.finalize.auto_upgrade!

get '/hot' do
    @links = Link.all_sorted_desc 
    haml :index 
end