Class: Fauxhai::Fetcher

Inherits:
Object
  • Object
show all
Defined in:
lib/fauxhai/fetcher.rb

Instance Method Summary collapse

Constructor Details

#initialize(options = {}) {|@data| ... } ⇒ Fetcher

Returns a new instance of Fetcher.

Yields:

  • (@data)


6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
# File 'lib/fauxhai/fetcher.rb', line 6

def initialize(options = {}, &override_attributes)
  @options = options

  if !force_cache_miss? && cached?
    @data = cache
  else
    require "net/ssh" unless defined?(Net::SSH)
    Net::SSH.start(host, user, @options) do |ssh|
      @data = JSON.parse(ssh.exec!("ohai"))
    end

    # cache this data so we do not have to SSH again
    File.open(cache_file, "w+") { |f| f.write(@data.to_json) }
  end

  yield(@data) if block_given?

  if defined?(ChefSpec)
    data = @data
    ::ChefSpec::Runner.send :define_method, :fake_ohai do |ohai|
      data.each_pair do |attribute, value|
        ohai[attribute] = value
      end
    end
  end

  @data
end

Instance Method Details

#cacheObject



35
36
37
# File 'lib/fauxhai/fetcher.rb', line 35

def cache
  @cache ||= JSON.parse(File.read(cache_file))
end

#cache_fileObject



47
48
49
# File 'lib/fauxhai/fetcher.rb', line 47

def cache_file
  File.expand_path(File.join(Fauxhai.root, "tmp", cache_key))
end

#cache_keyObject



43
44
45
# File 'lib/fauxhai/fetcher.rb', line 43

def cache_key
  Digest::SHA2.hexdigest("#{user}@#{host}")
end

#cached?Boolean

Returns:

  • (Boolean)


39
40
41
# File 'lib/fauxhai/fetcher.rb', line 39

def cached?
  File.exist?(cache_file)
end

#force_cache_miss?Boolean

Returns:

  • (Boolean)


51
52
53
# File 'lib/fauxhai/fetcher.rb', line 51

def force_cache_miss?
  @force_cache_miss ||= @options.delete(:force_cache_miss) || false
end

#to_hash(*args) ⇒ Hash

Return the given ‘@data` attribute as a Ruby hash instead of a JSON object

Returns:

  • (Hash)

    the ‘@data` represented as a Ruby hash



58
59
60
# File 'lib/fauxhai/fetcher.rb', line 58

def to_hash(*args)
  @data.to_hash(*args)
end

#to_sObject



62
63
64
# File 'lib/fauxhai/fetcher.rb', line 62

def to_s
  "#<Fauxhai::Fetcher @host=#{host}, @options=#{@options}>"
end