Browse | Submit A New Snippet | Create A Package

 

DRuby on Rails

Type:
Full Script
Category:
Database Manipulation
License:
GNU General Public License
Language:
Ruby
 
Description:
Small script for sharing all your models via druby. Note: You should use ACL + SSL or something for security reason.

Versions Of This Snippet::

Konstantin Haase
Snippet ID Download Version Date Posted Author Delete
3740.22008-06-11 17:33Konstantin Haase
Changes since last version::
corrected secon file path
3730.12008-06-11 17:31Konstantin Haase

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 version

You can submit a new version of this snippet if you have modified it and you feel it is appropriate to share with others..