Class: Themeable::CssPathResolver

Inherits:
Object
  • Object
show all
Defined in:
lib/themeable/css_path_resolver.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(theme) ⇒ CssPathResolver

Returns a new instance of CssPathResolver.



7
8
9
# File 'lib/themeable/css_path_resolver.rb', line 7

def initialize(theme)
  @theme = theme
end

Instance Attribute Details

#themeObject (readonly)

Returns the value of attribute theme.



6
7
8
# File 'lib/themeable/css_path_resolver.rb', line 6

def theme
  @theme
end

Instance Method Details

#resolveObject



11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
# File 'lib/themeable/css_path_resolver.rb', line 11

def resolve
  root_directory = File.join(theme.root_path, 'vendor')
  Dir["#{root_directory}/**/*.css"].each do |filename|
    contents = File.read(filename) if FileTest.file?(filename)
    # http://www.w3.org/TR/CSS2/syndata.html#uri
    url_regex = /url\((?!\#)\s*['"]?((?![a-z]+:)([^'"\)]*?)([?#][^'"\)]*)?)['"]?\s*\)/

    # Resolve paths in CSS file if it contains a url
    if contents =~ url_regex
      directory_path = Pathname.new(File.dirname(filename))
      .relative_path_from(Pathname.new(root_directory))

      # Replace relative paths in URLs with Rails asset_path helper
      new_contents = contents.gsub(url_regex) do |match|
        relative_path = $2
        params = $3
        image_path = directory_path.join(relative_path).cleanpath

        "asset-url('#{image_path}#{params}')"
      end

      # Replace CSS with ERB CSS file with resolved asset paths
      FileUtils.rm(filename)
      File.write(filename.gsub(/css$/, 'scss'), new_contents)
    end
  end
end