Module: Bj::ClassMethods

Defined in:
lib/bj/bj.rb

Instance Method Summary collapse

Instance Method Details

#ar_connectionObject



64
65
66
67
68
69
70
# File 'lib/bj/bj.rb', line 64

def ar_connection
  begin
    ActiveRecord::Base.connection
  rescue ActiveRecord::ConnectionNotEstablished 
    ActiveRecord::Base.establish_connection configurations[rails_env] 
  end
end

#ar_connectionsObject



56
57
58
59
60
61
62
# File 'lib/bj/bj.rb', line 56

def ar_connections
  if defined?(RAILS_ENV)
    { RAILS_ENV => ar_connection } 
  else
    {}
  end
end

#bootObject



86
87
88
89
# File 'lib/bj/bj.rb', line 86

def boot
  load File.join(rails_root, "config", "boot.rb")
  load File.join(rails_root, "config", "environment.rb")
end

#chroot(options = {}, &block) ⇒ Object



72
73
74
75
76
77
78
79
80
81
82
83
84
# File 'lib/bj/bj.rb', line 72

def chroot options = {}, &block
  if defined? @chrooted and @chrooted
    return block.call(@chrooted)
  end
  begin
    Dir.chdir @chrooted = rails_root do |pwd|
      raise RailsRoot, "<#{ pwd }> is not a rails root" unless Util.valid_rails_root?(pwd)
      block.call(@chrooted)
    end
  ensure
    @chrooted = nil 
  end
end

#connecting(options = {}, &block) ⇒ Object



35
36
37
38
39
40
41
42
43
44
45
# File 'lib/bj/bj.rb', line 35

def connecting options = {}, &block
  options.to_options!
  rails_env = (options[:rails_env] || Bj.rails_env).to_s
  previous = ar_connection
  ActiveRecord::Base.connection = connections[rails_env] unless ActiveRecord::Base.connection == connections[rails_env]
  begin
    block.call ActiveRecord::Base.connection
  ensure
    ActiveRecord::Base.connection = previous unless ActiveRecord::Base.connection == previous
  end
end

#connectionsObject



47
48
49
50
51
52
53
54
# File 'lib/bj/bj.rb', line 47

def connections
  @connections ||= Hash.new do |hash, rails_env|
    rails_env = rails_env.to_s
    ActiveRecord::Base.establish_connection configurations[rails_env]
    hash[rails_env] = ActiveRecord::Base.connection
  end.merge(ar_connections)
  @connections
end

#transaction(options = {}, &block) ⇒ Object



19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
# File 'lib/bj/bj.rb', line 19

def transaction options = {}, &block
  options.to_options!
  options.reverse_merge! :rails_env => Bj.rails_env
  bj_rails_env = Bj.rails_env
  begin
    Bj.rails_env = options[:rails_env].to_s
    connecting(options) do
      ActiveRecord::Base.transaction do 
        block.call ActiveRecord::Base.connection
      end
    end
  ensure
    Bj.rails_env = bj_rails_env 
  end
end