2014-05-22 4 views
1

현재 as_json 메서드의 동작이 다릅니다. 이것이 사양이 성공적으로 실행되지 않는 이유입니다.as_json의 다른 동작

it "response in json format" do 
    expect(json).to eq assigns[:user].as_json 
end 

:

def serializable_hash(options={}) 
    super(only: [:username, :created_at]) 
end 

내 RSpec에 행동이 오류가 발생합니다 다음 테스트 : 내 모델에서

User.first.as_json 
# => {"username"=>"Joe", "created_at"=>Thu, 24 Apr 2014 09:41:17 UTC +00:00 } 

User.first.created_at.as_json 
# => "2014-04-24T09:41:17Z" 

나는 JSON과 XML의 필드를 제한하는 serializable_hash 방법을 추가 이 오류는 두 타임 스탬프가 동일하지 않음을 나타냅니다.

-"created_at" => Thu, 24 Apr 2014 09:41:17 UTC +00:00, 
+"created_at" => "2014-04-24T09:41:17Z", 

첫 번째 줄에 멤버 개체의 날짜 시간 형식을 어떻게 설정합니까?

도움 주셔서 감사합니다.

스테에서 as_json를 호출가 개체의 유형에 따라 다른 시리얼 때문에 무슨 일이 일어나고

+0

'as_json' 메소드는 어떻게 생겼습니까? 당신이 그것을 커스터마이징했다는 말입니까? – pdobb

+0

@ pdobb : 필자는 모델에 serializable_hash 메서드를 추가했습니다. 하지만 이것은 json 출력에서 ​​좋아하는 필드를 설정하는 경우에만 관련이 있습니다. – sts

답변

0

합니다.

as_json 하나 xmlschema를 호출하고,이 같은 형식으로 복귀된다 시간 : % Y- % M- % DT % H %의 M %의 S를 Z.은 (PRY 사용) 여기에서 소스 코드를 따르세요 % Y- % M- % D % H : %의 M % S UTC

pry(main)> show-source User.first.validated_at.as_json 
def as_json(options = nil) 
    if ActiveSupport::JSON::Encoding.use_standard_json_time_format 
    xmlschema 
    else 
    %(#{time.strftime("%Y/%m/%d %H:%M:%S")} #{formatted_offset(false)}) 
    end 
end 

pry(main)> show-source User.first.validated_at.xmlschema 
def xmlschema(fraction_digits = 0) 
    fraction = if fraction_digits > 0 
    (".%06i" % time.usec)[0, fraction_digits + 1] 
    end 

    "#{time.strftime("%Y-%m-%dT%H:%M:%S")}#{fraction}#{formatted_offset(true, 'Z')}" 
end 

액티브as_jsonserializable_hash를 호출하고, 각 필드의 마지막 포맷의 종류를 반환하는 to_s 하 반면

pry(main)> show-source User.first.as_json 
def as_json(options = nil) 
    root = include_root_in_json 
    root = options[:root] if options.try(:key?, :root) 
    if root 
    root = self.class.model_name.element if root == true 
    { root => serializable_hash(options) } 
    else 
    serializable_hash(options) 
    end 
end 

pry(main)> show-source User.first.serializable_hash 
def serializable_hash(options = nil) 
    options = options.try(:clone) || {} 

    options[:except] = Array.wrap(options[:except]).map { |n| n.to_s } 
    options[:except] |= Array.wrap(self.class.inheritance_column) 

    super(options) 
end 

pry(main)> show-source User.first.validated_at.to_s 
def to_s(format = :default) 
    if format == :db 
    utc.to_s(format) 
    elsif formatter = ::Time::DATE_FORMATS[format] 
    formatter.respond_to?(:call) ? formatter.call(self).to_s : strftime(formatter) 
    else 
    "#{time.strftime("%Y-%m-%d %H:%M:%S")} #{formatted_offset(false, 'UTC')}" # mimicking Ruby 1.9 Time#to_s format 
    end 
end 
+0

Thanx @Rafa. 두 형식을 동일하게 설정하는 방법이 있습니까? 클래스 ActiveSupport :: TimeWithZone이 두 번째 예제에서 도움이된다는 것을 알았습니다. 첫 번째 질문에 대해이 모든 것이 있습니까? – sts

+0

출력으로 얻고 자하는 것에 따라 다릅니다. JSON을 원한다면 두 가지 모두에서 .to_json을 할 수 있으며 같은 형식으로 시간을 반환합니다. –

+0

'.to_json'은 json 출력 만 반영하기 때문에 원하는 내용이 아닙니다. 'serializable_hash'를 사용하면 json과 xml 필드를 설정할 수 있습니다. – sts