Skip to content

Instantly share code, notes, and snippets.

@ngauthier
Created January 13, 2015 13:28
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ngauthier/8ecc7aa7b24ba1ba7f25 to your computer and use it in GitHub Desktop.
Save ngauthier/8ecc7aa7b24ba1ba7f25 to your computer and use it in GitHub Desktop.
poro json
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}
@ngauthier
Copy link
Author

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).

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment