Specification Pattern in IronRuby
The Specification Pattern is one that I admire and have used often and most recently to good effect with both LINQ To SQL and the Entity Framework. This little gem of a pattern came in very useful with both ORM’s to enable dynamic queries built off Expressions or to be precise Expression<Func<T>>. If you want to know more about these implementations, then look here.
More recently in my travels down the polyglot road, I wanted to give the pattern a run with IronRuby. And boy I wasn’t disappointed. Getting a specification together in IronRuby was noticeably quicker and easier however please note that it lacks the happy ORM by-product as detailed above. Best to dive straight in to the code:
class Specification def initialize(expression) @expression = expression end def Matches(match_object) @expression.call(match_object) end end
And that’s all folks. Compared to C# it’s certainly less code and I can’t help but enjoy it’s brevity. Let’s add some spice with a user defined class to test with specifications.
class Customer def Name @name end def Age @age end def initialize(name, age) @name = name @age = age end end
And now let’s test this baby out:
#pass some code to test if a given number is less than 200 spec = Specification.new(lambda {|num| num < 200}) num_to_spec_on = 123 number_is_less_than_two_hundred = spec.Matches(num_to_spec_on) puts "It is #{number_is_less_than_two_hundred} " + "that #{num_to_spec_on} is less than 200" #use a user defined class to test with a specification cust = Customer.new("Simon Segal", 35) spec = Specification.new(lambda {|cust| cust.Name == "Simon Segal"}) customer_name_is_simon_segal = spec.Matches(cust) puts "It is #{customer_name_is_simon_segal} that the customer is Simon Segal" #combining lambdas into more complex specifications l1 = lambda {|num| num > 1} l2 = lambda {|num| num < 100} l3 = l1 && l2 num = 54 spec = Specification.new(l3) number_between_1_and_100 = spec.Matches(54) puts "#{number_between_1_and_100} #{num} is between 1 and 100"
The Result’s
Looking at this code, you will see that we have dialled up an explicit arithmetic specification to test a given numbers value is less than 200 followed by an evaluation of a Customer object, testing if it’s name is equal to my very own moniker. Finally, an example of combining lambdas to produce more complex specifications. Here are the results (I am still using Ruby In Steel, which I prefer to the other options and it’s still free).
Download my learning IronRuby Visual Studio Project and code
No comments yet. Be the first.
Leave a reply








