Created
January 13, 2015 13:28
-
-
Save ngauthier/8ecc7aa7b24ba1ba7f25 to your computer and use it in GitHub Desktop.
poro json
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
require 'active_support' | |
require 'active_support/core_ext/object/json' | |
class Person | |
def initialize(name, age, car) | |
@name = name | |
@age = age | |
@car = car | |
@birthyear = compute_birth_year | |
end | |
def compute_birth_year | |
Time.now.year - @age.to_i | |
end | |
end | |
class Car | |
def initialize(make, model) | |
@make = make | |
@model = model | |
end | |
end | |
p = Person.new("nick", "29", Car.new("mazda", "3")) | |
puts p.to_json | |
# {"name":"nick","age":"29","car":{"make":"mazda","model":"3"},"birthyear":1986} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Uses ActiveSupport Object#as_json:
https://github.com/rails/rails/blob/master/activesupport/lib/active_support/core_ext/object/json.rb#L46
Which either uses the instance variables (in this example) or #to_hash if it is defined (great way for complex objects that need instance variables for internal state: just expose what you want via to_hash).