0.0
No commit activity in last 3 years
No release in over 3 years
Make a class encodable into JSON format.
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
 Dependencies

Development

Runtime

 Project Readme

JSON::Encodable

Make a class encodable into JSON format.

Usage

  1. Include JSON::Encodable module
  2. Call .property method with property name
  3. Then the instance will be able to respond to to_json method

#to_json

class Blog
  include JSON::Encodable

  property :id
  property :title
  property :username

  def id
    1
  end

  def title
    "wonderland"
  end

  def username
    "alice"
  end
end

Blog.new.to_json
#=> '{"id":1,"title":"wonderland","username":"alice"}'

#as_json(options = {})

You can also call .as_json method with :except and :only options.

Blog.new.as_json(only: [:id, :username])
#=> { "id" => 1, "username" => "alice" }

Blog.new.as_json(except: :username)
#=> { "id" => 1, "title" => "wonderland" }

Advanced

You can contain any optional metadata on each properties, and access to them by .properties method.

class Blog
  include JSON::Encodable

  property :id, type: Integer
  property :title, type: String
  property :username, type: String
end

# Returns an array of `JSON::Encodable::Property` instances.
# Each instance has `#name` and `#options` methods.
Blog.properties