class KindleHighlights::Book

Attributes

asin[RW]
author[RW]
mechanize_agent[R]
title[RW]

Public Class Methods

from_html_elements(html_element:, mechanize_agent:) click to toggle source
# File lib/kindle_highlights/book.rb, line 5
def self.from_html_elements(html_element:, mechanize_agent:)
  new(
    mechanize_agent: mechanize_agent,
    asin: html_element.attributes["id"].value.squish,
    title: html_element.children.search("h2").first.text.squish,
    author: html_element.children.search("p").first.text.split(":").last.strip.squish
  )
end
new(asin:, author:, title:, mechanize_agent: nil) click to toggle source
# File lib/kindle_highlights/book.rb, line 14
def initialize(asin:, author:, title:, mechanize_agent: nil)
  @asin = asin
  @author = author
  @title = title
  @mechanize_agent = mechanize_agent
end

Public Instance Methods

highlights_from_amazon() click to toggle source
# File lib/kindle_highlights/book.rb, line 29
def highlights_from_amazon
  return [] unless mechanize_agent.present?

  @highlights ||= fetch_highlights_from_amazon
end
inspect() click to toggle source
# File lib/kindle_highlights/book.rb, line 25
def inspect
  "<#{self.class}: #{inspectable_vars}>"
end
to_s() click to toggle source
# File lib/kindle_highlights/book.rb, line 21
def to_s
  "#{title} by #{author}"
end

Private Instance Methods

fetch_highlights_from_amazon() click to toggle source
# File lib/kindle_highlights/book.rb, line 39
def fetch_highlights_from_amazon
  mechanize_agent
    .get("https://read.amazon.com/kp/notebook?captcha_verified=1&asin=#{asin}&contentLimitState=&")
    .search("div#kp-notebook-annotations")
    .children
    .select { |child| child.name == "div" }
    .select { |child| child.children.search("div.kp-notebook-highlight").first.present? }
    .map    { |html_elements| Highlight.from_html_elements(book: self, html_elements: html_elements) }
end
inspectable_vars() click to toggle source
# File lib/kindle_highlights/book.rb, line 49
def inspectable_vars
  instance_variables
    .select { |ivar| ivar != :@mechanize_agent }
    .map    { |ivar| "#{ivar}=#{instance_variable_get(ivar).inspect}" }
    .join(", ")
end