Module: SFKB::Decoration

Included in:
Knowledge
Defined in:
lib/sfkb/decoration.rb

Overview

Methods to smartly apply singleton methods to REST objects

Instance Method Summary collapse

Instance Method Details

#autodefine(object) ⇒ Object


24
25
26
27
28
29
30
31
# File 'lib/sfkb/decoration.rb', line 24

def autodefine(object)
  return unless object.respond_to?(:additionalInformation)
  return unless info = object.additionalInformation
  autodefine_data(object, info[:data])
  autodefine_links(object, info[:urls])
  autodefine_predicates(object, info)
  object
end

#autodefine_data(object, data) ⇒ Object


41
42
43
44
45
# File 'lib/sfkb/decoration.rb', line 41

def autodefine_data(object, data)
  return object if data.nil?
  define_link(object, :data, data)
  object
end

47
48
49
50
51
# File 'lib/sfkb/decoration.rb', line 47

def autodefine_links(object, urls)
  return if urls.nil?
  define_links(object, urls) { |o| autodefine(o) }
  object
end

#autodefine_predicates(object, predicates) ⇒ Object


33
34
35
36
37
38
39
# File 'lib/sfkb/decoration.rb', line 33

def autodefine_predicates(object, predicates)
  predicates.each do |k, v|
    next unless [true, false].include?(v)
    define_predicate(object, k, v)
  end
  object
end

#decorate(object) {|object| ... } ⇒ Object

Yields:

  • (object)

4
5
6
7
8
# File 'lib/sfkb/decoration.rb', line 4

def decorate(object)
  return object unless block_given?
  yield object
  object
end

10
11
12
13
14
# File 'lib/sfkb/decoration.rb', line 10

def define_link(object, name, url, &block)
  getter = -> (url) { get(url).body }
  decorator = -> (o) { decorate(o, &block) }
  object.define_singleton_method(name) { decorator.call(getter.call(url)) }
end

16
17
18
# File 'lib/sfkb/decoration.rb', line 16

def define_links(object, urls, &block)
  urls.each { |k, v| define_link(object, k, v, &block) }
end

#define_predicate(object, name, value) ⇒ Object


20
21
22
# File 'lib/sfkb/decoration.rb', line 20

def define_predicate(object, name, value)
  object.define_singleton_method(:"#{name}?") { value }
end