JSON::Encodable
Note
This project is archived because I no longer actively use it, and there seems to be no recent activity from other users either. If you are still using it and would like to take over maintenance, please contact me somewhere.
Make a class encodable into JSON format.
Usage
- Include
JSON::Encodablemodule - Call
.propertymethod with property name - Then the instance will be able to respond to
to_jsonmethod
#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