Class: Hacker::News::Item
- Inherits:
-
Object
- Object
- Hacker::News::Item
- 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.
Instance Attribute Summary collapse
-
#by ⇒ Object
readonly
Common fields on every variant.
-
#dead ⇒ Object
readonly
Common fields on every variant.
- #id ⇒ Integer readonly
-
#time ⇒ Object
readonly
Common fields on every variant.
-
#type ⇒ String
readonly
One of “story” / “comment” / “job” / “poll” / “pollopt”.
Class Method Summary collapse
-
.from_hash(data) ⇒ Item
Build the matching Item subclass from a decoded API payload.
Instance Method Summary collapse
- #assign(_h) ⇒ Object abstract
-
#initialize(data) ⇒ Item
constructor
A new instance of Item.
Constructor Details
#initialize(data) ⇒ Item
Returns a new instance of Item.
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
#by ⇒ Object (readonly)
Common fields on every variant.
20 21 22 |
# File 'lib/hacker/news/items.rb', line 20 def by @by end |
#dead ⇒ Object (readonly)
Common fields on every variant.
20 21 22 |
# File 'lib/hacker/news/items.rb', line 20 def dead @dead end |
#id ⇒ Integer (readonly)
20 21 22 |
# File 'lib/hacker/news/items.rb', line 20 def id @id end |
#time ⇒ Object (readonly)
Common fields on every variant.
20 21 22 |
# File 'lib/hacker/news/items.rb', line 20 def time @time end |
#type ⇒ String (readonly)
Returns 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.
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 |