Class: Nm::Source

Inherits:
Object
  • Object
show all
Defined in:
lib/nm/source.rb

Defined Under Namespace

Classes: NullCache

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(root, extension: nil, cache: false, locals: {}) ⇒ Source

Returns a new instance of Source.



11
12
13
14
15
16
# File 'lib/nm/source.rb', line 11

def initialize(root, extension: nil, cache: false, locals: {})
  @root = Pathname.new(root.to_s)
  @extension = extension ? ".#{extension}" : nil
  @cache = cache ? {} : NullCache.new
  @locals = locals
end

Instance Attribute Details

#cacheObject (readonly)

Returns the value of attribute cache.



9
10
11
# File 'lib/nm/source.rb', line 9

def cache
  @cache
end

#extensionObject (readonly)

Returns the value of attribute extension.



9
10
11
# File 'lib/nm/source.rb', line 9

def extension
  @extension
end

#localsObject (readonly)

Returns the value of attribute locals.



9
10
11
# File 'lib/nm/source.rb', line 9

def locals
  @locals
end

#rootObject (readonly)

Returns the value of attribute root.



9
10
11
# File 'lib/nm/source.rb', line 9

def root
  @root
end

Instance Method Details

#==(other) ⇒ Object



45
46
47
48
49
50
51
52
# File 'lib/nm/source.rb', line 45

def ==(other)
  return super unless other.is_a?(self.class)

  root == other.root &&
  extension == other.extension &&
  cache == other.cache &&
  locals == other.locals
end

#data(file_path) ⇒ Object



22
23
24
25
26
27
# File 'lib/nm/source.rb', line 22

def data(file_path)
  @cache[file_path] ||=
    begin
      File.send(File.respond_to?(:binread) ? :binread : :read, file_path)
    end
end

#file_path!(template_name) ⇒ Object



35
36
37
38
39
40
41
42
43
# File 'lib/nm/source.rb', line 35

def file_path!(template_name)
  if (path = file_path(template_name)).nil?
    message  = "a template file named #{template_name.inspect}"
    message += " that ends in #{@extension.inspect}" unless @extension.nil?
    message += " does not exist"
    raise ArgumentError, message
  end
  path
end

#inspectObject



18
19
20
# File 'lib/nm/source.rb', line 18

def inspect
  "#<#{self.class}:#{"0x0%x" % (object_id << 1)} @root=#{@root.inspect}>"
end

#render(template_name, context: Nm.default_context, locals: {}) ⇒ Object



29
30
31
32
33
# File 'lib/nm/source.rb', line 29

def render(template_name, context: Nm.default_context, locals: {})
  Nm::Context
    .new(context, source: self, locals: @locals)
    .render(template_name, locals)
end