Skip to content

Instantly share code, notes, and snippets.

@dpoindexter
Created January 30, 2015 23:47
Show Gist options
  • Save dpoindexter/fdc8942f5885227d3663 to your computer and use it in GitHub Desktop.
Save dpoindexter/fdc8942f5885227d3663 to your computer and use it in GitHub Desktop.
Strategy to select a string formatter for a generic object
using System;
using System.Collections.Generic;
using System.Linq;
using FubuCore;
using uShip.Api.Common.Dto.Location;
namespace uShip.Web.Mvc.Builders
{
public class ObjectFormatter<TFormattable>
{
private readonly TFormattable _objectToFormat;
private readonly Func<string, bool> _formatPredicate;
private readonly List<FormatOption<TFormattable>> _formatOptions = new List<FormatOption<TFormattable>>();
private ObjectFormatter(TFormattable objectToFormat, Func<string, bool> applyFormatIfAllFieldsPass)
{
_objectToFormat = objectToFormat;
_formatPredicate = applyFormatIfAllFieldsPass;
}
public ObjectFormatter<TFormattable> Define(string format, params Func<TFormattable, string>[] propertyAccessors)
{
var option = new FormatOption<TFormattable>
{
Format = format,
PropertyAccessors = propertyAccessors
};
_formatOptions.Add(option);
return this;
}
public string Format()
{
var firstValidFormat =
_formatOptions.FirstOrDefault(o => o.PropertyAccessors.All(x => _formatPredicate(x(_objectToFormat))));
if (firstValidFormat == null)
{
return string.Empty;
}
return firstValidFormat.Format.ToFormat(firstValidFormat.PropertyAccessors.Select(x => x(_objectToFormat)));
}
public static ObjectFormatter<TFormattable> Create(TFormattable objectToFormat,
Func<string, bool> applyFormatIfAllFieldsPass)
{
return new ObjectFormatter<TFormattable>(objectToFormat, applyFormatIfAllFieldsPass);
}
private class FormatOption<T>
{
public string Format { get; set; }
public IEnumerable<Func<T, string>> PropertyAccessors { get; set; }
}
}
public class Foo
{
public Foo()
{
var foo = new Address();
var formattedAddress = ObjectFormatter<Address>.Create(foo, x => !string.IsNullOrWhiteSpace(x))
.Define("{0}, {1} {2}", x => x.City, x => x.AdministrativeDivision, x => x.PostalCode)
.Format();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment