Module: Bulldog::Interpolation

Defined in:
lib/bulldog/interpolation.rb

Constant Summary collapse

Error =
Class.new(Bulldog::Error)

Class Method Summary collapse

Class Method Details

.interpolate(template, record, name, style, overrides = {}) ⇒ Object



5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
# File 'lib/bulldog/interpolation.rb', line 5

def self.interpolate(template, record, name, style, overrides={})
  unless overrides[:extension]
    overrides = overrides.dup
    overrides[:extension] ||= style[:format]
    if overrides[:basename]
      overrides[:extension] ||= File.extname(overrides[:basename]).sub(/\A./, '')
    end
  end
  template.gsub(/:(?:(\w+)|\{(\w+?)\})/) do
    key = ($1 || $2).to_sym
    if (override = overrides[key])
      override
    elsif @interpolations.key?(key)
      @interpolations[key].call(record, name, style)
    else
      raise Error, "no such interpolation key: #{key}"
    end
  end
end

.resetObject



29
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
# File 'lib/bulldog/interpolation.rb', line 29

def self.reset
  @interpolations = {}

  to_interpolate :class do |record, name, style|
    record.class.name.underscore.pluralize
  end

  to_interpolate :id do |record, name, style|
    record.send(record.class.primary_key)
  end

  to_interpolate :id_partition do |record, name, style|
    id = record.send(record.class.primary_key)
    ("%09d" % id).scan(/\d{3}/).join("/")
  end

  to_interpolate :attachment do |record, name, style|
    name
  end

  to_interpolate :style do |record, name, style|
    style.name
  end

  to_interpolate :basename do |record, name, style|
    reflection = record.attachment_reflection_for(name)
    column_name = reflection.column_name_for_stored_attribute(:file_name) or
      raise Error, ":basename interpolation requires storing the file name - add a column #{name}_file_name or use store_attributes"
    record.send(column_name)
  end

  to_interpolate :extension do |record, name, style|
    reflection = record.attachment_reflection_for(name)
    column_name = reflection.column_name_for_stored_attribute(:file_name) or
      raise Error, ":extension interpolation requires storing the file name - add a column #{name}_file_name or use store_attributes"
    basename = record.send(column_name) or
      raise Error, ":extension interpolation used when file_name not set - if you need to interpolate the url, pass a :basename override"
    File.extname(basename).sub(/\A\./, '')
  end

  to_interpolate(:root) do
    Bulldog.path_root
  end
end

.to_interpolate(key, &substitution) ⇒ Object



25
26
27
# File 'lib/bulldog/interpolation.rb', line 25

def self.to_interpolate(key, &substitution)
  @interpolations[key] = substitution
end