Sha256: b7ad6e8357097938cf1cd413c0e0ce273af336cd85f36b454d282a0cb8249859

Contents?: true

Size: 1.53 KB

Versions: 2

Compression:

Stored size: 1.53 KB

Contents

module Sequel
  module Plugins; end
  
  class Model
    class << self
      # Loads a plugin for use with the model class, passing optional arguments
      # to the plugin.
      def is(plugin, *args)
        m = plugin_module(plugin)
        if m.respond_to?(:apply)
          m.apply(self, *args)
        end
        if m.const_defined?("InstanceMethods")
          class_def(:"#{plugin}_opts") {args.first}
          include(m::InstanceMethods)
        end
        if m.const_defined?("ClassMethods")
          meta_def(:"#{plugin}_opts") {args.first}
          metaclass.send(:include, m::ClassMethods)
        end
        if m.const_defined?("DatasetMethods")
          unless @dataset
            raise Sequel::Error, "Plugin cannot be applied because the model class has no dataset"
          end
          dataset.meta_def(:"#{plugin}_opts") {args.first}
          dataset.metaclass.send(:include, m::DatasetMethods)
        end
      end
      alias_method :is_a, :is
    
      private
        # Returns the module for the specified plugin. If the module is not 
        # defined, the corresponding plugin gem is automatically loaded.
        def plugin_module(plugin)
          module_name = plugin.to_s.gsub(/(^|_)(.)/) {$2.upcase}
          if not Sequel::Plugins.const_defined?(module_name)
            require plugin_gem(plugin)
          end
          Sequel::Plugins.const_get(module_name)
        end
  
        # Returns the gem name for the given plugin.
        def plugin_gem(plugin)
          "sequel_#{plugin}"
        end
    end
  end
end

Version data entries

2 entries across 2 versions & 1 rubygems

Version Path
sequel-1.5.0 lib/sequel_model/plugins.rb
sequel-1.5.1 lib/sequel_model/plugins.rb