我可以加入ActiveRecord连接建立吗? [英] Can I hook into ActiveRecord connection establishment?

查看:63
本文介绍了我可以加入ActiveRecord连接建立吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用Sqlite3的create_function添加一个用户定义的函数,该函数将由数据库触发器使用。

I would like to add a user-defined function using Sqlite3's create_function, which will be used by database triggers.

是否可以挂接到ActiveRecord连接建立中?每次与数据库建立连接时都要运行一些代码,在哪里可以创建函数并将其提供给触发器?

Is there a way to hook into ActiveRecord connection establishment to run some code each time a connection to the database is made, where one could create the function and make it available to the triggers? This would also be useful for setting pragmas on the connection.

推荐答案

这是我自己发现的内容。我在app / config / initializers中使用初始化程序:

Here is what I've found on my own. Using an initializer in app/config/initializers I do this:

ActiveRecord::ConnectionAdapters::AbstractAdapter.class_eval do
  alias_method :orig_initialize, :initialize

  def initialize(connection, logger = nil, pool = nil)
    orig_initialize(connection, logger, pool)
    if connection.is_a? SQLite3::Database
      # 'reverse' is just an example :^)
      connection.create_function('reverse', 1) { |func, value| func.result = if value then value.to_s.reverse end }
    end
  end
end

我不确定是否可以重装该类,但是如果能到达,我会过桥。

I'm not sure if this class gets reloaded, but I'll cross that bridge if I get to it.

这篇关于我可以加入ActiveRecord连接建立吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆