Module: Acts::Partitionable::ClassMethods

Defined in:
lib/acts_as_partitionable.rb

Defined Under Namespace

Modules: ReadonlyInstanceMethods

Instance Method Summary collapse

Instance Method Details

#acts_as_partitionable(options = {}) ⇒ Object

Readonly Simple Sample: class User acts_as_partitionable :access => :readonly, :db_config => … end User.readonly do

me = find(1)   # DB hit

end

  • or -

User.readonly.find(:all)

:access => [:readonly, :readwrite (default), :writeonly]



26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
# File 'lib/acts_as_partitionable.rb', line 26

def acts_as_partitionable(options = {})
  # default options
  default_partition_name = "partition"
  options = {:access => :readwrite, :name => default_partition_name}.merge(options)
  
  partition_name = options[:name]
  
  partition_db_klass_readonly = false
  if options[:access] == :readonly
    partition_db_klass_readonly = true
    include ReadonlyInstanceMethods if partition_name == default_partition_name
  end

  if options[:db_config].is_a?(Hash)
    db_config = options[:db_config]
  elsif options[:db_config].is_a?(Symbol) or options[:db_config].is_a?(String)
    begin
      db_config = configurations[RAILS_ENV].merge(configurations[RAILS_ENV][options[:db_config].to_s])
    rescue
      raise ::ActiveRecord::ConfigurationError.new
    end
  end
  
  self_name = (self.name.include?('::') ? '' : '::') + self.name
  partition_db_klass = ("#{self_name}Partitionable#{partition_name}".constantize rescue nil)

  if partition_db_klass.nil?
    partition_db_klass ||= eval <<-TOS
      class #{self_name}Partitionable#{partition_name} < #{self_name}
        # setting abstract_class to true so that ActiveRecord doesn't look
        # for a db table for this base model class
        self.abstract_class = true
        def self.find_every(options)
          (options ||= {})[:readonly] = true if #{partition_db_klass_readonly}
          super(options)
        end
        def self.readonly?; #{partition_db_klass_readonly}; end
      end 
      #{self_name}Partitionable#{partition_name}
    TOS

    partition_db_klass.establish_connection(db_config)
  end

  class_eval <<-PART_PROC_END    
  def self.#{partition_name}(&block)
    return #{partition_db_klass}.module_eval(&block) if block_given?
    #{partition_db_klass}
  end
  def self.acts_as_partitionable?
    true
  end
  PART_PROC_END
end