Class: Chef::Knife::Core::ObjectLoader

Inherits:
Object
  • Object
show all
Defined in:
lib/chef/knife/core/object_loader.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(klass, ui) ⇒ ObjectLoader

Returns a new instance of ObjectLoader.



27
28
29
30
# File 'lib/chef/knife/core/object_loader.rb', line 27

def initialize(klass, ui)
  @klass = klass
  @ui = ui
end

Instance Attribute Details

#klassObject (readonly)

Returns the value of attribute klass.



25
26
27
# File 'lib/chef/knife/core/object_loader.rb', line 25

def klass
  @klass
end

#uiObject (readonly)

Returns the value of attribute ui.



24
25
26
# File 'lib/chef/knife/core/object_loader.rb', line 24

def ui
  @ui
end

Instance Method Details

#file_exists_and_is_readable?(file) ⇒ Boolean

Returns:

  • (Boolean)


67
68
69
# File 'lib/chef/knife/core/object_loader.rb', line 67

def file_exists_and_is_readable?(file)
  File.exists?(file) && File.readable?(file)
end

#find_file(repo_location, *components) ⇒ Object



40
41
42
43
44
45
46
47
48
49
50
51
# File 'lib/chef/knife/core/object_loader.rb', line 40

def find_file(repo_location, *components)
  if file_exists_and_is_readable?(File.expand_path( components.last ))
    File.expand_path( components.last )
  else
    relative_path = File.join(Dir.pwd, repo_location, *components)
    if file_exists_and_is_readable?(relative_path)
      relative_path
    else
      nil
    end
  end
end

#load_from(repo_location, *components) ⇒ Object



32
33
34
35
36
37
38
# File 'lib/chef/knife/core/object_loader.rb', line 32

def load_from(repo_location, *components)
  unless object_file = find_file(repo_location, *components)
    ui.error "Could not find or open file for #{components.join(' ')}"
    exit 1
  end
  object_from_file(object_file)
end

#object_from_file(filename) ⇒ Object



53
54
55
56
57
58
59
60
61
62
63
64
65
# File 'lib/chef/knife/core/object_loader.rb', line 53

def object_from_file(filename)
  case filename
  when /\.(js|json)$/
    Chef::JSONCompat.from_json(IO.read(filename))
  when /\.rb$/
    r = klass.new
    r.from_file(filename)
    r
  else
    ui.fatal("File must end in .js, .json, or .rb")
    exit 30
  end
end