【问题标题】:Massaging a mongoid habtm with a string for a class用一个类的字符串按摩一个 mongoid habtm
【发布时间】:2013-07-31 19:21:31
【问题描述】:

我以https://gist.github.com/scttnlsn/1295485 为基础,开始制作一个宁静的 sinatra 应用程序。不过,我在管理 HaBTM 关系的路径时遇到了困难,例如

delete '/:objecttype/:objid/:habtm_type/:habtm_id'

多亏了地图(根据那个要点),我已经有了对象类型,并且从带有 id 的数据库中提取正确的对象是直截了当的。但是,获取 habtm 的另一面并在 objecttype 上调用适当的方法来删除关系涉及将少量字符串转换为适当的对象和方法。

我想出了一个解决方案,但它使用了 eval。我知道使用 eval 是邪恶的,这样做会腐蚀我的灵魂。有没有更好的方法来处理这个问题,或者我应该采取一些保护措施来保护代码并收工?

这是一个工作的、自包含的、无 sinatra 的示例,用于展示我是如何进行 eval 的:

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

【问题讨论】:

    标签: ruby rest sinatra mongoid eval


    【解决方案1】:

    freenode 上的一位好先生帮助了我。这两个 eval 可以替换为:

    obj= self.send(relationship.to_sym).find(did)
    self.send(relationship.to_sym).delete(obj)
    

    【讨论】:

      猜你喜欢
      • 2016-02-28
      • 1970-01-01
      • 1970-01-01
      • 2021-07-23
      • 2021-06-15
      • 2013-12-03
      • 2011-03-25
      相关资源
      最近更新 更多