Class: Microdata::Schema::Thing

Inherits:
Microdata::Schema show all
Defined in:
lib/microdata/schema/thing.rb

Constant Summary collapse

ATTRIBUTES =
[:id, :additional_type, :alternate_name, :description, :disambiguating_description, :identifier, :image, :main_entity_of_page, :name, :potential_action, :same_as, :url].freeze

Instance Attribute Summary

Attributes inherited from Microdata::Schema

#assined_attributes, #top_level

Instance Method Summary collapse

Constructor Details

#initialize(*args) ⇒ Thing

Returns a new instance of Thing.



8
9
10
11
12
13
14
15
16
17
18
19
# File 'lib/microdata/schema/thing.rb', line 8

def initialize(*args)
  hash = args.first
  return super if hash.nil?
  raise "args needs Hash" if hash.class != Hash
  super
  hash.each do |key, value|
    raise "key not found (#{key})" unless attributes.include?(key)
    value.top_level = false if value.is_a? Thing
    instance_variable_set("@#{key}", value)
    @assined_attributes << key
  end
end

Instance Method Details

#as_json(options = nil) ⇒ Object



21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
# File 'lib/microdata/schema/thing.rb', line 21

def as_json(options = nil)
  hash = {}
  assined_attributes.each do |attribute|
    camelCase = to_camel_case(attribute.to_s)
    camelCase = "@id" if camelCase == "id"
    hash[camelCase] = instance_variable_get("@#{attribute}")
  end
  hash = @required_attributes.merge(hash)
  if @top_level
    @required_attributes_for_top_level_things.merge!(hash)
    @required_attributes_for_top_level_things
  else
    hash
  end
end

#to_json(options = nil) ⇒ Object



37
38
39
# File 'lib/microdata/schema/thing.rb', line 37

def to_json(options = nil)
  as_json(options).to_json
end

#to_json_ld(options = nil) ⇒ Object



41
42
43
# File 'lib/microdata/schema/thing.rb', line 41

def to_json_ld(options = nil)
  "<script type=\"application/ld+json\">" + to_json(options) + "</script>"
end