Class: Saper::Item

Inherits:
Object
  • Object
show all
Defined in:
lib/saper/core/item.rb

Overview

This class that serves as a foundation for a number of other classes: Saper::Items::Atom, Saper::Items::Document, Saper::Items::HTML, etc. It should not be used directly other than for the purposes of instantiating its subclasses, e.g.:

Saper::Item.new(:text, "Hello World")

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.[](type) ⇒ Saper::Argument

Returns a subclass with specified type.

Parameters:

  • type (Symbol)

    action type

Returns:


41
42
43
# File 'lib/saper/core/item.rb', line 41

def self.[](type)
  subclasses[type.to_s] || raise(Errors::InvalidItem, "Invalid action argument: %s" % type)
end

.exists?(type) ⇒ Boolean

Returns `true` if there is a subclass with specified type.

Parameters:

  • type (Symbol)

    action type

Returns:

  • (Boolean)

50
51
52
# File 'lib/saper/core/item.rb', line 50

def self.exists?(type)
  subclasses.keys.include?(type.to_s)
end

.inherited(base) ⇒ Class

Tracks subclasses of Saper::Item.

Returns:

  • (Class)

16
17
18
# File 'lib/saper/core/item.rb', line 16

def self.inherited(base)
  subclasses[base.type] = base
end

.new(*args, &block) ⇒ Saper::Argument

Returns a new instance of Saper::Argument.

Returns:


71
72
73
74
75
76
77
# File 'lib/saper/core/item.rb', line 71

def self.new(*args, &block)
  if self == Item
    self[args.shift].new(*args, &block)
  else
    super(*args, &block)
  end
end

.subclassesHash

Returns a hash of subclasses.

Returns:

  • (Hash)

24
25
26
# File 'lib/saper/core/item.rb', line 24

def self.subclasses
  @subclasses ||= {}
end

.try(*args, &block) ⇒ Saper::Argument

Returns a new instance of Saper::Argument. Returns nil and fails silently if there is an error during initialization.

Returns:


59
60
61
62
63
64
65
# File 'lib/saper/core/item.rb', line 59

def self.try(*args, &block)
  begin
    new(*args, &block)
  rescue Errors::InvalidItem, ArgumentError
    nil
  end
end

.typeString

Returns class name as an underscored string.

Returns:

  • (String)

32
33
34
# File 'lib/saper/core/item.rb', line 32

def self.type
  name.split("::").last.gsub(/([a-z])([A-Z])/,'\1_\2').downcase
end

Instance Method Details

#==(other) ⇒ Boolean

Returns `true` if other item contains the same data.

Returns:

  • (Boolean)

83
84
85
# File 'lib/saper/core/item.rb', line 83

def ==(other)
  to_s == other.to_s
end

#serializeObject

Returns native Ruby object of a similar type (e.g. String, Hash, Time, nil).

Returns:

  • (Object)

100
101
102
# File 'lib/saper/core/item.rb', line 100

def serialize
  to_native
end

#typeSymbol

Returns class name as a Symbol.

Returns:

  • (Symbol)

91
92
93
# File 'lib/saper/core/item.rb', line 91

def type
  self.class.type.to_sym
end