lang/ruby

Ruby JSON multiJson activeSupport

푸른바람 C/H 2018. 6. 21. 08:30


ActiveSupport 젬을 사용하면 시간대, 국제화(i18n), JSON 인코딩 및 디코딩 같은 Rails로부터 가져온 기능을 쓸 수 있다. ActiveSupport의 JSON 모듈은

  • 카멜 카이스와 스네이크 케이스의 상호변환
  • 객체의 일부만을 직렬화

sudo jem install multi_json
sudo gem install activesupport
sudo gem install awesome_print
require 'multi_json'
require 'active_support/json'
require 'active_support/core_ext/string'
require 'ostruct'
require 'awesome_print'

class Speaker
    def initialize(first_name, last_name, email, about, company, tags, registered)
    @first_name = first_name
    @last_name = last_name
    @email = email
    @about = about
    @company = company
    @tags = tags
    @registered = registered
    end
end

speaker = Speaker.new('Larson', 'Richard', 'larsonrichard@ecratic.com',
            'Incididunt mollit cupidatat magna excepteur do tempor ex non ...',
            'Ecratic', %w(JavaScript, AngularJS, Yeoman), true)

json_speaker = ActiveSupport::JSON.encode(speaker)
puts "speaker (using oj gem) = #{ActiveSupport::JSON.encode(speaker)}"
puts

ostruct_spkr = OpenStruct.new(ActiveSupport::JSON.decode(json_speaker))

speaker2 =  Speaker.new(ostruct_spkr.first_name, ostruct_spkr.last_name, 
                        ostruct_spkr.email, ostruct_spkr.about, ostruct_spkr.company,
                        ostruct_spkr.tags, ostruct_spkr.registered)

puts "speaker 2 after ActiveSupport::JSON.decode()"
ap speaker2
puts
ruby obj_serialize_active_support.rb 
    speaker (using oj gem) = {"first_name":"Larson","last_name":"Richard","email":"larsonrichard@ecratic.com","about":"Incididunt mollit cupidatat magna excepteur do tempor ex non ...","company":"Ecratic","tags":["JavaScript,","AngularJS,","Yeoman"],"registered":true}

    speaker 2 after ActiveSupport::JSON.decode()
    #


API 설계 실무에 바로 적용하는 JSON. 토마스 지음, 심효섭 옮김, 2018년 ⓒ인사이트
반응형

'lang > ruby' 카테고리의 다른 글

Ruby JSON multiJson activeSupport  (0) 2018.06.21
Ruby JSON multiJson oj  (0) 2018.06.20
Ruby helloWorld  (0) 2018.06.09
RadRails와 Eclipse로 Ruby on Rails를 쉽게! (한글)  (0) 2007.05.13
RoR(Ruby on Rails)  (0) 2006.10.26
1 2 3 4 5