我从https://gist.github.com/scttnlsn/1295485开始,作为制作一个安静的 sinatra 应用程序的基础。不过,我在管理 HaBTM 关系的路径时遇到了困难,例如
delete '/:objecttype/:objid/:habtm_type/:habtm_id'
多亏了地图(根据那个要点),我已经有了对象类型,并且从带有 id 的数据库中提取正确的对象是直截了当的。但是,获取 habtm 的另一面并在 objecttype 上调用适当的方法来删除关系涉及将少量字符串转换为适当的对象和方法。
我想出了一个解决方案,但它使用了 eval。我知道使用 eval 是邪恶的,这样做会腐蚀我的灵魂。有没有更好的方法来处理这个问题,或者我应该采取一些保护措施来保护代码并收工?
这是一个工作的、自包含的、无 sinatra 的示例,展示了我是如何进行评估的:
require 'mongoid'
require 'pp'
def go
seed
frank = Person.find_by(name:"Frank")
apt = Appointment.find_by(name:"Arbor day")
pp frank
really_a_sinatra_route(frank.id, "appointments", apt.id)
frank.reload
pp frank
end
def really_a_sinatra_route(id, rel_type,rel_id)
# I use "model" in the actual app, but hardwired a person here to
# make a simpler example
person = Person.find_by(id: id)
person.deassociate(rel_type,rel_id)
end
class Base
def deassociate(relationship,did)
objname = associations[relationship].class_name
# Here's the real question... this scares me as dangerous. Is there
# a safer way to do this?
obj = eval "#{objname}.find(did)"
eval "#{relationship}.delete(obj)"
end
end
class Person < Base
include Mongoid::Document
has_and_belongs_to_many :appointments
end
class Appointment < Base
include Mongoid::Document
has_and_belongs_to_many :persons
end
def seed
Mongoid.configure do |config|
config.connect_to("test_habtmexample")
end
Mongoid.purge!
frank=Person.create(name:"Frank")
joe=Person.create(name:"Joe")
ccon = Appointment.create(name:"Comicon")
aday = Appointment.create(name:"Arbor day")
frank.appointments << ccon
frank.appointments << aday
ccon.persons << joe
joe.reload
end
go