Skip to content

Instantly share code, notes, and snippets.

@mkmurray
Created May 17, 2012 14:07
Show Gist options
  • Save mkmurray/2719139 to your computer and use it in GitHub Desktop.
Save mkmurray/2719139 to your computer and use it in GitHub Desktop.
FubuMVC asset pipeline transformer that finds and replaces an InputModel place holder with its route URL. Helpful in avoiding hard-coding an AJAX URL in your JavaScript asset files (though any asset file type will be feed through this transformer).
using System;
using System.Collections.Generic;
using System.Text;
using FubuMVC.Core.Assets.Files;
namespace Some.Namespace.Here
{
public class UrlTransformationException : Exception
{
string _message;
public UrlTransformationException(string message)
: base(message)
{
}
public UrlTransformationException(string contents, IEnumerable<AssetFile> files)
{
var message = new StringBuilder("A url was not resolved");
foreach (var assetFile in files)
{
message.AppendFormat("File: {0}", assetFile.Name);
message.AppendLine();
}
_message = message.ToString();
}
public override string Message
{
get { return _message; }
}
}
}
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;
using FubuCore;
using FubuMVC.Core.Assets.Content;
using FubuMVC.Core.Assets.Files;
namespace Some.Namespace.Here
{
public class UrlTransformer : ITransformer
{
readonly IModelUrlResolver _urlResolver;
public UrlTransformer(IModelUrlResolver urlResolver)
{
_urlResolver = urlResolver;
}
public string Transform(string contents, IEnumerable<AssetFile> files)
{
var regex = new Regex(@"url::(?<InputModel>[A-Za-z\.]+)");
var matches = regex.Matches(contents);
var replacements = findReplacements(matches).Distinct();
var replacedContents = contents;
replacements.Each(r =>
{
var url = _urlResolver.GetUrlForInputModelName(r);
var alteredUrl = @"url::{0}".ToFormat(r);
replacedContents = replacedContents.Replace(alteredUrl, url);
});
if (replacedContents.Contains("url::"))
throw new UrlTransformationException(contents, files);
return replacedContents;
}
private IEnumerable<string> findReplacements(MatchCollection matchCollection)
{
return from Match match in matchCollection select match.Groups["InputModel"].Value;
}
}
}
@mkmurray
Copy link
Author

It looks like a better sample is over at Corey Kaylor's gist: https://gist.github.com/1563424

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment