Module: Ety

Extended by:
Ety
Included in:
Ety
Defined in:
lib/ety.rb,
lib/ety/version.rb

Constant Summary collapse

VERSION =
"0.1.0"

Instance Method Summary collapse

Instance Method Details

#entry(args) ⇒ Object



10
11
12
13
14
15
16
17
18
19
# File 'lib/ety.rb', line 10

def entry(args)
  if !(args & %w[--help -h]).empty? or args.empty?
    help
  end

  @word=args.pop
  etymology, related_words=fetch_site
  puts "\e[1;4mEtymology of \"#{word}\":\e[m\n#{etymology}"
  puts "\n\e[1;4mRelated words:\e[m\n#{related(related_words).join(', ')}"
end

#fetch_siteObject



28
29
30
31
32
33
34
35
# File 'lib/ety.rb', line 28

def fetch_site
  html=Nokogiri::HTML(open(url,headers))
  pattern='//section[starts-with(@class,"word__defination")]'
  content=html.xpath(pattern)
  etymology=content[0].css('p').text
  related_words=content.map {|s| s.css('span').map(&:text)}.flatten!
  [etymology,related_words]
end

#headersObject



57
58
59
# File 'lib/ety.rb', line 57

def headers
  {'User-Agent' => 'ety-rubygem', 'accept' => 'text/html'}
end

#helpObject



21
22
23
24
25
26
# File 'lib/ety.rb', line 21

def help
  puts <<~eof
  Usage: ety <word>
  eof
  exit
end


37
38
39
40
41
42
43
44
45
46
47
# File 'lib/ety.rb', line 37

def related(words)
  str=''
  words.chunk {|e| e[0]=='-'}
       .flat_map do |tf,a|
    if tf
      str+a[0][1..-1]
    else
      a.size>1 ? [str=a.pop, a].last : a
    end
  end
end

#urlObject



53
54
55
# File 'lib/ety.rb', line 53

def url
  "https://www.etymonline.com/search?q=#{word}"
end

#wordObject



49
50
51
# File 'lib/ety.rb', line 49

def word
  @word
end