我的模型中有几个函数
#app/model/game.rb
...
def uncompress_game_files_to_s3
UncompressToS3Job.perform_now(self.files, "assets/#{self.id}/game") if self.files
end
def delete_game_files_from_s3
DeleteFromS3Job.perform_now("assets/#{self.id}/game")
end
def update_game_index_file_url
files = FindFilesOnS3Job.perform_now("index.html", "assets/#{self.id}/game")
self.update_attributes(url: files.first)
end
在所有这些功能中,我使用"assets/#{self.id}/game"
作为S3键属性。我想将此表达式用作全局变量aws_game_path
。
我尝试在初始化文件中初始化它。
#config/initializers/aws.rb
aws_game_path = "assets/#{self.id}/game"
但由于它超出了模型范围,因此会引发错误undefined method `id'
。我怎样才能声明这样的变量?
答案 0 :(得分:0)
如果您只是从该模型中使用它,那么它不需要是全局的。可以只是一个私人方法:
def update_game_index_file_url
files = FindFilesOnS3Job.perform_now("index.html", game_path)
self.update_attributes(url: files.first)
end
private
def game_path
"assets/#{id}/game"
end
我如何声明这种可变性。
变量不会以这种方式表现。它必须是某个对象的方法。共享的,如果你想在模型之外使用这个逻辑。这样的事情,也许是:
module PathHelpers
def self.game_path(game)
"assets/#{game.id}/game"
end
end
class Game
def update_game_index_file_url
files = FindFilesOnS3Job.perform_now("index.html", PathHelpers.game_path(self))
end
end
答案 1 :(得分:0)
我认为ActiveSupport::Concern
在这种情况下是最佳做法。
按照以下步骤使所有型号
可用 1:创建 rb
,在active_record_global_var.rb
中添加lib
个lib
扩展名为 module ActiveRecordExtension
extend ActiveSupport::Concern
def set_global_valiable
set_global_id = self
end
module ClassMethods
end
end
ActiveRecord::Base.send(:include, ActiveRecordExtension)
首先加载文件。
2:粘贴以下代码。
config/initializers/
3:在 extensions.rb
目录中创建文件。让我们说require "active_record_global_var"
并将此代码剪切到此文件中。
4: set_global_variable
5:现在在模型对象上调用User.last.set_global_valiable.id
实例方法。此方法适用于所有模型。
例如:
CbResume.last.set_global_valiable.id
为您提供用户ID
var size = new List<t>() ;
using (SqlConnection connection = new SqlConnection(ConfigurationManager.ConnectionStrings["batch"].ConnectionString))
{
size = FileBusinessLogic.LoadBatchAvgFileSizes(connection);
}
与CbResume模型相同
希望这能帮到你!!!