Class: Fauxhai::Mocker
- Inherits:
-
Object
- Object
- Fauxhai::Mocker
- Defined in:
- lib/fauxhai/mocker.rb
Constant Summary collapse
- RAW_BASE =
The base URL for the GitHub project (raw)
"https://raw.githubusercontent.com/chef/fauxhai/main".freeze
- PLATFORM_LIST_MESSAGE =
A message about where to find a list of platforms
"A list of available platforms is available at https://github.com/chef/fauxhai/blob/main/PLATFORMS.md".freeze
Instance Method Summary collapse
- #data ⇒ Object
-
#initialize(options = {}) {|data| ... } ⇒ Mocker
constructor
Create a new Ohai Mock with fauxhai.
Constructor Details
#initialize(options = {}) {|data| ... } ⇒ Mocker
Create a new Ohai Mock with fauxhai.
24 25 26 27 28 |
# File 'lib/fauxhai/mocker.rb', line 24 def initialize( = {}, &override_attributes) @options = { github_fetching: true }.merge() yield(data) if block_given? end |
Instance Method Details
#data ⇒ Object
30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 |
# File 'lib/fauxhai/mocker.rb', line 30 def data @fauxhai_data ||= lambda do # If a path option was specified, use it if @options[:path] filepath = File.(@options[:path]) unless File.exist?(filepath) raise Fauxhai::Exception::InvalidPlatform.new("You specified a path to a JSON file on the local system that does not exist: '#{filepath}'") end else filepath = File.join(platform_path, "#{version}.json") end if File.exist?(filepath) parse_and_validate(File.read(filepath)) elsif @options[:github_fetching] # Try loading from github (in case someone submitted a PR with a new file, but we haven't # yet updated the gem version). Cache the response locally so it's faster next time. require "open-uri" unless defined?(OpenURI) begin response = URI.open("#{RAW_BASE}/lib/fauxhai/platforms/#{platform}/#{version}.json") rescue OpenURI::HTTPError raise Fauxhai::Exception::InvalidPlatform.new("Could not find platform '#{platform}/#{version}' on the local disk and an HTTP error was encountered when fetching from Github. #{PLATFORM_LIST_MESSAGE}") end if response.status.first.to_i == 200 response_body = response.read path = Pathname.new(filepath) FileUtils.mkdir_p(path.dirname) begin File.open(filepath, "w") { |f| f.write(response_body) } rescue Errno::EACCES # a pretty common problem in CI systems puts "Fetched '#{platform}/#{version}' from GitHub, but could not write to the local path: #{filepath}. Fix the local file permissions to avoid downloading this file every run." end return parse_and_validate(response_body) else raise Fauxhai::Exception::InvalidPlatform.new("Could not find platform '#{platform}/#{version}' on the local disk and an Github fetching returned http error code #{response.status.first.to_i}! #{PLATFORM_LIST_MESSAGE}") end else raise Fauxhai::Exception::InvalidPlatform.new("Could not find platform '#{platform}/#{version}' on the local disk and Github fetching is disabled! #{PLATFORM_LIST_MESSAGE}") end end.call end |