|
Versions Of This Snippet::
Download a raw-text version of this code by clicking on "Download Version"
Latest Snippet Version: :0.2
###################################################################
# Server: lib/share_models.rb
require 'drb'
require 'find'
# add other classes / modules here if transmitted
%w[ActiveRecord ActiveRecord::Base].each do |c|
eval "class #{c}; include DRb::DRbUndumped; end" rescue nil
eval "module #{c}; include DRb::DRbUndumped; end" rescue nil
class << c; include DRb::DRbUndumped; end
end
# This class enables you to share your rails models via druby
class ShareModels
include DRb::DRbUndumped
# Takes the name of a Model and returns the class.
def model str
return unless models.include? str
class << str.constantize; include DRb::DRbUndumped; end
eval "class #{str}; include DRb::DRbUndumped; end"
str.constantize
end
# List of all models (will use cached version, if available).
def models
@@models ||= models!
end
# List of all models (won't use cached version).
def models!
@@models = []
path = "#{RAILS_ROOT}/app/models"
Find.find(path) do |p|
if FileTest.directory?(p) and p!=path
Find.prune
next
end
@@models << File.basename(p,".*").camelize if p =~ /\.rb$/ and not p =~ /_observer\.rb$/i
end
@@models
end
# Shares the models. Parameters are the same as for DRb.start_service (minus the object to be shared).
def self.start uri, config = nil
DRb.start_service uri, self.new, config
end
end
###################################################################
# Server: config/initializers/share.rb
ShareModels.start 'druby://localhost:1234' # you should use ssl instead
###################################################################
# Client - example
require 'drb'
remote = DRbObject.new(nil, 'druby://localhost:1234')
remote.models.each { |name| eval "#{name} = remote.model '#{name}'" }
# Now you can access your models as if running inside rails.
# However, active_record, rails, or such things are not necessary.
puts SomeModel.find(:first).some_attribute
Submit a new versionYou can submit a new version of this snippet if you have modified it and you feel it is appropriate to share with others..
|
||||||||||||||||||||||||||||||||||||
