Is there a way to write rules for incoming calls?
Without jail breaking iOS - you can't get a phone call on any app but the Apple phone app (which doesn't support call screening as you asked).

Some carriers will let you set this up - but it's nothing to do with the iPhone.

Lastly, there are tons of services that require another phone number. Google Voice is one where you can program quiet hours, white list or black list and have exactly such control. 

The downside to these other apps is that you'll need to have people call your alternate number, so it's not as easy - even with the ability to port an existing number to GV and then get a new number from your carrier.

Several iOS apps work with Google Voice like the official app and GV Mobile + and there are probably a hundred other VOIP solutions on the app store, but Google and Skype are the big players today.