Search code examples
rubyruby-on-rails-4metadataschema.orgjson-ld

How to setup "application/ld+json" schema.org meta data in rails 4 app


I want to setup schema.org metadata using json ld. for example following link uses ghost and it has "application/ld+json" meta data. http://blog.ghost.org/distributed-team-tools/

I want to achieve similar for my rails app. How should I implement it. is there some gem for doing this etc.

Thanks!


Solution

  • There is a JSON-LD gem (http://rubygems.org/gems/json-ld), but it might not be specifically what you're looking for. Note that the point of JSON-LD is that it's just JSON, in this case using the schema.org context to interpret the values. Assuming that your data is in ActiveRecord models, you'll need a way to make sure that the record properties correspond to the appropriate schema.org properties. If this were the case, then just serializing your model to JSON (#to_json) gets you most of the way there. What remains is to add the @context, @id, and @type fields to the JSON.

    For example, say you have a User model which serialized to something like the following:

    {
      "name": "Harry",
      "email": "[email protected]"
    }
    

    As both "name" and "email" properties of http://schema.org/Person, you could get partway there by simply adding a @context and @type as follows:

    {
      "@context": "http://schema.org/",
      "@type": "Person",
      "name": "Harry",
      "email": "[email protected]"
    }
    

    Presuming that you're building a RESTful app, it's good practice to give every object an @id, which corresponds to the resource URL for this person. This could be like the following:

    {
      "@context": "http://schema.org/",
      "@id": "http://example.com/people/harry",
      "@type": "Person",
      "name": "Harry",
      "email": "[email protected]"
    }
    

    Now, if you retrieve http://example.com/people/harry as JSON (or JSON-LD), you could get back that representation.

    The other thing about JSON-LD is that it's for "Linked Data", so including references to other resources is useful for allowing them to be found, much as you probably do within your HTML. The schema.org documentation includes numerous examples for how to generate different types of markup, including JSON-LD, for most all of the types they define. See http://schema.org/Person for one example, or http://schema.org/docs/full.html for their complete type hierarchy.

    The JSON-LD gem comes in handy when you want to generate this data from other sources (typically some RDF format), or interpret data you've received. You can experiment with this at http://json-ld.org/playground.

    You can also include your JSON-LD in HTML using a script tag with type="application/ld+json" as your example does. If you want to see how your data looks, you can test it either on Google structured-data testing tool, or on http://linter.structured-data.org/