class Fauxhai::Fetcher

Public Class Methods

new(options = {}) { |data| ... } click to toggle source
# File lib/fauxhai/fetcher.rb, line 7
def initialize(options = {}, &override_attributes)
  @options = options

  if !force_cache_miss? && cached?
    @data = cache
  else
    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

Public Instance Methods

cache() click to toggle source
# File lib/fauxhai/fetcher.rb, line 35
def cache
  @cache ||= JSON.parse(File.read(cache_file))
end
cache_file() click to toggle source
# File lib/fauxhai/fetcher.rb, line 47
def cache_file
  File.expand_path(File.join(Fauxhai.root, 'tmp', cache_key))
end
cache_key() click to toggle source
# File lib/fauxhai/fetcher.rb, line 43
def cache_key
  Digest::SHA2.hexdigest("#{user}@#{host}")
end
cached?() click to toggle source
# File lib/fauxhai/fetcher.rb, line 39
def cached?
  File.exist?(cache_file)
end
force_cache_miss?() click to toggle source
# File lib/fauxhai/fetcher.rb, line 51
def force_cache_miss?
  @force_cache_miss ||= @options.delete(:force_cache_miss) || false
end
to_hash(*args) click to toggle source

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

@return [Hash] the `@data` represented as a Ruby hash

# File lib/fauxhai/fetcher.rb, line 58
def to_hash(*args)
  @data.to_hash(*args)
end
to_s() click to toggle source
# File lib/fauxhai/fetcher.rb, line 62
def to_s
  "#<Fauxhai::Fetcher @host=#{host}, @options=#{@options}>"
end

Private Instance Methods

host() click to toggle source
# File lib/fauxhai/fetcher.rb, line 68
def host
  @host ||= begin
    raise ArgumentError, ':host is a required option for Fauxhai.fetch' unless @options[:host]
    @options.delete(:host)
  end
end
user() click to toggle source
# File lib/fauxhai/fetcher.rb, line 75
def user
  @user ||= (@options.delete(:user) || ENV['USER'] || ENV['USERNAME']).chomp
end