ruby - Massaging a mongoid habtm with a string for a class -


i started off https://gist.github.com/scttnlsn/1295485 basis make restful sinatra app. i'm having difficulty, though, managing habtm relationships paths such as

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

i have objecttype map (as per gist), , pulling right object db id straightfoward. however, getting other side of habtm , calling appropriate method on objecttype delete relationship involves turning handful of strings appropriate objects , methods.

i came solution, uses eval. i'm aware using eval evil , doing rot soul. there better way handle this, or should put in safeguards protect code , call day?

here's working, self contained, sinatra-free example show how i'm doing 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)   # use "model" in actual app, hardwired person here    # make 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 real question... scares me dangerous. there      # safer way 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 |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 

a nice gentleman on freenode helped me out. 2 evals can replaced with:

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

Comments

Popular posts from this blog

c++ - Creating new partition disk winapi -

Android Prevent Bluetooth Pairing Dialog -

VBA function to include CDATA -