Skip to content

Suffix visitor #1795

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
mausch opened this issue Feb 3, 2016 · 1 comment
Closed

Suffix visitor #1795

mausch opened this issue Feb 3, 2016 · 1 comment
Assignees

Comments

@mausch
Copy link
Contributor

mausch commented Feb 3, 2016

Now that #1089 is solved, we can include the suffix visitor I was talking about in that issue.
This is safer and more clear than using the current SuffixExtensions.Suffix because it only applies to Expression<Func<T, object>> instead of any object.
It also allows me to build a list of fields (of type Expression<Func<T, object>>) and apply a suffix to that whole list (useful for mapping multiple string fields with multiple analysers).

// put this anywhere you want
public static Expression<Func<T, object>> AppendSuffix<T>(this Expression<Func<T, object>> property, string suffix)
{
    var newBody = new SuffixExprVisitor(suffix).Visit(property.Body);
    return Expression.Lambda<Func<T, object>>(newBody, property.Parameters[0]);
}

/// <summary>
/// Calls <see cref="SuffixExtensions.Suffix"/> on a member expression.
/// </summary>
private class SuffixExprVisitor : ExpressionVisitor
{
    readonly string Suffix;

    public SuffixExprVisitor(string suffix)
    {
        Suffix = suffix;
    }

    protected override Expression VisitMember(MemberExpression node)
    {
        return Expression.Call(typeof(SuffixExtensions), "Suffix", null, node, Expression.Constant(Suffix));
    }

    protected override Expression VisitUnary(UnaryExpression node)
    {
        // allow rewriting child expressions
        return node;
    }
}
@gmarz
Copy link
Contributor

gmarz commented Feb 3, 2016

Great stuff, thanks @mausch ! Will look into implementing this in the next few days.

@russcam russcam self-assigned this Feb 4, 2016
@russcam russcam closed this as completed in 0a8352c Feb 4, 2016
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants