Class: SchemaDotOrg::SchemaType

Inherits:
ValidatedObject::Base
  • Object
show all
Defined in:
lib/schema_dot_org.rb

Overview

Base class for schema types. Refactors out common code.

Direct Known Subclasses

Organization, Person, Place, WebSite

Constant Summary collapse

ROOT_ATTR =
{"@context" => "http://schema.org"}

Instance Method Summary collapse

Instance Method Details

#_to_json_structObject



41
42
43
# File 'lib/schema_dot_org.rb', line 41

def _to_json_struct
  raise "For subclasses to implement"
end

#to_json(pretty: false, as_root: false) ⇒ Object



23
24
25
26
27
28
29
30
31
# File 'lib/schema_dot_org.rb', line 23

def to_json(pretty: false, as_root: false)
  structure = as_root ? ROOT_ATTR.merge(to_json_struct) : to_json_struct

  if pretty
    JSON.pretty_generate(structure)
  else
    structure.to_json
  end
end

#to_json_ld(pretty: false) ⇒ Object



18
19
20
# File 'lib/schema_dot_org.rb', line 18

def to_json_ld(pretty: false)
  "<script type=\"application/ld+json\">\n" + to_json(pretty: pretty, as_root: true) + "\n</script>"
end

#to_json_structObject

Use the class name to create the “@type” attribute.

Returns:

  • a hash structure representing json.



36
37
38
# File 'lib/schema_dot_org.rb', line 36

def to_json_struct
  { "@type" => un_namespaced_classname }.merge( _to_json_struct )
end

#to_sObject



13
14
15
# File 'lib/schema_dot_org.rb', line 13

def to_s
  to_json_ld(pretty: true)
end

#un_namespaced_classnameObject

Returns the classname without the module namespace.

Returns:

  • the classname without the module namespace.



47
48
49
50
# File 'lib/schema_dot_org.rb', line 47

def un_namespaced_classname
  self.class.name =~ /([^:]+)$/
  $1
end