Class: Hacker::News::Item

Inherits:
Object
  • Object
show all
Defined in:
lib/hacker/news/items.rb

Overview

Sum-type root class. Concrete subclasses: Story, Comment, Job, Poll, PollOpt. Use from_hash to build the right subclass from a decoded API payload.

Examples:

item = Hacker::News::Item.from_hash(api_payload)
case item
when Hacker::News::Story then item.title
when Hacker::News::Comment then item.text
end

Direct Known Subclasses

Comment, Job, Poll, PollOpt, Story

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(data) ⇒ Item

Returns a new instance of Item.

Parameters:

  • data (Hash{String, Symbol => Object})

    decoded API payload.

Raises:

  • (NotImplementedError)

    if instantiated directly. Always construct via Item.from_hash or a concrete subclass (Story, Comment, etc.).



25
26
27
28
29
30
31
32
33
34
35
36
37
38
# File 'lib/hacker/news/items.rb', line 25

def initialize(data)
  if instance_of?(Item)
    raise NotImplementedError,
          'Hacker::News::Item is abstract — use Item.from_hash or a concrete subclass'
  end

  h = data.transform_keys(&:to_s)
  @id = h['id']
  @type = h['type']
  @by = h['by']
  @time = h['time']
  @dead = h['dead'] == true
  assign(h)
end

Instance Attribute Details

#byObject (readonly)

Common fields on every variant.



20
21
22
# File 'lib/hacker/news/items.rb', line 20

def by
  @by
end

#deadObject (readonly)

Common fields on every variant.



20
21
22
# File 'lib/hacker/news/items.rb', line 20

def dead
  @dead
end

#idInteger (readonly)

Returns:

  • (Integer)


20
21
22
# File 'lib/hacker/news/items.rb', line 20

def id
  @id
end

#timeObject (readonly)

Common fields on every variant.



20
21
22
# File 'lib/hacker/news/items.rb', line 20

def time
  @time
end

#typeString (readonly)

Returns one of “story” / “comment” / “job” / “poll” / “pollopt”.

Returns:

  • (String)

    one of “story” / “comment” / “job” / “poll” / “pollopt”.



20
# File 'lib/hacker/news/items.rb', line 20

attr_reader :id, :type, :by, :time, :dead

Class Method Details

.from_hash(data) ⇒ Item

Build the matching Item subclass from a decoded API payload.

Parameters:

  • data (Hash)

    decoded API payload.

Returns:

Raises:

  • (ArgumentError)

    if the type field is missing or unknown.



44
45
46
47
48
49
50
51
52
53
54
# File 'lib/hacker/news/items.rb', line 44

def self.from_hash(data)
  kind = data['type'] || data[:type]
  case kind
  when 'story'   then Story.new(data)
  when 'comment' then Comment.new(data)
  when 'job'     then Job.new(data)
  when 'poll'    then Poll.new(data)
  when 'pollopt' then PollOpt.new(data)
  else raise ArgumentError, "unknown item type: #{kind.inspect}"
  end
end

Instance Method Details

#assign(_h) ⇒ Object

This method is abstract.

override in subclasses to unpack variant-specific fields.



57
# File 'lib/hacker/news/items.rb', line 57

def assign(_h); end