Extending AngelaSmith’s Fluent API

AngelaSmith is a package that can intelligently fill objects with random data (See Go Beyond Lorem Ipsum). In my last post, we saw how to extend AngelaSmith by implementing custom property fillers. In this post, we will see how to extend the fluent API.

The Fluent API

Just a quick over of AngelaSmith’s fluent API. The API allows you to tell AngelaSmith more information about how to fill a specific property of an object. For example, if you had a property named EmailAddress that you wanted filled with email addresses from a particular domain, you could configure AngelaSmith using the AsEmailAddressFromDomain method:

var person = Angie.Configure<Person>()
.Fill(p=> p.EmailAddress)
.AsEmailAddressForDomain(domain)
.Make<Person>();

Extending the API

Writing your own extension methods for the API is fairly straight forward. Here is the code for the AsEmailAddressForDomain method.

public static AngieConfigurator<T> AsEmailAddressForDomain<T>(this AngieStringConfigurator<T> configurator, string domain) where T : new()
{
    CustomFiller<string> filler = new CustomFiller<string>(configurator.PropertyInfo.Name, typeof(T), () => Jen.Email(domain));
    configurator.Maggie.RegisterFiller(filler);
    return configurator;
}

Since this method is intended for String properties only, this extension method is for the AngieStringConfigurator<T> class. Other options include AngieIntegerConfigurator<T>, AngieShortConfigurator<T>, AngieDateTimeConfigurator<T>, and AngieDecimalConfigurator<T>.

 

The method simply registers a custom filler for the specified property (that’s the property that was specified using the Fill method of the fluent API), and returns the configurator that was passed in. Now, AngelaSmith will use this custom filler for the specified property on type T instead of using the default built in property filler.

 

Notice that the return type is AngieConfigurator<T> instead of AngieStringConfigurator<T>. This is important because it ensures that we do not chain 2 String methods together. If we chained 2 String methods together, the second method call would always overwrite the previous method call.

What’s next?

You can find AngelaSmith on GitHub and on Nuget. Give it a try and let us know what type of extension methods you write. Feel free to submit a pull request on GitHub. We are happy to accept contributions from the community.

Install-Package AngelaSmith