2017-02-15 35 views
1

我需要將由api返回的所有日期轉換爲Unix日期格式(秒)。個別很容易...Active Model Serializer將所有日期轉換爲秒

class ChimichangaSerializer < ActiveModel::Serializer 
    attributes :updated_at, 

    def updated_at 
    object.updated_at.to_i 
    end 
end 

但是因爲我必須爲所有事情做到這一點,那就是錯誤和瘋狂。我如何才能實現這些功能?

+0

這是所有'updated_at'字段或一堆其他無關的字段? – tadman

+0

所有在其中都有日期的字段。目前,我有幾個不同型號的5。 作爲獎勵,輸入相反的東西。目前,我手動轉換每一個。 – TiggerToo

+0

您可以繼承ActiveModel :: Serializer並引入您自己的'attributes'方法,它可以使用諸如':as_integer'之類的選項。 – tadman

回答

1

在看到有關輸入轉換的評論之後,我想你可以重寫這些字段的getter和setter方法,如果你沒有以任何其他形式使用它們。也許沿着這些線會有所幫助。

重要的是要指出,這不僅會影響該字段的序列化。如果你想保持這些領域的正常行爲,我會按照塔德曼的建議去做。

# with_unix_time.rb 
module WithUnixTime 
    # These methods lack error handling 
    def to_unix_time(*fields) 
    fields.each do |field| 

     # Override getter. 
     define_method field do 
     self[field].to_i 
     end 

     # Override setter 
     define_method "#{field}=" do |value| 
     self[field] = Time.at(value) 
     end 

     # Convenience method to retrieve the original DateTime type 
     define_method "raw_#{field}" do 
     self[field] 
     end 
    end 
    end 
end 

# chimichanga.rb 
class Chimichanga < ActiveRecord::Base 
    extend WithUnixTime 
    to_unix_time :time_to_kill, :time_for_joke 
end 
+0

只是爲了讓你知道,所以你不會覺得你掛了,我會試試看,看看它是如何發展的,但由於它目前的功能不能擴展,它贏得了'直到我在下一個星期左右的截止日期之後,我纔會馬上選擇最佳答案。 – TiggerToo

+0

@TiggerToo根本沒有問題 –

0

添加以下內容:

app/config/initializers/time_with_zone.rb

class ActiveSupport::TimeWithZone 
    def as_json(options = {}) 
    to_i 
    end 
end 

當轉換成JSON這將覆蓋所有的時間戳的默認行爲。