2015-12-22 36 views
0

我有幾個功能,在我的模型全球動態路徑變量

#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

這不是一個全局變量,它是一個局部變量。 – sawa

回答

0

我認爲ActiveSupport::Concern會在這種情況下,最好的做法。

按照下面的步驟來讓所有模型

1:創建rb可以說在libactive_record_global_var.rb擴展文件爲lib文件加載第一。

2:粘貼以下一段代碼。

module ActiveRecordExtension 

    extend ActiveSupport::Concern 

    def set_global_valiable 
    set_global_id = self 
    end 

    module ClassMethods 

    end 

end 

ActiveRecord::Base.send(:include, ActiveRecordExtension) 

3:創建config/initializers/目錄中的文件。假設說extensions.rb並將此代碼剪切到此文件中。

4:require "active_record_global_var"

5:現在調用模型對象實例set_global_variable方法。這種方法將可用於所有模型。

例如:

User.last.set_global_valiable.id爲您提供了ID爲用戶

CbResume.last.set_global_valiable.id相同CbResume型號

希望這可以幫助您!

+0

Thabk你這是有幫助的! – user3301847

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 

我如何聲明這樣varaible。

變量不會這樣。它必須是某個對象的一種方法。一個共享的,如果你想在模型之外使用這個邏輯。事情是這樣的,也許:

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 
+0

感謝您的回覆。這很有幫助,但是如果我想在其他模型中使用它,我可以在哪裏聲明它? – user3301847